diff --git a/src/client/index.tsx b/src/client/index.tsx index b2798bc..7ee81e3 100644 --- a/src/client/index.tsx +++ b/src/client/index.tsx @@ -22,6 +22,7 @@ * 排查「面板没出现」时,先在开发者工具控制台确认这几行走没走。 */ +import { CodeReviewPanel } from './panel.js' import { CodeReviewSettings } from './page.js' import type { ClientContext, PluginConfigViewProps } from './types.js' @@ -43,6 +44,13 @@ export const SLOT_NAME = 'plugins.row.config' */ export const SLOT_KEY = 'dsh-code-review#dsh-code-review' +/** 左侧栏「全局面板」列表 slot(宿主 dsh-client-ui-sidebar 声明)。 */ +const SIDEBAR_SLOT = 'sidebar.panellist' +/** 主区内容 slot(宿主按 activePanelId 选 key)。 */ +const MAIN_SLOT = 'main' +/** 面板 id:侧栏条目与主区 key 必须一致。 */ +export const PANEL_ID = 'dsh-code-review' + /** 空卸载函数(失败路径统一返回它,别让调用方处理 undefined)。 */ function noop(): void { /* 无可释放 */ @@ -65,6 +73,27 @@ export function apply(ctx: ClientContext): () => void { } try { + // ── 侧栏入口 ── + // 宿主 sidebar 读 'sidebar.panellist' 的 { id, order, label } 生成左侧栏行; + // 点击时调用 layout.selectPanel(id),主区再按这个 id 渲染 'main' 槽。 + // 两处 id 必须一致,否则点进去是空白。 + ctx.slots.inject(SIDEBAR_SLOT, () => { + const drop = ctx.slots.register( + { name: SIDEBAR_SLOT, id: PANEL_ID, order: 60, label: '代码审查' }, + () => null, + ) + return drop + }) + + // ── 主区面板 ── + ctx.slots.inject(MAIN_SLOT, () => { + const drop = ctx.slots.register( + { name: MAIN_SLOT, key: PANEL_ID }, + () => CodeReviewPanel(), + ) + return drop + }) + // 等宿主把 plugins.row.config 声明出来(打开插件页时)再注册。 // 不声明 locale:本插件没有自己的词条表,声明一个不存在的命名空间只会多一个失败点。 const dispose = ctx.slots.inject(SLOT_NAME, () => { diff --git a/src/client/panel.tsx b/src/client/panel.tsx new file mode 100644 index 0000000..a270972 --- /dev/null +++ b/src/client/panel.tsx @@ -0,0 +1,300 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 dsh-code-review contributors + +/** + * panel.tsx —— 左侧栏「代码审查」面板。 + * + * 三条设计约束(来自使用反馈): + * 1. 绝对路径必须**可复制**——人眼记不住 `C:\\Users\\...\\2026-...md`; + * 2. 评审结果要**在这里直接看**,不必去翻文件; + * 3. 状态三色:绿=已完成、黄=进行中、红=失败。 + * + * 字体不写死 px:DSH 的字号由宿主决定,写死会和界面不一致。 + * 这里只用 em 相对大小与字重/颜色做层次,跟随宿主基准。 + */ + +import { useEffect, useState } from 'react' + +interface ProgressItem { + readonly taskId: string + readonly repoPath: string + readonly command: string + readonly mode: string | null + readonly stage: string + readonly detail: string | null + readonly round: number | null + readonly maxRounds: number | null + readonly startedAt: string + readonly updatedAt: string + readonly finished: boolean + readonly reportPath: string | null + readonly findingCount: number | null + readonly status: string | null +} + +interface ReportFinding { + readonly id: string + readonly severity: string + readonly category: string + readonly path: string + readonly lineStart: number | null + readonly title: string + readonly explanation: string | null + readonly recommendation: string | null + readonly confidence: number | null +} + +const LIMIT = 3 +const POLL_MS = 3000 + +const C = { + card: 'rgba(255,255,255,0.035)', + border: 'rgba(255,255,255,0.08)', + muted: 'rgba(255,255,255,0.55)', + faint: 'rgba(255,255,255,0.35)', + green: '#3fb950', + yellow: '#d29922', + red: '#f85149', +} as const + +/** 阶段 → 中文。 */ +const STAGE_TEXT: Record = { + queued: '排队中', collect: '采集代码', collecting: '采集代码', select: '筛选文件', + sizing: '估算规模', reviewing: '评审中', 'main-agent': '评审中', 'child-agent': '深挖子任务', + aggregating: '汇总结果', reporting: '写报告中', completed: '已完成', failed: '失败', cancelled: '已取消', +} + +/** 严重度 → 颜色。 */ +const SEV_COLOR: Record = { + critical: '#f85149', high: '#ff8f4d', medium: '#d29922', low: 'rgba(255,255,255,0.55)', info: 'rgba(255,255,255,0.4)', +} + +/** 三态判定:失败红、运行黄、其余绿。 */ +export function stateColor(item: ProgressItem): string { + if (item.stage === 'failed' || item.stage === 'cancelled' || item.status === 'failed') return C.red + if (!item.finished) return C.yellow + return C.green +} + +function shortRepo(repoPath: string): string { + const parts = repoPath.replace(/\\/g, '/').split('/').filter(Boolean) + return parts.slice(-2).join('/') +} + +function formatElapsed(fromIso: string, toIso: string): string { + const from = Date.parse(fromIso) + const to = Date.parse(toIso) + if (!Number.isFinite(from) || !Number.isFinite(to) || to < from) return '' + const sec = Math.round((to - from) / 1000) + if (sec < 60) return String(sec) + ' 秒' + return String(Math.floor(sec / 60)) + ' 分 ' + String(sec % 60) + ' 秒' +} + +/** 小图标按钮(复制)。 */ +function CopyButton({ text, label }: { text: string; label: string }) { + const [done, setDone] = useState(false) + const copy = async (): Promise => { + try { + await navigator.clipboard.writeText(text) + } catch { + // 老浏览器/无权限时退回到临时 textarea + try { + const el = document.createElement('textarea') + el.value = text + document.body.appendChild(el) + el.select() + document.execCommand('copy') + el.remove() + } catch { return } + } + setDone(true) + window.setTimeout(() => setDone(false), 1200) + } + return ( + + ) +} + +/** 展开后的结果列表。 */ +function ReportView({ taskId }: { taskId: string }) { + const [report, setReport] = useState<{ status: string; findings: ReportFinding[] } | null>(null) + const [error, setError] = useState('') + + useEffect(() => { + let alive = true + void (async () => { + try { + const res = await fetch('/api/code-review/report?taskId=' + encodeURIComponent(taskId)) + const json = (await res.json()) as { ok?: boolean; report?: { status: string; findings: ReportFinding[] }; error?: string } + if (!alive) return + if (json.ok === true && json.report !== undefined) setReport(json.report) + else setError(json.error ?? '报告不可用') + } catch (e) { + if (alive) setError(e instanceof Error ? e.message : String(e)) + } + })() + return () => { alive = false } + }, [taskId]) + + if (error !== '') return
{error}
+ if (report === null) return
读取中…
+ if (report.findings.length === 0) return
没有发现问题。
+ + return ( +
+ {report.findings.map((f) => ( +
+
+ + {f.severity} + + + {f.path}{f.lineStart === null ? '' : ':' + String(f.lineStart)} + +
+
{f.title}
+ {f.explanation !== null && f.explanation !== '' && ( +
{f.explanation}
+ )} + {f.recommendation !== null && f.recommendation !== '' && ( +
+ 建议:{f.recommendation} +
+ )} +
+ ))} +
+ ) +} + +/** 一张任务卡。 */ +function Item({ item, onCancel }: { item: ProgressItem; onCancel: (id: string) => void }) { + const [open, setOpen] = useState(false) + const color = stateColor(item) + const stage = STAGE_TEXT[item.stage] ?? item.stage + const round = item.round !== null && item.maxRounds !== null ? '第 ' + String(item.round) + '/' + String(item.maxRounds) + ' 轮' : '' + const elapsed = formatElapsed(item.startedAt, item.finished ? item.updatedAt : new Date().toISOString()) + const scope = item.command + (item.mode === null ? '' : ' / ' + item.mode) + const reportName = item.reportPath === null ? '' : item.reportPath.split(/[\\/]/).pop() ?? '' + + return ( +
+
setOpen((v) => !v)} + style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: item.finished ? 'pointer' : 'default' }} + > + + {stage} + {round !== '' && {round}} + {item.status === 'partial' && ( + 部分 + )} + + {item.taskId.slice(0, 8)} + + {item.finished && {open ? '收起' : '展开'}} +
+ +
+ {shortRepo(item.repoPath)} + ·{scope} + {elapsed !== '' && <>·{elapsed}} +
+ + {item.detail !== null && item.detail !== '' && ( +
{item.detail}
+ )} + + {open && item.finished && } + +
+ {item.finished && item.findingCount !== null && ( + 发现 {String(item.findingCount)} 个问题 + )} + {item.reportPath !== null && ( + <> + + {reportName} + + + + )} + {!item.finished && ( + + )} +
+
+ ) +} + +/** 面板主体。 */ +export function CodeReviewPanel() { + const [items, setItems] = useState([]) + const [error, setError] = useState('') + const [loaded, setLoaded] = useState(false) + + useEffect(() => { + let alive = true + const load = async (): Promise => { + try { + const res = await fetch('/api/code-review/progress') + const json = (await res.json()) as { ok?: boolean; tasks?: ProgressItem[]; error?: string } + if (!alive) return + if (json.ok === true && Array.isArray(json.tasks)) { setItems(json.tasks.slice(0, LIMIT)); setError('') } + else setError(json.error ?? '宿主未返回数据') + } catch (e) { + if (alive) setError(e instanceof Error ? e.message : String(e)) + } finally { + if (alive) setLoaded(true) + } + } + void load() + const timer = setInterval(() => { void load() }, POLL_MS) + return () => { alive = false; clearInterval(timer) } + }, []) + + const cancel = async (taskId: string): Promise => { + try { + await fetch('/api/code-review/cancel', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ taskId }) }) + } catch { /* 下一轮轮询会刷新真实状态 */ } + } + + return ( +
+
+

代码审查

+ 最近 {LIMIT} 条 +
+

+ 用 code_review 工具或 + /review 命令发起评审。已完成的条目可点开直接看结果。 +

+ + {error !== '' &&
读取进度失败:{error}
} + + {loaded && items.length === 0 && error === '' && ( +
+ 还没有评审任务 +
+ )} + + {items.map((item) => void cancel(id)} />)} +
+ ) +} diff --git a/src/client/types.ts b/src/client/types.ts index 1fee387..6c88bd4 100644 --- a/src/client/types.ts +++ b/src/client/types.ts @@ -75,7 +75,18 @@ export interface SlotsService { * @returns 卸载函数 */ register( - options: { readonly name: string; readonly key?: string; readonly locale?: string }, + options: { + readonly name: string + /** keyed slot 用:本条目占的键(main 面板靠它和侧栏 id 对应)。 */ + readonly key?: string + /** list slot 用:条目 id。 */ + readonly id?: string + /** list slot 用:排序权重。 */ + readonly order?: number + /** list slot 用:显示名。 */ + readonly label?: string + readonly locale?: string + }, component: (props: PluginConfigViewProps) => unknown, ): () => void /** diff --git a/src/kernel/execute-task.ts b/src/kernel/execute-task.ts index 7130ce1..772a697 100644 --- a/src/kernel/execute-task.ts +++ b/src/kernel/execute-task.ts @@ -25,6 +25,7 @@ import { renderMarkdown } from '../report/markdown.js' import { redact } from '../report/redact.js' import type { ReviewReport } from '../report/schema.js' import { writeReport } from '../report/writer.js' +import { writeProgress } from '../plugin/progress.js' /** 执行所需的宿主能力(便于测试注入)。 */ export interface ExecuteDeps { @@ -36,8 +37,25 @@ export interface ExecuteDeps { readonly runnerEntry: string /** 当前时间(ISO-8601)。 */ readonly now: () => string - /** 进度回调。 */ - readonly onProgress?: (detail: string) => void + /** + * 数据根目录。 + * + * 传了才写进度文件;不传就完全不写。 + * 为什么这样设计:进度是"给人看的附加物",而单测会直接调 executeTask。 + * 一旦默认落到 resolveDshRoot(),测试就会往用户真实的 ~/.dsh 里写假任务 + * (实机踩过:面板里冒出 dcr-e2e-repo / scan-1 这类永远停在"写报告"的条目)。 + */ + readonly dshRoot?: string + /** + * 进度回调。 + * detail 给人看;round/maxRounds 让界面能画「第 5/8 轮」。 + */ + readonly onProgress?: (event: { + readonly stage: string + readonly detail?: string + readonly round?: number + readonly maxRounds?: number + }) => void } /** 执行结果。 */ @@ -147,7 +165,37 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis memoryMb: config.execution.runnerMemoryMb, } - deps.onProgress?.('reviewing') + // ── 进度上报 ── + // 内核的 stdout 在拉起时是 'ignore'(见 plugin/process.ts),全部丢弃。 + // 所以进度只能落文件:/progress/.json,由宿主的 HTTP 路由读给浏览器。 + const progressStartedAt = deps.now() + const emitProgress = (event: { + stage: string + detail?: string + round?: number + maxRounds?: number + }): void => { + if (deps.dshRoot === undefined) { + // 没给根目录 = 不写进度(测试路径) + deps.onProgress?.(event) + return + } + writeProgress({ + taskId: record.id, + repoPath: record.scope.repoPath, + command: record.scope.command, + mode: record.scope.mode, + stage: event.stage, + detail: event.detail ?? null, + round: event.round ?? null, + maxRounds: event.maxRounds ?? null, + startedAt: progressStartedAt, + updatedAt: deps.now(), + }, deps.dshRoot) + deps.onProgress?.(event) + } + + emitProgress({ stage: 'reviewing' }) let out try { out = await runReview({ @@ -164,10 +212,11 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis config, llm, runner, - ...(deps.onProgress ? { onProgress: (e) => deps.onProgress?.(e.stage) } : {}), + onProgress: (e) => emitProgress(e), }) } catch (error) { const ke = error instanceof KernelError ? error : new KernelError('INTERNAL_UNEXPECTED', error instanceof Error ? error.message : String(error)) + emitProgress({ stage: 'failed', detail: ke.message }) return { ok: false, summary: null, @@ -179,7 +228,7 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis const elapsedSec = (Date.now() - startedAt) / 1000 // 收敛 finding:行号定位 + 指纹 - deps.onProgress?.('aggregating') + emitProgress({ stage: 'aggregating' }) const findings: Finding[] = out.findings.map((raw, i) => { return { id: 'f-' + String(i + 1), @@ -271,7 +320,7 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis // 它们是用于核对的标识,脱敏反而破坏可追溯性。 } - deps.onProgress?.('reporting') + emitProgress({ stage: 'reporting' }) const written = writeReport({ directory: config.report.directory, repoName: repoNameOf(record.scope.repoPath), @@ -283,6 +332,10 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis const severityCounts: Record = {} for (const f of deduped) severityCounts[f.severity] = (severityCounts[f.severity] ?? 0) + 1 + // 终态也要落一条:否则进度文件会永远停在 "reporting", + // 界面上一条已经跑完的任务会一直显示成"在跑"(实机踩过)。 + emitProgress({ stage: out.status === 'failed' ? 'failed' : 'completed', detail: out.status }) + return { ok: out.status !== 'failed', summary: { diff --git a/src/kernel/main.ts b/src/kernel/main.ts index 1b4b794..ab92c9d 100644 --- a/src/kernel/main.ts +++ b/src/kernel/main.ts @@ -74,6 +74,7 @@ export function makeDeps(dshRoot: string): ExecuteDeps { // dist/kernel/main.js → dist/ptc/runner-entry.js const runnerEntry = join(resolve(here, '..'), 'ptc', 'runner-entry.js') return { + dshRoot, resolveCredential: (ref: string) => resolveCredential(ref, { dshRoot }), nodePath: process.execPath, runnerEntry, diff --git a/src/orchestrator/review.ts b/src/orchestrator/review.ts index acc35f1..6b682de 100644 --- a/src/orchestrator/review.ts +++ b/src/orchestrator/review.ts @@ -43,7 +43,16 @@ export interface ReviewInput { /** runner 配置。 */ readonly runner: RunnerOptions /** 进度回调。 */ - readonly onProgress?: (event: { stage: string; detail?: string }) => void + /** + * 进度回调。 + * detail 是给人看的说明;round/maxRounds 让界面能画「第 5/8 轮」。 + */ + readonly onProgress?: (event: { + readonly stage: string + readonly detail?: string + readonly round?: number + readonly maxRounds?: number + }) => void } /** 编排结果。 */ @@ -217,7 +226,17 @@ export async function runReview(input: ReviewInput): Promise { prices, runner: input.runner, tools: policy.sdk ? ['read', 'glob', 'grep'] : [], - ...(input.onProgress ? { onProgress: (e) => input.onProgress?.({ stage: 'main-agent', detail: 'round ' + String(e.round) }) } : {}), + ...(input.onProgress + ? { + onProgress: (e: { round: number }) => + input.onProgress?.({ + stage: 'main-agent', + detail: 'round ' + String(e.round), + round: e.round, + maxRounds: config.budget.maxAgentRounds, + }), + } + : {}), }) agentStops.push({ agent: 'main', stopReason: main.stopReason, rounds: main.rounds }) usage.inputTokens += main.usage.inputTokens diff --git a/src/plugin/index.ts b/src/plugin/index.ts index 96722fb..785df52 100644 --- a/src/plugin/index.ts +++ b/src/plugin/index.ts @@ -28,6 +28,7 @@ import { normalizeConfig } from '../config/schema.js' import { writeCachedCredential } from '../store/credential-cache.js' import { configFilePath, legacyConfigFilePath, resolveDshRoot } from '../store/paths.js' import { parseReviewCommand } from './command-args.js' +import { registerWebApi } from './webapi.js' import { resolveCredentialFromHost } from './credentials.js' import { listTasks, readTask, requestCancellation } from '../store/task-store.js' import { settingsConfig, CONFIG_FIELDS, configObject } from '../settings/schema.js' @@ -384,6 +385,21 @@ export function apply(ctx: Ctx, rawConfig?: unknown): () => void { register(createStatusTool(), STATUS_TOOL_NAME) register(createSetConfigTool(ctx), SET_CONFIG_TOOL_NAME) + // 浏览器半区用的 HTTP 接口(可选服务:没有 webServer 就只是没有 GUI 进度面板) + try { + ctx.inject(['webServer'], (sctx) => { + try { + const webServer = (sctx as unknown as { webServer?: unknown }).webServer + if (webServer === undefined || webServer === null) return + for (const dispose of registerWebApi(webServer as never, ctx.logger)) disposers.push(dispose) + } catch (error) { + ctx.logger?.warn?.('[dsh-code-review] 进度接口注册失败:' + (error instanceof Error ? error.message : String(error))) + } + }) + } catch (error) { + ctx.logger?.warn?.('[dsh-code-review] webServer 服务不可用,GUI 进度面板跳过:' + (error instanceof Error ? error.message : String(error))) + } + // 斜杠命令(可选服务,缺失不阻塞工具) try { ctx.inject(['commands'], (sctx) => { diff --git a/src/plugin/progress.ts b/src/plugin/progress.ts new file mode 100644 index 0000000..1203600 --- /dev/null +++ b/src/plugin/progress.ts @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 dsh-code-review contributors + +/** + * progress.ts —— 评审进度的落地与读取(供 GUI 展示)。 + * + * 为什么需要它:内核是独立进程,而且拉起时 stdio 是 'ignore', + * 它的所有 console 输出都被丢弃。用户(和运维者)在评审跑 14 分钟时只能看到一个 + * 不会动的「评审中」,既不知道第几轮,也不知道花了多少。 + * + * 形态:/progress/.json,每个任务一个文件,原子写。 + * 为什么不用任务卡:任务卡是权威状态(阶段机、迁移校验都在那儿), + * 进度是高频易变数据,混写会让权威文件反复落盘、也让不变量变复杂。 + * + * 全部函数都接受显式 root,便于测试;不传时退回 resolveDshRoot()。 + */ + +import { readdirSync, readFileSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { writeJsonAtomic } from '../store/atomic.js' +import { pluginRoot, resolveDshRoot } from '../store/paths.js' + +/** 一份进度快照(字段都可缺,缺表示"还没到那一步")。 */ +export interface ProgressSnapshot { + readonly taskId: string + readonly repoPath: string + readonly command: string + readonly mode: string | null + /** 粗阶段:queued / collecting / reviewing / aggregating / reporting / completed / failed。 */ + readonly stage: string + /** 细分说明,例如 'round 5/8'、'扫描 493 个文件'。 */ + readonly detail: string | null + /** 主 agent 当前轮次(可选)。 */ + readonly round: number | null + /** 轮次上限(可选)。 */ + readonly maxRounds: number | null + /** 开始时间(ISO)。 */ + readonly startedAt: string + /** 最后更新时间(ISO)。 */ + readonly updatedAt: string +} + +/** 进度目录。 */ +export function progressDir(root: string = resolveDshRoot()): string { + return join(pluginRoot(root), 'progress') +} + +/** 单个任务的进度文件路径(id 只允许安全字符)。 */ +export function progressPath(taskId: string, root: string = resolveDshRoot()): string { + const safe = taskId.replace(/[^A-Za-z0-9._-]/g, '_') + return join(progressDir(root), safe + '.json') +} + +/** + * 写入一份进度快照。 + * 失败不抛:进度是"锦上添花",它坏了不能影响评审本身。 + */ +export function writeProgress(snapshot: ProgressSnapshot, root: string = resolveDshRoot()): void { + try { + writeJsonAtomic(progressPath(snapshot.taskId, root), snapshot) + } catch { + // 忽略:磁盘满/权限问题不该让评审失败 + } +} + +/** 读取全部进度快照,按更新时间倒序。目录不存在时返回空数组。 */ +export function readAllProgress(root: string = resolveDshRoot()): ProgressSnapshot[] { + let names: string[] + try { + names = readdirSync(progressDir(root)).filter((n) => n.endsWith('.json')) + } catch { + return [] + } + const out: ProgressSnapshot[] = [] + for (const name of names) { + try { + const raw = JSON.parse(readFileSync(join(progressDir(root), name), 'utf8')) as ProgressSnapshot + if (typeof raw?.taskId === 'string') out.push(raw) + } catch { + // 半截文件/损坏文件跳过 + } + } + return out.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)) +} + +/** 删除某个任务的进度文件(任务结束时若不想保留历史)。 */ +export function removeProgress(taskId: string, root: string = resolveDshRoot()): void { + try { rmSync(progressPath(taskId, root), { force: true }) } catch { /* 忽略 */ } +} + +/** + * 只保留最近 N 条进度文件,其余删除。 + * 为什么需要:每个任务一个文件,长期运行会堆积成千上万个小文件。 + * @param keep 保留条数(按更新时间倒序) + */ +export function pruneProgress(keep = 20, root: string = resolveDshRoot()): number { + const all = readAllProgress(root) + let removed = 0 + for (const snapshot of all.slice(keep)) { + removeProgress(snapshot.taskId, root) + removed += 1 + } + return removed +} diff --git a/src/plugin/webapi.ts b/src/plugin/webapi.ts new file mode 100644 index 0000000..17b0aaa --- /dev/null +++ b/src/plugin/webapi.ts @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 dsh-code-review contributors + +/** + * webapi.ts —— 给浏览器半区用的两个 HTTP 接口。 + * + * 为什么走 webServer 而不是 remote/typert: + * 本机的 mac-tunnel / dsh-opencode-ip-guard 已经证明这条路可行且最简单—— + * 宿主侧 ctx.webServer.register 挂一个 exact 路由,客户端直接 fetch。 + * 不需要生成描述符,也不引入新的依赖。 + * + * 两个接口: + * GET /api/code-review/progress → 最近若干条任务的进度(倒序) + * POST /api/code-review/cancel → { taskId } 请求取消 + * + * 安全边界:只读进度文件 + 取消任务,**不返回任何绝对路径以外的敏感信息**, + * 也不提供"打开文件/执行命令"这类能力。 + */ + +import { existsSync, readFileSync } from 'node:fs' +import { readAllProgress, type ProgressSnapshot } from './progress.js' +import { listTasks, requestCancellation } from '../store/task-store.js' +import { resolveDshRoot } from '../store/paths.js' + +/** 路由前缀。 */ +export const API_PREFIX = '/api/code-review' + +/** 一条给界面看的数据。 */ +export interface ProgressItem { + readonly taskId: string + readonly repoPath: string + readonly command: string + readonly mode: string | null + readonly stage: string + readonly detail: string | null + readonly round: number | null + readonly maxRounds: number | null + readonly startedAt: string + readonly updatedAt: string + /** 已经不在进度文件里(进程重启后)时,用任务卡补上的终态。 */ + readonly finished: boolean + readonly reportPath: string | null + readonly findingCount: number | null + /** 报告状态:completed / partial / failed(界面用它标「部分」)。 */ + readonly status: string | null +} + +/** 报告里一条发现(只取界面要用的字段)。 */ +export interface ReportFinding { + readonly id: string + readonly severity: string + readonly category: string + readonly path: string + readonly lineStart: number | null + readonly title: string + readonly explanation: string | null + readonly recommendation: string | null + readonly confidence: number | null +} + +/** 一条任务的报告摘要。 */ +export interface ReportDetail { + readonly taskId: string + readonly status: string + readonly findings: readonly ReportFinding[] + readonly reportPath: string +} + +/** + * 读一份报告。 + * + * 安全:只读任务卡里记录的那个路径,且要求「绝对路径 + .json + 文件存在」。 + * 不提供按任意路径读取的能力,避免变成文件读取接口。 + * @param taskId 任务 id + * @param cards 任务卡(调用方传入,便于测试) + */ +export function readReportFor( + taskId: string, + cards: ReadonlyArray<{ id: string; summary: unknown }>, +): ReportDetail | null { + const card = cards.find((c) => c.id === taskId) + if (card === undefined) return null + const summary = card.summary as { reportJsonPath?: string | null; status?: string } | null | undefined + const path = typeof summary?.reportJsonPath === 'string' ? summary.reportJsonPath : '' + if (path === '' || !path.toLowerCase().endsWith('.json') || !existsSync(path)) return null + try { + const raw = JSON.parse(readFileSync(path, 'utf8')) as { + status?: string + findings?: Array> + } + const findings: ReportFinding[] = (raw.findings ?? []).map((f) => ({ + id: typeof f.id === 'string' ? f.id : '', + severity: typeof f.severity === 'string' ? f.severity : 'info', + category: typeof f.category === 'string' ? f.category : '', + path: typeof f.path === 'string' ? f.path : '', + lineStart: typeof f.lineStart === 'number' ? f.lineStart : null, + title: typeof f.title === 'string' ? f.title : '', + explanation: typeof f.explanation === 'string' ? f.explanation : null, + recommendation: typeof f.recommendation === 'string' ? f.recommendation : null, + confidence: typeof f.confidence === 'number' ? f.confidence : null, + })) + return { + taskId, + status: typeof raw.status === 'string' ? raw.status : (summary?.status ?? 'completed'), + findings, + reportPath: path, + } + } catch { + return null + } +} + +/** 判断是不是"还在跑"的阶段。 */ +export function isRunningStage(stage: string): boolean { + return !['completed', 'failed', 'cancelled'].includes(stage) +} + +/** + * 合并进度快照与任务卡,产出界面要的列表。 + * @param snapshots 进度文件读到的快照(倒序) + * @param cards 任务卡(用于补终态与报告路径) + * @param limit 最多返回几条 + */ +export function buildProgressItems( + snapshots: readonly ProgressSnapshot[], + cards: ReadonlyArray<{ id: string; stage: string; summary: unknown }>, + limit = 5, +): ProgressItem[] { + const byId = new Map(cards.map((c) => [c.id, c])) + return snapshots.slice(0, limit).map((s) => { + const card = byId.get(s.taskId) + const summary = card?.summary as { reportPath?: string | null; findingCount?: number } | undefined + return { + taskId: s.taskId, + repoPath: s.repoPath, + command: s.command, + mode: s.mode, + stage: s.stage, + detail: s.detail, + round: s.round, + maxRounds: s.maxRounds, + startedAt: s.startedAt, + updatedAt: s.updatedAt, + finished: !isRunningStage(s.stage) || (card !== undefined && !isRunningStage(card.stage)), + reportPath: summary?.reportPath ?? null, + findingCount: summary?.findingCount ?? null, + status: (summary as { status?: string } | undefined)?.status ?? null, + } + }) +} + +/** 读进度 + 任务卡,返回可直接 JSON 化的列表。 */ +export function currentProgress(limit = 5): ProgressItem[] { + const root = resolveDshRoot() + const snapshots = readAllProgress(root) + const cards = listTasks(root, 50).map((c) => ({ id: c.id, stage: c.stage, summary: c.summary })) + return buildProgressItems(snapshots, cards, limit) +} + +/** + * 注册路由。 + * @param webServer 宿主的 webServer 服务 + * @param logger 可选日志 + */ +export function registerWebApi( + webServer: { + register: (route: { + kind: 'exact' + path: string + handler: (req: unknown, res: unknown) => void + }) => () => void + }, + logger?: { warn?: (m: string) => void }, +): Array<() => void> { + const disposers: Array<() => void> = [] + + try { + disposers.push(webServer.register({ + kind: 'exact', + path: API_PREFIX + '/progress', + handler: (_req: unknown, res: any) => { + try { + res.setHeader?.('content-type', 'application/json') + res.end?.(JSON.stringify({ ok: true, tasks: currentProgress(5) })) + } catch (error) { + res.statusCode = 500 + res.end?.(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) })) + } + }, + })) + } catch (error) { + logger?.warn?.('[dsh-code-review] 注册进度路由失败:' + (error instanceof Error ? error.message : String(error))) + } + + try { + disposers.push(webServer.register({ + kind: 'exact', + path: API_PREFIX + '/cancel', + handler: (req: any, res: any) => { + res.setHeader?.('content-type', 'application/json') + // 只接受 POST:GET 不应该有副作用 + if (req?.method !== 'POST') { + res.statusCode = 405 + res.end?.(JSON.stringify({ ok: false, error: 'method not allowed' })) + return + } + let body = '' + req.on?.('data', (chunk: Buffer) => { body += chunk.toString('utf8') }) + req.on?.('end', () => { + try { + const parsed = JSON.parse(body) as { taskId?: unknown } + const taskId = typeof parsed.taskId === 'string' ? parsed.taskId.trim() : '' + if (taskId === '') { + res.statusCode = 400 + res.end?.(JSON.stringify({ ok: false, error: 'taskId required' })) + return + } + requestCancellation(taskId, new Date().toISOString(), resolveDshRoot()) + res.end?.(JSON.stringify({ ok: true })) + } catch (error) { + res.statusCode = 400 + res.end?.(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) })) + } + }) + }, + })) + } catch (error) { + logger?.warn?.('[dsh-code-review] 注册取消路由失败:' + (error instanceof Error ? error.message : String(error))) + } + + try { + disposers.push(webServer.register({ + kind: 'exact', + path: API_PREFIX + '/report', + handler: (req: any, res: any) => { + res.setHeader?.('content-type', 'application/json') + try { + const url = String(req?.url ?? '') + const query = url.includes('?') ? url.slice(url.indexOf('?') + 1) : '' + const params = new URLSearchParams(query) + const taskId = (params.get('taskId') ?? '').trim() + if (taskId === '') { + res.statusCode = 400 + res.end?.(JSON.stringify({ ok: false, error: 'taskId required' })) + return + } + const root = resolveDshRoot() + const cards = listTasks(root, 50).map((c) => ({ id: c.id, summary: c.summary })) + const detail = readReportFor(taskId, cards) + if (detail === null) { + res.statusCode = 404 + res.end?.(JSON.stringify({ ok: false, error: '报告不存在或尚未生成' })) + return + } + res.end?.(JSON.stringify({ ok: true, report: detail })) + } catch (error) { + res.statusCode = 500 + res.end?.(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) })) + } + }, + })) + } catch (error) { + logger?.warn?.('[dsh-code-review] 注册报告路由失败:' + (error instanceof Error ? error.message : String(error))) + } + + return disposers +} diff --git a/test/plugin/progress.test.ts b/test/plugin/progress.test.ts new file mode 100644 index 0000000..168d617 --- /dev/null +++ b/test/plugin/progress.test.ts @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 dsh-code-review contributors + +/** + * progress.test.ts —— 进度落地与读取的契约测试。 + * + * 这条链路的失败模式是"静默"的:进度写不进去,界面就一直显示"还没有任务", + * 用户只会以为功能没做。所以这里逐条钉住:写进去能读回、坏文件不拖垮整体、 + * 只保留最近 N 条、以及合并任务卡终态的逻辑。 + */ + +import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + progressDir, + progressPath, + pruneProgress, + readAllProgress, + removeProgress, + writeProgress, + type ProgressSnapshot, +} from '../../src/plugin/progress.js' +import { buildProgressItems, isRunningStage, readReportFor } from '../../src/plugin/webapi.js' + +const roots: string[] = [] +function tempRoot(): string { + const d = mkdtempSync(join(tmpdir(), 'dcr-progress-')) + roots.push(d) + return d +} +afterEach(() => { + while (roots.length > 0) { + const d = roots.pop() + if (d) rmSync(d, { recursive: true, force: true }) + } +}) + +/** 造一份快照。 */ +function snap(taskId: string, over: Partial = {}): ProgressSnapshot { + return { + taskId, + repoPath: 'D:/repo', + command: 'review', + mode: 'uncommitted', + stage: 'main-agent', + detail: null, + round: null, + maxRounds: null, + startedAt: '2026-11-05T00:00:00.000Z', + updatedAt: '2026-11-05T00:00:00.000Z', + ...over, + } +} + +describe('写入与读取', () => { + it('写进去能原样读回', () => { + const root = tempRoot() + writeProgress(snap('t1', { detail: 'round 3', round: 3, maxRounds: 8 }), root) + const all = readAllProgress(root) + expect(all).toHaveLength(1) + expect(all[0]!.taskId).toBe('t1') + expect(all[0]!.round).toBe(3) + expect(all[0]!.maxRounds).toBe(8) + }) + + it('按更新时间倒序', () => { + const root = tempRoot() + writeProgress(snap('old', { updatedAt: '2026-11-05T00:00:00.000Z' }), root) + writeProgress(snap('mid', { updatedAt: '2026-11-05T01:00:00.000Z' }), root) + writeProgress(snap('new', { updatedAt: '2026-11-05T02:00:00.000Z' }), root) + expect(readAllProgress(root).map((s) => s.taskId)).toEqual(['new', 'mid', 'old']) + }) + + it('目录不存在时返回空数组而不是抛错', () => { + expect(readAllProgress(join(tempRoot(), 'nope'))).toEqual([]) + }) + + it('损坏的文件被跳过,不影响其它条目', () => { + const root = tempRoot() + writeProgress(snap('good'), root) + mkdirSync(progressDir(root), { recursive: true }) + writeFileSync(join(progressDir(root), 'broken.json'), '{ 不是 json', 'utf8') + expect(readAllProgress(root).map((s) => s.taskId)).toEqual(['good']) + }) + + it('taskId 里的路径分隔符被清洗(不逃出目录)', () => { + // 关键不是"没有点号",而是"文件必须落在进度目录里、且文件名不再含分隔符"。 + // '..' 作为普通字符留在名字里完全无害,只要它不构成路径段。 + const dir = progressDir('C:/root') + const p = progressPath('../../evil', 'C:/root') + expect(p.startsWith(dir)).toBe(true) + const tail = p.slice(dir.length) + expect(tail).toMatch(/^[\\/][^\\/]+$/) + expect(p.endsWith('.json')).toBe(true) + }) + + it('removeProgress 删掉单条', () => { + const root = tempRoot() + writeProgress(snap('a'), root) + removeProgress('a', root) + expect(readAllProgress(root)).toEqual([]) + }) +}) + +describe('裁剪', () => { + it('只保留最近 N 条', () => { + const root = tempRoot() + for (let i = 0; i < 5; i += 1) { + writeProgress(snap('t' + String(i), { updatedAt: '2026-11-05T0' + String(i) + ':00:00.000Z' }), root) + } + const removed = pruneProgress(2, root) + expect(removed).toBe(3) + expect(readAllProgress(root).map((s) => s.taskId)).toEqual(['t4', 't3']) + }) +}) + +describe('合并成界面数据', () => { + it('运行中的条目 running=true', () => { + const items = buildProgressItems([snap('t1')], [], 5) + expect(items).toHaveLength(1) + expect(items[0]!.finished).toBe(false) + }) + + it('终态从任务卡补齐,并带出报告路径与问题数', () => { + const items = buildProgressItems( + [snap('t1', { stage: 'reporting' })], + [{ id: 't1', stage: 'completed', summary: { reportPath: 'C:/r/x.md', findingCount: 7 } }], + 5, + ) + expect(items[0]!.finished).toBe(true) + expect(items[0]!.reportPath).toBe('C:/r/x.md') + expect(items[0]!.findingCount).toBe(7) + }) + + it('stage 判定:只有 completed/failed/cancelled 算结束', () => { + expect(isRunningStage('main-agent')).toBe(true) + expect(isRunningStage('reporting')).toBe(true) + expect(isRunningStage('completed')).toBe(false) + expect(isRunningStage('failed')).toBe(false) + expect(isRunningStage('cancelled')).toBe(false) + }) + + it('limit 生效', () => { + const many = Array.from({ length: 10 }, (_, i) => snap('t' + String(i))) + expect(buildProgressItems(many, [], 3)).toHaveLength(3) + }) +}) + +describe('读报告', () => { + /** 写一份最小可用的报告 JSON。 */ + function writeReport(dir: string, findings: unknown[] = []): string { + const p = join(dir, 'report.json') + writeFileSync(p, JSON.stringify({ status: 'completed', findings }), 'utf8') + return p + } + + it('按任务卡里的路径读出 findings', () => { + const dir = tempRoot() + const path = writeReport(dir, [{ + id: 'f-1', severity: 'high', category: 'security', path: 'a.js', lineStart: 3, + title: '标题', explanation: '解释', recommendation: '建议', confidence: 0.8, + }]) + const r = readReportFor('t1', [{ id: 't1', summary: { reportJsonPath: path, status: 'completed' } }]) + expect(r).not.toBeNull() + expect(r!.findings).toHaveLength(1) + expect(r!.findings[0]!.severity).toBe('high') + expect(r!.findings[0]!.lineStart).toBe(3) + }) + + it('任务卡不存在时返回 null', () => { + expect(readReportFor('nope', [])).toBeNull() + }) + + it('路径不是 .json 时拒绝(不当作任意文件读取接口)', () => { + const dir = tempRoot() + const p = join(dir, 'note.txt') + writeFileSync(p, 'x', 'utf8') + expect(readReportFor('t1', [{ id: 't1', summary: { reportJsonPath: p } }])).toBeNull() + }) + + it('文件不存在时返回 null', () => { + expect(readReportFor('t1', [{ id: 't1', summary: { reportJsonPath: join(tempRoot(), 'x.json') } }])).toBeNull() + }) + + it('损坏的 JSON 返回 null 而不是抛错', () => { + const dir = tempRoot() + const p = join(dir, 'bad.json') + writeFileSync(p, '{ 坏', 'utf8') + expect(readReportFor('t1', [{ id: 't1', summary: { reportJsonPath: p } }])).toBeNull() + }) +})