From ebd76859a165f5f43d40e3c9d141fc08764f2cca Mon Sep 17 00:00:00 2001 From: mutallip Date: Mon, 9 Nov 2026 01:45:10 +0800 Subject: [PATCH] =?UTF-8?q?fix(supervisor):=20=E9=81=BF=E5=85=8D=E6=8B=92?= =?UTF-8?q?=E7=BB=9D=E8=AF=8A=E6=96=AD=E5=9C=A8=E6=8A=98=E5=8F=A0=E5=8D=A1?= =?UTF-8?q?=E7=89=87=E5=A4=96=E9=87=8D=E5=A4=8D=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/pi-tool-supervisor/README.md | 2 +- packages/pi-tool-supervisor/README.zh-CN.md | 2 +- packages/pi-tool-supervisor/src/index.ts | 16 +-- .../src/tool-display-bridge.ts | 4 +- .../tests/pi-tool-supervisor.test.ts | 102 ++++++++++++++++++ 5 files changed, 115 insertions(+), 11 deletions(-) diff --git a/packages/pi-tool-supervisor/README.md b/packages/pi-tool-supervisor/README.md index abbe4227..30a96559 100644 --- a/packages/pi-tool-supervisor/README.md +++ b/packages/pi-tool-supervisor/README.md @@ -317,7 +317,7 @@ A condition returning `false` skips the reviewer without loading its rules or ca - A before reviewer rejection blocks the native tool call and sends the complete reason to the Agent; model failures/skips remain fail-open and stay only in the audit details, without appending an error to the tool result. Condition module load or execution failures are treated as a failed gate and block the before call. - An after rejection is diagnostic only and sends the diagnostic to the Agent without rolling back a completed tool call; an after model failure stays only in the audit details and does not append an error diagnostic. A failed tool skips after review and preserves the original error. -- Review rejections and configuration warnings use Pi's `ctx.ui.notify`; reviewer failures remain in the audit card and are not injected into the Agent's context. The extension does not call `console.warn` or `console.error` directly. +- After rejections appear in the audit card without a duplicate notification when the tool-display middleware is active in TUI mode; expand the card with Ctrl+O for details. Without an active display pipeline or outside TUI mode, the rejection is also notified. Before rejections and configuration warnings retain their notifications; reviewer failures remain in the audit card and are not injected into the Agent's context. The extension does not call `console.warn` or `console.error` directly. - If the parent Agent request is interrupted, every in-flight reviewer model request is cancelled together; reviewers not yet started are skipped, and parent cancellation is reported as skipped rather than as a provider failure. - A failed tool call or an unchanged file is skipped. - The extension does not roll back edits, block the operating system, or replace Pi's permission and sandbox controls. diff --git a/packages/pi-tool-supervisor/README.zh-CN.md b/packages/pi-tool-supervisor/README.zh-CN.md index 46a988bb..3f8c2627 100644 --- a/packages/pi-tool-supervisor/README.zh-CN.md +++ b/packages/pi-tool-supervisor/README.zh-CN.md @@ -319,7 +319,7 @@ condition 返回 `false` 时跳过该 reviewer,不读取其规则文件,也 - before reviewer 明确拒绝会阻断 Pi 原生工具调用,并把完整 reason 展示给 Agent;模型失败/跳过会放行,但失败信息只保留在审计详情中,不追加到 tool result。condition 模块加载或执行失败会阻断 before 调用。 - after 拒绝只提供诊断并展示给 Agent,不回滚已完成的工具调用;after 模型失败只保留在审计详情中,不追加错误诊断;工具失败时跳过 after 审查并保留原始错误。 -- 审查拒绝和配置警告通过 Pi 的 `ctx.ui.notify` 展示;审查失败保留在审计卡片中,不向 Agent 注入错误文本;扩展不直接调用 `console.warn` 或 `console.error`。 +- TUI 模式下对应工具的展示中间件活跃时,after 拒绝只显示在审计卡片中,不重复发送通知;按 Ctrl+O 展开查看详情。展示管线未活跃或不在 TUI 模式时仍发送拒绝通知。before 拒绝和配置警告保留原有通知;审查失败保留在审计卡片中,不向 Agent 注入错误文本。扩展不直接调用 `console.warn` 或 `console.error`。 - 如果用户打断上级 Agent 请求,所有尚未完成的 reviewer 模型请求会一起取消;尚未发起的 reviewer 会跳过;上级中断记为 skipped,而不是模型调用失败。 - 工具调用失败或文件内容没有变化时跳过审查。 - 扩展不会回滚编辑、阻断操作系统,也不替代 Pi 的权限与沙箱控制。 diff --git a/packages/pi-tool-supervisor/src/index.ts b/packages/pi-tool-supervisor/src/index.ts index d43d316a..24b65b89 100644 --- a/packages/pi-tool-supervisor/src/index.ts +++ b/packages/pi-tool-supervisor/src/index.ts @@ -227,6 +227,12 @@ function notify(ctx: ExtensionContext | ExtensionCommandContext, message: string notifyWithSource({ ctx: { mode: ctx.mode, ui: ctx.ui }, source: NOTICE_SOURCE, level, message }); } +function notifyAfterRejection(context: FileReviewExecutionContext, diagnostic: string | undefined): void { + if (!diagnostic) return; + if (context.ctx.mode === "tui" && isSupervisorToolDisplayMiddlewareActive(context.toolName)) return; + notify(context.ctx, diagnostic, "error"); +} + /** Detects tool execution failure without inspecting arbitrary detail fields. */ function isFailedToolResult(result: ToolResult): boolean { return result.isError === true || getRecord(result).isError === true; @@ -667,7 +673,7 @@ async function reviewToolResult(options: { warnings: [...configWarnings, ...(beforeAudit?.warnings ?? []), i18n.t("unchangedFileSkipped")], }; const diagnostic = createReviewRejectionDiagnostic(audit); - if (diagnostic) notify(context.ctx, diagnostic, "error"); + notifyAfterRejection(context, diagnostic); return { ...result, details: { ...(result.details ?? {}), fileEditReview: audit }, @@ -710,7 +716,7 @@ async function reviewToolResult(options: { warnings: [...configWarnings, ...(beforeAudit?.warnings ?? [])], }; const diagnostic = createReviewRejectionDiagnostic(audit); - if (diagnostic) notify(context.ctx, diagnostic, "error"); + notifyAfterRejection(context, diagnostic); return { ...result, details: { ...(result.details ?? {}), fileEditReview: audit }, @@ -753,9 +759,7 @@ async function reviewToolResult(options: { warnings: auditWarnings, }; const diagnostic = createReviewRejectionDiagnostic(audit); - if (diagnostic) { - notify(context.ctx, diagnostic, "error"); - } + notifyAfterRejection(context, diagnostic); return { ...result, details: { ...(result.details ?? {}), fileEditReview: audit }, @@ -946,7 +950,7 @@ async function processGenericReviewResult(context: FileReviewExecutionContext, p ); const audit: FileEditReviewAudit = { status: getOverallReviewStatus(reviewersWithBefore), toolName: context.toolName, trigger: AFTER_TRIGGER, reviewers: reviewersWithBefore, durationMs: (pending.beforeAudit?.durationMs ?? 0) + afterDurationMs, warnings }; const diagnostic = createReviewRejectionDiagnostic({ ...audit, filePath: context.toolName }); - if (diagnostic) notify(context.ctx, diagnostic, "error"); + notifyAfterRejection(context, diagnostic); return { ...result, details: { ...(result.details ?? {}), fileEditReview: audit }, content: diagnostic ? [...result.content, { type: "text", text: diagnostic }] : result.content }; } diff --git a/packages/pi-tool-supervisor/src/tool-display-bridge.ts b/packages/pi-tool-supervisor/src/tool-display-bridge.ts index b8924bda..5a50e831 100644 --- a/packages/pi-tool-supervisor/src/tool-display-bridge.ts +++ b/packages/pi-tool-supervisor/src/tool-display-bridge.ts @@ -37,9 +37,7 @@ const supervisorMiddleware: ResultMiddleware = (context, next) => { if (!rendered) return next(); const panel = createSupervisorAuditComponent(rendered, context.theme); - // The full diagnostic remains in result.content for the model, while the - // TUI shows the audit panel and the notify toast instead of printing it as - // ordinary tool output in the editor area. + // 完整诊断保留在 result.content 给模型;TUI 用审计卡片替代原始诊断输出。 return isDiagnosticAudit(audit) ? panel : appendResultRenderPanel(next(), panel); }; diff --git a/packages/pi-tool-supervisor/tests/pi-tool-supervisor.test.ts b/packages/pi-tool-supervisor/tests/pi-tool-supervisor.test.ts index f6c95b50..f7e0dc68 100644 --- a/packages/pi-tool-supervisor/tests/pi-tool-supervisor.test.ts +++ b/packages/pi-tool-supervisor/tests/pi-tool-supervisor.test.ts @@ -538,6 +538,108 @@ test("pi-tool-supervisor 通过通用 tool-display result middleware 追加审 } }); +test("after 拒绝仅在 TUI 活跃卡片中展示,其他模式保留通知和完整诊断", async () => { + const { default: piSupervisorExtension } = await import("../src/index.ts"); + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + const agentDir = await mkdtemp(join(tmpdir(), "pi-supervisor-rejection-display-")); + const handlers = new Map any>(); + const entries: Array<{ type: string; data: any }> = []; + const notifications: string[] = []; + const apiKey = Symbol.for("pi-tool-display.api.v1"); + const faux = registerFauxProvider({ provider: "rejection-display", models: [{ id: "model" }] }); + let registration: any; + let activeTool = "write"; + process.env.PI_CODING_AGENT_DIR = agentDir; + (globalThis as any)[apiKey] = { + registerResultRenderMiddleware: (value: any) => { registration = value; return value.id; }, + unregisterResultRenderMiddleware: () => true, + hasResultRenderMiddleware: (id: string) => id === registration?.id, + isResultRenderPipelineActive: (name: string) => name === activeTool, + }; + try { + const rulesFile = join(agentDir, "rules.md"); + await writeFile(rulesFile, "# rules\n"); + const configDirectory = join(agentDir, "extensions", "pi-tool-supervisor"); + await mkdir(configDirectory, { recursive: true }); + const configPath = join(configDirectory, "config.json"); + const configure = (trigger: string) => writeFile(configPath, JSON.stringify({ + enabled: true, + reviewers: [{ name: "reviewer", model: "rejection-display/model", rulesFile, tools: ["*"], trigger }], + })); + const reject = () => faux.setResponses([fauxAssistantMessage(JSON.stringify({ + passed: false, summary: "审查摘要", findings: [{ ruleGroup: "style", line: 1, message: "具体问题" }], + }))]); + const pi = { + getAllTools: () => [], + registerCommand: () => undefined, + registerEntryRenderer: () => undefined, + appendEntry: (type: string, data: any) => entries.push({ type, data }), + on: (event: string, handler: (...args: any[]) => any) => handlers.set(event, handler), + } as any; + piSupervisorExtension(pi); + const context = { + cwd: agentDir, + mode: "tui", + ui: { notify: (message: string) => notifications.push(message) }, + sessionManager: { getSessionId: () => "session-test" }, + modelRegistry: { + find: () => faux.getModel(), + getApiKeyAndHeaders: async () => ({ ok: true, apiKey: "test", headers: {}, env: {} }), + }, + }; + const input = { path: "example.ts", content: "const value = 2;\n" }; + const theme = { fg: (_color: string, text: string) => text, bold: (text: string) => text }; + await configure("after"); + for (const scenario of [ + { mode: "tui", tool: "write", active: "write", notices: 0 }, + { mode: "tui", tool: "write", active: "edit", notices: 1 }, + { mode: "rpc", tool: "write", active: "write", notices: 1 }, + { mode: "tui", tool: "custom", active: "custom", notices: 0 }, + { mode: "tui", tool: "custom", active: "write", notices: 1 }, + ]) { + entries.length = 0; + notifications.length = 0; + context.mode = scenario.mode; + activeTool = scenario.active; + reject(); + await writeFile(join(agentDir, "example.ts"), "const value = 1;\n"); + await handlers.get("tool_call")?.({ toolName: scenario.tool, toolCallId: "write-1", input }, context); + await writeFile(join(agentDir, "example.ts"), input.content); + const result = await handlers.get("tool_result")?.({ toolName: scenario.tool, toolCallId: "write-1", input, content: [{ type: "text", text: "written" }], details: {}, isError: false }, context); + assert.equal(result.details.fileEditReview.status, "rejected"); + assert.match(result.content[1].text, /审查摘要/); + assert.match(result.content[1].text, /\[style\] 第 1 行:具体问题/); + assert.equal(await readFile(join(agentDir, "example.ts"), "utf8"), input.content); + if (scenario.mode === "tui" && scenario.active === scenario.tool) { + const render = (expanded: boolean) => registration.middleware({ toolName: scenario.tool, result, options: { expanded }, theme }, () => new Text("raw", 0, 0)).render(160).join("\n"); + assert.match(render(false), /Supervisor.*未通过/); + assert.doesNotMatch(render(false), /具体问题|raw/); + assert.match(render(true), /具体问题/); + } + const notices = entries.filter((entry) => entry.type === "pi-extensions-notice").map((entry) => String(entry.data.message)).concat(notifications); + assert.equal(notices.length, scenario.notices, `${scenario.mode} tool=${scenario.tool} active=${scenario.active}`); + if (scenario.notices) assert.match(notices[0], /具体问题/); + } + entries.length = 0; + notifications.length = 0; + context.mode = "tui"; + activeTool = "write"; + await configure("before"); + reject(); + const blocked = await handlers.get("tool_call")?.({ toolName: "write", toolCallId: "before-1", input }, context); + assert.equal(blocked.block, true); + assert.match(blocked.reason, /具体问题/); + assert.equal(entries.filter((entry) => entry.type === "pi-extensions-notice").length, 1); + assert.equal(entries.filter((entry) => entry.type === SUPERVISOR_AUDIT_ENTRY_TYPE).length, 1); + } finally { + await handlers.get("session_shutdown")?.(); + faux.unregister(); + delete (globalThis as any)[apiKey]; + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + } +}); + test("Supervisor 展开态按 distill 风格展示文件、审查器详情和发现项", () => { const audit = buildSupervisorAuditLines("edit", { status: "rejected",