feat: 设置面板 + Provider 扩展 + 构建脚本
- 设置面板:三步引导 / AI 配置 / API Key / 规则管理 / 连接测试 - Provider 重构:统一 OpenAICompatibleProvider 基类,新增 Gemini/Claude/混元/智谱等 - 审查面板 Webview:三 Tab、统计卡片、问题列表、postMessage 通信 - esbuild 构建脚本 + 生产打包 + PMD 下载 - 保存文件自动静态分析(500ms debounce)
This commit is contained in:
@@ -7,3 +7,21 @@ enabled:
|
|||||||
rules:
|
rules:
|
||||||
no-magic-numbers:
|
no-magic-numbers:
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|
||||||
|
no-console-log:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
no-hardcoded-secret:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
no-sql-injection:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
no-command-injection:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
naming-convention-pascal:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
naming-convention-camel:
|
||||||
|
enabled: false
|
||||||
|
|||||||
@@ -9,3 +9,11 @@ vsc-extension-quickstart.md
|
|||||||
**/*.map
|
**/*.map
|
||||||
**/*.ts
|
**/*.ts
|
||||||
**/.vscode-test.*
|
**/.vscode-test.*
|
||||||
|
**/*.mjs
|
||||||
|
!node_modules/**/*.mjs
|
||||||
|
AGENTS.md
|
||||||
|
opencode.json
|
||||||
|
docs/**
|
||||||
|
scripts/**
|
||||||
|
**/*.d.ts
|
||||||
|
.opencode/**
|
||||||
|
|||||||
@@ -10,10 +10,10 @@
|
|||||||
|
|
||||||
## 日志规则(自动执行)
|
## 日志规则(自动执行)
|
||||||
每次创建或修改代码文件后,在项目根目录的 `_AI_USAGE_LOG.md` 中追加一条记录,必须包含以下字段:
|
每次创建或修改代码文件后,在项目根目录的 `_AI_USAGE_LOG.md` 中追加一条记录,必须包含以下字段:
|
||||||
- **日期时间**:当前时间
|
- **日期时间**:文件修改时间(用 `Get-Item LastWriteTime` 或 `Get-Date` 获取),不可乱填或估算
|
||||||
- **范式步骤**:当前已完成的阶段累积链(如 `① 用户提出 → ② 需求澄清`),按实际执行顺序
|
- **范式步骤**:当前已完成的阶段累积链(如 `① 用户提出 → ② 需求澄清`),按实际执行顺序
|
||||||
- **修改摘要**:简要描述改了什么
|
- **修改摘要**:简要描述改了什么
|
||||||
- **中间产物**:AI 交互过程中被淘汰的草稿或过程稿
|
- **中间产物**:AI 交互过程中被淘汰的草稿或过程稿,包括但不限于:先给了伪代码后改正式实现、输出了多个方案选了其中一个、调试时生成的废弃代码版本、类型试错(如先用 `typeof import()` 后改 `interface`)、先改文件 A 后发现不够又改了文件 B
|
||||||
- **涉及文件**:文件路径列表
|
- **涉及文件**:文件路径列表
|
||||||
- **使用模型**:当前使用的模型名
|
- **使用模型**:当前使用的模型名
|
||||||
|
|
||||||
|
|||||||
@@ -1,71 +1,16 @@
|
|||||||
# vscode-code-reviewer README
|
# vscode-code-reviewer
|
||||||
|
|
||||||
This is the README for your extension "vscode-code-reviewer". After writing up a brief description, we recommend including the following sections.
|
VS Code 代码审查与规范检查一体化插件。集成 ESLint、Stylelint、PMD、SQLFluff 等多种 linter,并支持 AI 辅助审查。
|
||||||
|
|
||||||
## Features
|
## 功能
|
||||||
|
|
||||||
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
|
- 一键运行代码审查
|
||||||
|
- 选中代码片段审查
|
||||||
|
- TreeView 面板展示审查结果
|
||||||
|
- 自动修复
|
||||||
|
- 报告导出
|
||||||
|
- 自定义规则管理
|
||||||
|
|
||||||
For example if there is an image subfolder under your extension project workspace:
|
## 配置
|
||||||
|
|
||||||
\!\[feature X\]\(images/feature-x.png\)
|
通过 `Ctrl+Shift+P` → `CodeGuard: 打开设置面板` 进行配置,或编辑 `.vscode/settings.json`。
|
||||||
|
|
||||||
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
|
|
||||||
|
|
||||||
## Extension Settings
|
|
||||||
|
|
||||||
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
|
|
||||||
|
|
||||||
For example:
|
|
||||||
|
|
||||||
This extension contributes the following settings:
|
|
||||||
|
|
||||||
* `myExtension.enable`: Enable/disable this extension.
|
|
||||||
* `myExtension.thing`: Set to `blah` to do something.
|
|
||||||
|
|
||||||
## Known Issues
|
|
||||||
|
|
||||||
Calling out known issues can help limit users opening duplicate issues against your extension.
|
|
||||||
|
|
||||||
## Release Notes
|
|
||||||
|
|
||||||
Users appreciate release notes as you update your extension.
|
|
||||||
|
|
||||||
### 1.0.0
|
|
||||||
|
|
||||||
Initial release of ...
|
|
||||||
|
|
||||||
### 1.0.1
|
|
||||||
|
|
||||||
Fixed issue #.
|
|
||||||
|
|
||||||
### 1.1.0
|
|
||||||
|
|
||||||
Added features X, Y, and Z.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Following extension guidelines
|
|
||||||
|
|
||||||
Ensure that you've read through the extensions guidelines and follow the best practices for creating your extension.
|
|
||||||
|
|
||||||
* [Extension Guidelines](https://code.visualstudio.com/api/references/extension-guidelines)
|
|
||||||
|
|
||||||
## Working with Markdown
|
|
||||||
|
|
||||||
You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
|
|
||||||
|
|
||||||
* Split the editor (`Cmd+\` on macOS or `Ctrl+\` on Windows and Linux).
|
|
||||||
* Toggle preview (`Shift+Cmd+V` on macOS or `Shift+Ctrl+V` on Windows and Linux).
|
|
||||||
* Press `Ctrl+Space` (Windows, Linux, macOS) to see a list of Markdown snippets.
|
|
||||||
|
|
||||||
## For more information
|
|
||||||
|
|
||||||
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
|
|
||||||
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
|
|
||||||
|
|
||||||
**Enjoy!**
|
|
||||||
|
|||||||
@@ -36,3 +36,25 @@
|
|||||||
| 2026-07-14 21:10 | ⑤ 编码实现 → ⑥ 审查验证 | Phase 5.3 审查面板:ReviewPanel Webview(三 Tab 切换/统计卡片/问题列表/postMessage 通信/降级提示)+ commands.ts 集成(review/openPanel/exportReport 对接面板) | 按 docs/superpowers/specs/implementation-steps/17-phase5.3-review-panel.md 直接编码,无中间产物 | src/panel/webview.ts src/activation/commands.ts | deepseek-v4-pro |
|
| 2026-07-14 21:10 | ⑤ 编码实现 → ⑥ 审查验证 | Phase 5.3 审查面板:ReviewPanel Webview(三 Tab 切换/统计卡片/问题列表/postMessage 通信/降级提示)+ commands.ts 集成(review/openPanel/exportReport 对接面板) | 按 docs/superpowers/specs/implementation-steps/17-phase5.3-review-panel.md 直接编码,无中间产物 | src/panel/webview.ts src/activation/commands.ts | deepseek-v4-pro |
|
||||||
| 2026-07-14 21:13 | ⑤ 编码实现 → ⑥ 审查验证 | Phase 6.1 构建脚本:esbuild 打包脚本 + package.json 脚本更新(build / vscode:prepublish) | 按 docs/superpowers/specs/implementation-steps/18-phase6.1-build-scripts.md 直接编码,无中间产物 | scripts/build.mjs package.json | deepseek-v4-flash |
|
| 2026-07-14 21:13 | ⑤ 编码实现 → ⑥ 审查验证 | Phase 6.1 构建脚本:esbuild 打包脚本 + package.json 脚本更新(build / vscode:prepublish) | 按 docs/superpowers/specs/implementation-steps/18-phase6.1-build-scripts.md 直接编码,无中间产物 | scripts/build.mjs package.json | deepseek-v4-flash |
|
||||||
| 2026-07-14 21:14 | ⑤ 编码实现 → ⑥ 审查验证 | Phase 6.2 工具脚本:PMD JAR 下载脚本 + 生产打包脚本 + vsce 依赖 + package.json 脚本更新 | 按 docs/superpowers/specs/implementation-steps/19-phase6.2-tool-scripts.md 直接编码,无中间产物 | scripts/download-pmd.mjs scripts/package-prod.mjs package.json | deepseek-v4-flash |
|
| 2026-07-14 21:14 | ⑤ 编码实现 → ⑥ 审查验证 | Phase 6.2 工具脚本:PMD JAR 下载脚本 + 生产打包脚本 + vsce 依赖 + package.json 脚本更新 | 按 docs/superpowers/specs/implementation-steps/19-phase6.2-tool-scripts.md 直接编码,无中间产物 | scripts/download-pmd.mjs scripts/package-prod.mjs package.json | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 21:20 | ⑤ 编码实现 → ⑥ 审查验证 | 打包 VSIX:优化 .vscodeignore、补全 README、创建 placeholder icon | 无 | .vscodeignore README.md images/icon.png | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 21:35 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 | Bug fix: codeReviewer.openSetup 添加 try/catch 错误处理和用户提示回退 | 无 | src/activation/commands.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 21:52 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: stylelint 模块找不到(.vscodeignore 排除 .mjs 文件 + CJS/ESM 互操作) | 初版只改了 .vscodeignore 没改 CJS/ESM,第二次迭代才补了动态 import | .vscodeignore src/adapters/stylelint.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 22:04 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 设置面板 TreeView → WebView 重构,对齐 setup-panel-preview.html 卡片式 UI 设计 | `type StylelintModule = typeof import('stylelint')` 类型废弃 → 改为内联 interface;`Awaited<typeof import()>` 试错 → 改为 `as` 断言 | package.json src/views/setupView.ts src/extension.ts src/activation/commands.ts src/adapters/stylelint.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 22:16 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 重写快速开始区域:替换步骤圆圈为卡片布局,步骤编号改为 1/2/3 圆形数字,第三步增加快捷键和面板指引副标题 | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 22:24 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 审核引擎三卡片纵向 → 横向三等分布局 | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-14 23:00 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 新增 6 个 AI Provider(Gemini/Claude/腾讯混元/智谱AI/月之暗面/阿里通义),合并 DeepSeek/OpenAI 为通用兼容类,Provider 切换联动模型下拉 | 先试了为每家单独写类,后改为 OpenAICompatibleProvider 统一类 + 子类注入 ID | src/ai/providers/openai-compatible.ts src/ai/providers/gemini.ts src/ai/providers/claude.ts src/ai/providers/deepseek.ts(删) src/ai/providers/openai.ts(删) src/ai/factory.ts src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 22:06 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: 模型提供商/名称下拉框不显示 — 真正根因是 JS 消息传递(ready→initConfig)未送达导致 select 永远空;改为在 getHtml() 模板中直接渲染 option,彻底不依赖异步消息 | 第一轮错误修复(只加 CSS min-height+try-catch)无效,第二轮改为 HTML 模板直接嵌入 option 数据才解决 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 22:17 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: 更换提供商模型不联动 + 徽章显示异常 — 发现 JS 全程未执行(内联脚本被 CSP 屏蔽),JS 改为外部文件 vscode-resource 加载,provider 数据嵌入 JSON script tag,change 事件前端直接查表更新模型下拉 | 第 3 轮:内联 addEventListener(仍不执行),第 4 轮:改为外部 JS 文件才解决 | src/views/setupView.ts src/views/setupView.js scripts/build.mjs scripts/copy-webview-js.mjs package.json | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 22:25 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 新增 Base URL 输入框 + setEndpoint 消息处理 + initConfig 同步端点值 | 第一版给了初始值(config.endpoint),用户要求去掉,第二版清空 value 保留 placeholder | src/views/setupView.ts src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 23:04 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 | 修复 badge 判定逻辑:providerBadge 改为 provider&&model;apiKeyBadge 改为 apiKeyConfigured&&endpoint;pushConfig 补充 endpoint 字段 | 无 | src/views/setupView.ts src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 23:14 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 修复 API Key 模块三个问题:①去掉 programmatic 设置输入框值消除竞态;②去掉 URL 自动填入;③清理死代码 | 无 | src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 23:25 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 修复 inline onclick/onchange 无法调用 IIFE 内函数(postMsg/addRule/toggleRule/deleteRule 未暴露到全局),暴露到 window | 初版分析为 CSP 问题已修复,实际是 IIFE 作用域隔离 | src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-15 23:34 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 全量重命名 endpoint → baseUrl:16 文件 73 处。config 键 ai.endpoint→ai.baseUrl(破坏性变更),所有函数/变量/接口/elementId 同步更名 | 无 | src/config/ai.ts src/ai/providers/base.ts src/ai/providers/openai-compatible.ts src/ai/providers/claude.ts src/ai/providers/gemini.ts src/ai/factory.ts src/ai/engine.ts src/views/setupView.ts src/views/setupView.js package.json docs/superpowers/specs/*.md | deepseek-v4-pro |
|
||||||
|
| 2026-07-16 18:22 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: Base URL 输入框不显示已保存值(initConfig 未设置 baseUrlInput.value)+ API Key 已配置时输入框填入 •••••••• 可编辑视觉提示 | 初版用 placeholder 用户反馈不可编辑 → 改为 value | src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 18:30 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: 用户输入 API Key 后失焦被 pushConfig 覆写为 ••••••••,增加保护条件仅初始/空值时覆写;讨论是否传真实密钥给 webview,确认安全策略,保持 •••••••• 方案 | 尝试评估是否传真实密钥给 webview → 用户确认保持 •••••••• 方案 | src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 18:41 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: isBaseUrlConfigured 误判空字符串(用户 settings.json 有 "" 导致 globalValue 非 undefined),改为 !! 检查非空;setBaseUrl 空值时存 undefined 而非 "" | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 18:48 | ① 用户提出 → ⑤ 编码实现 → ⑥ 审查验证 | 去掉选择提供商自动填入 Base URL 的功能(移除 setProvider 中 cfg.update ai.baseUrl 行及无用 import) | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 18:53 | ① 用户提出 → ⑤ 编码实现 → ⑥ 审查验证 | Bug fix: 清除 URL 后 initConfig 又把默认值填回,改为 pushConfig 仅 baseUrlConfigured 为 true 时才传保存值 | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 19:06 | ① 用户提出 → ⑤ 编码实现 → ⑥ 审查验证 | 保存并测试连接时,Base URL 未配置也报错提示,不再静默使用默认值 | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 21:18 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 快速开始三步序号动态高亮:完成=绿色(#3fb950)、有后继步骤完成但本步未完成=黄色(#f0883e)、默认=灰色 | 三态逻辑先在"仅步骤3触发才变黄"和"任意后继触发变黄"间迭代一次 | src/views/setupView.ts src/views/setupView.js | deepseek-v4-flash |
|
||||||
|
| 2026-07-16 21:57 | ① 用户提出 → ② 需求澄清 → ③ 方案设计 → ④ 人类审批 → ⑤ 编码实现 → ⑥ 审查验证 | 修复 addRule/deleteRule 不同步规则定义文件:addRule 现在在 .code-review/rules/user-rules.yaml 创建模板定义;deleteRule 从 user-rules.yaml 移除规则项 | 无 | src/views/setupView.ts | deepseek-v4-flash |
|
||||||
|
|||||||
@@ -243,7 +243,7 @@ export abstract class AIProvider {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
protected apiKey: string,
|
protected apiKey: string,
|
||||||
protected endpoint: string
|
protected baseUrl: string
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
abstract chat(
|
abstract chat(
|
||||||
@@ -258,15 +258,15 @@ export abstract class AIProvider {
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// factory.ts
|
// factory.ts
|
||||||
const registry: Record<string, new (apiKey: string, endpoint: string) => AIProvider> = {
|
const registry: Record<string, new (apiKey: string, baseUrl: string) => AIProvider> = {
|
||||||
deepseek: DeepSeekProvider,
|
deepseek: DeepSeekProvider,
|
||||||
openai: OpenAIProvider,
|
openai: OpenAIProvider,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createProvider(providerId: string, apiKey: string, endpoint: string): AIProvider {
|
export function createProvider(providerId: string, apiKey: string, baseUrl: string): AIProvider {
|
||||||
const Cls = registry[providerId];
|
const Cls = registry[providerId];
|
||||||
if (!Cls) throw new Error(`Unknown provider: ${providerId}`);
|
if (!Cls) throw new Error(`Unknown provider: ${providerId}`);
|
||||||
return new Cls(apiKey, endpoint);
|
return new Cls(apiKey, baseUrl);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -471,7 +471,7 @@ interface AIFinding {
|
|||||||
|--------|------|--------|------|
|
|--------|------|--------|------|
|
||||||
| `vscode-code-reviewer.ai.provider` | enum | `deepseek` | 模型提供商:`deepseek` / `openai` |
|
| `vscode-code-reviewer.ai.provider` | enum | `deepseek` | 模型提供商:`deepseek` / `openai` |
|
||||||
| `vscode-code-reviewer.ai.model` | string | `deepseek-chat` | 模型名称 |
|
| `vscode-code-reviewer.ai.model` | string | `deepseek-chat` | 模型名称 |
|
||||||
| `vscode-code-reviewer.ai.endpoint` | string | `https://api.deepseek.com/v1` | API 端点 |
|
| `vscode-code-reviewer.ai.baseUrl` | string | `https://api.deepseek.com/v1` | API Base URL |
|
||||||
| `vscode-code-reviewer.ai.temperature` | number | 0.2 | AI 温度参数(建议 0.1-0.3) |
|
| `vscode-code-reviewer.ai.temperature` | number | 0.2 | AI 温度参数(建议 0.1-0.3) |
|
||||||
| `vscode-code-reviewer.ai.timeout` | number | 300 | AI 请求超时(秒) |
|
| `vscode-code-reviewer.ai.timeout` | number | 300 | AI 请求超时(秒) |
|
||||||
| `vscode-code-reviewer.ai.outputLanguage` | string | `zh-CN` | 输出语言:`zh-CN` / `en` / `ja` |
|
| `vscode-code-reviewer.ai.outputLanguage` | string | `zh-CN` | 输出语言:`zh-CN` / `en` / `ja` |
|
||||||
@@ -975,7 +975,7 @@ rules:
|
|||||||
```
|
```
|
||||||
src/config/
|
src/config/
|
||||||
├── index.ts # 统一导出
|
├── index.ts # 统一导出
|
||||||
├── ai.ts # AI 配置(provider/model/endpoint/temperature/timeout/outputLanguage)
|
├── ai.ts # AI 配置(provider/model/baseUrl/temperature/timeout/outputLanguage)
|
||||||
├── linter.ts # Linter 配置(linters.<language>、PMD 路径)
|
├── linter.ts # Linter 配置(linters.<language>、PMD 路径)
|
||||||
├── fixer.ts # 修复器配置(contextLines)
|
├── fixer.ts # 修复器配置(contextLines)
|
||||||
└── secret.ts # API Key SecretStorage(get/set/delete/isConfigured)
|
└── secret.ts # API Key SecretStorage(get/set/delete/isConfigured)
|
||||||
@@ -1047,7 +1047,7 @@ src/config/
|
|||||||
| 快速开始 | 三步引导(圆形序号,完成变紫色) | — |
|
| 快速开始 | 三步引导(圆形序号,完成变紫色) | — |
|
||||||
| 审核引擎 | 三个模块标签(紫/琥珀/绿圆点) | — |
|
| 审核引擎 | 三个模块标签(紫/琥珀/绿圆点) | — |
|
||||||
| AI 模型配置 | 卡片:提供商下拉框 + 模型下拉框 + 状态标签 | `ai.provider` / `ai.model` |
|
| AI 模型配置 | 卡片:提供商下拉框 + 模型下拉框 + 状态标签 | `ai.provider` / `ai.model` |
|
||||||
| API Key | 卡片:密码输入框 + Base URL + 状态标签 | SecretStorage / `ai.endpoint` |
|
| API Key | 卡片:密码输入框 + Base URL + 状态标签 | SecretStorage / `ai.baseUrl` |
|
||||||
| 输出语言 | 下拉框 | `ai.outputLanguage` |
|
| 输出语言 | 下拉框 | `ai.outputLanguage` |
|
||||||
| 自定义规则 | 卡片:开关列表 + 添加行 | `.code-review/config.yaml` |
|
| 自定义规则 | 卡片:开关列表 + 添加行 | `.code-review/config.yaml` |
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ Phase 4 内部必须按 4.1 → 4.2 → 4.3 → 4.4 → 4.5 → 4.6 顺序,Fix
|
|||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `src/types.ts` | 新建 | `LinterDiagnostic`、`AdapterResult`、`LinterAdapter` 等公共类型 |
|
| `src/types.ts` | 新建 | `LinterDiagnostic`、`AdapterResult`、`LinterAdapter` 等公共类型 |
|
||||||
| `src/config/index.ts` | 新建 | 统一导出 |
|
| `src/config/index.ts` | 新建 | 统一导出 |
|
||||||
| `src/config/ai.ts` | 新建 | AI 配置 getter(provider/model/endpoint/temperature/timeout/outputLanguage) |
|
| `src/config/ai.ts` | 新建 | AI 配置 getter(provider/model/baseUrl/temperature/timeout/outputLanguage) |
|
||||||
| `src/config/linter.ts` | 新建 | Linter 配置 getter(linters.xxx 语言-linter 映射、PMD 路径) |
|
| `src/config/linter.ts` | 新建 | Linter 配置 getter(linters.xxx 语言-linter 映射、PMD 路径) |
|
||||||
| `src/config/fixer.ts` | 新建 | 修复器配置(contextLines) |
|
| `src/config/fixer.ts` | 新建 | 修复器配置(contextLines) |
|
||||||
| `src/config/secret.ts` | 新建 | API Key SecretStorage(get/set/delete/isConfigured) |
|
| `src/config/secret.ts` | 新建 | API Key SecretStorage(get/set/delete/isConfigured) |
|
||||||
@@ -91,7 +91,7 @@ export interface LinterAdapter {
|
|||||||
|------|--------|------|--------|
|
|------|--------|------|--------|
|
||||||
| ai | `ai.provider` | enum | `deepseek` |
|
| ai | `ai.provider` | enum | `deepseek` |
|
||||||
| ai | `ai.model` | string | `deepseek-chat` |
|
| ai | `ai.model` | string | `deepseek-chat` |
|
||||||
| ai | `ai.endpoint` | string | `https://api.deepseek.com/v1` |
|
| ai | `ai.baseUrl` | string | `https://api.deepseek.com/v1` |
|
||||||
| ai | `ai.temperature` | number | 0.2 |
|
| ai | `ai.temperature` | number | 0.2 |
|
||||||
| ai | `ai.timeout` | number | 300 |
|
| ai | `ai.timeout` | number | 300 |
|
||||||
| ai | `ai.outputLanguage` | string | `zh-CN` |
|
| ai | `ai.outputLanguage` | string | `zh-CN` |
|
||||||
@@ -270,7 +270,7 @@ jars/pmd/
|
|||||||
| `src/ai/providers/base.ts` | 新建 | `AIProvider` 抽象基类 + `ChatOptions` 接口 |
|
| `src/ai/providers/base.ts` | 新建 | `AIProvider` 抽象基类 + `ChatOptions` 接口 |
|
||||||
| `src/ai/providers/deepseek.ts` | 新建 | `DeepSeekProvider extends AIProvider` |
|
| `src/ai/providers/deepseek.ts` | 新建 | `DeepSeekProvider extends AIProvider` |
|
||||||
| `src/ai/providers/openai.ts` | 新建 | `OpenAIProvider extends AIProvider` |
|
| `src/ai/providers/openai.ts` | 新建 | `OpenAIProvider extends AIProvider` |
|
||||||
| `src/ai/factory.ts` | 新建 | `createProvider(providerId, apiKey, endpoint)` 工厂函数 |
|
| `src/ai/factory.ts` | 新建 | `createProvider(providerId, apiKey, baseUrl)` 工厂函数 |
|
||||||
|
|
||||||
**Provider 接口**:
|
**Provider 接口**:
|
||||||
```typescript
|
```typescript
|
||||||
@@ -283,7 +283,7 @@ interface ChatOptions {
|
|||||||
abstract class AIProvider {
|
abstract class AIProvider {
|
||||||
abstract id: string;
|
abstract id: string;
|
||||||
abstract name: string;
|
abstract name: string;
|
||||||
constructor(protected apiKey: string, protected endpoint: string) {}
|
constructor(protected apiKey: string, protected baseUrl: string) {}
|
||||||
abstract chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string>;
|
abstract chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string>;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -499,7 +499,7 @@ applyFix() 应用修复到编辑器(单条 / 批量倒序)
|
|||||||
| 快速开始 | 三步引导(①②③ 圆形序号,完成变紫色) | 实时状态 |
|
| 快速开始 | 三步引导(①②③ 圆形序号,完成变紫色) | 实时状态 |
|
||||||
| 审核引擎 | 三个模块标签(紫/琥珀/绿圆点) | 静态 |
|
| 审核引擎 | 三个模块标签(紫/琥珀/绿圆点) | 静态 |
|
||||||
| AI 模型配置 | 提供商下拉框 + 模型下拉框 + 状态标签 | `ai.provider` / `ai.model` |
|
| AI 模型配置 | 提供商下拉框 + 模型下拉框 + 状态标签 | `ai.provider` / `ai.model` |
|
||||||
| API Key | 密码输入框 + Base URL + 状态标签 | SecretStorage / `ai.endpoint` |
|
| API Key | 密码输入框 + Base URL + 状态标签 | SecretStorage / `ai.baseUrl` |
|
||||||
| 输出语言 | 下拉框 | `ai.outputLanguage` |
|
| 输出语言 | 下拉框 | `ai.outputLanguage` |
|
||||||
| 自定义规则 | 开关列表 + 添加行 | `.code-review/config.yaml` |
|
| 自定义规则 | 开关列表 + 添加行 | `.code-review/config.yaml` |
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ import * as vscode from 'vscode';
|
|||||||
export interface AIConfig {
|
export interface AIConfig {
|
||||||
provider: string;
|
provider: string;
|
||||||
model: string;
|
model: string;
|
||||||
endpoint: string;
|
baseUrl: string;
|
||||||
temperature: number;
|
temperature: number;
|
||||||
timeout: number;
|
timeout: number;
|
||||||
outputLanguage: string;
|
outputLanguage: string;
|
||||||
@@ -72,7 +72,7 @@ export function getAIConfig(): AIConfig {
|
|||||||
return {
|
return {
|
||||||
provider: config.get<string>('ai.provider', 'deepseek'),
|
provider: config.get<string>('ai.provider', 'deepseek'),
|
||||||
model: config.get<string>('ai.model', 'deepseek-chat'),
|
model: config.get<string>('ai.model', 'deepseek-chat'),
|
||||||
endpoint: config.get<string>('ai.endpoint', 'https://api.deepseek.com/v1'),
|
baseUrl: config.get<string>('ai.baseUrl', 'https://api.deepseek.com/v1'),
|
||||||
temperature: config.get<number>('ai.temperature', 0.2),
|
temperature: config.get<number>('ai.temperature', 0.2),
|
||||||
timeout: config.get<number>('ai.timeout', 300),
|
timeout: config.get<number>('ai.timeout', 300),
|
||||||
outputLanguage: config.get<string>('ai.outputLanguage', 'zh-CN'),
|
outputLanguage: config.get<string>('ai.outputLanguage', 'zh-CN'),
|
||||||
@@ -86,7 +86,7 @@ export function getAIConfig(): AIConfig {
|
|||||||
|-----|------|--------|
|
|-----|------|--------|
|
||||||
| `ai.provider` | enum | `deepseek` |
|
| `ai.provider` | enum | `deepseek` |
|
||||||
| `ai.model` | string | `deepseek-chat` |
|
| `ai.model` | string | `deepseek-chat` |
|
||||||
| `ai.endpoint` | string | `https://api.deepseek.com/v1` |
|
| `ai.baseUrl` | string | `https://api.deepseek.com/v1` |
|
||||||
| `ai.temperature` | number | 0.2 |
|
| `ai.temperature` | number | 0.2 |
|
||||||
| `ai.timeout` | number | 300 |
|
| `ai.timeout` | number | 300 |
|
||||||
| `ai.outputLanguage` | string | `zh-CN` |
|
| `ai.outputLanguage` | string | `zh-CN` |
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export abstract class AIProvider {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
protected apiKey: string,
|
protected apiKey: string,
|
||||||
protected endpoint: string
|
protected baseUrl: string
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
abstract chat(
|
abstract chat(
|
||||||
@@ -56,7 +56,7 @@ export class DeepSeekProvider extends AIProvider {
|
|||||||
name = 'DeepSeek';
|
name = 'DeepSeek';
|
||||||
|
|
||||||
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
||||||
const url = `${this.endpoint}/chat/completions`;
|
const url = `${this.baseUrl}/chat/completions`;
|
||||||
|
|
||||||
const body = JSON.stringify({
|
const body = JSON.stringify({
|
||||||
model: options.model,
|
model: options.model,
|
||||||
@@ -112,7 +112,7 @@ export class OpenAIProvider extends AIProvider {
|
|||||||
name = 'OpenAI';
|
name = 'OpenAI';
|
||||||
|
|
||||||
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
||||||
const url = `${this.endpoint}/chat/completions`;
|
const url = `${this.baseUrl}/chat/completions`;
|
||||||
|
|
||||||
const body = JSON.stringify({
|
const body = JSON.stringify({
|
||||||
model: options.model,
|
model: options.model,
|
||||||
@@ -165,19 +165,19 @@ import { AIProvider } from './providers/base';
|
|||||||
import { DeepSeekProvider } from './providers/deepseek';
|
import { DeepSeekProvider } from './providers/deepseek';
|
||||||
import { OpenAIProvider } from './providers/openai';
|
import { OpenAIProvider } from './providers/openai';
|
||||||
|
|
||||||
type ProviderConstructor = new (apiKey: string, endpoint: string) => AIProvider;
|
type ProviderConstructor = new (apiKey: string, baseUrl: string) => AIProvider;
|
||||||
|
|
||||||
const registry: Record<string, ProviderConstructor> = {
|
const registry: Record<string, ProviderConstructor> = {
|
||||||
deepseek: DeepSeekProvider,
|
deepseek: DeepSeekProvider,
|
||||||
openai: OpenAIProvider,
|
openai: OpenAIProvider,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createProvider(providerId: string, apiKey: string, endpoint: string): AIProvider {
|
export function createProvider(providerId: string, apiKey: string, baseUrl: string): AIProvider {
|
||||||
const Cls = registry[providerId];
|
const Cls = registry[providerId];
|
||||||
if (!Cls) {
|
if (!Cls) {
|
||||||
throw new Error(`未知的 Provider: ${providerId}`);
|
throw new Error(`未知的 Provider: ${providerId}`);
|
||||||
}
|
}
|
||||||
return new Cls(apiKey, endpoint);
|
return new Cls(apiKey, baseUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getProviderIds(): string[] {
|
export function getProviderIds(): string[] {
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ export async function runAIReview(
|
|||||||
|
|
||||||
let provider: AIProvider;
|
let provider: AIProvider;
|
||||||
try {
|
try {
|
||||||
provider = createProvider(config.provider, apiKey, config.endpoint);
|
provider = createProvider(config.provider, apiKey, config.baseUrl);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return {
|
return {
|
||||||
customRuleResults: [],
|
customRuleResults: [],
|
||||||
|
|||||||
@@ -343,7 +343,7 @@ context.subscriptions.push(
|
|||||||
cancellable: false,
|
cancellable: false,
|
||||||
}, async () => {
|
}, async () => {
|
||||||
try {
|
try {
|
||||||
const provider = createProvider(config.provider, apiKey, config.endpoint);
|
const provider = createProvider(config.provider, apiKey, config.baseUrl);
|
||||||
await provider.chat('回复 ok', 'ping', {
|
await provider.chat('回复 ok', 'ping', {
|
||||||
model: config.model,
|
model: config.model,
|
||||||
temperature: 0,
|
temperature: 0,
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 478 B |
+4
-4
@@ -65,7 +65,7 @@
|
|||||||
"views": {
|
"views": {
|
||||||
"code-reviewer": [
|
"code-reviewer": [
|
||||||
{
|
{
|
||||||
"type": "tree",
|
"type": "webview",
|
||||||
"id": "codeReviewer.setupView",
|
"id": "codeReviewer.setupView",
|
||||||
"name": "设置"
|
"name": "设置"
|
||||||
}
|
}
|
||||||
@@ -100,10 +100,10 @@
|
|||||||
"default": "deepseek-chat",
|
"default": "deepseek-chat",
|
||||||
"description": "AI 模型名称"
|
"description": "AI 模型名称"
|
||||||
},
|
},
|
||||||
"vscode-code-reviewer.ai.endpoint": {
|
"vscode-code-reviewer.ai.baseUrl": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "https://api.deepseek.com/v1",
|
"default": "https://api.deepseek.com/v1",
|
||||||
"description": "API 端点"
|
"description": "API Base URL"
|
||||||
},
|
},
|
||||||
"vscode-code-reviewer.ai.temperature": {
|
"vscode-code-reviewer.ai.temperature": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
@@ -217,7 +217,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"compile": "tsc -p ./",
|
"compile": "tsc -p ./ && node scripts/copy-webview-js.mjs",
|
||||||
"watch": "tsc -watch -p ./",
|
"watch": "tsc -watch -p ./",
|
||||||
"build": "node scripts/build.mjs",
|
"build": "node scripts/build.mjs",
|
||||||
"vscode:prepublish": "npm run build",
|
"vscode:prepublish": "npm run build",
|
||||||
|
|||||||
@@ -39,4 +39,19 @@ if (existsSync(jarsSrc)) {
|
|||||||
cpSync(jarsSrc, jarsDest, { recursive: true, force: true });
|
cpSync(jarsSrc, jarsDest, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* copy webview JS files */
|
||||||
|
const viewsSrc = resolve(rootDir, 'src', 'views');
|
||||||
|
const viewsDest = resolve(outDir, 'views');
|
||||||
|
if (existsSync(viewsSrc)) {
|
||||||
|
const files = ['setupView.js'];
|
||||||
|
for (const f of files) {
|
||||||
|
const src = resolve(viewsSrc, f);
|
||||||
|
const dest = resolve(viewsDest, f);
|
||||||
|
if (existsSync(src)) {
|
||||||
|
mkdirSync(dirname(dest), { recursive: true });
|
||||||
|
copyFileSync(src, dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
console.log('Build complete.');
|
console.log('Build complete.');
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { copyFileSync, mkdirSync, existsSync } from 'fs';
|
||||||
|
import { resolve, dirname } from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const rootDir = resolve(__dirname, '..');
|
||||||
|
const outViews = resolve(rootDir, 'out', 'views');
|
||||||
|
const srcViews = resolve(rootDir, 'src', 'views');
|
||||||
|
|
||||||
|
const files = ['setupView.js'];
|
||||||
|
for (const f of files) {
|
||||||
|
const src = resolve(srcViews, f);
|
||||||
|
const dest = resolve(outViews, f);
|
||||||
|
if (existsSync(src)) {
|
||||||
|
mkdirSync(dirname(dest), { recursive: true });
|
||||||
|
copyFileSync(src, dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-147
@@ -1,14 +1,10 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import * as path from 'path';
|
|
||||||
import * as fs from 'fs';
|
|
||||||
import { Orchestrator } from '../orchestrator/orchestrator';
|
import { Orchestrator } from '../orchestrator/orchestrator';
|
||||||
import { runAIReview } from '../ai/engine';
|
import { runAIReview } from '../ai/engine';
|
||||||
import { loadActiveRules } from '../rules/yaml-parser';
|
import { loadActiveRules } from '../rules/yaml-parser';
|
||||||
import { mergeResults, MergedReport } from '../merger/merger';
|
import { mergeResults, MergedReport } from '../merger/merger';
|
||||||
import { reportToMarkdown } from '../utils/report';
|
import { reportToMarkdown } from '../utils/report';
|
||||||
import { getAIConfig, setApiKey, getApiKey, isApiKeyConfigured } from '../config';
|
import { getApiKey } from '../config';
|
||||||
import { createProvider } from '../ai/factory';
|
|
||||||
import { SetupViewProvider } from '../views/setupView';
|
|
||||||
import { ReviewPanel } from '../panel/webview';
|
import { ReviewPanel } from '../panel/webview';
|
||||||
|
|
||||||
let currentReport: MergedReport | null = null;
|
let currentReport: MergedReport | null = null;
|
||||||
@@ -16,7 +12,6 @@ let currentReport: MergedReport | null = null;
|
|||||||
export function registerCommands(
|
export function registerCommands(
|
||||||
context: vscode.ExtensionContext,
|
context: vscode.ExtensionContext,
|
||||||
orchestrator: Orchestrator,
|
orchestrator: Orchestrator,
|
||||||
setupProvider: SetupViewProvider
|
|
||||||
): void {
|
): void {
|
||||||
|
|
||||||
context.subscriptions.push(
|
context.subscriptions.push(
|
||||||
@@ -129,7 +124,7 @@ export function registerCommands(
|
|||||||
vscode.window.showWarningMessage('请先打开工作区');
|
vscode.window.showWarningMessage('请先打开工作区');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
vscode.window.showInformationMessage('添加自定义规则功能开发中');
|
vscode.window.showInformationMessage('请在设置面板中管理自定义规则');
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -146,148 +141,18 @@ export function registerCommands(
|
|||||||
);
|
);
|
||||||
|
|
||||||
context.subscriptions.push(
|
context.subscriptions.push(
|
||||||
vscode.commands.registerCommand('codeReviewer.openSetup', () => {
|
vscode.commands.registerCommand('codeReviewer.openSetup', async () => {
|
||||||
vscode.commands.executeCommand('workbench.view.extension.code-reviewer');
|
try {
|
||||||
})
|
await vscode.commands.executeCommand('workbench.view.extension.code-reviewer');
|
||||||
);
|
} catch {
|
||||||
|
const action = await vscode.window.showErrorMessage(
|
||||||
context.subscriptions.push(
|
'无法打开设置面板',
|
||||||
vscode.commands.registerCommand('codeReviewer.setApiKey', async () => {
|
'打开设置 (JSON)'
|
||||||
const key = await vscode.window.showInputBox({
|
);
|
||||||
prompt: '请输入 API Key',
|
if (action === '打开设置 (JSON)') {
|
||||||
password: true,
|
await vscode.commands.executeCommand('workbench.action.openSettingsJson');
|
||||||
placeHolder: 'sk-...',
|
|
||||||
});
|
|
||||||
if (key) {
|
|
||||||
await setApiKey(context, key);
|
|
||||||
setupProvider.refresh();
|
|
||||||
vscode.window.showInformationMessage('API Key 已保存');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
context.subscriptions.push(
|
|
||||||
vscode.commands.registerCommand('codeReviewer.focusApiKey', async () => {
|
|
||||||
const key = await vscode.window.showInputBox({
|
|
||||||
prompt: '请输入 API Key',
|
|
||||||
password: true,
|
|
||||||
placeHolder: 'sk-...',
|
|
||||||
});
|
|
||||||
if (key) {
|
|
||||||
await setApiKey(context, key);
|
|
||||||
setupProvider.refresh();
|
|
||||||
vscode.window.showInformationMessage('API Key 已保存');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
context.subscriptions.push(
|
|
||||||
vscode.commands.registerCommand('codeReviewer.selectProvider', async () => {
|
|
||||||
const config = vscode.workspace.getConfiguration('vscode-code-reviewer');
|
|
||||||
const selected = await vscode.window.showQuickPick(['deepseek', 'openai'], {
|
|
||||||
placeHolder: '选择模型提供商',
|
|
||||||
});
|
|
||||||
if (selected) {
|
|
||||||
await config.update('ai.provider', selected, vscode.ConfigurationTarget.Global);
|
|
||||||
setupProvider.refresh();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
context.subscriptions.push(
|
|
||||||
vscode.commands.registerCommand('codeReviewer.selectModel', async () => {
|
|
||||||
const config = vscode.workspace.getConfiguration('vscode-code-reviewer');
|
|
||||||
const current = config.get<string>('ai.model', '');
|
|
||||||
const selected = await vscode.window.showInputBox({
|
|
||||||
prompt: '输入模型名称',
|
|
||||||
value: current,
|
|
||||||
placeHolder: 'deepseek-chat',
|
|
||||||
});
|
|
||||||
if (selected) {
|
|
||||||
await config.update('ai.model', selected, vscode.ConfigurationTarget.Global);
|
|
||||||
setupProvider.refresh();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
context.subscriptions.push(
|
|
||||||
vscode.commands.registerCommand('codeReviewer.selectLanguage', async () => {
|
|
||||||
const config = vscode.workspace.getConfiguration('vscode-code-reviewer');
|
|
||||||
const selected = await vscode.window.showQuickPick(
|
|
||||||
[
|
|
||||||
{ label: '中文(简体)', description: 'zh-CN' },
|
|
||||||
{ label: 'English', description: 'en' },
|
|
||||||
{ label: '日本語', description: 'ja' },
|
|
||||||
],
|
|
||||||
{ placeHolder: '选择输出语言' }
|
|
||||||
);
|
|
||||||
if (selected) {
|
|
||||||
await config.update('ai.outputLanguage', selected.description, vscode.ConfigurationTarget.Global);
|
|
||||||
setupProvider.refresh();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
context.subscriptions.push(
|
|
||||||
vscode.commands.registerCommand('codeReviewer.saveAndTest', async () => {
|
|
||||||
const apiKey = await getApiKey(context);
|
|
||||||
if (!apiKey) {
|
|
||||||
vscode.window.showWarningMessage('请先设置 API Key');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = getAIConfig();
|
|
||||||
|
|
||||||
await vscode.window.withProgress({
|
|
||||||
location: vscode.ProgressLocation.Notification,
|
|
||||||
title: '测试连接...',
|
|
||||||
cancellable: false,
|
|
||||||
}, async () => {
|
|
||||||
try {
|
|
||||||
const provider = createProvider(config.provider, apiKey, config.endpoint);
|
|
||||||
await provider.chat('回复 ok', 'ping', {
|
|
||||||
model: config.model,
|
|
||||||
temperature: 0,
|
|
||||||
timeoutMs: 15000,
|
|
||||||
});
|
|
||||||
setupProvider.connectionTested = true;
|
|
||||||
setupProvider.connectionSuccess = true;
|
|
||||||
setupProvider.refresh();
|
|
||||||
vscode.window.showInformationMessage('✓ 连接成功', { modal: false });
|
|
||||||
} catch (err) {
|
|
||||||
setupProvider.connectionTested = true;
|
|
||||||
setupProvider.connectionSuccess = false;
|
|
||||||
setupProvider.refresh();
|
|
||||||
const message = err instanceof Error ? err.message : String(err);
|
|
||||||
vscode.window.showErrorMessage(`✗ 连接失败: ${message}`, { modal: false });
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
context.subscriptions.push(
|
|
||||||
vscode.commands.registerCommand('codeReviewer.toggleRule', async (ruleId: string) => {
|
|
||||||
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
|
||||||
if (!workspaceRoot) { return; }
|
|
||||||
|
|
||||||
const configPath = path.join(workspaceRoot, '.code-review', 'config.yaml');
|
|
||||||
if (!fs.existsSync(configPath)) { return; }
|
|
||||||
|
|
||||||
let content = fs.readFileSync(configPath, 'utf-8');
|
|
||||||
const enabledPattern = new RegExp(`^(\\s*${ruleId}\\s*:\\s*\\n\\s*enabled\\s*:\\s*)(true|false)`, 'm');
|
|
||||||
|
|
||||||
if (enabledPattern.test(content)) {
|
|
||||||
const match = enabledPattern.exec(content);
|
|
||||||
if (match) {
|
|
||||||
const newValue = match[2] === 'true' ? 'false' : 'true';
|
|
||||||
content = content.replace(enabledPattern, `$1${newValue}`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
content += `\n ${ruleId}:\n enabled: false\n`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.writeFileSync(configPath, content, 'utf-8');
|
|
||||||
setupProvider.refresh();
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,46 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import stylelint from 'stylelint';
|
import type { LinterAdapter, AdapterResult, LinterDiagnostic, Severity } from './adapter';
|
||||||
import type { LinterAdapter, AdapterResult, LinterDiagnostic } from './adapter';
|
|
||||||
|
interface LinterOptions {
|
||||||
|
code?: string;
|
||||||
|
codeFilename?: string;
|
||||||
|
cwd?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LinterResult {
|
||||||
|
results: Array<{
|
||||||
|
warnings: Array<{
|
||||||
|
line: number;
|
||||||
|
column: number;
|
||||||
|
endLine?: number;
|
||||||
|
endColumn?: number;
|
||||||
|
rule: string;
|
||||||
|
severity: string;
|
||||||
|
text: string;
|
||||||
|
}>;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
export class StylelintAdapter implements LinterAdapter {
|
export class StylelintAdapter implements LinterAdapter {
|
||||||
id = 'stylelint';
|
id = 'stylelint';
|
||||||
supportedLanguages = ['css'];
|
supportedLanguages = ['css'];
|
||||||
|
|
||||||
|
private _module: { lint: (opts: LinterOptions) => Promise<LinterResult> } | undefined;
|
||||||
|
|
||||||
|
private async getModule(): Promise<{ lint: (opts: LinterOptions) => Promise<LinterResult> }> {
|
||||||
|
if (!this._module) {
|
||||||
|
this._module = await import('stylelint') as { lint: (opts: LinterOptions) => Promise<LinterResult> };
|
||||||
|
}
|
||||||
|
return this._module;
|
||||||
|
}
|
||||||
|
|
||||||
isAvailable(): boolean {
|
isAvailable(): boolean {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async check(document: vscode.TextDocument, workingDir: string): Promise<AdapterResult> {
|
async check(document: vscode.TextDocument, workingDir: string): Promise<AdapterResult> {
|
||||||
try {
|
try {
|
||||||
|
const stylelint = await this.getModule();
|
||||||
const result = await stylelint.lint({
|
const result = await stylelint.lint({
|
||||||
code: document.getText(),
|
code: document.getText(),
|
||||||
codeFilename: document.fileName,
|
codeFilename: document.fileName,
|
||||||
@@ -22,7 +51,7 @@ export class StylelintAdapter implements LinterAdapter {
|
|||||||
for (const res of result.results) {
|
for (const res of result.results) {
|
||||||
for (const w of res.warnings) {
|
for (const w of res.warnings) {
|
||||||
diagnostics.push({
|
diagnostics.push({
|
||||||
severity: w.severity,
|
severity: w.severity as Severity,
|
||||||
ruleId: `stylelint:${w.rule}`,
|
ruleId: `stylelint:${w.rule}`,
|
||||||
message: w.text,
|
message: w.text,
|
||||||
range: new vscode.Range(
|
range: new vscode.Range(
|
||||||
|
|||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import type { AIProvider } from './providers/base';
|
import type { AIProvider } from './providers/base';
|
||||||
import { createProvider } from './factory';
|
import { createProvider } from './factory';
|
||||||
import { getAIProvider, getAIModel, getAIEndpoint, getAITemperature, getAITimeout, getAIOutputLanguage, getApiKey } from '../config';
|
import { getAIProvider, getAIModel, getAIBaseUrl, getAITemperature, getAITimeout, getAIOutputLanguage, getApiKey } from '../config';
|
||||||
import type { LinterDiagnostic, CustomRule } from '../types';
|
import type { LinterDiagnostic, CustomRule } from '../types';
|
||||||
import type {
|
import type {
|
||||||
AIEngineResult,
|
AIEngineResult,
|
||||||
@@ -73,11 +73,11 @@ export async function runAIReview(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const providerId = getAIProvider();
|
const providerId = getAIProvider();
|
||||||
const endpoint = getAIEndpoint();
|
const baseUrl = getAIBaseUrl();
|
||||||
|
|
||||||
let provider: AIProvider;
|
let provider: AIProvider;
|
||||||
try {
|
try {
|
||||||
provider = createProvider(providerId, apiKey, endpoint);
|
provider = createProvider(providerId, apiKey, baseUrl);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return {
|
return {
|
||||||
customRuleResults: [],
|
customRuleResults: [],
|
||||||
|
|||||||
+106
-10
@@ -1,22 +1,118 @@
|
|||||||
import { AIProvider } from './providers/base';
|
import { AIProvider } from './providers/base';
|
||||||
import { DeepSeekProvider } from './providers/deepseek';
|
import { OpenAICompatibleProvider } from './providers/openai-compatible';
|
||||||
import { OpenAIProvider } from './providers/openai';
|
import { GeminiProvider } from './providers/gemini';
|
||||||
|
import { ClaudeProvider } from './providers/claude';
|
||||||
|
|
||||||
type ProviderConstructor = new (apiKey: string, endpoint: string) => AIProvider;
|
interface ProviderInfo {
|
||||||
|
cls: new (apiKey: string, baseUrl: string) => AIProvider;
|
||||||
|
defaultBaseUrl: string;
|
||||||
|
models: string[];
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
const registry: Record<string, ProviderConstructor> = {
|
const registry: Record<string, ProviderInfo> = {
|
||||||
deepseek: DeepSeekProvider,
|
deepseek: {
|
||||||
openai: OpenAIProvider,
|
cls: class extends OpenAICompatibleProvider {
|
||||||
|
constructor(apiKey: string, baseUrl: string) {
|
||||||
|
super(apiKey, baseUrl, 'deepseek', 'DeepSeek');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
defaultBaseUrl: 'https://api.deepseek.com/v1',
|
||||||
|
models: ['deepseek-v4-pro', 'deepseek-v4-flash'],
|
||||||
|
name: 'DeepSeek',
|
||||||
|
},
|
||||||
|
openai: {
|
||||||
|
cls: class extends OpenAICompatibleProvider {
|
||||||
|
constructor(apiKey: string, baseUrl: string) {
|
||||||
|
super(apiKey, baseUrl, 'openai', 'OpenAI');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
defaultBaseUrl: 'https://api.openai.com/v1',
|
||||||
|
models: ['GPT-5.6 Sol', 'GPT-5.6 Terra', 'GPT-5.6 Luna', 'GPT-5.5', 'GPT-5.4'],
|
||||||
|
name: 'OpenAI',
|
||||||
|
},
|
||||||
|
gemini: {
|
||||||
|
cls: GeminiProvider,
|
||||||
|
defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1',
|
||||||
|
models: ['Gemini 3.1 Pro', 'Gemini 3.1 Flash', 'Gemini 3.1 Flash-Lite', 'Gemini 3 Pro', 'Gemini 3 Flash'],
|
||||||
|
name: 'Google Gemini',
|
||||||
|
},
|
||||||
|
claude: {
|
||||||
|
cls: ClaudeProvider,
|
||||||
|
defaultBaseUrl: 'https://api.anthropic.com/v1',
|
||||||
|
models: ['Claude Fable 5', 'Claude Mythos 5', 'Claude Opus 4.8', 'Claude Sonnet 4.6'],
|
||||||
|
name: 'Anthropic Claude',
|
||||||
|
},
|
||||||
|
hunyuan: {
|
||||||
|
cls: class extends OpenAICompatibleProvider {
|
||||||
|
constructor(apiKey: string, baseUrl: string) {
|
||||||
|
super(apiKey, baseUrl, 'hunyuan', '腾讯混元');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
defaultBaseUrl: 'https://api.hunyuan.cloud.tencent.com/v1',
|
||||||
|
models: ['Hy3'],
|
||||||
|
name: '腾讯混元',
|
||||||
|
},
|
||||||
|
zhipu: {
|
||||||
|
cls: class extends OpenAICompatibleProvider {
|
||||||
|
constructor(apiKey: string, baseUrl: string) {
|
||||||
|
super(apiKey, baseUrl, 'zhipu', '智谱AI');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
defaultBaseUrl: 'https://open.bigmodel.cn/api/paas/v4',
|
||||||
|
models: ['GLM-5.2', 'GLM-5.1', 'GLM-5'],
|
||||||
|
name: '智谱AI',
|
||||||
|
},
|
||||||
|
moonshot: {
|
||||||
|
cls: class extends OpenAICompatibleProvider {
|
||||||
|
constructor(apiKey: string, baseUrl: string) {
|
||||||
|
super(apiKey, baseUrl, 'moonshot', '月之暗面');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
defaultBaseUrl: 'https://api.moonshot.cn/v1',
|
||||||
|
models: ['Kimi K2.7 Code', 'Kimi K2.6', 'Kimi K2.5'],
|
||||||
|
name: '月之暗面',
|
||||||
|
},
|
||||||
|
tongyi: {
|
||||||
|
cls: class extends OpenAICompatibleProvider {
|
||||||
|
constructor(apiKey: string, baseUrl: string) {
|
||||||
|
super(apiKey, baseUrl, 'tongyi', '阿里通义');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
defaultBaseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||||
|
models: ['Qwen3-2507', 'Qwen3.6-35B-A3B', 'Qwen3.5-397B-A17B'],
|
||||||
|
name: '阿里通义',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createProvider(providerId: string, apiKey: string, endpoint: string): AIProvider {
|
export function createProvider(providerId: string, apiKey: string, baseUrl: string): AIProvider {
|
||||||
const Cls = registry[providerId];
|
const info = registry[providerId];
|
||||||
if (!Cls) {
|
if (!info) {
|
||||||
throw new Error(`未知的 Provider: ${providerId}`);
|
throw new Error(`未知的 Provider: ${providerId}`);
|
||||||
}
|
}
|
||||||
return new Cls(apiKey, endpoint);
|
return new info.cls(apiKey, baseUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getProviderIds(): string[] {
|
export function getProviderIds(): string[] {
|
||||||
return Object.keys(registry);
|
return Object.keys(registry);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getProviderInfo(providerId: string): ProviderInfo | undefined {
|
||||||
|
return registry[providerId];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getProviderDefaultBaseUrl(providerId: string): string {
|
||||||
|
return registry[providerId]?.defaultBaseUrl ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getProviderModels(providerId: string): string[] {
|
||||||
|
return registry[providerId]?.models ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllProviderMeta(): Record<string, { name: string; models: string[] }> {
|
||||||
|
const result: Record<string, { name: string; models: string[] }> = {};
|
||||||
|
for (const [id, info] of Object.entries(registry)) {
|
||||||
|
result[id] = { name: info.name, models: info.models };
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export abstract class AIProvider {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
protected apiKey: string,
|
protected apiKey: string,
|
||||||
protected endpoint: string
|
protected baseUrl: string
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
abstract chat(
|
abstract chat(
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
import { AIProvider, ChatOptions } from './base';
|
import { AIProvider, ChatOptions } from './base';
|
||||||
|
|
||||||
export class OpenAIProvider extends AIProvider {
|
export class ClaudeProvider extends AIProvider {
|
||||||
id = 'openai';
|
id = 'claude';
|
||||||
name = 'OpenAI';
|
name = 'Anthropic Claude';
|
||||||
|
|
||||||
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
||||||
const url = `${this.endpoint}/chat/completions`;
|
const url = `${this.baseUrl}/messages`;
|
||||||
|
|
||||||
const body = JSON.stringify({
|
const body = JSON.stringify({
|
||||||
model: options.model,
|
model: options.model,
|
||||||
|
max_tokens: 4096,
|
||||||
temperature: options.temperature,
|
temperature: options.temperature,
|
||||||
|
system: systemPrompt,
|
||||||
messages: [
|
messages: [
|
||||||
{ role: 'system', content: systemPrompt },
|
|
||||||
{ role: 'user', content: userPrompt },
|
{ role: 'user', content: userPrompt },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -24,7 +25,8 @@ export class OpenAIProvider extends AIProvider {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Authorization: `Bearer ${this.apiKey}`,
|
'x-api-key': this.apiKey,
|
||||||
|
'anthropic-version': '2023-06-01',
|
||||||
},
|
},
|
||||||
body,
|
body,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
@@ -35,13 +37,13 @@ export class OpenAIProvider extends AIProvider {
|
|||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
throw new Error('API Key 无效,请重新设置');
|
throw new Error('API Key 无效,请重新设置');
|
||||||
}
|
}
|
||||||
throw new Error(`API 请求失败 (${response.status}): ${errorText}`);
|
throw new Error(`Claude API 请求失败 (${response.status}): ${errorText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json() as {
|
const data = await response.json() as {
|
||||||
choices: Array<{ message: { content: string } }>;
|
content?: Array<{ text?: string }>;
|
||||||
};
|
};
|
||||||
return data.choices[0]?.message?.content ?? '';
|
return data.content?.[0]?.text ?? '';
|
||||||
} finally {
|
} finally {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { AIProvider, ChatOptions } from './base';
|
||||||
|
|
||||||
|
export class GeminiProvider extends AIProvider {
|
||||||
|
id = 'gemini';
|
||||||
|
name = 'Google Gemini';
|
||||||
|
|
||||||
|
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
||||||
|
const url = `${this.baseUrl}/models/${options.model}:generateContent?key=${this.apiKey}`;
|
||||||
|
|
||||||
|
const body = JSON.stringify({
|
||||||
|
systemInstruction: {
|
||||||
|
parts: [{ text: systemPrompt }],
|
||||||
|
},
|
||||||
|
contents: [
|
||||||
|
{
|
||||||
|
parts: [{ text: userPrompt }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
generationConfig: {
|
||||||
|
temperature: options.temperature,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text();
|
||||||
|
throw new Error(`Gemini API 请求失败 (${response.status}): ${errorText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json() as {
|
||||||
|
candidates?: Array<{
|
||||||
|
content?: { parts?: Array<{ text?: string }> };
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
return data.candidates?.[0]?.content?.parts?.[0]?.text ?? '';
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,17 @@
|
|||||||
import { AIProvider, ChatOptions } from './base';
|
import { AIProvider, ChatOptions } from './base';
|
||||||
|
|
||||||
export class DeepSeekProvider extends AIProvider {
|
export class OpenAICompatibleProvider extends AIProvider {
|
||||||
id = 'deepseek';
|
id: string;
|
||||||
name = 'DeepSeek';
|
name: string;
|
||||||
|
|
||||||
|
constructor(apiKey: string, baseUrl: string, id: string, name: string) {
|
||||||
|
super(apiKey, baseUrl);
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
async chat(systemPrompt: string, userPrompt: string, options: ChatOptions): Promise<string> {
|
||||||
const url = `${this.endpoint}/chat/completions`;
|
const url = `${this.baseUrl}/chat/completions`;
|
||||||
|
|
||||||
const body = JSON.stringify({
|
const body = JSON.stringify({
|
||||||
model: options.model,
|
model: options.model,
|
||||||
+3
-3
@@ -10,8 +10,8 @@ export function getAIModel(): string {
|
|||||||
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.model', 'deepseek-chat');
|
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.model', 'deepseek-chat');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getAIEndpoint(): string {
|
export function getAIBaseUrl(): string {
|
||||||
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.endpoint', 'https://api.deepseek.com/v1');
|
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.baseUrl', 'https://api.deepseek.com/v1');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getAITemperature(): number {
|
export function getAITemperature(): number {
|
||||||
@@ -30,7 +30,7 @@ export function getAIConfig() {
|
|||||||
return {
|
return {
|
||||||
provider: getAIProvider(),
|
provider: getAIProvider(),
|
||||||
model: getAIModel(),
|
model: getAIModel(),
|
||||||
endpoint: getAIEndpoint(),
|
baseUrl: getAIBaseUrl(),
|
||||||
outputLanguage: getAIOutputLanguage(),
|
outputLanguage: getAIOutputLanguage(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-2
@@ -11,9 +11,11 @@ export function activate(context: vscode.ExtensionContext) {
|
|||||||
orchestrator = new Orchestrator();
|
orchestrator = new Orchestrator();
|
||||||
|
|
||||||
const setupProvider = new SetupViewProvider(context);
|
const setupProvider = new SetupViewProvider(context);
|
||||||
vscode.window.registerTreeDataProvider('codeReviewer.setupView', setupProvider);
|
context.subscriptions.push(
|
||||||
|
vscode.window.registerWebviewViewProvider('codeReviewer.setupView', setupProvider)
|
||||||
|
);
|
||||||
|
|
||||||
registerCommands(context, orchestrator, setupProvider);
|
registerCommands(context, orchestrator);
|
||||||
|
|
||||||
const debounceTimers = new Map<string, NodeJS.Timeout>();
|
const debounceTimers = new Map<string, NodeJS.Timeout>();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
(function () {
|
||||||
|
var data = JSON.parse(document.getElementById('setupViewData').textContent);
|
||||||
|
var PROVIDERS = data.providers;
|
||||||
|
|
||||||
|
var vscode = acquireVsCodeApi();
|
||||||
|
|
||||||
|
function postMsg(type, value) {
|
||||||
|
vscode.postMessage({ type: type, value: value });
|
||||||
|
}
|
||||||
|
|
||||||
|
function addRule() {
|
||||||
|
var input = document.getElementById('newRuleInput');
|
||||||
|
var name = input.value.trim();
|
||||||
|
if (!name) { return; }
|
||||||
|
vscode.postMessage({ type: 'addRule', name: name });
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleRule(ruleId) {
|
||||||
|
vscode.postMessage({ type: 'toggleRule', ruleId: ruleId });
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteRule(ruleId) {
|
||||||
|
vscode.postMessage({ type: 'deleteRule', ruleId: ruleId });
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(text) {
|
||||||
|
var d = document.createElement('div');
|
||||||
|
d.textContent = text;
|
||||||
|
return d.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
function populateModelOptions(providerId, selectModel) {
|
||||||
|
var modelSelect = document.getElementById('modelSelect');
|
||||||
|
if (!modelSelect) { return; }
|
||||||
|
var models = (PROVIDERS[providerId] && PROVIDERS[providerId].models) || [];
|
||||||
|
modelSelect.innerHTML = '';
|
||||||
|
for (var i = 0; i < models.length; i++) {
|
||||||
|
var opt = document.createElement('option');
|
||||||
|
opt.value = models[i];
|
||||||
|
opt.textContent = models[i];
|
||||||
|
modelSelect.appendChild(opt);
|
||||||
|
}
|
||||||
|
if (models.length > 0) {
|
||||||
|
modelSelect.value = selectModel && models.indexOf(selectModel) !== -1 ? selectModel : models[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('providerSelect').addEventListener('change', function () {
|
||||||
|
populateModelOptions(this.value, null);
|
||||||
|
postMsg('setProvider', this.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('modelSelect').addEventListener('change', function () {
|
||||||
|
postMsg('setModel', this.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('baseUrlInput').addEventListener('change', function () {
|
||||||
|
postMsg('setBaseUrl', this.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('message', function (event) {
|
||||||
|
var msg = event.data;
|
||||||
|
|
||||||
|
if (msg.type === 'initConfig') {
|
||||||
|
var c = msg.config;
|
||||||
|
document.getElementById('languageSelect').value = c.language || 'zh-CN';
|
||||||
|
|
||||||
|
var bu = document.getElementById('baseUrlInput');
|
||||||
|
if (bu) { bu.value = c.baseUrl || ''; }
|
||||||
|
|
||||||
|
var ak = document.getElementById('apiKeyInput');
|
||||||
|
if (ak) {
|
||||||
|
if (c.apiKeyConfigured) {
|
||||||
|
if (!ak.value || ak.value === '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022') {
|
||||||
|
ak.value = '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022';
|
||||||
|
}
|
||||||
|
ak.placeholder = '';
|
||||||
|
} else {
|
||||||
|
if (ak.value === '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022') {
|
||||||
|
ak.value = '';
|
||||||
|
}
|
||||||
|
ak.placeholder = 'sk-...';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c.provider && PROVIDERS[c.provider]) {
|
||||||
|
populateModelOptions(c.provider, c.model);
|
||||||
|
var ps = document.getElementById('providerSelect');
|
||||||
|
if (ps) { ps.value = c.provider; }
|
||||||
|
}
|
||||||
|
|
||||||
|
var pb = document.getElementById('providerBadge');
|
||||||
|
if (pb) {
|
||||||
|
pb.textContent = c.provider && c.model ? '已配置' : '未配置';
|
||||||
|
pb.className = 'badge ' + (c.provider && c.model ? 'badge-configured' : 'badge-unconfigured');
|
||||||
|
}
|
||||||
|
|
||||||
|
var akb = document.getElementById('apiKeyBadge');
|
||||||
|
akb.textContent = c.apiKeyConfigured && c.baseUrlConfigured ? '已配置' : '未配置';
|
||||||
|
akb.className = 'badge ' + (c.apiKeyConfigured && c.baseUrlConfigured ? 'badge-configured' : 'badge-unconfigured');
|
||||||
|
|
||||||
|
var connDone = msg.connectionTested && msg.connectionSuccess;
|
||||||
|
var btnTest = document.getElementById('btnTest');
|
||||||
|
if (connDone) {
|
||||||
|
btnTest.innerHTML = '✓ 已连接';
|
||||||
|
} else if (msg.connectionTested && !msg.connectionSuccess) {
|
||||||
|
btnTest.innerHTML = '✗ 重试';
|
||||||
|
} else {
|
||||||
|
btnTest.innerHTML = '保存并测试连接';
|
||||||
|
}
|
||||||
|
btnTest.disabled = false;
|
||||||
|
|
||||||
|
var ruleList = document.getElementById('ruleList');
|
||||||
|
var countBadge = document.getElementById('ruleCountBadge');
|
||||||
|
if (msg.rules && msg.rules.length > 0) {
|
||||||
|
countBadge.textContent = msg.rules.length + ' 条';
|
||||||
|
countBadge.className = 'badge badge-configured';
|
||||||
|
ruleList.innerHTML = msg.rules.map(function (r) {
|
||||||
|
return '<div class="rule-item">' +
|
||||||
|
'<label class="switch"><input type="checkbox" onclick="toggleRule(\'' + r.id + '\')" ' + (r.severity !== 'info' ? 'checked' : '') + '><div class="switch-track"></div><div class="switch-thumb"></div></label>' +
|
||||||
|
'<span class="rule-name">' + escapeHtml(r.id) + '</span>' +
|
||||||
|
'<button class="rule-del" onclick="deleteRule(\'' + r.id + '\')">×</button></div>';
|
||||||
|
}).join('');
|
||||||
|
} else {
|
||||||
|
countBadge.textContent = '0 条';
|
||||||
|
countBadge.className = 'badge badge-unconfigured';
|
||||||
|
ruleList.innerHTML = '<div style="font-size:12px;color:#484f58;padding:8px 0;text-align:center;">暂无规则</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
var step1Done = c.provider && c.model && c.apiKeyConfigured && c.baseUrlConfigured;
|
||||||
|
var step2Done = msg.rules && msg.rules.length > 0;
|
||||||
|
var step3Done = msg.connectionTested && msg.connectionSuccess;
|
||||||
|
var steps = [step1Done, step2Done, step3Done];
|
||||||
|
for (var i = 0; i < steps.length; i++) {
|
||||||
|
var el = document.querySelector('.gs-step[data-step="' + (i + 1) + '"]');
|
||||||
|
if (!el) { continue; }
|
||||||
|
el.classList.remove('gs-step-done', 'gs-step-skip');
|
||||||
|
if (steps[i]) {
|
||||||
|
el.classList.add('gs-step-done');
|
||||||
|
} else if (step3Done) {
|
||||||
|
el.classList.add('gs-step-skip');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.type === 'testResult') {
|
||||||
|
var toast = document.getElementById('toast');
|
||||||
|
toast.textContent = msg.message;
|
||||||
|
toast.className = 'toast show ' + (msg.success ? 'toast-success' : 'toast-error');
|
||||||
|
setTimeout(function () { toast.className = 'toast'; }, 5000);
|
||||||
|
|
||||||
|
var btnTest = document.getElementById('btnTest');
|
||||||
|
btnTest.disabled = false;
|
||||||
|
if (msg.success) {
|
||||||
|
btnTest.innerHTML = '✓ 已连接';
|
||||||
|
} else {
|
||||||
|
btnTest.innerHTML = '✗ 重试';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
vscode.postMessage({ type: 'ready' });
|
||||||
|
|
||||||
|
window.postMsg = postMsg;
|
||||||
|
window.addRule = addRule;
|
||||||
|
window.toggleRule = toggleRule;
|
||||||
|
window.deleteRule = deleteRule;
|
||||||
|
})();
|
||||||
+607
-204
@@ -1,232 +1,635 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { getAIConfig, setApiKey, getApiKey, isApiKeyConfigured } from '../config';
|
import { getAIProvider, getAIModel, getAIOutputLanguage, getAIConfig } from '../config/ai';
|
||||||
import { createProvider } from '../ai/factory';
|
import { getApiKey, setApiKey } from '../config/secret';
|
||||||
|
import { createProvider, getAllProviderMeta, getProviderModels } from '../ai/factory';
|
||||||
import { loadActiveRules } from '../rules/yaml-parser';
|
import { loadActiveRules } from '../rules/yaml-parser';
|
||||||
import type { CustomRule } from '../types';
|
import type { CustomRule } from '../types';
|
||||||
|
|
||||||
type SetupItemType = 'section' | 'step' | 'providerGroup' | 'provider' | 'model' | 'apiKey' | 'language' | 'rule' | 'ruleAdd' | 'action';
|
const languageLabels: Record<string, string> = {
|
||||||
|
'zh-CN': '中文(简体)',
|
||||||
|
'en': 'English',
|
||||||
|
'ja': '日本語',
|
||||||
|
};
|
||||||
|
|
||||||
class SetupItem extends vscode.TreeItem {
|
export class SetupViewProvider implements vscode.WebviewViewProvider {
|
||||||
constructor(
|
private _view?: vscode.WebviewView;
|
||||||
public readonly label: string,
|
|
||||||
public readonly itemType: SetupItemType,
|
|
||||||
public readonly collapsibleState: vscode.TreeItemCollapsibleState,
|
|
||||||
public readonly command?: vscode.Command,
|
|
||||||
public readonly iconPath?: vscode.ThemeIcon,
|
|
||||||
public readonly description?: string,
|
|
||||||
public readonly contextValue?: string,
|
|
||||||
) {
|
|
||||||
super(label, collapsibleState);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class SetupViewProvider implements vscode.TreeDataProvider<SetupItem> {
|
|
||||||
private _onDidChangeTreeData = new vscode.EventEmitter<SetupItem | undefined>();
|
|
||||||
readonly onDidChangeTreeData = this._onDidChangeTreeData.event;
|
|
||||||
|
|
||||||
private customRules: CustomRule[] = [];
|
|
||||||
private apiKeyConfigured = false;
|
|
||||||
public connectionTested = false;
|
public connectionTested = false;
|
||||||
public connectionSuccess = false;
|
public connectionSuccess = false;
|
||||||
|
|
||||||
constructor(private context: vscode.ExtensionContext) {
|
constructor(private context: vscode.ExtensionContext) {}
|
||||||
this.refresh();
|
|
||||||
|
resolveWebviewView(
|
||||||
|
webviewView: vscode.WebviewView,
|
||||||
|
_context: vscode.WebviewViewResolveContext,
|
||||||
|
_token: vscode.CancellationToken,
|
||||||
|
): void {
|
||||||
|
this._view = webviewView;
|
||||||
|
|
||||||
|
webviewView.webview.options = {
|
||||||
|
enableScripts: true,
|
||||||
|
localResourceRoots: [this.context.extensionUri],
|
||||||
|
};
|
||||||
|
|
||||||
|
const config = getAIConfig();
|
||||||
|
const providers = getAllProviderMeta();
|
||||||
|
const scriptUri = webviewView.webview.asWebviewUri(
|
||||||
|
vscode.Uri.joinPath(this.context.extensionUri, 'out', 'views', 'setupView.js')
|
||||||
|
);
|
||||||
|
const aiConfig = getAIConfig();
|
||||||
|
webviewView.webview.html = this.getHtml(providers, aiConfig, scriptUri);
|
||||||
|
|
||||||
|
webviewView.webview.onDidReceiveMessage(async (msg) => {
|
||||||
|
switch (msg.type) {
|
||||||
|
case 'ready':
|
||||||
|
try {
|
||||||
|
await this.pushConfig();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('pushConfig failed:', err);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'setApiKey':
|
||||||
|
await setApiKey(this.context, msg.value);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'setProvider': {
|
||||||
|
const cfg = vscode.workspace.getConfiguration('vscode-code-reviewer');
|
||||||
|
await cfg.update('ai.provider', msg.value, vscode.ConfigurationTarget.Global);
|
||||||
|
const models = getProviderModels(msg.value);
|
||||||
|
if (models.length > 0) {
|
||||||
|
await cfg.update('ai.model', models[0], vscode.ConfigurationTarget.Global);
|
||||||
|
}
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'setModel':
|
||||||
|
await vscode.workspace.getConfiguration('vscode-code-reviewer').update('ai.model', msg.value, vscode.ConfigurationTarget.Global);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'setBaseUrl':
|
||||||
|
await vscode.workspace.getConfiguration('vscode-code-reviewer')
|
||||||
|
.update('ai.baseUrl', msg.value || undefined, vscode.ConfigurationTarget.Global);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'setLanguage':
|
||||||
|
await vscode.workspace.getConfiguration('vscode-code-reviewer').update('ai.outputLanguage', msg.value, vscode.ConfigurationTarget.Global);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'saveAndTest':
|
||||||
|
await this.testConnection();
|
||||||
|
break;
|
||||||
|
case 'toggleRule':
|
||||||
|
await this.toggleRule(msg.ruleId);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'deleteRule':
|
||||||
|
await this.deleteRule(msg.ruleId);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'addRule':
|
||||||
|
await this.addRule(msg.name);
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
case 'reset':
|
||||||
|
await this.resetConfig();
|
||||||
|
await this.pushConfig();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async refresh(): Promise<void> {
|
private async pushConfig(): Promise<void> {
|
||||||
|
if (!this._view) {return;}
|
||||||
|
|
||||||
|
const config = getAIConfig();
|
||||||
|
const apiKeyConfigured = await isApiKeyConfigured(this.context);
|
||||||
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? '';
|
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? '';
|
||||||
this.customRules = loadActiveRules(workspaceRoot);
|
const rules = loadActiveRules(workspaceRoot);
|
||||||
this.apiKeyConfigured = await isApiKeyConfigured(this.context);
|
|
||||||
this._onDidChangeTreeData.fire(undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
getTreeItem(element: SetupItem): vscode.TreeItem {
|
const ruleItems = rules.map(r => ({
|
||||||
return element;
|
id: r.id,
|
||||||
}
|
severity: r.severity,
|
||||||
|
description: r.description,
|
||||||
|
}));
|
||||||
|
|
||||||
async getChildren(element?: SetupItem): Promise<SetupItem[]> {
|
const baseUrlConfigured = isBaseUrlConfigured();
|
||||||
if (!element) {
|
|
||||||
return this.getRootItems();
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (element.itemType) {
|
this._view.webview.postMessage({
|
||||||
case 'providerGroup': return this.getProviderItems();
|
type: 'initConfig',
|
||||||
case 'apiKey': return this.getApiKeyItems();
|
config: {
|
||||||
case 'language': return this.getLanguageItems();
|
provider: config.provider,
|
||||||
default: return [];
|
model: config.model,
|
||||||
}
|
baseUrl: baseUrlConfigured ? config.baseUrl : '',
|
||||||
}
|
baseUrlConfigured,
|
||||||
|
language: config.outputLanguage,
|
||||||
private getRootItems(): SetupItem[] {
|
languageLabel: languageLabels[config.outputLanguage] || config.outputLanguage,
|
||||||
const items: SetupItem[] = [];
|
apiKeyConfigured,
|
||||||
|
|
||||||
const step1Done = this.apiKeyConfigured;
|
|
||||||
const step2Done = this.customRules.some(r => r.id);
|
|
||||||
const step3Done = this.connectionTested && this.connectionSuccess;
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
'快速开始',
|
|
||||||
'section',
|
|
||||||
vscode.TreeItemCollapsibleState.Expanded,
|
|
||||||
undefined,
|
|
||||||
undefined,
|
|
||||||
undefined,
|
|
||||||
'section'
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
step1Done ? '① 完成 AI 模型配置' : '① 配置 AI 模型及 API Key',
|
|
||||||
'step',
|
|
||||||
vscode.TreeItemCollapsibleState.None,
|
|
||||||
step1Done ? undefined : {
|
|
||||||
command: 'codeReviewer.focusApiKey',
|
|
||||||
title: '配置 API Key',
|
|
||||||
},
|
},
|
||||||
step1Done ? new vscode.ThemeIcon('pass-filled', new vscode.ThemeColor('charts.purple')) : undefined
|
providers: getAllProviderMeta(),
|
||||||
));
|
rules: ruleItems,
|
||||||
|
connectionTested: this.connectionTested,
|
||||||
|
connectionSuccess: this.connectionSuccess,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
items.push(new SetupItem(
|
private async testConnection(): Promise<void> {
|
||||||
step2Done ? '② 完成规则启用' : '② 启用自定义规则',
|
const apiKey = await getApiKey(this.context);
|
||||||
'step',
|
if (!apiKey) {
|
||||||
vscode.TreeItemCollapsibleState.None,
|
this._view?.webview.postMessage({ type: 'testResult', success: false, message: '请先设置 API Key' });
|
||||||
undefined,
|
return;
|
||||||
step2Done ? new vscode.ThemeIcon('pass-filled', new vscode.ThemeColor('charts.purple')) : undefined
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
step3Done ? '③ 完成连接测试' : '③ 保存并测试连接',
|
|
||||||
'step',
|
|
||||||
vscode.TreeItemCollapsibleState.None,
|
|
||||||
step3Done ? undefined : {
|
|
||||||
command: 'codeReviewer.saveAndTest',
|
|
||||||
title: '测试连接',
|
|
||||||
},
|
|
||||||
step3Done ? new vscode.ThemeIcon('pass-filled', new vscode.ThemeColor('charts.purple')) : undefined
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
'审核引擎',
|
|
||||||
'section',
|
|
||||||
vscode.TreeItemCollapsibleState.Collapsed
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
'AI 模型配置',
|
|
||||||
'providerGroup',
|
|
||||||
vscode.TreeItemCollapsibleState.Collapsed
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
'API Key',
|
|
||||||
'apiKey',
|
|
||||||
vscode.TreeItemCollapsibleState.Collapsed
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
'输出语言',
|
|
||||||
'language',
|
|
||||||
vscode.TreeItemCollapsibleState.Collapsed
|
|
||||||
));
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
`自定义规则 [${this.customRules.length} 条]`,
|
|
||||||
'section',
|
|
||||||
vscode.TreeItemCollapsibleState.Expanded
|
|
||||||
));
|
|
||||||
|
|
||||||
for (const rule of this.customRules) {
|
|
||||||
items.push(new SetupItem(
|
|
||||||
rule.id,
|
|
||||||
'rule',
|
|
||||||
vscode.TreeItemCollapsibleState.None,
|
|
||||||
{
|
|
||||||
command: 'codeReviewer.toggleRule',
|
|
||||||
title: '切换规则',
|
|
||||||
arguments: [rule.id],
|
|
||||||
},
|
|
||||||
undefined,
|
|
||||||
rule.severity,
|
|
||||||
'rule'
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
items.push(new SetupItem(
|
if (!isBaseUrlConfigured()) {
|
||||||
'输入规则名称... [+ 添加]',
|
this._view?.webview.postMessage({ type: 'testResult', success: false, message: '请先设置 Base URL' });
|
||||||
'ruleAdd',
|
return;
|
||||||
vscode.TreeItemCollapsibleState.None,
|
}
|
||||||
{
|
|
||||||
command: 'codeReviewer.addCustomRule',
|
|
||||||
title: '添加规则',
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
const connectionLabel = this.connectionTested
|
|
||||||
? (this.connectionSuccess ? '✓ 已连接' : '✗ 重试')
|
|
||||||
: '保存并测试连接';
|
|
||||||
|
|
||||||
items.push(new SetupItem(
|
|
||||||
connectionLabel,
|
|
||||||
'action',
|
|
||||||
vscode.TreeItemCollapsibleState.None,
|
|
||||||
{
|
|
||||||
command: 'codeReviewer.saveAndTest',
|
|
||||||
title: '测试连接',
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
return items;
|
|
||||||
}
|
|
||||||
|
|
||||||
private getProviderItems(): SetupItem[] {
|
|
||||||
const config = getAIConfig();
|
const config = getAIConfig();
|
||||||
return [
|
|
||||||
new SetupItem(`提供商: ${config.provider}`,
|
try {
|
||||||
'provider',
|
const provider = createProvider(config.provider, apiKey, config.baseUrl);
|
||||||
vscode.TreeItemCollapsibleState.None,
|
await provider.chat('回复 ok', 'ping', {
|
||||||
{
|
model: config.model,
|
||||||
command: 'codeReviewer.selectProvider',
|
temperature: 0,
|
||||||
title: '选择提供商',
|
timeoutMs: 15000,
|
||||||
}
|
});
|
||||||
),
|
this.connectionTested = true;
|
||||||
new SetupItem(`模型: ${config.model}`,
|
this.connectionSuccess = true;
|
||||||
'model',
|
this._view?.webview.postMessage({ type: 'testResult', success: true, message: '✓ 连接成功' });
|
||||||
vscode.TreeItemCollapsibleState.None,
|
} catch (err) {
|
||||||
{
|
this.connectionTested = true;
|
||||||
command: 'codeReviewer.selectModel',
|
this.connectionSuccess = false;
|
||||||
title: '选择模型',
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
}
|
this._view?.webview.postMessage({ type: 'testResult', success: false, message: `✗ 连接失败: ${message}` });
|
||||||
),
|
}
|
||||||
];
|
|
||||||
|
await this.pushConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
private getApiKeyItems(): SetupItem[] {
|
private async toggleRule(ruleId: string): Promise<void> {
|
||||||
return [
|
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||||
new SetupItem(
|
if (!workspaceRoot) {return;}
|
||||||
'设置 API Key...',
|
|
||||||
'apiKey',
|
const configPath = path.join(workspaceRoot, '.code-review', 'config.yaml');
|
||||||
vscode.TreeItemCollapsibleState.None,
|
if (!fs.existsSync(configPath)) {return;}
|
||||||
{
|
|
||||||
command: 'codeReviewer.setApiKey',
|
let content = fs.readFileSync(configPath, 'utf-8');
|
||||||
title: '设置 API Key',
|
const pattern = new RegExp(`^(\\s*${ruleId}\\s*:\\s*\\n\\s*enabled\\s*:\\s*)(true|false)`, 'm');
|
||||||
}
|
|
||||||
),
|
if (pattern.test(content)) {
|
||||||
];
|
const match = pattern.exec(content);
|
||||||
|
if (match) {
|
||||||
|
const newValue = match[2] === 'true' ? 'false' : 'true';
|
||||||
|
content = content.replace(pattern, `$1${newValue}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
content += `\n ${ruleId}:\n enabled: false\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(configPath, content, 'utf-8');
|
||||||
}
|
}
|
||||||
|
|
||||||
private getLanguageItems(): SetupItem[] {
|
private async deleteRule(ruleId: string): Promise<void> {
|
||||||
const config = getAIConfig();
|
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||||
return [
|
if (!workspaceRoot) {return;}
|
||||||
new SetupItem(
|
|
||||||
`当前: ${config.outputLanguage === 'zh-CN' ? '中文(简体)' : config.outputLanguage}`,
|
const configPath = path.join(workspaceRoot, '.code-review', 'config.yaml');
|
||||||
'language',
|
if (!fs.existsSync(configPath)) {return;}
|
||||||
vscode.TreeItemCollapsibleState.None,
|
|
||||||
{
|
let content = fs.readFileSync(configPath, 'utf-8');
|
||||||
command: 'codeReviewer.selectLanguage',
|
const pattern = new RegExp(`^\\s*${ruleId}\\s*:\\n(?:\\s+.*\\n)*`, 'm');
|
||||||
title: '选择输出语言',
|
content = content.replace(pattern, '');
|
||||||
}
|
fs.writeFileSync(configPath, content, 'utf-8');
|
||||||
),
|
|
||||||
];
|
const userRulesPath = path.join(workspaceRoot, '.code-review', 'rules', 'user-rules.yaml');
|
||||||
|
if (fs.existsSync(userRulesPath)) {
|
||||||
|
let rulesContent = fs.readFileSync(userRulesPath, 'utf-8');
|
||||||
|
const rulePattern = new RegExp(`(?:^|\\n)- id: ${ruleId}\\n(?: .*\\n)*`, '');
|
||||||
|
rulesContent = rulesContent.replace(rulePattern, '');
|
||||||
|
fs.writeFileSync(userRulesPath, rulesContent, 'utf-8');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async addRule(name: string): Promise<void> {
|
||||||
|
if (!name.trim()) {return;}
|
||||||
|
|
||||||
|
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||||
|
if (!workspaceRoot) {return;}
|
||||||
|
|
||||||
|
const configPath = path.join(workspaceRoot, '.code-review', 'config.yaml');
|
||||||
|
if (!fs.existsSync(configPath)) {
|
||||||
|
fs.writeFileSync(configPath, 'rules:\n', 'utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = fs.readFileSync(configPath, 'utf-8');
|
||||||
|
if (!content.includes('rules:')) {
|
||||||
|
content += '\nrules:\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
content += ` ${name}:\n enabled: true\n`;
|
||||||
|
fs.writeFileSync(configPath, content, 'utf-8');
|
||||||
|
|
||||||
|
const rulesDir = path.join(workspaceRoot, '.code-review', 'rules');
|
||||||
|
if (!fs.existsSync(rulesDir)) {
|
||||||
|
fs.mkdirSync(rulesDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userRulesPath = path.join(rulesDir, 'user-rules.yaml');
|
||||||
|
const ruleEntry = `\n- id: ${name}\n severity: warning\n description: 请编辑规则描述\n message: 违反规则,请修改\n`;
|
||||||
|
fs.appendFileSync(userRulesPath, ruleEntry, 'utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resetConfig(): Promise<void> {
|
||||||
|
const config = vscode.workspace.getConfiguration('vscode-code-reviewer');
|
||||||
|
await config.update('ai.provider', undefined, vscode.ConfigurationTarget.Global);
|
||||||
|
await config.update('ai.model', undefined, vscode.ConfigurationTarget.Global);
|
||||||
|
await config.update('ai.outputLanguage', undefined, vscode.ConfigurationTarget.Global);
|
||||||
|
await this.deleteApiKey();
|
||||||
|
this.connectionTested = false;
|
||||||
|
this.connectionSuccess = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteApiKey(): Promise<void> {
|
||||||
|
await this.context.secrets.delete('vscode-code-reviewer.apiKey');
|
||||||
|
}
|
||||||
|
|
||||||
|
private getHtml(
|
||||||
|
providers: Record<string, { name: string; models: string[] }>,
|
||||||
|
config: { provider: string; model: string; outputLanguage: string; baseUrl: string },
|
||||||
|
scriptUri: vscode.Uri,
|
||||||
|
): string {
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
|
background: #0d1117;
|
||||||
|
color: #c9d1d9;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
.panel { width: 100%; }
|
||||||
|
|
||||||
|
/* Header */
|
||||||
|
.panel-header {
|
||||||
|
display: flex; align-items: center; gap: 8px;
|
||||||
|
padding: 10px 0 14px; font-size: 15px; font-weight: 600; color: #e6edf3;
|
||||||
|
border-bottom: 1px solid #21262d; margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Section */
|
||||||
|
.section { margin-bottom: 16px; }
|
||||||
|
.section-title {
|
||||||
|
font-size: 11px; font-weight: 700; text-transform: uppercase;
|
||||||
|
letter-spacing: .04em; color: #8b949e; margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Getting Started */
|
||||||
|
.getting-started {
|
||||||
|
background: #0d1117; border: 1px solid #21262d;
|
||||||
|
border-radius: 8px; padding: 12px;
|
||||||
|
}
|
||||||
|
.gs-title {
|
||||||
|
display: flex; align-items: center; gap: 8px;
|
||||||
|
font-size: 13px; font-weight: 600; color: #e6edf3;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
.gs-title-dot {
|
||||||
|
width: 8px; height: 8px; border-radius: 50%; background: #8b5cf6;
|
||||||
|
}
|
||||||
|
.gs-steps { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.gs-step { display: flex; gap: 8px; font-size: 13px; color: #c9d1d9; line-height: 1.6; }
|
||||||
|
.gs-step-num {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 20px; height: 20px; border-radius: 50%;
|
||||||
|
background: #21262d; color: #8b949e;
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
font-size: 11px; font-weight: 700;
|
||||||
|
margin-top: 1px;
|
||||||
|
}
|
||||||
|
.gs-step-body { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.gs-step-hint { font-size: 11px; color: #8b949e; }
|
||||||
|
.gs-step-done .gs-step-num { background: #3fb950; color: #fff; }
|
||||||
|
.gs-step-skip .gs-step-num { background: #f0883e; color: #fff; }
|
||||||
|
|
||||||
|
/* Engines */
|
||||||
|
.engines { display: flex; flex-direction: row; gap: 6px; }
|
||||||
|
.engine-tab {
|
||||||
|
flex: 1; display: flex; flex-direction: column; gap: 4px;
|
||||||
|
padding: 10px; border: 1px solid #21262d;
|
||||||
|
border-radius: 6px; background: #0d1117;
|
||||||
|
}
|
||||||
|
.engine-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
|
||||||
|
.dot-purple { background: #8b5cf6; }
|
||||||
|
.dot-amber { background: #d29922; }
|
||||||
|
.dot-green { background: #3fb950; }
|
||||||
|
.engine-label { font-size: 13px; color: #e6edf3; }
|
||||||
|
.engine-desc { font-size: 11px; color: #8b949e; }
|
||||||
|
|
||||||
|
/* Card */
|
||||||
|
.card {
|
||||||
|
background: #0d1117; border: 1px solid #21262d;
|
||||||
|
border-radius: 8px; padding: 10px 12px;
|
||||||
|
}
|
||||||
|
.card-row {
|
||||||
|
display: flex; align-items: center;
|
||||||
|
justify-content: space-between; margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
.card-row:last-child { margin-bottom: 0; }
|
||||||
|
.card-label { font-size: 12px; color: #8b949e; }
|
||||||
|
|
||||||
|
/* Badge */
|
||||||
|
.badge {
|
||||||
|
display: inline-flex; align-items: center;
|
||||||
|
padding: 1px 8px; border-radius: 10px;
|
||||||
|
font-size: 11px; font-weight: 600; line-height: 18px;
|
||||||
|
}
|
||||||
|
.badge-configured { background: rgba(35, 134, 54, 0.15); color: #3fb950; }
|
||||||
|
.badge-unconfigured { background: rgba(139, 148, 158, 0.12); color: #8b949e; }
|
||||||
|
|
||||||
|
/* Field */
|
||||||
|
.field { margin-bottom: 8px; }
|
||||||
|
.field:last-child { margin-bottom: 0; }
|
||||||
|
.field-label {
|
||||||
|
display: block; font-size: 12px; color: #8b949e; margin-bottom: 3px;
|
||||||
|
}
|
||||||
|
select, input[type="text"], input[type="password"] {
|
||||||
|
width: 100%; padding: 6px 10px;
|
||||||
|
background: #0d1117; border: 1px solid #30363d;
|
||||||
|
border-radius: 6px; color: #e6edf3;
|
||||||
|
font-size: 13px; font-family: inherit; outline: none;
|
||||||
|
}
|
||||||
|
select:focus, input:focus { border-color: #8b5cf6; }
|
||||||
|
select {
|
||||||
|
appearance: none; min-height: 32px;
|
||||||
|
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%238b949e' viewBox='0 0 16 16'%3E%3Cpath d='M4.427 6.427l3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 6H4.604a.25.25 0 0 0-.177.427z'/%3E%3C/svg%3E");
|
||||||
|
background-repeat: no-repeat; background-position: right 8px center;
|
||||||
|
padding-right: 30px; cursor: pointer;
|
||||||
|
}
|
||||||
|
input::placeholder { color: #484f58; }
|
||||||
|
.field-hint { font-size: 11px; color: #484f58; margin-top: 4px; }
|
||||||
|
|
||||||
|
/* Input group */
|
||||||
|
.input-group { display: flex; gap: 4px; }
|
||||||
|
.input-group input { flex: 1; }
|
||||||
|
.input-group .btn { flex-shrink: 0; }
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex; align-items: center; gap: 4px;
|
||||||
|
padding: 5px 12px; border: 1px solid #30363d;
|
||||||
|
background: #21262d; color: #c9d1d9;
|
||||||
|
border-radius: 6px; cursor: pointer; font-size: 12px;
|
||||||
|
transition: background .15s, border-color .15s; white-space: nowrap;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
.btn:hover { background: #30363d; }
|
||||||
|
.btn-primary { background: #7c3aed; color: #fff; border-color: #7c3aed; }
|
||||||
|
.btn-primary:hover { background: #8b5cf6; }
|
||||||
|
.btn-primary:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
|
.btn-sm { padding: 2px 8px; font-size: 11px; line-height: 20px; }
|
||||||
|
|
||||||
|
/* Toggle switch */
|
||||||
|
.switch {
|
||||||
|
position: relative; display: inline-flex; align-items: center;
|
||||||
|
width: 32px; height: 18px; flex-shrink: 0; cursor: pointer;
|
||||||
|
}
|
||||||
|
.switch input { display: none; }
|
||||||
|
.switch-track {
|
||||||
|
width: 100%; height: 100%; border-radius: 9px;
|
||||||
|
background: #30363d; transition: background .2s;
|
||||||
|
}
|
||||||
|
.switch input:checked + .switch-track { background: #7c3aed; }
|
||||||
|
.switch-thumb {
|
||||||
|
position: absolute; top: 2px; left: 2px;
|
||||||
|
width: 14px; height: 14px; border-radius: 50%;
|
||||||
|
background: #e6edf3; transition: transform .2s;
|
||||||
|
box-shadow: 0 1px 3px rgba(0,0,0,0.3);
|
||||||
|
}
|
||||||
|
.switch input:checked ~ .switch-thumb { transform: translateX(14px); }
|
||||||
|
|
||||||
|
/* Rule item */
|
||||||
|
.rule-item {
|
||||||
|
display: flex; align-items: center; gap: 8px;
|
||||||
|
padding: 6px 8px; margin-top: 4px;
|
||||||
|
border: 1px solid #21262d; border-radius: 6px;
|
||||||
|
background: #0d1117;
|
||||||
|
}
|
||||||
|
.rule-item:first-child { margin-top: 0; }
|
||||||
|
.rule-name {
|
||||||
|
flex: 1; font-size: 13px;
|
||||||
|
font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;
|
||||||
|
color: #e6edf3; overflow: hidden;
|
||||||
|
text-overflow: ellipsis; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.rule-del {
|
||||||
|
flex-shrink: 0; width: 20px; height: 20px; border-radius: 4px;
|
||||||
|
border: none; background: transparent; color: #8b949e;
|
||||||
|
font-size: 14px; cursor: pointer;
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
transition: color .15s, background .15s;
|
||||||
|
}
|
||||||
|
.rule-del:hover { color: #f48771; background: rgba(248,81,73,0.15); }
|
||||||
|
|
||||||
|
/* Actions */
|
||||||
|
.actions { display: flex; gap: 8px; padding-top: 12px; border-top: 1px solid #21262d; }
|
||||||
|
.actions .btn { flex: 1; justify-content: center; }
|
||||||
|
|
||||||
|
/* Toast */
|
||||||
|
.toast {
|
||||||
|
display: none; margin-bottom: 12px; padding: 8px 12px;
|
||||||
|
border-radius: 6px; font-size: 12px; text-align: center;
|
||||||
|
animation: fadeIn .2s ease;
|
||||||
|
}
|
||||||
|
@keyframes fadeIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }
|
||||||
|
.toast.show { display: block; }
|
||||||
|
.toast-success { background: rgba(35, 134, 54, 0.15); border: 1px solid rgba(35, 134, 54, 0.3); color: #3fb950; }
|
||||||
|
.toast-error { background: rgba(248, 81, 73, 0.15); border: 1px solid rgba(248, 81, 73, 0.3); color: #f48771; }
|
||||||
|
|
||||||
|
/* Spinner */
|
||||||
|
@keyframes spin { to { transform: rotate(360deg); } }
|
||||||
|
.spinner {
|
||||||
|
display: inline-block; width: 14px; height: 14px;
|
||||||
|
border: 2px solid rgba(255,255,255,0.2);
|
||||||
|
border-top-color: #fff; border-radius: 50%;
|
||||||
|
animation: spin .6s linear infinite;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<circle cx="12" cy="12" r="3"/>
|
||||||
|
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||||
|
</svg>
|
||||||
|
代码审查 · 设置
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 1. 快速开始 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-title">快速开始</div>
|
||||||
|
<div class="getting-started">
|
||||||
|
<div class="gs-title">
|
||||||
|
<span class="gs-title-dot"></span>
|
||||||
|
三步启用代码审核
|
||||||
|
</div>
|
||||||
|
<div class="gs-steps">
|
||||||
|
<div class="gs-step" data-step="1">
|
||||||
|
<span class="gs-step-num">1</span>
|
||||||
|
<span>安装插件后,<b>配置 AI 模型</b>及 API Key,激活智能审核能力</span>
|
||||||
|
</div>
|
||||||
|
<div class="gs-step" data-step="2">
|
||||||
|
<span class="gs-step-num">2</span>
|
||||||
|
<span>启用 <b>自定义规则</b>,补充团队特有的编码规范</span>
|
||||||
|
</div>
|
||||||
|
<div class="gs-step" data-step="3">
|
||||||
|
<span class="gs-step-num">3</span>
|
||||||
|
<div class="gs-step-body">
|
||||||
|
<span><b>保存并测试连接</b>,验证配置无误后即可触发审核</span>
|
||||||
|
<span class="gs-step-hint">按 <b>Ctrl + Shift + R</b> 快捷键触发审核,结果实时显示在 <b>审核结果报告</b>页面中</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 2. 审核引擎 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-title">审核引擎</div>
|
||||||
|
<div class="engines">
|
||||||
|
<div class="engine-tab">
|
||||||
|
<span class="engine-dot dot-purple"></span>
|
||||||
|
<div>
|
||||||
|
<div class="engine-label">共通规则</div>
|
||||||
|
<div class="engine-desc">Linter 静态分析</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="engine-tab">
|
||||||
|
<span class="engine-dot dot-amber"></span>
|
||||||
|
<div>
|
||||||
|
<div class="engine-label">自定义规则</div>
|
||||||
|
<div class="engine-desc">团队编码规范</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="engine-tab">
|
||||||
|
<span class="engine-dot dot-green"></span>
|
||||||
|
<div>
|
||||||
|
<div class="engine-label">AI 审核</div>
|
||||||
|
<div class="engine-desc">深度代码审查</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 3. AI 模型配置 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-title">AI 模型配置</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-row">
|
||||||
|
<span class="card-label">模型提供商</span>
|
||||||
|
<span class="badge" id="providerBadge">未配置</span>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<select id="providerSelect">${Object.entries(providers).map(([id, meta]) =>
|
||||||
|
`<option value="${id}"${config.provider === id ? ' selected' : ''}>${meta.name}</option>`
|
||||||
|
).join('\n ')}</select>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label class="field-label">模型名称</label>
|
||||||
|
<select id="modelSelect">${(providers[config.provider]?.models ?? []).map(m =>
|
||||||
|
`<option value="${m}"${config.model === m ? ' selected' : ''}>${m}</option>`
|
||||||
|
).join('\n ')}</select>
|
||||||
|
</div>
|
||||||
|
<div class="field-hint">建议使用支持结构化输出的模型。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 4. API Key -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-title">API Key</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-row">
|
||||||
|
<span class="card-label">API Key</span>
|
||||||
|
<span class="badge" id="apiKeyBadge">未配置</span>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<input type="password" id="apiKeyInput" placeholder="sk-..." onchange="postMsg('setApiKey', this.value)">
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label class="field-label">Base URL</label>
|
||||||
|
<input type="text" id="baseUrlInput" placeholder="https://api.deepseek.com/v1" onchange="postMsg('setBaseUrl', this.value)">
|
||||||
|
</div>
|
||||||
|
<div class="field-hint">Key 仅存储在本地 VS Code 安全存储中。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 5. 输出语言 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-title">输出语言</div>
|
||||||
|
<div class="field">
|
||||||
|
<label class="field-label">AI 审查结果输出语言</label>
|
||||||
|
<select id="languageSelect" onchange="postMsg('setLanguage', this.value)">
|
||||||
|
<option value="zh-CN"${config.outputLanguage === 'zh-CN' ? ' selected' : ''}>中文(简体)</option>
|
||||||
|
<option value="en"${config.outputLanguage === 'en' ? ' selected' : ''}>English</option>
|
||||||
|
<option value="ja"${config.outputLanguage === 'ja' ? ' selected' : ''}>日本語</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 6. 自定义规则 -->
|
||||||
|
<div class="section">
|
||||||
|
<div class="section-title">自定义规则</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-row">
|
||||||
|
<span class="card-label">规则列表</span>
|
||||||
|
<span class="badge" style="background:rgba(139,148,158,0.12);color:#8b949e;" id="ruleCountBadge">0 条</span>
|
||||||
|
</div>
|
||||||
|
<div id="ruleList"></div>
|
||||||
|
<div class="field" style="margin-top:8px;">
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="text" id="newRuleInput" placeholder="输入规则名称...">
|
||||||
|
<button class="btn btn-sm" style="background:#7c3aed;color:#fff;border-color:#7c3aed;" onclick="addRule()">+ 添加</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Actions -->
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn" onclick="postMsg('reset')">重置</button>
|
||||||
|
<button class="btn btn-primary" id="btnTest" onclick="postMsg('saveAndTest')">保存并测试连接</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Toast -->
|
||||||
|
<div id="toast"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script id="setupViewData" type="application/json">${JSON.stringify({
|
||||||
|
providers,
|
||||||
|
provider: config.provider,
|
||||||
|
model: config.model,
|
||||||
|
baseUrl: config.baseUrl,
|
||||||
|
})}</script>
|
||||||
|
<script src="${scriptUri}"></script>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function isApiKeyConfigured(context: vscode.ExtensionContext): Promise<boolean> {
|
||||||
|
const key = await context.secrets.get('vscode-code-reviewer.apiKey');
|
||||||
|
return !!key;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBaseUrlConfigured(): boolean {
|
||||||
|
const info = vscode.workspace.getConfiguration('vscode-code-reviewer').inspect<string>('ai.baseUrl');
|
||||||
|
return !!info?.globalValue || !!info?.workspaceValue;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user