From c901431781ffa5c43507307625a31c4b670ac3a2 Mon Sep 17 00:00:00 2001 From: Nicholas023 Date: Thu, 5 Nov 2026 03:25:09 +0800 Subject: [PATCH 1/4] feat(gui): show review progress in a sidebar panel A scan could run for 14 minutes with nothing on screen but a frozen "reviewing": the kernel is spawned with stdio "ignore", so every progress line it writes was discarded. - kernel writes /progress/.json on each stage/round - host serves GET /api/code-review/progress and POST /api/code-review/cancel over webServer, the same route mechanism mac-tunnel uses here - client registers a sidebar.panellist entry plus the matching main panel, polling every 3s; running items get a Cancel button 11 new tests. Full suite: 502 passed. --- src/client/index.tsx | 29 +++++++ src/client/panel.tsx | 145 +++++++++++++++++++++++++++++++ src/client/types.ts | 13 ++- src/kernel/execute-task.ts | 47 ++++++++-- src/orchestrator/review.ts | 23 ++++- src/plugin/index.ts | 16 ++++ src/plugin/progress.ts | 104 ++++++++++++++++++++++ src/plugin/webapi.ts | 163 +++++++++++++++++++++++++++++++++++ test/plugin/progress.test.ts | 149 ++++++++++++++++++++++++++++++++ 9 files changed, 680 insertions(+), 9 deletions(-) create mode 100644 src/client/panel.tsx create mode 100644 src/plugin/progress.ts create mode 100644 src/plugin/webapi.ts create mode 100644 test/plugin/progress.test.ts 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..5d9318c --- /dev/null +++ b/src/client/panel.tsx @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 dsh-code-review contributors + +/** + * panel.tsx —— 左侧栏「代码审查」面板(主区页面)。 + * + * 它只做一件事:把宿主 /api/code-review/progress 返回的最近几条任务画出来, + * 并给运行中的任务一个「取消」按钮。 + * + * 为什么轮询而不是推送:宿主侧的进度本来就是文件轮询产生的, + * 3 秒一次的代价可以忽略;推送需要接 remote/typert,收益不成正比。 + */ + +import { useEffect, useState } from 'react' + +/** 与宿主 webapi.ts 的 ProgressItem 对应(只取用到的字段)。 */ +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 +} + +const hintStyle = { fontSize: '12px', opacity: 0.65, lineHeight: 1.5 } +const cardStyle = { + border: '1px solid rgba(128,128,128,0.25)', + borderRadius: '8px', + padding: '10px 12px', + marginBottom: '10px', +} +const rowStyle = { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' } + +/** 阶段 → 中文。 */ +const STAGE_TEXT: Record = { + queued: '排队中', + collecting: '采集代码', + collect: '采集代码', + select: '筛选文件', + sizing: '估算规模', + reviewing: '评审中', + 'main-agent': '主 agent', + 'child-agent': '子 agent', + aggregating: '汇总', + reporting: '写报告', + completed: '已完成', + failed: '失败', + cancelled: '已取消', +} + +/** 把一个进度项渲染成一张小卡。 */ +function Item({ item, onCancel }: { item: ProgressItem; onCancel: (id: string) => void }) { + const running = !item.finished + const repo = item.repoPath.replace(/\\/g, '/').split('/').filter(Boolean).pop() ?? item.repoPath + const stage = STAGE_TEXT[item.stage] ?? item.stage + const roundText = item.round !== null && item.maxRounds !== null ? ' 第 ' + String(item.round) + '/' + String(item.maxRounds) + ' 轮' : '' + const detail = item.detail !== null && item.detail !== '' ? ' · ' + item.detail : '' + + return ( +
+
+ {running ? '●' : '○'} + {stage}{roundText} + {repo} +
+
+ {item.command}{item.mode === null ? '' : ' / ' + item.mode}{detail} +
+ {item.finished && item.findingCount !== null && ( +
结果:{String(item.findingCount)} 个问题
+ )} + {item.reportPath !== null && ( +
{item.reportPath}
+ )} +
+ {item.taskId.slice(0, 8)} + {running && ( + + )} +
+
+ ) +} + +/** 面板主体。 */ +export function CodeReviewPanel() { + const [items, setItems] = useState([]) + const [error, setError] = useState('') + + 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) + setError('') + } else { + setError(json.error ?? '宿主未返回数据') + } + } catch (e) { + if (alive) setError(e instanceof Error ? e.message : String(e)) + } + } + void load() + const timer = setInterval(() => { void load() }, 3000) + 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 ( +
+

代码审查

+

+ 最近 5 条任务的进度。在会话里用 code_review 工具或 /review 命令发起。 +

+ {error !== '' &&

读取进度失败:{error}

} + {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..1d89869 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,16 @@ export interface ExecuteDeps { readonly runnerEntry: string /** 当前时间(ISO-8601)。 */ readonly now: () => string - /** 进度回调。 */ - readonly onProgress?: (detail: string) => void + /** + * 进度回调。 + * detail 给人看;round/maxRounds 让界面能画「第 5/8 轮」。 + */ + readonly onProgress?: (event: { + readonly stage: string + readonly detail?: string + readonly round?: number + readonly maxRounds?: number + }) => void } /** 执行结果。 */ @@ -147,7 +156,32 @@ 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 => { + 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.onProgress?.(event) + } + + emitProgress({ stage: 'reviewing' }) let out try { out = await runReview({ @@ -164,10 +198,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 +214,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 +306,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), 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..151ec75 --- /dev/null +++ b/src/plugin/webapi.ts @@ -0,0 +1,163 @@ +// 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 { 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 +} + +/** 判断是不是"还在跑"的阶段。 */ +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, + } + }) +} + +/** 读进度 + 任务卡,返回可直接 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))) + } + + return disposers +} diff --git a/test/plugin/progress.test.ts b/test/plugin/progress.test.ts new file mode 100644 index 0000000..fd14daf --- /dev/null +++ b/test/plugin/progress.test.ts @@ -0,0 +1,149 @@ +// 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 } 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) + }) +}) From 3af366abd681ab3d24bc261222ab7e5362c8a360 Mon Sep 17 00:00:00 2001 From: Nicholas023 Date: Thu, 5 Nov 2026 03:30:29 +0800 Subject: [PATCH 2/4] fix(progress): keep test runs out of the real progress dir, restyle the panel The panel shipped in the previous commit showed six phantom tasks named dcr-e2e-repo / scan-1 / e2e-task, all stuck on "writing report" with a cancel button. They were written by the test suite: executeTask fell back to resolveDshRoot() and every e2e test therefore wrote into the real ~/.dsh. executeTask now writes progress only when the caller passes dshRoot; the kernel passes it, tests do not. Verified empirically: 502 tests, progress dir still empty afterwards. The panel itself is redrawn: neutral rgba palette, one card per task with status / target / detail / action rows, live elapsed time, three items, and a dashed empty state instead of a blank page. --- src/client/panel.tsx | 196 +++++++++++++++++++++++++++++-------- src/kernel/execute-task.ts | 16 ++- src/kernel/main.ts | 1 + 3 files changed, 169 insertions(+), 44 deletions(-) diff --git a/src/client/panel.tsx b/src/client/panel.tsx index 5d9318c..0c44931 100644 --- a/src/client/panel.tsx +++ b/src/client/panel.tsx @@ -4,11 +4,14 @@ /** * panel.tsx —— 左侧栏「代码审查」面板(主区页面)。 * - * 它只做一件事:把宿主 /api/code-review/progress 返回的最近几条任务画出来, + * 只做一件事:把宿主 /api/code-review/progress 返回的最近几条任务画出来, * 并给运行中的任务一个「取消」按钮。 * - * 为什么轮询而不是推送:宿主侧的进度本来就是文件轮询产生的, - * 3 秒一次的代价可以忽略;推送需要接 remote/typert,收益不成正比。 + * 样式原则: + * - 只用 rgba 中性色,不引用宿主 CSS 变量(版本耦合),也不写死深/浅主题; + * 在 DSH 的深色界面上实测可读; + * - 一张卡只承载一条任务,层次是「状态 → 目标 → 细节 → 操作」四行; + * - 空态与错误态都给出可执行的下一步,不留白屏。 */ import { useEffect, useState } from 'react' @@ -30,60 +33,142 @@ interface ProgressItem { readonly findingCount: number | null } -const hintStyle = { fontSize: '12px', opacity: 0.65, lineHeight: 1.5 } -const cardStyle = { - border: '1px solid rgba(128,128,128,0.25)', - borderRadius: '8px', - padding: '10px 12px', - marginBottom: '10px', -} -const rowStyle = { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' } +/** 最多显示几条。 */ +const LIMIT = 3 +/** 轮询间隔(毫秒)。 */ +const POLL_MS = 3000 + +const C = { + card: 'rgba(255,255,255,0.035)', + cardHover: 'rgba(255,255,255,0.055)', + border: 'rgba(255,255,255,0.08)', + muted: 'rgba(255,255,255,0.55)', + faint: 'rgba(255,255,255,0.35)', + green: '#3fb950', + gray: '#6e7681', + red: '#f85149', + amber: '#d29922', +} as const /** 阶段 → 中文。 */ const STAGE_TEXT: Record = { queued: '排队中', - collecting: '采集代码', collect: '采集代码', + collecting: '采集代码', select: '筛选文件', sizing: '估算规模', reviewing: '评审中', - 'main-agent': '主 agent', - 'child-agent': '子 agent', - aggregating: '汇总', - reporting: '写报告', + 'main-agent': '评审中', + 'child-agent': '深挖子任务', + aggregating: '汇总结果', + reporting: '写报告中', completed: '已完成', failed: '失败', cancelled: '已取消', } -/** 把一个进度项渲染成一张小卡。 */ +/** 取路径最后两段,太长会撑破标题行。 */ +function shortRepo(repoPath: string): string { + const parts = repoPath.replace(/\\/g, '/').split('/').filter(Boolean) + return parts.slice(-2).join('/') +} + +/** 把毫秒差格式化成 "3 分 12 秒"。 */ +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) + ' 秒' + const min = Math.floor(sec / 60) + const rest = sec % 60 + return String(min) + ' 分 ' + String(rest) + ' 秒' +} + +/** 一张任务卡。 */ function Item({ item, onCancel }: { item: ProgressItem; onCancel: (id: string) => void }) { const running = !item.finished - const repo = item.repoPath.replace(/\\/g, '/').split('/').filter(Boolean).pop() ?? item.repoPath const stage = STAGE_TEXT[item.stage] ?? item.stage - const roundText = item.round !== null && item.maxRounds !== null ? ' 第 ' + String(item.round) + '/' + String(item.maxRounds) + ' 轮' : '' - const detail = item.detail !== null && item.detail !== '' ? ' · ' + item.detail : '' + const round = item.round !== null && item.maxRounds !== null + ? '第 ' + String(item.round) + '/' + String(item.maxRounds) + ' 轮' + : '' + const elapsed = formatElapsed(item.startedAt, running ? new Date().toISOString() : item.updatedAt) + const scope = item.command + (item.mode === null ? '' : ' / ' + item.mode) return ( -
-
- {running ? '●' : '○'} - {stage}{roundText} - {repo} +
+ {/* 第一行:状态 + 轮次 + 短 id */} +
+ + {stage} + {round !== '' && {round}} + + {item.taskId.slice(0, 8)} +
-
- {item.command}{item.mode === null ? '' : ' / ' + item.mode}{detail} + + {/* 第二行:仓库 + 模式 + 时长 */} +
+ {shortRepo(item.repoPath)} + · + {scope} + {elapsed !== '' && <>·{elapsed}}
- {item.finished && item.findingCount !== null && ( -
结果:{String(item.findingCount)} 个问题
- )} - {item.reportPath !== null && ( -
{item.reportPath}
+ + {/* 第三行:细节(有才显示) */} + {item.detail !== null && item.detail !== '' && ( +
{item.detail}
)} -
- {item.taskId.slice(0, 8)} + + {/* 第四行:结果 或 操作 */} +
+ {item.finished && item.findingCount !== null && ( + + 发现 {String(item.findingCount)} 个问题 + + )} + {item.finished && item.reportPath !== null && ( + + {item.reportPath.split(/[\\/]/).pop()} + + )} {running && ( - )} @@ -96,6 +181,7 @@ function Item({ item, onCancel }: { item: ProgressItem; onCancel: (id: string) = export function CodeReviewPanel() { const [items, setItems] = useState([]) const [error, setError] = useState('') + const [loaded, setLoaded] = useState(false) useEffect(() => { let alive = true @@ -105,17 +191,19 @@ export function CodeReviewPanel() { 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) + 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() }, 3000) + const timer = setInterval(() => { void load() }, POLL_MS) return () => { alive = false; clearInterval(timer) } }, []) @@ -132,13 +220,35 @@ export function CodeReviewPanel() { } return ( -
-

代码审查

-

- 最近 5 条任务的进度。在会话里用 code_review 工具或 /review 命令发起。 +

+
+

代码审查

+ 最近 {LIMIT} 条 +
+

+ 在会话里用 code_review 工具 + 或 /review 命令发起评审。

- {error !== '' &&

读取进度失败:{error}

} - {items.length === 0 && error === '' &&

还没有评审任务。

} + + {error !== '' && ( +
读取进度失败:{error}
+ )} + + {loaded && items.length === 0 && error === '' && ( +
+ 还没有评审任务 +
+ )} + {items.map((item) => void cancel(id)} />)}
) diff --git a/src/kernel/execute-task.ts b/src/kernel/execute-task.ts index 1d89869..ba12e52 100644 --- a/src/kernel/execute-task.ts +++ b/src/kernel/execute-task.ts @@ -37,6 +37,15 @@ export interface ExecuteDeps { readonly runnerEntry: string /** 当前时间(ISO-8601)。 */ readonly now: () => string + /** + * 数据根目录。 + * + * 传了才写进度文件;不传就完全不写。 + * 为什么这样设计:进度是"给人看的附加物",而单测会直接调 executeTask。 + * 一旦默认落到 resolveDshRoot(),测试就会往用户真实的 ~/.dsh 里写假任务 + * (实机踩过:面板里冒出 dcr-e2e-repo / scan-1 这类永远停在"写报告"的条目)。 + */ + readonly dshRoot?: string /** * 进度回调。 * detail 给人看;round/maxRounds 让界面能画「第 5/8 轮」。 @@ -166,6 +175,11 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis round?: number maxRounds?: number }): void => { + if (deps.dshRoot === undefined) { + // 没给根目录 = 不写进度(测试路径) + deps.onProgress?.(event) + return + } writeProgress({ taskId: record.id, repoPath: record.scope.repoPath, @@ -177,7 +191,7 @@ export async function executeTask(record: TaskRecord, deps: ExecuteDeps): Promis maxRounds: event.maxRounds ?? null, startedAt: progressStartedAt, updatedAt: deps.now(), - }) + }, deps.dshRoot) deps.onProgress?.(event) } 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, From 59dad4a7291328aa77896afcd30226a0340b8c90 Mon Sep 17 00:00:00 2001 From: Nicholas023 Date: Thu, 5 Nov 2026 03:30:58 +0800 Subject: [PATCH 3/4] fix(kernel): write a terminal progress row instead of stopping at "reporting" Without it a finished task kept its last progress file at stage=reporting, so the panel can only tell it is done by looking the task card up. If the card is gone (as with the six phantom test rows) the item looks like it is still running and keeps offering a cancel button. --- src/kernel/execute-task.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/kernel/execute-task.ts b/src/kernel/execute-task.ts index ba12e52..772a697 100644 --- a/src/kernel/execute-task.ts +++ b/src/kernel/execute-task.ts @@ -332,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: { From 70a2a7a12a88175194f5b36ca86e968fb759dcb1 Mon Sep 17 00:00:00 2001 From: Nicholas023 Date: Thu, 5 Nov 2026 03:46:54 +0800 Subject: [PATCH 4/4] feat(gui): expandable results, copyable report path, tri-state colours Feedback from the first real look: - an absolute report path is unreadable by eye, so it needs a copy button; - the result should be readable in place instead of opening a file; - green/yellow/red for done/running/failed rather than one grey dot. GET /api/code-review/report?taskId= serves the findings of a finished task, guarded to an absolute .json path recorded on its own task card, so it never becomes a general file reader. The panel expands inline, and every font size is now em-relative so it follows the host base size instead of fighting it. --- src/client/panel.tsx | 295 ++++++++++++++++++++--------------- src/plugin/webapi.ts | 104 ++++++++++++ test/plugin/progress.test.ts | 46 +++++- 3 files changed, 319 insertions(+), 126 deletions(-) diff --git a/src/client/panel.tsx b/src/client/panel.tsx index 0c44931..a270972 100644 --- a/src/client/panel.tsx +++ b/src/client/panel.tsx @@ -2,21 +2,19 @@ // Copyright 2026 dsh-code-review contributors /** - * panel.tsx —— 左侧栏「代码审查」面板(主区页面)。 + * panel.tsx —— 左侧栏「代码审查」面板。 * - * 只做一件事:把宿主 /api/code-review/progress 返回的最近几条任务画出来, - * 并给运行中的任务一个「取消」按钮。 + * 三条设计约束(来自使用反馈): + * 1. 绝对路径必须**可复制**——人眼记不住 `C:\\Users\\...\\2026-...md`; + * 2. 评审结果要**在这里直接看**,不必去翻文件; + * 3. 状态三色:绿=已完成、黄=进行中、红=失败。 * - * 样式原则: - * - 只用 rgba 中性色,不引用宿主 CSS 变量(版本耦合),也不写死深/浅主题; - * 在 DSH 的深色界面上实测可读; - * - 一张卡只承载一条任务,层次是「状态 → 目标 → 细节 → 操作」四行; - * - 空态与错误态都给出可执行的下一步,不留白屏。 + * 字体不写死 px:DSH 的字号由宿主决定,写死会和界面不一致。 + * 这里只用 em 相对大小与字重/颜色做层次,跟随宿主基准。 */ import { useEffect, useState } from 'react' -/** 与宿主 webapi.ts 的 ProgressItem 对应(只取用到的字段)。 */ interface ProgressItem { readonly taskId: string readonly repoPath: string @@ -31,143 +29,211 @@ interface ProgressItem { 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)', - cardHover: 'rgba(255,255,255,0.055)', border: 'rgba(255,255,255,0.08)', muted: 'rgba(255,255,255,0.55)', faint: 'rgba(255,255,255,0.35)', green: '#3fb950', - gray: '#6e7681', + yellow: '#d29922', red: '#f85149', - amber: '#d29922', } as const /** 阶段 → 中文。 */ const STAGE_TEXT: Record = { - queued: '排队中', - collect: '采集代码', - collecting: '采集代码', - select: '筛选文件', - sizing: '估算规模', - reviewing: '评审中', - 'main-agent': '评审中', - 'child-agent': '深挖子任务', - aggregating: '汇总结果', - reporting: '写报告中', - completed: '已完成', - failed: '失败', - cancelled: '已取消', + 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('/') } -/** 把毫秒差格式化成 "3 分 12 秒"。 */ 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) + ' 秒' - const min = Math.floor(sec / 60) - const rest = sec % 60 - return String(min) + ' 分 ' + String(rest) + ' 秒' + 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 running = !item.finished + 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, running ? new Date().toISOString() : item.updatedAt) + 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 ( -
- {/* 第一行:状态 + 轮次 + 短 id */} -
- - {stage} - {round !== '' && {round}} - +
+
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} + ·{scope} {elapsed !== '' && <>·{elapsed}}
- {/* 第三行:细节(有才显示) */} {item.detail !== null && item.detail !== '' && ( -
{item.detail}
+
{item.detail}
)} - {/* 第四行:结果 或 操作 */} -
+ {open && item.finished && } + +
{item.finished && item.findingCount !== null && ( - - 发现 {String(item.findingCount)} 个问题 - + 发现 {String(item.findingCount)} 个问题 )} - {item.finished && item.reportPath !== null && ( - - {item.reportPath.split(/[\\/]/).pop()} - + {item.reportPath !== null && ( + <> + + {reportName} + + + )} - {running && ( + {!item.finished && ( @@ -190,12 +256,8 @@ export function CodeReviewPanel() { 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 ?? '宿主未返回数据') - } + 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 { @@ -209,42 +271,25 @@ export function CodeReviewPanel() { 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 { - // 取消失败不弹窗:下一轮轮询会把真实状态刷回来 - } + await fetch('/api/code-review/cancel', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ taskId }) }) + } catch { /* 下一轮轮询会刷新真实状态 */ } } return ( -
+
-

代码审查

- 最近 {LIMIT} 条 +

代码审查

+ 最近 {LIMIT} 条
-

- 在会话里用 code_review 工具 - 或 /review 命令发起评审。 +

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

- {error !== '' && ( -
读取进度失败:{error}
- )} + {error !== '' &&
读取进度失败:{error}
} {loaded && items.length === 0 && error === '' && ( -
+
还没有评审任务
)} diff --git a/src/plugin/webapi.ts b/src/plugin/webapi.ts index 151ec75..17b0aaa 100644 --- a/src/plugin/webapi.ts +++ b/src/plugin/webapi.ts @@ -17,6 +17,7 @@ * 也不提供"打开文件/执行命令"这类能力。 */ +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' @@ -40,6 +41,73 @@ export interface ProgressItem { 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 + } } /** 判断是不是"还在跑"的阶段。 */ @@ -76,6 +144,7 @@ export function buildProgressItems( 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, } }) } @@ -159,5 +228,40 @@ export function registerWebApi( 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 index fd14daf..168d617 100644 --- a/test/plugin/progress.test.ts +++ b/test/plugin/progress.test.ts @@ -22,7 +22,7 @@ import { writeProgress, type ProgressSnapshot, } from '../../src/plugin/progress.js' -import { buildProgressItems, isRunningStage } from '../../src/plugin/webapi.js' +import { buildProgressItems, isRunningStage, readReportFor } from '../../src/plugin/webapi.js' const roots: string[] = [] function tempRoot(): string { @@ -147,3 +147,47 @@ describe('合并成界面数据', () => { 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() + }) +})