feat: 设置面板 + Provider 扩展 + 构建脚本

- 设置面板:三步引导 / AI 配置 / API Key / 规则管理 / 连接测试
- Provider 重构:统一 OpenAICompatibleProvider 基类,新增 Gemini/Claude/混元/智谱等
- 审查面板 Webview:三 Tab、统计卡片、问题列表、postMessage 通信
- esbuild 构建脚本 + 生产打包 + PMD 下载
- 保存文件自动静态分析(500ms debounce)
This commit is contained in:
范智鹏
2026-07-16 22:20:30 +08:00
parent 1144c9b5db
commit 805737fcfc
27 changed files with 1130 additions and 481 deletions
+12 -147
View File
@@ -1,14 +1,10 @@
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { Orchestrator } from '../orchestrator/orchestrator';
import { runAIReview } from '../ai/engine';
import { loadActiveRules } from '../rules/yaml-parser';
import { mergeResults, MergedReport } from '../merger/merger';
import { reportToMarkdown } from '../utils/report';
import { getAIConfig, setApiKey, getApiKey, isApiKeyConfigured } from '../config';
import { createProvider } from '../ai/factory';
import { SetupViewProvider } from '../views/setupView';
import { getApiKey } from '../config';
import { ReviewPanel } from '../panel/webview';
let currentReport: MergedReport | null = null;
@@ -16,7 +12,6 @@ let currentReport: MergedReport | null = null;
export function registerCommands(
context: vscode.ExtensionContext,
orchestrator: Orchestrator,
setupProvider: SetupViewProvider
): void {
context.subscriptions.push(
@@ -129,7 +124,7 @@ export function registerCommands(
vscode.window.showWarningMessage('请先打开工作区');
return;
}
vscode.window.showInformationMessage('添加自定义规则功能开发中');
vscode.window.showInformationMessage('请在设置面板中管理自定义规则');
})
);
@@ -146,148 +141,18 @@ export function registerCommands(
);
context.subscriptions.push(
vscode.commands.registerCommand('codeReviewer.openSetup', () => {
vscode.commands.executeCommand('workbench.view.extension.code-reviewer');
})
);
context.subscriptions.push(
vscode.commands.registerCommand('codeReviewer.setApiKey', 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.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 });
vscode.commands.registerCommand('codeReviewer.openSetup', async () => {
try {
await vscode.commands.executeCommand('workbench.view.extension.code-reviewer');
} catch {
const action = await vscode.window.showErrorMessage(
'无法打开设置面板',
'打开设置 (JSON)'
);
if (action === '打开设置 (JSON)') {
await vscode.commands.executeCommand('workbench.action.openSettingsJson');
}
});
})
);
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();
})
);
}
+32 -3
View File
@@ -1,17 +1,46 @@
import * as vscode from 'vscode';
import stylelint from 'stylelint';
import type { LinterAdapter, AdapterResult, LinterDiagnostic } from './adapter';
import type { LinterAdapter, AdapterResult, LinterDiagnostic, Severity } 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 {
id = 'stylelint';
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 {
return true;
}
async check(document: vscode.TextDocument, workingDir: string): Promise<AdapterResult> {
try {
const stylelint = await this.getModule();
const result = await stylelint.lint({
code: document.getText(),
codeFilename: document.fileName,
@@ -22,7 +51,7 @@ export class StylelintAdapter implements LinterAdapter {
for (const res of result.results) {
for (const w of res.warnings) {
diagnostics.push({
severity: w.severity,
severity: w.severity as Severity,
ruleId: `stylelint:${w.rule}`,
message: w.text,
range: new vscode.Range(
+3 -3
View File
@@ -1,7 +1,7 @@
import * as vscode from 'vscode';
import type { AIProvider } from './providers/base';
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 {
AIEngineResult,
@@ -73,11 +73,11 @@ export async function runAIReview(
}
const providerId = getAIProvider();
const endpoint = getAIEndpoint();
const baseUrl = getAIBaseUrl();
let provider: AIProvider;
try {
provider = createProvider(providerId, apiKey, endpoint);
provider = createProvider(providerId, apiKey, baseUrl);
} catch (err) {
return {
customRuleResults: [],
+106 -10
View File
@@ -1,22 +1,118 @@
import { AIProvider } from './providers/base';
import { DeepSeekProvider } from './providers/deepseek';
import { OpenAIProvider } from './providers/openai';
import { OpenAICompatibleProvider } from './providers/openai-compatible';
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> = {
deepseek: DeepSeekProvider,
openai: OpenAIProvider,
const registry: Record<string, ProviderInfo> = {
deepseek: {
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 {
const Cls = registry[providerId];
if (!Cls) {
export function createProvider(providerId: string, apiKey: string, baseUrl: string): AIProvider {
const info = registry[providerId];
if (!info) {
throw new Error(`未知的 Provider: ${providerId}`);
}
return new Cls(apiKey, endpoint);
return new info.cls(apiKey, baseUrl);
}
export function getProviderIds(): string[] {
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;
}
+1 -1
View File
@@ -10,7 +10,7 @@ export abstract class AIProvider {
constructor(
protected apiKey: string,
protected endpoint: string
protected baseUrl: string
) {}
abstract chat(
@@ -1,17 +1,18 @@
import { AIProvider, ChatOptions } from './base';
export class OpenAIProvider extends AIProvider {
id = 'openai';
name = 'OpenAI';
export class ClaudeProvider extends AIProvider {
id = 'claude';
name = 'Anthropic Claude';
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({
model: options.model,
max_tokens: 4096,
temperature: options.temperature,
system: systemPrompt,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt },
],
});
@@ -24,7 +25,8 @@ export class OpenAIProvider extends AIProvider {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
},
body,
signal: controller.signal,
@@ -35,13 +37,13 @@ export class OpenAIProvider extends AIProvider {
if (response.status === 401) {
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 {
choices: Array<{ message: { content: string } }>;
content?: Array<{ text?: string }>;
};
return data.choices[0]?.message?.content ?? '';
return data.content?.[0]?.text ?? '';
} finally {
clearTimeout(timeout);
}
+51
View File
@@ -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';
export class DeepSeekProvider extends AIProvider {
id = 'deepseek';
name = 'DeepSeek';
export class OpenAICompatibleProvider extends AIProvider {
id: string;
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> {
const url = `${this.endpoint}/chat/completions`;
const url = `${this.baseUrl}/chat/completions`;
const body = JSON.stringify({
model: options.model,
+3 -3
View File
@@ -10,8 +10,8 @@ export function getAIModel(): string {
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.model', 'deepseek-chat');
}
export function getAIEndpoint(): string {
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.endpoint', 'https://api.deepseek.com/v1');
export function getAIBaseUrl(): string {
return vscode.workspace.getConfiguration(ROOT).get<string>('ai.baseUrl', 'https://api.deepseek.com/v1');
}
export function getAITemperature(): number {
@@ -30,7 +30,7 @@ export function getAIConfig() {
return {
provider: getAIProvider(),
model: getAIModel(),
endpoint: getAIEndpoint(),
baseUrl: getAIBaseUrl(),
outputLanguage: getAIOutputLanguage(),
};
}
+4 -2
View File
@@ -11,9 +11,11 @@ export function activate(context: vscode.ExtensionContext) {
orchestrator = new Orchestrator();
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>();
+169
View File
@@ -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 + '\')">&times;</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
View File
@@ -1,232 +1,635 @@
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { getAIConfig, setApiKey, getApiKey, isApiKeyConfigured } from '../config';
import { createProvider } from '../ai/factory';
import { getAIProvider, getAIModel, getAIOutputLanguage, getAIConfig } from '../config/ai';
import { getApiKey, setApiKey } from '../config/secret';
import { createProvider, getAllProviderMeta, getProviderModels } from '../ai/factory';
import { loadActiveRules } from '../rules/yaml-parser';
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 {
constructor(
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;
export class SetupViewProvider implements vscode.WebviewViewProvider {
private _view?: vscode.WebviewView;
public connectionTested = false;
public connectionSuccess = false;
constructor(private context: vscode.ExtensionContext) {
this.refresh();
constructor(private context: vscode.ExtensionContext) {}
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 ?? '';
this.customRules = loadActiveRules(workspaceRoot);
this.apiKeyConfigured = await isApiKeyConfigured(this.context);
this._onDidChangeTreeData.fire(undefined);
}
const rules = loadActiveRules(workspaceRoot);
getTreeItem(element: SetupItem): vscode.TreeItem {
return element;
}
const ruleItems = rules.map(r => ({
id: r.id,
severity: r.severity,
description: r.description,
}));
async getChildren(element?: SetupItem): Promise<SetupItem[]> {
if (!element) {
return this.getRootItems();
}
const baseUrlConfigured = isBaseUrlConfigured();
switch (element.itemType) {
case 'providerGroup': return this.getProviderItems();
case 'apiKey': return this.getApiKeyItems();
case 'language': return this.getLanguageItems();
default: return [];
}
}
private getRootItems(): SetupItem[] {
const items: SetupItem[] = [];
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',
this._view.webview.postMessage({
type: 'initConfig',
config: {
provider: config.provider,
model: config.model,
baseUrl: baseUrlConfigured ? config.baseUrl : '',
baseUrlConfigured,
language: config.outputLanguage,
languageLabel: languageLabels[config.outputLanguage] || config.outputLanguage,
apiKeyConfigured,
},
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(
step2Done ? '② 完成规则启用' : '② 启用自定义规则',
'step',
vscode.TreeItemCollapsibleState.None,
undefined,
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'
));
private async testConnection(): Promise<void> {
const apiKey = await getApiKey(this.context);
if (!apiKey) {
this._view?.webview.postMessage({ type: 'testResult', success: false, message: '请先设置 API Key' });
return;
}
items.push(new SetupItem(
'输入规则名称... [+ 添加]',
'ruleAdd',
vscode.TreeItemCollapsibleState.None,
{
command: 'codeReviewer.addCustomRule',
title: '添加规则',
}
));
if (!isBaseUrlConfigured()) {
this._view?.webview.postMessage({ type: 'testResult', success: false, message: '请先设置 Base URL' });
return;
}
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();
return [
new SetupItem(`提供商: ${config.provider}`,
'provider',
vscode.TreeItemCollapsibleState.None,
{
command: 'codeReviewer.selectProvider',
title: '选择提供商',
}
),
new SetupItem(`模型: ${config.model}`,
'model',
vscode.TreeItemCollapsibleState.None,
{
command: 'codeReviewer.selectModel',
title: '选择模型',
}
),
];
try {
const provider = createProvider(config.provider, apiKey, config.baseUrl);
await provider.chat('回复 ok', 'ping', {
model: config.model,
temperature: 0,
timeoutMs: 15000,
});
this.connectionTested = true;
this.connectionSuccess = true;
this._view?.webview.postMessage({ type: 'testResult', success: true, message: '✓ 连接成功' });
} catch (err) {
this.connectionTested = true;
this.connectionSuccess = false;
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[] {
return [
new SetupItem(
'设置 API Key...',
'apiKey',
vscode.TreeItemCollapsibleState.None,
{
command: 'codeReviewer.setApiKey',
title: '设置 API Key',
}
),
];
private async toggleRule(ruleId: string): Promise<void> {
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 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[] {
const config = getAIConfig();
return [
new SetupItem(
`当前: ${config.outputLanguage === 'zh-CN' ? '中文(简体)' : config.outputLanguage}`,
'language',
vscode.TreeItemCollapsibleState.None,
{
command: 'codeReviewer.selectLanguage',
title: '选择输出语言',
}
),
];
private async deleteRule(ruleId: string): Promise<void> {
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 pattern = new RegExp(`^\\s*${ruleId}\\s*:\\n(?:\\s+.*\\n)*`, 'm');
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;
}