Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(assistant): surface specific CLI failures and export turn diagnostics (#468)
crispinhu272ddddc563437
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsxindex e7f73116..d1b3e5a9 100644--- a/chatbot/src/App.jsx+++ b/chatbot/src/App.jsx@@ -10,6 +10,7 @@ import { useChat } from "./useChat";import { AgentBrowserLinks } from "./agent-browser-links.js";import ActivityTrace, { ReplyTimeline } from "./ActivityTrace";import MessageInfo from "./MessageInfo";+import GenerationDiagnostics from "./GenerationDiagnostics";import { fullTime, messageSentAt, messageTimeLabel } from "./message-info.js";import {activityForReply,@@ -224,7 +225,7 @@ function ReplyHeading({ message, steps }) {</div>);}-function AssistantTurn({ message, steps, assets, projectId }) {+function AssistantTurn({ message, steps, assets, projectId, sessionId, local, readOnly, onCLIInstall }) {const reply = parseReply(message);const answer = hasTextSegments(steps)? finalReply(reply.message, steps)@@ -243,7 +244,9 @@ function AssistantTurn({ message, steps, assets, projectId }) {<div className="message-body"><RichContent message={answer} assets={assets} projectId={projectId} /></div>- {message.unfinished ? (+ {message.failure && message.generationId && !local ? (+ <GenerationDiagnostics sessionId={sessionId} generationId={message.generationId} failure={message.failure} onCLIInstall={onCLIInstall} readOnly={readOnly} />+ ) : message.unfinished ? (<p className="reply-stopped">本轮未完成 · {message.unfinished}</p>) : reply.stopped ? (<p className="reply-stopped">已停止,以上是停止前的内容。</p>@@ -251,7 +254,7 @@ function AssistantTurn({ message, steps, assets, projectId }) {</>);}-function LiveMessage({ live, generation, finished = false }) {+function LiveMessage({ live, generation, finished = false, local = false, readOnly = false }) {const steps = live.activity || [];const textual = hasTextSegments(steps);// A streamed paragraph followed by tool calls stays in the process above;@@ -288,6 +291,7 @@ function LiveMessage({ live, generation, finished = false }) {</div>)}{answer ? <RichContent message={answer} /> : null}+ {!finished && !local && !readOnly && generation?.id ? <GenerationDiagnostics sessionId={generation.sessionId} generationId={generation.id} compact /> : null}{finished ? (<p className="reply-stopped">{generation?.status === "failed" && generation?.error@@ -1497,6 +1501,10 @@ export default function App() {)}assets={artifactList}projectId={chat.session?.projectId}+ sessionId={chat.session?.id}+ local={chat.local}+ readOnly={chat.readOnly}+ onCLIInstall={chat.adoptCLIInstall}/>) : null}{message.role === "user" ? (@@ -1621,6 +1629,7 @@ export default function App() {label="复制回复"/><MessageInfo message={message} />+ {!chat.local && !chat.readOnly && message.generationId && !message.failure ? <GenerationDiagnostics sessionId={chat.session.id} generationId={message.generationId} compact /> : null}</div></>) : null}@@ -1630,7 +1639,7 @@ export default function App() {{/* The live reply belongs right under its question. Alerts staylast, so a finished reply does not jump above them. */}{chat.busy ? (- <LiveMessage live={chat.live} generation={chat.generation} />+ <LiveMessage live={chat.live} generation={chat.generation} local={chat.local} readOnly={chat.readOnly} />) : chat.generation &&!generationStored(messages, chat.generation) &&!["completed", "running"].includes(chat.generation.status) &&@@ -1640,8 +1649,12 @@ export default function App() {live={chat.live}generation={chat.generation}finished+ local={chat.local}+ readOnly={chat.readOnly}/>) : null}+ {!chat.local && !chat.busy && chat.generation?.failure && !messages.some((m) => m.generationId === chat.generation.id && m.failure) ? <GenerationDiagnostics sessionId={chat.session?.id} generationId={chat.generation.id} failure={chat.generation.failure} onCLIInstall={chat.adoptCLIInstall} readOnly={chat.readOnly} /> : null}+ {!chat.local && !chat.readOnly && !chat.busy && chat.generation?.id && chat.generation.status === "cancelled" && !chat.generation.failure && !messages.some((m) => m.generationId === chat.generation.id) ? <GenerationDiagnostics sessionId={chat.session?.id} generationId={chat.generation.id} compact /> : null}<RunAlertsruns={conversationRuns}user={chat.user}@@ -1673,7 +1686,7 @@ export default function App() {)}<div className="composer-region"><div className="composer-column">- {chat.error ? (+ {chat.error && !(chat.generation?.failure && chat.error === chat.generation.error) ? (<div role="alert" className="chat-error"><span>{chat.error}</span><CredentialAction text={chat.error} />diff --git a/chatbot/src/GenerationDiagnostics.jsx b/chatbot/src/GenerationDiagnostics.jsxnew file mode 100644index 00000000..4a97edeb--- /dev/null+++ b/chatbot/src/GenerationDiagnostics.jsx@@ -0,0 +1,399 @@+import React, { useEffect, useRef, useState } from "react";+import { api, sessionPath } from "./api.js";+import HarnessIcon from "./HarnessIcon";+import { CredentialAction } from "./ui";+import { CLIInstallAction } from "./cli-install.jsx";+import "./generation-diagnostics.css";++const phases = {+ setup: "启动与配置",+ execution: "CLI 执行",+ protocol: "结果解析",+ provider: "模型服务",+ connection: "连接模型服务",+ server: "平台服务",+ orchestration: "对话处理",+};+const statuses = {+ running: "执行中",+ completed: "已完成",+ failed: "失败",+ cancelled: "已停止",+ interrupted: "已中断",+ unfinished: "未完成",+};+const processStates = {+ not_started: "未启动",+ running: "运行中",+ start_failed: "启动失败",+ exited: "已退出",+ unknown_after_interruption: "中断后未知",+};+const toolSources = {+ gateway: "平台网关",+ cli: "CLI 协议",+};+const time = (value) =>+ value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "—";++async function copyText(text) {+ if (navigator.clipboard?.writeText)+ return navigator.clipboard.writeText(text);+ const input = document.createElement("textarea");+ input.value = text;+ input.style.position = "fixed";+ input.style.opacity = "0";+ document.body.append(input);+ try {+ input.select();+ if (!document.execCommand("copy"))+ throw new Error("请手动选择诊断内容复制");+ } finally {+ input.remove();+ }+}++export default function GenerationDiagnostics({+ sessionId,+ generationId,+ failure,+ onCLIInstall,+ compact = false,+ readOnly = false,+}) {+ const [open, setOpen] = useState(false);+ const [report, setReport] = useState(null);+ const [loading, setLoading] = useState(false);+ const [notice, setNotice] = useState("");+ const [error, setError] = useState("");+ const identity = `${sessionId}/${generationId}`;+ const current = useRef(identity);+ current.current = identity;+ useEffect(() => {+ setOpen(false);+ setReport(null);+ setNotice("");+ setError("");+ setLoading(false);+ }, [identity]);+ // Read-only viewers (shared conversation links) cannot read the report, so+ // they only see the fixed failure summary without detail actions.+ if (!sessionId || !generationId || (readOnly && compact)) return null;+ const path = `${sessionPath(sessionId)}/generations/${encodeURIComponent(generationId)}/diagnostics`;++ async function load() {+ setLoading(true);+ setError("");+ setNotice("");+ try {+ const data = await api(path);+ if (current.current !== identity) return null;+ setReport(data);+ return data;+ } catch (e) {+ if (current.current === identity)+ setError(e.message || "读取诊断信息失败,请重试");+ return null;+ } finally {+ if (current.current === identity) setLoading(false);+ }+ }+ async function toggle() {+ setOpen(!open);+ if (!open) await load();+ }+ async function copy() {+ const data = await load();+ if (!data) return;+ try {+ await copyText(JSON.stringify(data, null, 2));+ if (current.current === identity) setNotice("已复制诊断信息");+ } catch {+ if (current.current === identity)+ setError("复制失败,请下载诊断文件或手动复制详情");+ }+ }+ const shown = failure || report?.failure;+ return (+ <section+ className={`generation-diagnostics${compact ? " compact" : " failure"}`}+ aria-label={failure ? "本轮失败诊断" : "本轮诊断信息"}+ >+ {!compact && shown ? (+ <>+ <div className="diagnostic-heading">+ <HarnessIcon name="warning" size={17} aria-hidden="true" />+ <strong>{shown.message}</strong>+ <code>{shown.code}</code>+ </div>+ {shown.suggestion ? (+ <p className="diagnostic-suggestion">{shown.suggestion}</p>+ ) : null}+ <CredentialAction text={shown.message} />+ <CLIInstallAction text={shown.message} onResult={onCLIInstall} />+ </>+ ) : null}+ {readOnly ? null : (+ <div className="diagnostic-actions">+ <button+ type="button"+ onClick={toggle}+ aria-expanded={open}+ disabled={loading}+ >+ <HarnessIcon+ name={open ? "chevron-down" : "chevron-right"}+ size={14}+ aria-hidden="true"+ />+ {compact ? "诊断信息" : "查看详情"}+ </button>+ {!compact || open ? (+ <>+ <button type="button" onClick={copy} disabled={loading}>+ <HarnessIcon name="copy" size={14} aria-hidden="true" />+ 复制诊断+ </button>+ <a href={`${path}?download=1`} download>+ <HarnessIcon name="download" size={14} aria-hidden="true" />+ 下载诊断+ </a>+ </>+ ) : null}+ {loading ? (+ <span role="status">读取中…</span>+ ) : notice ? (+ <span role="status">{notice}</span>+ ) : null}+ </div>+ )}+ {error ? (+ <p className="diagnostic-fetch-error" role="alert">+ {error}+ </p>+ ) : null}+ {open && report ? (+ <div className="diagnostic-details">+ {report.assessment ? (+ <div className="diagnostic-assessment">+ <strong>{report.assessment.summary}</strong>+ {report.assessment.evidence?.length ? (+ <ul className="diagnostic-list">+ {report.assessment.evidence.map((item, i) => (+ <li key={i}>{item}</li>+ ))}+ </ul>+ ) : null}+ {report.assessment.unknowns?.length ? (+ <p className="diagnostic-subnote">+ 边界说明:{report.assessment.unknowns.join(" ")}+ </p>+ ) : null}+ {report.assessment.nextSteps?.length ? (+ <p className="diagnostic-subnote">+ 排查建议:{report.assessment.nextSteps.join(" ")}+ </p>+ ) : null}+ </div>+ ) : null}+ <dl className="diagnostic-meta">+ <dt>诊断编号</dt>+ <dd>+ <code>{report.generationId}</code>+ </dd>+ <dt>状态</dt>+ <dd>{statuses[report.status] || report.status}</dd>+ <dt>开始时间</dt>+ <dd>{time(report.startedAt)}</dd>+ {report.termination ? (+ <>+ <dt>结束原因</dt>+ <dd>+ <code>{report.termination.code}</code> ·{" "}+ {report.termination.message}+ </dd>+ </>+ ) : null}+ {shown?.phase ? (+ <>+ <dt>失败阶段</dt>+ <dd>{phases[shown.phase] || shown.phase}</dd>+ </>+ ) : null}+ {report.environment ? (+ <>+ <dt>运行实例</dt>+ <dd>+ <code>{report.environment.instanceId}</code> ·{" "}+ {report.environment.platformVersion}+ {report.environment.revision+ ? ` (${report.environment.revision.slice(0, 8)})`+ : ""}{" "}+ · {report.environment.os}/{report.environment.arch}+ </dd>+ </>+ ) : null}+ </dl>+ {(report.attempts || []).map((attempt, index) => {+ const proc = attempt.process;+ const lastOut = proc?.lastStdoutAt || proc?.lastStderrAt;+ return (+ <div className="diagnostic-attempt" key={attempt.id}>+ <div className="diagnostic-attempt-heading">+ <strong>+ 调用 {attempt.id?.split("/").at(-1) || index + 1} ·{" "}+ {attempt.engine}+ {attempt.cliVersion ? ` v${attempt.cliVersion}` : ""}+ </strong>+ <span>{attempt.model}</span>+ <span>{statuses[attempt.status] || attempt.status}</span>+ {attempt.exitCode != null ? (+ <code>退出码 {attempt.exitCode}</code>+ ) : null}+ </div>+ <p className="diagnostic-attempt-meta">+ {attempt.resume ? "恢复会话" : "新会话"} ·{" "}+ {phases[attempt.phase] || attempt.phase} ·{" "}+ {time(attempt.startedAt)}+ {attempt.endpoint ? ` · ${attempt.endpoint}` : ""}+ {attempt.protocol ? ` (${attempt.protocol})` : ""}+ </p>+ {proc ? (+ <p className="diagnostic-attempt-meta">+ 进程:{processStates[proc.state] || proc.state}+ {proc.pid ? ` · PID ${proc.pid}` : ""}+ {proc.signal ? ` · 信号 ${proc.signal}` : ""}+ {` · 输出 ${proc.stdoutLines || 0}/${proc.stderrLines || 0} 行`}+ {lastOut ? ` · 最近输出 ${time(lastOut)}` : ""}+ </p>+ ) : null}+ {attempt.firstError && report.dropped?.protocolEvents > 0 ? (+ <div className="diagnostic-event">+ <div>+ <strong>首次异常</strong>+ <code>{attempt.firstError.kind}</code>+ {attempt.firstError.statusCode ? (+ <span>HTTP {attempt.firstError.statusCode}</span>+ ) : null}+ </div>+ {attempt.firstError.message ? (+ <pre>{attempt.firstError.message}</pre>+ ) : null}+ </div>+ ) : null}+ {attempt.error ? (+ <pre className="diagnostic-excerpt">{attempt.error}</pre>+ ) : null}+ {(attempt.events || []).map((event, i) => (+ <div className="diagnostic-event" key={i}>+ <div>+ <code>{event.kind}</code>+ {event.statusCode ? (+ <span>HTTP {event.statusCode}</span>+ ) : null}+ {event.code ? <code>{event.code}</code> : null}+ {event.retryable != null ? (+ <span>{event.retryable ? "可重试" : "不可重试"}</span>+ ) : null}+ </div>+ {event.message ? <pre>{event.message}</pre> : null}+ {event.requestId ? (+ <p>+ Request ID <code>{event.requestId}</code>+ </p>+ ) : null}+ {event.traceId ? (+ <p>+ Trace ID <code>{event.traceId}</code>+ </p>+ ) : null}+ </div>+ ))}+ {attempt.firstStderr?.length &&+ report.dropped?.stderrLines > 0 ? (+ <details className="diagnostic-stderr">+ <summary>+ CLI 起始输出 · 前 {attempt.firstStderr.length} 行+ </summary>+ <pre>{attempt.firstStderr.join("\n")}</pre>+ </details>+ ) : null}+ {attempt.stderr?.length ? (+ <details className="diagnostic-stderr">+ <summary>+ CLI 错误输出 · 最近 {attempt.stderr.length} 行+ </summary>+ <pre>{attempt.stderr.join("\n")}</pre>+ </details>+ ) : null}+ </div>+ );+ })}+ {report.tools?.length ? (+ <details+ className="diagnostic-stderr"+ open={report.tools.some((t) => t.status !== "completed")}+ >+ <summary>工具与网关调用 · {report.tools.length} 次</summary>+ <div className="diagnostic-tools">+ {report.tools.map((tool, i) => (+ <div className="diagnostic-event" key={`${tool.id}-${i}`}>+ <div>+ <code>{tool.name}</code>+ <span>{toolSources[tool.source] || tool.source}</span>+ <span>{statuses[tool.status] || tool.status}</span>+ {tool.exitCode != null ? (+ <code>退出码 {tool.exitCode}</code>+ ) : null}+ </div>+ {tool.error ? <pre>{tool.error}</pre> : null}+ {tool.requestId ? (+ <p>+ Request ID <code>{tool.requestId}</code>+ </p>+ ) : null}+ </div>+ ))}+ </div>+ </details>+ ) : null}+ {report.timeline?.length ? (+ <details className="diagnostic-stderr">+ <summary>执行时间线 · {report.timeline.length} 条记录</summary>+ <pre>+ {report.timeline+ .map(+ (e) =>+ `[${time(e.at)}] (${e.source || "cli"}) ${e.kind}${e.tool ? ` ${e.tool}` : ""}${e.code ? ` [${e.code}]` : ""}${e.message ? ` — ${e.message}` : ""}`,+ )+ .join("\n")}+ </pre>+ </details>+ ) : null}+ {report.error &&+ !report.attempts?.some((attempt) => attempt.error) ? (+ <pre className="diagnostic-excerpt">{report.error}</pre>+ ) : null}+ {!report.attempts?.length && !report.error ? (+ <p className="diagnostic-note">尚未记录 CLI 调用详情。</p>+ ) : null}+ <p className="diagnostic-note">+ 已脱敏,包含有限的执行现场与错误片段。Request / Trace ID 仅在 CLI+ 或上游实际返回时显示。+ {report.truncated ? "部分记录已按大小限制截断。" : ""}+ </p>+ {report.status === "running" ? (+ <button+ type="button"+ className="diagnostic-refresh"+ onClick={load}+ disabled={loading}+ >+ 刷新诊断+ </button>+ ) : null}+ </div>+ ) : null}+ </section>+ );+}diff --git a/chatbot/src/activity.js b/chatbot/src/activity.jsindex 8941e58e..65fd6d6f 100644--- a/chatbot/src/activity.js+++ b/chatbot/src/activity.js@@ -402,6 +402,8 @@ export function generationStored(messages, generation) {if (!Number.isFinite(start)) return false;return (messages || []).some((message) => {if (message.role !== "assistant") return false;+ if (message.generationId && generation?.id)+ return message.generationId === generation.id;const at = Date.parse(message.startedAt || "");return Number.isFinite(at) && Math.abs(at - start) < 5000;});@@ -413,6 +415,7 @@ export const savedActivity = (message) =>);export function activityForReply(message, generation, liveSteps = []) {if (message.activity?.length) return savedActivity(message);+ if (message.generationId && message.generationId !== generation?.id) return [];// The old implementation retained only the most recent generation. Recover// that visible stream only when its text AND start time match this exact reply.const start = Date.parse(message.startedAt),diff --git a/chatbot/src/cli-install.jsx b/chatbot/src/cli-install.jsxindex 6f8a1724..c937c788 100644--- a/chatbot/src/cli-install.jsx+++ b/chatbot/src/cli-install.jsx@@ -44,6 +44,7 @@ export function cliFailureSettles(text) {const value = String(text || "").trim();return (value === "AI 助手生成失败,请稍后重试" ||+ value === "AI 助手生成失败,具体原因见诊断信息" ||/([a-z0-9-]+)没有安装在当前服务器上/.test(value));}diff --git a/chatbot/src/generation-diagnostics.css b/chatbot/src/generation-diagnostics.cssnew file mode 100644index 00000000..6f3eea29--- /dev/null+++ b/chatbot/src/generation-diagnostics.css@@ -0,0 +1,215 @@+.generation-diagnostics {+ min-width: 0;+ font-size: 12px;+ color: var(--text);+}+.generation-diagnostics.failure {+ margin-top: 14px;+ border: 1px solid color-mix(in srgb, var(--error) 22%, var(--line));+ border-radius: 12px;+ padding: 15px 16px;+ background: color-mix(in srgb, var(--error) 3%, var(--surface));+}+.diagnostic-heading {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}+.diagnostic-heading > svg {+ color: var(--error);+ flex-shrink: 0;+}+.diagnostic-heading strong {+ font-size: 13px;+ font-weight: 600;+}+.diagnostic-heading > code {+ color: var(--muted);+ font-size: 10px;+ margin-left: auto;+}+.diagnostic-suggestion {+ color: var(--muted);+ margin: 7px 0 10px;+ line-height: 1.7;+}+.diagnostic-actions {+ display: flex;+ align-items: center;+ gap: 4px 12px;+ flex-wrap: wrap;+}+.diagnostic-actions button,+.diagnostic-actions a,+.diagnostic-refresh {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 5px 3px;+ border-radius: 5px;+ font-size: 12px;+ text-decoration: none;+ color: var(--text);+ line-height: 1.4;+}+.diagnostic-actions button:hover,+.diagnostic-actions a:hover,+.diagnostic-refresh:hover {+ background: var(--hover);+}+.diagnostic-actions > span {+ color: var(--muted);+ font-size: 11px;+}+.diagnostic-details {+ margin-top: 12px;+ border-top: 1px solid var(--line);+ padding-top: 12px;+}+.diagnostic-assessment {+ border: 1px solid var(--line);+ border-radius: 8px;+ padding: 10px 12px;+ background: var(--surface);+ margin-bottom: 12px;+}+.diagnostic-assessment > strong {+ display: block;+ font-size: 12px;+ font-weight: 600;+}+.diagnostic-list {+ margin: 6px 0 0;+ padding-left: 18px;+ line-height: 1.65;+ overflow-wrap: anywhere;+}+.diagnostic-subnote {+ margin: 6px 0 0;+ color: var(--muted);+ font-size: 11px;+ line-height: 1.65;+ overflow-wrap: anywhere;+}+.diagnostic-tools {+ margin-top: 6px;+}+.diagnostic-meta {+ display: grid;+ grid-template-columns: 70px minmax(0, 1fr);+ gap: 7px 14px;+ margin: 0 0 14px;+}+.diagnostic-meta dt {+ color: var(--muted);+}+.diagnostic-meta dd {+ margin: 0;+ overflow-wrap: anywhere;+}+.diagnostic-attempt {+ border: 1px solid var(--line);+ border-radius: 8px;+ padding: 11px 12px;+ background: var(--surface);+ margin-top: 9px;+}+.diagnostic-attempt-heading {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 6px 12px;+}+.diagnostic-attempt-heading strong {+ font-size: 12px;+ font-weight: 600;+}+.diagnostic-attempt-heading > span,+.diagnostic-attempt-meta {+ color: var(--muted);+ overflow-wrap: anywhere;+}+.diagnostic-attempt-heading > code {+ margin-left: auto;+}+.diagnostic-attempt-meta {+ font-size: 11px;+ margin: 6px 0;+}+.diagnostic-excerpt,+.diagnostic-stderr pre,+.diagnostic-event pre {+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ font-size: 11px;+ line-height: 1.7;+ max-height: 240px;+ overflow: auto;+ background: var(--subtle);+ border-radius: 6px;+ padding: 9px 11px;+ margin: 9px 0 0;+}+.diagnostic-event {+ border-top: 1px solid var(--line);+ margin-top: 10px;+ padding-top: 10px;+}+.diagnostic-event > div {+ display: flex;+ flex-wrap: wrap;+ gap: 8px 12px;+ color: var(--muted);+}+.diagnostic-event p {+ margin: 6px 0 0;+ overflow-wrap: anywhere;+ color: var(--muted);+}+.diagnostic-event p code {+ color: var(--text);+}+.diagnostic-stderr {+ margin-top: 10px;+}+.diagnostic-stderr summary {+ cursor: pointer;+ color: var(--muted);+}+.diagnostic-note {+ color: var(--muted);+ font-size: 11px;+ line-height: 1.7;+ margin: 10px 0 0;+}+.diagnostic-fetch-error {+ color: var(--error);+ margin: 7px 0;+}+.message-actions:has(.generation-diagnostics .diagnostic-details) {+ flex-wrap: wrap;+}+.message-actions .generation-diagnostics:has(.diagnostic-details) {+ flex-basis: 100%;+}+.message.live > .generation-diagnostics {+ margin-top: 8px;+ color: var(--muted);+}+@media (max-width: 640px) {+ .generation-diagnostics.failure {+ padding: 12px;+ }+ .diagnostic-heading > code {+ margin-left: 25px;+ width: 100%;+ }+ .diagnostic-attempt {+ padding: 10px;+ }+ .diagnostic-meta {+ grid-template-columns: 62px minmax(0, 1fr);+ gap: 8px;+ }+}diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 2339a811..27f16da1 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -1137,18 +1137,26 @@ export function useChat() {const adoptCLIInstall = useCallback((message) => {setError(message);setGeneration((current) =>- current?.error && cliFailureSettles(current.error)- ? { ...current, error: message }+ (current?.error && cliFailureSettles(current.error)) ||+ (current?.failure?.message && cliFailureSettles(current.failure.message))+ ? { ...current, error: message, failure: null }: current,);setSession((current) => {- if (!current?.messages?.some((item) => cliFailureSettles(item.unfinished)))+ if (+ !current?.messages?.some(+ (item) =>+ cliFailureSettles(item.unfinished) ||+ cliFailureSettles(item.failure?.message),+ )+ )return current;return {...current,messages: current.messages.map((item) =>- cliFailureSettles(item.unfinished)- ? { ...item, unfinished: message }+ cliFailureSettles(item.unfinished) ||+ cliFailureSettles(item.failure?.message)+ ? { ...item, unfinished: message, failure: null }: item,),};diff --git a/chatbot/tests/activity.test.mjs b/chatbot/tests/activity.test.mjsindex 059c17fd..af0708b9 100644--- a/chatbot/tests/activity.test.mjs+++ b/chatbot/tests/activity.test.mjs@@ -6,6 +6,7 @@ import {savedActivity,activityFace,activityForReply,+ generationStored,activityTarget,thoughtLine,hasTextSegments,@@ -312,3 +313,17 @@ test("tool rounds fold into one summary and only the trailing round stays active"已运行命令、读取文件、搜索代码等",);});++test("quick retries with matching timestamps keep generation identities separate", () => {+ const message = {+ role: "assistant", generationId: "failed-turn",+ startedAt: "2026-11-13T10:00:00Z", content: '{"message":"ok"}',+ };+ const generation = {+ id: "retry-turn", status: "completed",+ startedAt: message.startedAt, reply: { message: "ok" },+ };+ assert.equal(generationStored([message], generation), false);+ assert.deepEqual(activityForReply(message, generation, [{ kind: "tool", id: "new-tool" }]), []);+ assert.equal(generationStored([{ ...message, generationId: generation.id }], generation), true);+});diff --git a/chatbot/tests/generation-diagnostics.test.jsx b/chatbot/tests/generation-diagnostics.test.jsxnew file mode 100644index 00000000..c4db6ca4--- /dev/null+++ b/chatbot/tests/generation-diagnostics.test.jsx@@ -0,0 +1,231 @@+import React from "react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++const { read } = vi.hoisted(() => ({ read: vi.fn() }));+vi.mock("../src/api.js", async (original) => ({+ ...(await original()),+ api: read,+}));+import GenerationDiagnostics from "../src/GenerationDiagnostics.jsx";++const failure = {+ code: "RATE_LIMITED",+ phase: "provider",+ message: "模型服务请求过于频繁(429)",+ suggestion: "请稍后再试,或检查模型服务的限流配置。",+};+const report = {+ version: 1,+ generationId: "turn-one",+ sessionId: "session-one",+ status: "failed",+ startedAt: "2026-11-13T05:00:00Z",+ failure,+ attempts: [+ {+ id: "turn-one/1",+ engine: "codebuddy",+ model: "model-example",+ status: "failed",+ phase: "execution",+ exitCode: 7,+ events: [+ {+ kind: "error",+ message: "rate limit reached",+ statusCode: 429,+ requestId: "request-example",+ traceId: "trace-example",+ retryable: true,+ },+ ],+ stderr: ["Authorization: <redacted>"],+ },+ ],+};+beforeEach(() => {+ read.mockReset();+ read.mockResolvedValue(report);+});+afterEach(() => {+ vi.restoreAllMocks();+});++describe("generation diagnostics", () => {+ test("shows the failure and fetches details only on request", async () => {+ render(+ <GenerationDiagnostics+ sessionId="session-one"+ generationId="turn-one"+ failure={failure}+ />,+ );+ expect(screen.getByText(failure.message)).toBeInTheDocument();+ expect(read).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "查看详情" }));+ expect(await screen.findByText("request-example")).toBeInTheDocument();+ expect(screen.getByText("trace-example")).toBeInTheDocument();+ expect(screen.getByText("退出码 7")).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "下载诊断" })).toHaveAttribute(+ "href",+ "/api/assistant/sessions/session-one/generations/turn-one/diagnostics?download=1",+ );+ expect(screen.getByRole("button", { name: "查看详情" })).toHaveAttribute(+ "aria-expanded",+ "true",+ );+ });+ test("copies the report belonging to this failure even after a retry", async () => {+ const writeText = vi.fn(async () => {});+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText },+ });+ render(+ <GenerationDiagnostics+ sessionId="session-one"+ generationId="turn-one"+ failure={failure}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "复制诊断" }));+ expect(await screen.findByRole("status")).toHaveTextContent(+ "已复制诊断信息",+ );+ expect(read).toHaveBeenCalledWith(+ "/api/assistant/sessions/session-one/generations/turn-one/diagnostics",+ );+ expect(JSON.parse(writeText.mock.calls[0][0])).toEqual(report);+ });+ test("offers a quiet on-demand entry during execution and refreshes it", async () => {+ read.mockResolvedValue({ ...report, status: "running", failure: null });+ render(+ <GenerationDiagnostics+ sessionId="session-one"+ generationId="turn-one"+ compact+ />,+ );+ expect(+ screen.queryByText(/没有.*进展|已运行|90 秒/),+ ).not.toBeInTheDocument();+ expect(read).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "诊断信息" }));+ fireEvent.click(await screen.findByRole("button", { name: "刷新诊断" }));+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));+ });+ test("shows retrieval errors and ignores a late response from another turn", async () => {+ let resolve;+ read.mockReturnValueOnce(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const { rerender } = render(+ <GenerationDiagnostics+ sessionId="session-one"+ generationId="turn-one"+ failure={failure}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "查看详情" }));+ rerender(+ <GenerationDiagnostics+ sessionId="session-two"+ generationId="turn-two"+ failure={failure}+ />,+ );+ resolve(report);+ await waitFor(() =>+ expect(screen.queryByText("request-example")).not.toBeInTheDocument(),+ );+ read.mockRejectedValueOnce(new Error("该轮次没有可用的诊断记录"));+ fireEvent.click(screen.getByRole("button", { name: "查看详情" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "该轮次没有可用的诊断记录",+ );+ expect(screen.getByRole("link", { name: "下载诊断" })).toHaveAttribute(+ "href",+ expect.stringContaining("session-two/generations/turn-two"),+ );+ });+ test("renders v2 assessment, environment, tool failures and timeline", async () => {+ read.mockResolvedValueOnce({+ ...report,+ version: 2,+ environment: {+ platformVersion: "v0.9.0",+ revision: "43265cd12345",+ os: "linux",+ arch: "amd64",+ instanceId: "api-prod-1",+ },+ termination: {+ code: "CHECKPOINT_LOST",+ message: "超过 45 秒未收到运行实例心跳,生成已中断",+ },+ assessment: {+ outcome: "termination_recorded",+ summary: "超过 45 秒未收到运行实例心跳,生成已中断",+ evidence: [+ "工具 tapd__stories_list(gateway/1,来源:gateway)有开始记录,未收到结束记录",+ ],+ unknowns: ["只确认平台未继续保存执行状态"],+ nextSteps: ["按 environment.instanceId 查询服务端日志"],+ },+ tools: [+ {+ id: "gateway/1",+ source: "gateway",+ name: "tapd__stories_list",+ status: "unfinished",+ error: "upstream timeout",+ },+ ],+ timeline: [+ {+ at: "2026-11-13T05:00:01Z",+ source: "platform",+ kind: "generation.started",+ },+ ],+ });+ render(+ <GenerationDiagnostics+ sessionId="session-v2"+ generationId="turn-v2"+ failure={failure}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "查看详情" }));+ expect(await screen.findByText("api-prod-1")).toBeInTheDocument();+ expect(screen.getByText("CHECKPOINT_LOST")).toBeInTheDocument();+ expect(screen.getByText("tapd__stories_list")).toBeInTheDocument();+ expect(screen.getByText(/执行时间线 · 1 条记录/)).toBeInTheDocument();+ });+ test("read-only viewers see the failure without detail actions", () => {+ const { container, rerender } = render(+ <GenerationDiagnostics+ sessionId="session-one"+ generationId="turn-one"+ failure={failure}+ readOnly+ />,+ );+ expect(screen.getByText(failure.message)).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "查看详情" })).toBeNull();+ expect(screen.queryByRole("link", { name: "下载诊断" })).toBeNull();+ rerender(+ <GenerationDiagnostics+ sessionId="session-one"+ generationId="turn-two"+ compact+ readOnly+ />,+ );+ expect(container).toBeEmptyDOMElement();+ expect(read).not.toHaveBeenCalled();+ });+});diff --git a/docs/proposals/cli-execution-diagnostics.md b/docs/proposals/cli-execution-diagnostics.mdnew file mode 100644index 00000000..ece418eb--- /dev/null+++ b/docs/proposals/cli-execution-diagnostics.md@@ -0,0 +1,47 @@+# CLI 执行诊断与故障定位(v2)++日期:2026-11-13。基线:`43265cd`。++原问题是 CLI 卡住或报错后,多数错误被统一归并为“AI 助手生成失败”,stderr 与工具异常只留在服务端日志,且下一轮重试会覆盖按 session 保存的 generation 记录。++本方案分两步演进到 `version: 2` 离线自解释诊断档案:既在界面给出明确、安全的错误分类与建议,又让用户导出的单份 JSON 文件包含**环境版本、进程生命周期、平台 MCP 网关工具记录、终止原因、时间线与证据边界评估**,实现“拿到导出文件即可定界并定位问题”。按用户要求,运行中界面不增加“已运行多久 / 最近多久无进展”等静默提醒,不影响长耗时任务。++## 用户体验++- **具体错误卡片**:失败回复显示原因、稳定错误码、处理建议,并提供“查看详情 / 复制诊断 / 下载诊断”。即使 CLI 零输出失败,对话中仍保留该条失败卡片。+- **零输出停止可追溯**:运行中和成功回复提供按需打开的紧凑“诊断信息”;若因长时间零输出由用户点击“停止”,即使未写入空白聊天消息,页面当前轮次下方仍保留“诊断信息”入口供复制或下载快照。+- **结构化详情视图**:展开详情后可直接查看自动诊断结论(`assessment`)、证据与未知边界、结束原因(`termination`)、运行实例与版本(`environment`)、每次调用的 CLI 版本/端点/进程状态/信号/输出行数与最近输出时间、工具与网关异常(`tools`)以及可折叠的执行时间线(`timeline`)和起始/尾部 stderr。+- **重试不丢现场**:每轮诊断按 `generationId` 独立持久化,重试或继续对话后仍可随时导出历史失败轮次的诊断文件。++## 诊断文件结构(Version 2)++```text+GET /api/assistant/sessions/:id/generations/:generationId/diagnostics+GET /api/assistant/sessions/:id/generations/:generationId/diagnostics?download=1+```++单份导出的 JSON 包含以下核心维度:++1. **环境与实例(`environment` + 调用级配置)**+ - 平台侧:`platformVersion`、`revision`、`modified`、`goVersion`、`os`、`arch`、`instanceId`、`instanceStartedAt`。服务端关键诊断日志统一携带 `diagnostic=<generationId> instance=<instanceId>`,多副本部署可秒级关联后台日志。+ - 调用侧(`attempts[]`):`cliVersion`、`versionSource`(`managed_inventory` / `package_metadata` / `native_handshake` / `not_reported`)、`binarySource`(`explicit_override` / `managed_inventory` / `discovered`)、只保留 scheme 与 host 的 `endpoint`(不含路径、凭据和查询参数)、`protocol`、`effort`、`nativeSessionId`、`nativeTurnId`。+2. **CLI 进程现场(`attempts[].process`)**+ - 记录 `pid`、`state`(`not_started` / `running` / `start_failed` / `exited` / `unknown_after_interruption`)、`startedAt`、`finishedAt`、`signal`(捕获 SIGKILL/SIGTERM 等系统信号)、`userCpuMs`、`systemCpuMs`、`stdoutLines`、`stderrLines`、`firstStdoutAt`、`lastStdoutAt`、`firstStderrAt`、`lastStderrAt`。+ - 结合时间线的 `cli.initialized`、`model.turn_started`、`model.first_output_delta`、`protocol.result_received`,无需采集正文即可区分“卡在进程启动”、“卡在握手/MCP 列表”、“卡在等待模型首包”或“流式中途断流”。+3. **工具与平台 MCP 网关调用(`tools[]`)**+ - 同时覆盖 CLI 协议上报(`source: "cli"`)与平台会话 MCP 网关实收请求(`source: "gateway"`),自动关联当前 `attemptId`。+ - 记录 `mcp.gateway_initialized`、`mcp.tools_listed`(含工具数与耗时)及 `mcp.upstream_catalog_failed`(外部 TAPD/工蜂 MCP 拉取工具目录失败不再静默吞掉)。+ - 仅在工具失败时提取脱敏错误片段、`statusCode`、`requestId`、`traceId`;成功工具绝不保留输入参数与返回正文。未结束的工具在中断后标记为 `unfinished`,可直接定位卡死在哪个外部工具调用。+4. **抗冲刷首错保留(`firstError`、`firstStderr`、`dropped`)**+ - 保留前 8 行 `firstStderr` 与最近 20 行 `stderr`,防止后续重试冲掉初始报错。+ - 自动解析结构化 stderr 中的 `sampling_error`(如首轮重试时的上游 `401`/`429` 及 `request id`),过滤 Codex 流式顺序无害日志(如 `without active item`),并将泛化占位重连提示(`Reconnecting...`)升级为首个实质性错误事件存入 `firstError`。+ - 所有截断项按类别计入 `dropped`。+5. **终止归因与离线自解释评估(`termination`、`lastCheckpointAt`、`assessment`、`coverage`)**+ - 明确区分 `USER_CANCELLED`(用户主动停止;若停止前已捕获 `firstError` 会主动提示)、`USER_STEER`(中途转向)、`WORKSPACE_LEASE_LOST`(工作区续租失败)、`CHECKPOINT_FAILED`、`GENERATION_SUPERSEDED`、`SERVER_PANIC` 以及 `CHECKPOINT_LOST`(超过 45 秒未收到运行实例心跳,附带 `lastCheckpointAt`)。+ - `domain.AnalyzeAssistantDiagnostics` 纯确定性离线运行,明确分离**已观测证据(`evidence`)**、**受限于边界无法仅凭该文件判定的原因(`unknowns`)**与**下一步排查动作(`nextSteps`)**,绝不捏造根因或伪造分布式 `traceId`。++## 存储与隐私安全边界++- 新增手工迁移脚本 `migrations/029_assistant_diagnostics.sql`(遵循仓库规则,不在启动代码做 seed 或数据回填)。+- 权限校验与会话非正文附件一致:验证登录态与项目/会话访问范围,公开项目会话只读链接仅暴露固定文案摘要,不暴露详细诊断片段。+- 脱敏覆盖用户与平台注入的各类 API Key、Agent CLI Key、Git Token、Refresh Token、Authorization 头、常见密码/密钥键值、PEM 私钥、URL 查询参数/凭证段(含 `/mcp/` 会话令牌路径)、本机绝对路径及 ANSI 控制序列。不采集提示词、思考正文、工具参数、成功工具输出、环境变量或完整 stdout。diff --git a/internal/domain/assistant.go b/internal/domain/assistant.goindex 4bbaf7ba..d8611e32 100644--- a/internal/domain/assistant.go+++ b/internal/domain/assistant.go@@ -58,7 +58,9 @@ type AssistantMessage struct {Attachments []AssistantAttachment `json:"attachments,omitempty"`// Unfinished names why a reply stopped early (stopped, failed, timed out// or interrupted). The reply keeps its partial answer and activity.- Unfinished string `json:"unfinished,omitempty"`+ Unfinished string `json:"unfinished,omitempty"`+ GenerationID string `json:"generationId,omitempty"`+ Failure *AssistantFailure `json:"failure,omitempty"`}type AssistantAssetRef struct {diff --git a/internal/domain/assistant_diagnostic_analysis.go b/internal/domain/assistant_diagnostic_analysis.gonew file mode 100644index 00000000..67832e9e--- /dev/null+++ b/internal/domain/assistant_diagnostic_analysis.go@@ -0,0 +1,172 @@+package domain++import (+ "fmt"+ "strings"+)++// AnalyzeAssistantDiagnostics is deterministic and works on an exported file+// without database access. It separates terminal facts from unknown causes.+func AnalyzeAssistantDiagnostics(d *AssistantDiagnostics) {+ if d == nil || d.Version < 2 {+ return+ }+ a := &AssistantDiagnosticAssessment{Outcome: "undetermined", Summary: "现有证据不足以确认失败原因"}+ d.Assessment = a+ d.Coverage = []string{+ "采集平台生命周期、CLI 进程状态、原生错误元数据及工具调用状态;内容为脱敏后的有限片段。",+ "未采集提示词、思考正文、工具参数、成功工具输出、完整 stdout、环境变量或凭证。",+ "CLI 未暴露的内部网络等待、死锁或上游账号状态无法从本文件确认。",+ }+ requestIDs := map[string]bool{}+ traceIDs := map[string]bool{}+ toolFailures, pending := 0, 0+ firstFailedTool := ""+ for i := range d.Tools {+ t := &d.Tools[i]+ if t.Status == "failed" {+ toolFailures+++ if firstFailedTool == "" {+ firstFailedTool = fmt.Sprintf("%s(来源:%s)", t.Name, t.Source)+ }+ }+ if t.Status == "running" || t.Status == "unfinished" {+ if d.Status != "running" {+ t.Status = "unfinished"+ }+ pending+++ a.Evidence = append(a.Evidence, fmt.Sprintf("工具 %s(%s,来源:%s)有开始记录,未收到结束记录", t.Name, t.ID, t.Source))+ }+ if t.RequestID != "" {+ requestIDs[t.RequestID] = true+ }+ if t.TraceID != "" {+ traceIDs[t.TraceID] = true+ }+ }+ if toolFailures > 0 {+ a.Evidence = append(a.Evidence, fmt.Sprintf("记录到 %d 次工具失败(首个:%s);工具错误本身不直接等同于整轮生成失败", toolFailures, firstFailedTool))+ }+ hasEarlyError := false+ for i := range d.Attempts {+ attempt := &d.Attempts[i]+ if attempt.CLIVersion == "" {+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "CLI 未提供版本,安装元数据也未提供版本。")+ }+ if attempt.ExitCode != nil {+ a.Evidence = append(a.Evidence, fmt.Sprintf("调用 %s 的进程退出码为 %d,协议结果为 %s", attempt.ID, *attempt.ExitCode, attempt.Status))+ }+ if attempt.FirstError != nil {+ hasEarlyError = true+ desc := attempt.FirstError.Kind+ if attempt.FirstError.StatusCode > 0 {+ desc = fmt.Sprintf("%s (HTTP %d)", desc, attempt.FirstError.StatusCode)+ }+ if attempt.FirstError.RequestID != "" {+ requestIDs[attempt.FirstError.RequestID] = true+ }+ if attempt.FirstError.TraceID != "" {+ traceIDs[attempt.FirstError.TraceID] = true+ }+ a.Evidence = append(a.Evidence, fmt.Sprintf("调用 %s 首次捕获异常事件:%s", attempt.ID, desc))+ }+ if p := attempt.Process; p != nil {+ if p.State == "start_failed" {+ a.Evidence = append(a.Evidence, fmt.Sprintf("调用 %s 的 CLI 进程启动失败", attempt.ID))+ }+ if p.Signal != "" {+ a.Evidence = append(a.Evidence, "调用 "+attempt.ID+" 收到进程信号 "+p.Signal)+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "进程信号不能单独证明 OOM、管理员操作或宿主机故障。")+ }+ if (p.State == "running" || p.State == "unknown_after_interruption") && d.Status != "running" {+ p.State = "unknown_after_interruption"+ a.Evidence = append(a.Evidence, fmt.Sprintf("调用 %s 在平台记录结束前仍处于运行态,未收到进程退出事件", attempt.ID))+ }+ if (d.Status == "running" || d.Status == "cancelled" || d.Status == "interrupted") && p.State != "start_failed" && p.StdoutLines == 0 && p.StderrLines == 0 {+ a.Evidence = append(a.Evidence, fmt.Sprintf("调用 %s 的 CLI 进程已启动(PID %d),但尚未产生任何 stdout/stderr 输出", attempt.ID, p.PID))+ }+ }+ for _, e := range attempt.Events {+ if e.RequestID != "" {+ requestIDs[e.RequestID] = true+ }+ if e.TraceID != "" {+ traceIDs[e.TraceID] = true+ }+ }+ }+ if d.Termination != nil {+ switch d.Termination.Code {+ case "USER_CANCELLED":+ a.Outcome = "cancelled_by_user"+ if hasEarlyError {+ a.Evidence = append(a.Evidence, "用户停止前已捕获到 CLI 或上游错误(详见 firstError),可能是导致等待过久的原因")+ }+ case "USER_STEER":+ a.Outcome = "redirected_by_user"+ default:+ a.Outcome = "termination_recorded"+ }+ a.Summary = d.Termination.Message+ a.Evidence = append(a.Evidence, "平台记录的结束原因:"+d.Termination.Code)+ if d.Termination.Code == "CHECKPOINT_LOST" {+ if d.LastCheckpointAt != nil {+ a.Evidence = append(a.Evidence, "最后一次运行实例心跳时间:"+d.LastCheckpointAt.UTC().Format("2006-01-02T15:04:05Z"))+ }+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "只确认平台未继续保存执行状态;无法仅凭此记录区分进程崩溃、服务重启、OOM 或数据库写入中断。")+ a.NextSteps = appendUniqueDiagnostic(a.NextSteps, "按 environment.instanceId、generationId 和 lastCheckpointAt 查询平台与宿主机日志。")+ }+ } else {+ switch d.Status {+ case "completed":+ a.Outcome, a.Summary = "completed", "本轮已完成;CLI 警告和已恢复的工具错误仍保留供排查"+ case "running":+ a.Outcome, a.Summary = "pending", "本轮尚未结束,当前文件是执行现场快照"+ if pending == 0 {+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "未观察到正在执行的工具;无法仅凭没有输出区分模型推理等待、网络等待或 CLI 内部阻塞。")+ }+ case "failed":+ if d.Failure != nil {+ a.Summary = d.Failure.Message+ a.Evidence = append(a.Evidence, "失败阶段:"+d.Failure.Phase+";分类:"+d.Failure.Code)+ if d.Failure.Code != "GENERATION_FAILED" && d.Failure.Code != "CLI_EXIT_NONZERO" && d.Failure.Code != "MISSING_RESULT" {+ a.Outcome = "failure_observed"+ }+ switch d.Failure.Code {+ case "AUTHENTICATION_FAILED", "PERMISSION_DENIED", "RATE_LIMITED", "QUOTA_EXCEEDED", "UPSTREAM_UNAVAILABLE":+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "上游拒绝或服务异常已被观察到;账号配置、限流规则及服务内部原因需要上游记录确认。")+ case "NETWORK_ERROR":+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "连接失败的具体网络节点或代理原因未被 CLI 暴露。")+ case "CLI_EXIT_NONZERO", "MISSING_RESULT", "GENERATION_FAILED":+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "当前错误能确认执行失败,但不足以单独判定 CLI 内部根因。")+ }+ }+ case "interrupted", "cancelled":+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "未记录明确的终止发起方;不能认定为用户主动停止。")+ }+ }+ if len(requestIDs) > 0 {+ a.NextSteps = appendUniqueDiagnostic(a.NextSteps, "记录中包含真实 requestId,可据此关联上游模型服务或网关日志。")+ }+ if len(traceIDs) > 0 {+ a.NextSteps = appendUniqueDiagnostic(a.NextSteps, "记录中包含真实 traceId,可据此关联分布式链路日志。")+ }+ if d.Status != "completed" && d.Environment != nil && d.Environment.InstanceID != "" {+ a.NextSteps = appendUniqueDiagnostic(a.NextSteps, fmt.Sprintf("可在平台服务端日志检索 diagnostic=%s 与 instance=%s 查看完整后台记录。", d.GenerationID, d.Environment.InstanceID))+ }+ if d.Truncated {+ a.Unknowns = appendUniqueDiagnostic(a.Unknowns, "部分证据已按上限截断;首次错误、起始片段及最近记录已分别保留,截断计数见 dropped。")+ }+ if len(a.Unknowns) > 0 && d.Status != "completed" {+ a.NextSteps = appendUniqueDiagnostic(a.NextSteps, "优先检查 firstError、失败/未完成工具(tools)、termination 和 timeline;无法确认的部分以 unknowns 为准。")+ }+}++func appendUniqueDiagnostic(items []string, value string) []string {+ for _, item := range items {+ if strings.EqualFold(item, value) {+ return items+ }+ }+ return append(items, value)+}diff --git a/internal/domain/assistant_diagnostic_analysis_cases_test.go b/internal/domain/assistant_diagnostic_analysis_cases_test.gonew file mode 100644index 00000000..6517385f--- /dev/null+++ b/internal/domain/assistant_diagnostic_analysis_cases_test.go@@ -0,0 +1,189 @@+package domain++import (+ "strings"+ "testing"+ "time"+)++func diagnosticJoined(a *AssistantDiagnosticAssessment) string {+ return strings.Join(a.Evidence, "\n") + "\n" + strings.Join(a.Unknowns, "\n") + "\n" + strings.Join(a.NextSteps, "\n")+}++func TestAnalyzeAssistantDiagnosticsSkipsNilAndLegacyReports(t *testing.T) {+ AnalyzeAssistantDiagnostics(nil)+ legacy := AssistantDiagnostics{Version: 1, Status: "failed", Failure: &AssistantFailure{Code: "NETWORK_ERROR"}}+ AnalyzeAssistantDiagnostics(&legacy)+ if legacy.Assessment != nil || legacy.Coverage != nil {+ t.Fatalf("v1 report must stay untouched: %+v", legacy)+ }+}++func TestAnalyzeAssistantDiagnosticsFailureClassification(t *testing.T) {+ cases := []struct {+ code, outcome, unknown string+ }{+ {"AUTHENTICATION_FAILED", "failure_observed", "上游拒绝或服务异常已被观察到"},+ {"RATE_LIMITED", "failure_observed", "上游拒绝或服务异常已被观察到"},+ {"UPSTREAM_UNAVAILABLE", "failure_observed", "上游拒绝或服务异常已被观察到"},+ {"NETWORK_ERROR", "failure_observed", "连接失败的具体网络节点"},+ {"CLI_EXIT_NONZERO", "undetermined", "不足以单独判定 CLI 内部根因"},+ {"MISSING_RESULT", "undetermined", "不足以单独判定 CLI 内部根因"},+ {"GENERATION_FAILED", "undetermined", "不足以单独判定 CLI 内部根因"},+ {"CLI_NOT_INSTALLED", "failure_observed", ""},+ }+ for _, tc := range cases {+ t.Run(tc.code, func(t *testing.T) {+ report := AssistantDiagnostics{+ Version: 2,+ GenerationID: "gen-" + tc.code,+ Status: "failed",+ Failure: &AssistantFailure{Code: tc.code, Phase: "cli", Message: "失败:" + tc.code},+ Environment: &AssistantDiagnosticEnvironment{InstanceID: "api-1"},+ Attempts: []AssistantCLIAttempt{{ID: "a/1", CLIVersion: "1.0.0", Status: "failed"}},+ }+ AnalyzeAssistantDiagnostics(&report)+ a := report.Assessment+ if a.Outcome != tc.outcome || a.Summary != "失败:"+tc.code {+ t.Fatalf("outcome/summary = %q/%q, want %q", a.Outcome, a.Summary, tc.outcome)+ }+ joined := diagnosticJoined(a)+ if !strings.Contains(joined, "失败阶段:cli;分类:"+tc.code) {+ t.Fatalf("missing failure evidence:\n%s", joined)+ }+ if tc.unknown != "" && !strings.Contains(joined, tc.unknown) {+ t.Fatalf("missing unknown %q:\n%s", tc.unknown, joined)+ }+ if tc.unknown == "" && len(a.Unknowns) != 0 {+ t.Fatalf("unexpected unknowns for %s: %v", tc.code, a.Unknowns)+ }+ if !strings.Contains(joined, "diagnostic=gen-"+tc.code+" 与 instance=api-1") {+ t.Fatalf("failed run must point to server logs:\n%s", joined)+ }+ })+ }+}++func TestAnalyzeAssistantDiagnosticsFailedWithoutFailureDetail(t *testing.T) {+ report := AssistantDiagnostics{Version: 2, Status: "failed"}+ AnalyzeAssistantDiagnostics(&report)+ if report.Assessment.Outcome != "undetermined" || report.Assessment.Summary != "现有证据不足以确认失败原因" {+ t.Fatalf("failed without detail must stay undetermined: %+v", report.Assessment)+ }+}++func TestAnalyzeAssistantDiagnosticsTerminationOutcomes(t *testing.T) {+ now := time.Date(2026, 11, 13, 9, 0, 0, 0, time.UTC)+ for code, outcome := range map[string]string{+ "USER_STEER": "redirected_by_user",+ "SERVER_SHUTDOWN": "termination_recorded",+ "CHECKPOINT_LOST": "termination_recorded",+ } {+ report := AssistantDiagnostics{+ Version: 2,+ Status: "interrupted",+ Termination: &AssistantDiagnosticTermination{At: now, Code: code, Message: "结束:" + code},+ Attempts: []AssistantCLIAttempt{{ID: "t/1", CLIVersion: "1", FirstError: &AssistantDiagnosticEvent{Kind: "cli.stderr"}}},+ }+ AnalyzeAssistantDiagnostics(&report)+ a := report.Assessment+ if a.Outcome != outcome || a.Summary != "结束:"+code {+ t.Fatalf("%s: outcome %q summary %q", code, a.Outcome, a.Summary)+ }+ joined := diagnosticJoined(a)+ if !strings.Contains(joined, "平台记录的结束原因:"+code) {+ t.Fatalf("%s: missing termination evidence:\n%s", code, joined)+ }+ if strings.Contains(joined, "用户停止前") {+ t.Fatalf("%s: early-error hint is only for USER_CANCELLED:\n%s", code, joined)+ }+ // Without lastCheckpointAt the heartbeat line must not be fabricated.+ if strings.Contains(joined, "最后一次运行实例心跳时间") {+ t.Fatalf("%s: heartbeat time without lastCheckpointAt:\n%s", code, joined)+ }+ hasLostUnknown := strings.Contains(joined, "只确认平台未继续保存执行状态")+ if hasLostUnknown != (code == "CHECKPOINT_LOST") {+ t.Fatalf("%s: CHECKPOINT_LOST unknown presence = %v", code, hasLostUnknown)+ }+ }+}++func TestAnalyzeAssistantDiagnosticsStatusWithoutTermination(t *testing.T) {+ completed := AssistantDiagnostics{Version: 2, Status: "completed", Environment: &AssistantDiagnosticEnvironment{InstanceID: "api-1"},+ Tools: []AssistantDiagnosticTool{{ID: "x", Name: "read", Source: "cli", Status: "failed", RequestID: "req-1"}}}+ AnalyzeAssistantDiagnostics(&completed)+ if completed.Assessment.Outcome != "completed" {+ t.Fatalf("completed outcome = %+v", completed.Assessment)+ }+ joined := diagnosticJoined(completed.Assessment)+ if !strings.Contains(joined, "记录到 1 次工具失败(首个:read(来源:cli))") || !strings.Contains(joined, "requestId") {+ t.Fatalf("recovered tool failure must stay visible:\n%s", joined)+ }+ if strings.Contains(joined, "instance=api-1") {+ t.Fatalf("completed run must not ask to search server logs:\n%s", joined)+ }++ running := AssistantDiagnostics{Version: 2, Status: "running",+ Attempts: []AssistantCLIAttempt{{ID: "r/1", CLIVersion: "1", Process: &AssistantDiagnosticProcess{PID: 77, State: "running"}}}}+ AnalyzeAssistantDiagnostics(&running)+ a := running.Assessment+ joined = diagnosticJoined(a)+ if a.Outcome != "pending" || running.Attempts[0].Process.State != "running" {+ t.Fatalf("live snapshot must stay pending/running: %+v %+v", a, running.Attempts[0].Process)+ }+ if !strings.Contains(joined, "未观察到正在执行的工具") || !strings.Contains(joined, "PID 77") {+ t.Fatalf("idle running snapshot evidence missing:\n%s", joined)+ }++ busy := AssistantDiagnostics{Version: 2, Status: "running",+ Tools: []AssistantDiagnosticTool{{ID: "g/1", Name: "tapd", Source: "gateway", Status: "running"}}}+ AnalyzeAssistantDiagnostics(&busy)+ if busy.Tools[0].Status != "running" || strings.Contains(diagnosticJoined(busy.Assessment), "未观察到正在执行的工具") {+ t.Fatalf("running tool must stay running and suppress idle unknown: %+v", busy.Assessment)+ }++ for _, status := range []string{"interrupted", "cancelled"} {+ report := AssistantDiagnostics{Version: 2, Status: status}+ AnalyzeAssistantDiagnostics(&report)+ joined := diagnosticJoined(report.Assessment)+ if report.Assessment.Outcome != "undetermined" || !strings.Contains(joined, "不能认定为用户主动停止") || !strings.Contains(joined, "优先检查 firstError") {+ t.Fatalf("%s without termination: %+v", status, report.Assessment)+ }+ }+}++func TestAnalyzeAssistantDiagnosticsProcessSignalsAndIdentifiers(t *testing.T) {+ exit := 137+ report := AssistantDiagnostics{+ Version: 2,+ Status: "failed",+ Truncated: true,+ Attempts: []AssistantCLIAttempt{+ {ID: "p/1", Status: "failed", ExitCode: &exit, Process: &AssistantDiagnosticProcess{State: "exited", Signal: "killed", StdoutLines: 3}},+ {ID: "p/2", Status: "failed", Process: &AssistantDiagnosticProcess{State: "start_failed"},+ Events: []AssistantDiagnosticEvent{{Kind: "cli.error", TraceID: "trace-9"}}},+ },+ }+ AnalyzeAssistantDiagnostics(&report)+ a := report.Assessment+ joined := diagnosticJoined(a)+ for _, want := range []string{+ "调用 p/1 的进程退出码为 137,协议结果为 failed",+ "调用 p/1 收到进程信号 killed",+ "进程信号不能单独证明 OOM",+ "调用 p/2 的 CLI 进程启动失败",+ "traceId",+ "部分证据已按上限截断",+ } {+ if !strings.Contains(joined, want) {+ t.Fatalf("missing %q:\n%s", want, joined)+ }+ }+ // Both attempts lack a CLI version, but the unknown is reported once.+ if n := strings.Count(strings.Join(a.Unknowns, "\n"), "CLI 未提供版本"); n != 1 {+ t.Fatalf("missing-version unknown repeated %d times: %v", n, a.Unknowns)+ }+ if strings.Contains(joined, "requestId") {+ t.Fatalf("no requestId was recorded:\n%s", joined)+ }+}diff --git a/internal/domain/assistant_diagnostic_analysis_test.go b/internal/domain/assistant_diagnostic_analysis_test.gonew file mode 100644index 00000000..70a5edc6--- /dev/null+++ b/internal/domain/assistant_diagnostic_analysis_test.go@@ -0,0 +1,111 @@+package domain++import (+ "strings"+ "testing"+ "time"+)++func TestAnalyzeAssistantDiagnosticsIdempotencyAndBoundaries(t *testing.T) {+ started := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)+ checkpoint := started.Add(12 * time.Second)+ report := AssistantDiagnostics{+ Version: 2,+ GenerationID: "gen-hang-01",+ SessionID: "sess-01",+ Status: "interrupted",+ StartedAt: started,+ UpdatedAt: checkpoint.Add(time.Minute),+ LastCheckpointAt: &checkpoint,+ Environment: &AssistantDiagnosticEnvironment{+ PlatformVersion: "v0.9.0",+ InstanceID: "api-node-a",+ },+ Termination: &AssistantDiagnosticTermination{+ At: checkpoint.Add(time.Minute),+ Code: "CHECKPOINT_LOST",+ Source: "platform",+ Message: "超过 45 秒未收到运行实例心跳,生成已中断",+ },+ Attempts: []AssistantCLIAttempt{{+ ID: "gen-hang-01/1",+ Engine: "codex",+ Status: "running",+ Process: &AssistantDiagnosticProcess{+ PID: 4321,+ State: "running",+ StdoutLines: 0,+ StderrLines: 0,+ },+ }},+ Tools: []AssistantDiagnosticTool{{+ ID: "gateway/1",+ AttemptID: "gen-hang-01/1",+ Source: "gateway",+ Name: "tapd__stories_list",+ Status: "running",+ StartedAt: started.Add(2 * time.Second),+ }},+ }++ AnalyzeAssistantDiagnostics(&report)+ firstEvidenceCount := len(report.Assessment.Evidence)+ if report.Tools[0].Status != "unfinished" {+ t.Fatalf("expected running tool to become unfinished, got %q", report.Tools[0].Status)+ }+ if report.Attempts[0].Process.State != "unknown_after_interruption" {+ t.Fatalf("expected running process to become unknown_after_interruption, got %q", report.Attempts[0].Process.State)+ }++ // Running analysis again on an already-analyzed snapshot must preserve identical evidence.+ AnalyzeAssistantDiagnostics(&report)+ if len(report.Assessment.Evidence) != firstEvidenceCount {+ t.Fatalf("non-idempotent evidence count: got %d, want %d (%v)", len(report.Assessment.Evidence), firstEvidenceCount, report.Assessment.Evidence)+ }++ joined := strings.Join(report.Assessment.Evidence, "\n") + "\n" + strings.Join(report.Assessment.NextSteps, "\n")+ for _, want := range []string{"tapd__stories_list", "CHECKPOINT_LOST", "2026-11-13T08:00:12Z", "PID 4321", "api-node-a"} {+ if !strings.Contains(joined, want) {+ t.Fatalf("missing %q in assessment:\n%s", want, joined)+ }+ }+}++func TestAnalyzeAssistantDiagnosticsUserCancelWithEarlyError(t *testing.T) {+ now := time.Now().UTC()+ report := AssistantDiagnostics{+ Version: 2,+ GenerationID: "gen-cancel-401",+ SessionID: "sess-02",+ Status: "cancelled",+ StartedAt: now,+ UpdatedAt: now,+ Termination: &AssistantDiagnosticTermination{+ At: now,+ Code: "USER_CANCELLED",+ Source: "platform",+ Message: "用户主动停止了本轮生成",+ },+ Attempts: []AssistantCLIAttempt{{+ ID: "gen-cancel-401/1",+ Engine: "codex",+ CLIVersion: "0.163.0",+ Status: "cancelled",+ FirstError: &AssistantDiagnosticEvent{+ At: now,+ Kind: "cli.stderr.sampling_error",+ StatusCode: 401,+ RequestID: "req-early-401",+ Message: "unexpected status 401 Unauthorized",+ },+ }},+ }+ AnalyzeAssistantDiagnostics(&report)+ if report.Assessment.Outcome != "cancelled_by_user" {+ t.Fatalf("unexpected outcome: %+v", report.Assessment)+ }+ joined := strings.Join(report.Assessment.Evidence, "\n") + "\n" + strings.Join(report.Assessment.NextSteps, "\n")+ if !strings.Contains(joined, "firstError") || !strings.Contains(joined, "HTTP 401") || !strings.Contains(joined, "requestId") {+ t.Fatalf("missing early error context on user cancel:\n%s", joined)+ }+}diff --git a/internal/domain/assistant_diagnostics.go b/internal/domain/assistant_diagnostics.gonew file mode 100644index 00000000..a3ad831f--- /dev/null+++ b/internal/domain/assistant_diagnostics.go@@ -0,0 +1,139 @@+package domain++import "time"++// AssistantFailure is safe to show beside a reply. Native request/trace IDs+// belong to the diagnostic report; a generation ID is never called a trace ID.+type AssistantFailure struct {+ Code string `json:"code"`+ Phase string `json:"phase"`+ Message string `json:"message"`+ Suggestion string `json:"suggestion,omitempty"`+}++// AssistantDiagnostics is a bounded, sanitized record of one turn. It does+// not contain prompts, command arguments, environment or raw provider streams.+type AssistantDiagnostics struct {+ Version int `json:"version"`+ GenerationID string `json:"generationId"`+ SessionID string `json:"sessionId"`+ Status string `json:"status"`+ StartedAt time.Time `json:"startedAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ Failure *AssistantFailure `json:"failure,omitempty"`+ Error string `json:"error,omitempty"`+ Attempts []AssistantCLIAttempt `json:"attempts"`+ Truncated bool `json:"truncated,omitempty"`+ Environment *AssistantDiagnosticEnvironment `json:"environment,omitempty"`+ LastCheckpointAt *time.Time `json:"lastCheckpointAt,omitempty"`+ Timeline []AssistantDiagnosticEvent `json:"timeline,omitempty"`+ Tools []AssistantDiagnosticTool `json:"tools,omitempty"`+ Termination *AssistantDiagnosticTermination `json:"termination,omitempty"`+ Assessment *AssistantDiagnosticAssessment `json:"assessment,omitempty"`+ Coverage []string `json:"coverage,omitempty"`+ Dropped map[string]int `json:"dropped,omitempty"`+}++// These facts are portable: no hostname, user identity, installation path or+// environment dump is required to identify a build and execution instance.+type AssistantDiagnosticEnvironment struct {+ PlatformVersion string `json:"platformVersion"`+ Revision string `json:"revision,omitempty"`+ Modified *bool `json:"modified,omitempty"`+ GoVersion string `json:"goVersion"`+ OS string `json:"os"`+ Arch string `json:"arch"`+ InstanceID string `json:"instanceId"`+ InstanceStartedAt time.Time `json:"instanceStartedAt"`+}++type AssistantDiagnosticTermination struct {+ At time.Time `json:"at"`+ Code string `json:"code"`+ Source string `json:"source"`+ Message string `json:"message"`+}++// Assessment describes observed evidence, never an invented provider root cause.+type AssistantDiagnosticAssessment struct {+ Outcome string `json:"outcome"`+ Summary string `json:"summary"`+ Evidence []string `json:"evidence,omitempty"`+ Unknowns []string `json:"unknowns,omitempty"`+ NextSteps []string `json:"nextSteps,omitempty"`+}++type AssistantDiagnosticProcess struct {+ PID int `json:"pid,omitempty"`+ State string `json:"state"`+ StartedAt *time.Time `json:"startedAt,omitempty"`+ FinishedAt *time.Time `json:"finishedAt,omitempty"`+ Signal string `json:"signal,omitempty"`+ UserCPUMs int64 `json:"userCpuMs,omitempty"`+ SystemCPUMs int64 `json:"systemCpuMs,omitempty"`+ StdoutLines int `json:"stdoutLines"`+ StderrLines int `json:"stderrLines"`+ FirstStdoutAt *time.Time `json:"firstStdoutAt,omitempty"`+ LastStdoutAt *time.Time `json:"lastStdoutAt,omitempty"`+ FirstStderrAt *time.Time `json:"firstStderrAt,omitempty"`+ LastStderrAt *time.Time `json:"lastStderrAt,omitempty"`+}++type AssistantDiagnosticTool struct {+ ID string `json:"id"`+ AttemptID string `json:"attemptId,omitempty"`+ Source string `json:"source"`+ Name string `json:"name"`+ ParentID string `json:"parentId,omitempty"`+ Status string `json:"status"`+ StartedAt time.Time `json:"startedAt"`+ FinishedAt *time.Time `json:"finishedAt,omitempty"`+ Error string `json:"error,omitempty"`+ ExitCode *int `json:"exitCode,omitempty"`+ StatusCode int `json:"statusCode,omitempty"`+ RequestID string `json:"requestId,omitempty"`+ TraceID string `json:"traceId,omitempty"`+}++type AssistantCLIAttempt struct {+ ID string `json:"id"`+ Engine string `json:"engine"`+ Model string `json:"model,omitempty"`+ Resume bool `json:"resume"`+ StartedAt time.Time `json:"startedAt"`+ FinishedAt *time.Time `json:"finishedAt,omitempty"`+ Phase string `json:"phase"`+ Status string `json:"status"`+ ExitCode *int `json:"exitCode,omitempty"`+ Error string `json:"error,omitempty"`+ Stderr []string `json:"stderr,omitempty"`+ Events []AssistantDiagnosticEvent `json:"events,omitempty"`+ CLIVersion string `json:"cliVersion,omitempty"`+ VersionSource string `json:"versionSource,omitempty"`+ BinarySource string `json:"binarySource,omitempty"`+ Endpoint string `json:"endpoint,omitempty"`+ Protocol string `json:"protocol,omitempty"`+ Effort string `json:"effort,omitempty"`+ Process *AssistantDiagnosticProcess `json:"process,omitempty"`+ FirstStderr []string `json:"firstStderr,omitempty"`+ FirstError *AssistantDiagnosticEvent `json:"firstError,omitempty"`+ NativeSessionID string `json:"nativeSessionId,omitempty"`+ NativeTurnID string `json:"nativeTurnId,omitempty"`+}++type AssistantDiagnosticEvent struct {+ At time.Time `json:"at"`+ Kind string `json:"kind"`+ Message string `json:"message,omitempty"`+ Code string `json:"code,omitempty"`+ Phase string `json:"phase,omitempty"`+ RequestID string `json:"requestId,omitempty"`+ TraceID string `json:"traceId,omitempty"`+ StatusCode int `json:"statusCode,omitempty"`+ Retryable *bool `json:"retryable,omitempty"`+ Sequence int `json:"sequence,omitempty"`+ Source string `json:"source,omitempty"`+ AttemptID string `json:"attemptId,omitempty"`+ ToolID string `json:"toolId,omitempty"`+ Tool string `json:"tool,omitempty"`+}diff --git a/internal/domain/assistant_generation.go b/internal/domain/assistant_generation.goindex 46b962aa..a9da6e42 100644--- a/internal/domain/assistant_generation.go+++ b/internal/domain/assistant_generation.go@@ -19,6 +19,7 @@ type AssistantGeneration struct {Status string `json:"status"`WorkspaceWarning string `json:"workspaceWarning,omitempty"`Error string `json:"error,omitempty"`+ Failure *AssistantFailure `json:"failure,omitempty"`Events []AssistantGenerationEvent `json:"events"`Stream *AssistantStreamSnapshot `json:"stream,omitempty"`Reply json.RawMessage `json:"reply,omitempty"`diff --git a/internal/httpapi/agent_tool_catalog.go b/internal/httpapi/agent_tool_catalog.goindex 209d4366..490e38e3 100644--- a/internal/httpapi/agent_tool_catalog.go+++ b/internal/httpapi/agent_tool_catalog.go@@ -292,6 +292,7 @@ func (h *agentToolGateway) buildCatalog(ctx context.Context, session *AgentToolStools, err := h.listUpstreamTools(ctx, session, server)if err != nil {logAgentToolEvent("catalog-hide", "mode="+string(session.Mode), "kind="+kind, "err="+truncateRunes(err.Error(), 120))+ session.diagnostics().platform("mcp.upstream_catalog_failed", "外部 MCP 服务 "+server.Name+"("+kind+")拉取工具列表失败:"+err.Error(), session.User)continue}for _, tool := range tools {diff --git a/internal/httpapi/agent_tool_mcp.go b/internal/httpapi/agent_tool_mcp.goindex 69df4c4d..9ed86989 100644--- a/internal/httpapi/agent_tool_mcp.go+++ b/internal/httpapi/agent_tool_mcp.go@@ -83,6 +83,7 @@ func (h *agentToolGateway) handleRPC(ctx context.Context, session *AgentToolSess}switch request.Method {case "initialize":+ session.diagnostics().platform("mcp.gateway_initialized", "CLI 已连接平台会话 MCP 网关", session.User)return &agentToolRPCResponse{JSONRPC: "2.0", ID: request.ID, Result: map[string]any{"protocolVersion": agentToolProtocolVersion(request.Params),"capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},@@ -92,7 +93,10 @@ func (h *agentToolGateway) handleRPC(ctx context.Context, session *AgentToolSesscase "ping":return &agentToolRPCResponse{JSONRPC: "2.0", ID: request.ID, Result: map[string]any{}}case "tools/list":- return &agentToolRPCResponse{JSONRPC: "2.0", ID: request.ID, Result: map[string]any{"tools": h.toolList(ctx, session)}}+ started := time.Now()+ tools := h.toolList(ctx, session)+ session.diagnostics().platform("mcp.tools_listed", fmt.Sprintf("平台网关返回 %d 个工具(耗时 %dms)", len(tools), time.Since(started).Milliseconds()), session.User)+ return &agentToolRPCResponse{JSONRPC: "2.0", ID: request.ID, Result: map[string]any{"tools": tools}}case "tools/call":result, err := h.callTool(ctx, session, request.Params)if err != nil {@@ -152,7 +156,7 @@ func (h *agentToolGateway) toolList(ctx context.Context, session *AgentToolSessireturn out}-func (h *agentToolGateway) callTool(ctx context.Context, session *AgentToolSession, raw json.RawMessage) (map[string]any, error) {+func (h *agentToolGateway) callTool(ctx context.Context, session *AgentToolSession, raw json.RawMessage) (res map[string]any, retErr error) {if session.finished() {return nil, errAgentToolTerminalCommitted}@@ -176,6 +180,24 @@ func (h *agentToolGateway) callTool(ctx context.Context, session *AgentToolSessireturn nil, err}name := stripAgentToolServerPrefix(params.Name)+ diag := session.diagnostics()+ attemptID := diag.currentAttemptID()+ diagToolID := diag.toolStart("gateway", "", name, "", attemptID, session.User)+ defer func() {+ if diagToolID == "" {+ return+ }+ failed := retErr != nil || (res != nil && res["isError"] == true)+ errMsg := ""+ if retErr != nil {+ errMsg = retErr.Error()+ } else if failed {+ if data, err := json.Marshal(res["content"]); err == nil {+ errMsg = diagnosticErrorText(data)+ }+ }+ diag.toolEnd("gateway", diagToolID, attemptID, errMsg, failed, nil, session.User)+ }()logAgentToolEvent("call-start", "mode="+string(session.Mode), "tool="+name)if name == submitClarificationTool || name == submitAssistantReplyTool || name == submitNotificationReportTool {return h.callTerminal(session, name, params.Arguments)diff --git a/internal/httpapi/agent_tool_session.go b/internal/httpapi/agent_tool_session.goindex b26f55e7..f099ab2e 100644--- a/internal/httpapi/agent_tool_session.go+++ b/internal/httpapi/agent_tool_session.go@@ -474,3 +474,10 @@ func (s *AgentToolSession) dispatchRunning() bool {defer s.mu.Unlock()return len(s.dispatches) > 0}++func (s *AgentToolSession) diagnostics() *assistantDiagnosticsCollector {+ if s == nil || s.ctx == nil {+ return nil+ }+ return assistantDiagnosticsFrom(s.ctx)+}diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.goindex 841042a7..3ebae92e 100644--- a/internal/httpapi/assistant.go+++ b/internal/httpapi/assistant.go@@ -230,24 +230,27 @@ func (h *assistantHandlers) chat(c *gin.Context) {defer cancelModel()chatCompleted := falseif shared && sink == nil {- job, finish, err := h.claimDirectSharedGeneration(ctx, req, ownerID, user, cancelModel)+ job, diagnostics, finish, err := h.claimDirectSharedGeneration(ctx, req, ownerID, user, cancelModel)if err != nil {c.JSON(409, gin.H{"error": err.Error()})return}defer func() { finish(chatCompleted) }()+ modelCtx = context.WithValue(modelCtx, assistantDiagnosticsKey{}, diagnostics)modelCtx = context.WithValue(modelCtx, assistantControlScopeKey{}, assistantControlScope{RunID: req.RunID, SessionID: req.SessionID, GenerationID: job.ID, MessageIndex: len(req.Messages) - 1})}var toolSession *AgentToolSessionvar toolFiles agentToolFilesif sess, files, err := h.openAssistantToolSession(modelCtx, user, req.ProjectID, assistantExecModeForApproval(approvalMode), cancelModel); err != nil {+ assistantDiagnosticsFrom(modelCtx).fail(modelCtx, err, user)logAgentToolEvent("session-fallback", "mode=assistant", "err="+truncateRunes(err.Error(), 160))if modelCtx.Err() != nil {status, message := assistantGenerationFailure(modelCtx, err)c.JSON(status, gin.H{"error": message})return}- c.JSON(502, gin.H{"error": "无法启动工具会话,请重试"})+ failure := &domain.AssistantFailure{Code: "TOOL_SESSION_FAILED", Phase: "setup", Message: "无法启动工具会话,请重试", Suggestion: "请下载诊断信息,检查工具服务配置与连接。"}+ c.JSON(502, gin.H{"error": failure.Message, "failure": failure})return} else {toolSession = sess@@ -323,11 +326,15 @@ func (h *assistantHandlers) chat(c *gin.Context) {emit("thought", assistantStreamEvent{Kind: "status", Text: "正在调用模型…"})}fail := func(status int, msg string) {+ payload := gin.H{"error": msg}+ if failure := assistantDiagnosticsFrom(modelCtx).failureForMessage(msg); failure != nil {+ payload["failure"] = failure+ }if streaming {- emit("error", gin.H{"error": msg})+ emit("error", payload)return}- c.JSON(status, gin.H{"error": msg})+ c.JSON(status, payload)}var nativeSession *assistantNativeSession// Every conversation runs in its own CLI root; shared ones switch to the@@ -413,6 +420,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {}raw, _, err := runAssistantCLI(ctx, cliReq, u, relay)if errors.Is(err, errAssistantSessionMissing) && resume {+ assistantDiagnosticsFrom(ctx).platform("cli.resume_fallback", "未找到历史 CLI 会话,自动回退为完整上下文新会话重试", u)if nativeSession != nil {if err = nativeSession.restart(); err != nil {return "", err@@ -451,18 +459,21 @@ func (h *assistantHandlers) chat(c *gin.Context) {err = modelCtx.Err()}if errors.Is(err, errAssistantCredentialRejected) {- fail(400, err.Error())+ failure := assistantDiagnosticsFrom(modelCtx).fail(ctx, err, user)+ fail(400, failure.Message)return}if errors.Is(err, errAssistantCLIMissing) {- fail(503, err.Error())+ failure := assistantDiagnosticsFrom(modelCtx).fail(ctx, err, user)+ fail(503, failure.Message)return}if err != nil && !(toolSession != nil && toolSession.finished()) {// A failed process may already have executed tools. Report the cause// instead of treating it as a missing draft submission and rerunning it.- status, msg := assistantGenerationFailure(ctx, err)- fail(status, msg)+ status, _ := assistantGenerationFailure(ctx, err)+ failure := assistantDiagnosticsFrom(modelCtx).fail(ctx, err, user)+ fail(status, failure.Message)return}var reply assistantReply@@ -479,6 +490,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {logAgentProtocolFailure(AgentToolAssistant, req.Model, "missing_terminal", fmt.Errorf("submit_assistant_reply not called"))if jsonRetries < nativeTerminalMaxRetries {jsonRetries+++ assistantDiagnosticsFrom(modelCtx).platform("orchestration.retry_terminal", fmt.Sprintf("未收到提交工具调用,发起第 %d 次补交重试", jsonRetries), user)if streaming {emit("thought", assistantStreamEvent{Kind: "status", Text: "正在提交回答…"})}@@ -500,6 +512,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}presentationRetries+++ assistantDiagnosticsFrom(modelCtx).platform("orchestration.retry_slides", fmt.Sprintf("演示文稿页数不符(期望 %d,实际 %d),发起重写重试", want, got), user)if streaming {emit("thought", assistantStreamEvent{Kind: "answerReset"})emit("thought", assistantStreamEvent{Kind: "status", Text: fmt.Sprintf("正在调整为要求的 %d 页…", want)})@@ -514,6 +527,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}progressRetries+++ assistantDiagnosticsFrom(modelCtx).platform("orchestration.retry_progress", fmt.Sprintf("模型仅返回进度说明,发起第 %d 次续跑重试", progressRetries), user)if streaming {emit("thought", assistantStreamEvent{Kind: "status", Text: "继续执行尚未完成的步骤…"})}@@ -566,7 +580,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {assets = append(assets, toolSession.assets...)toolSession.mu.Unlock()}- stored = append(stored, assistantMessage{Assets: assets, RunIDs: runIDs, Activity: activityEvents, StartedAt: &startedAt, CreatedAt: time.Now().UTC(), SpeakerName: reply.SpeakerName, SpeakerAgentID: reply.SpeakerAgentID, Model: replyModel, Usage: turnUsage.snapshot(), Role: "assistant", Content: jsonObject(gin.H{"message": reply.Message, "drafts": reply.Drafts}), Attachments: reply.Images})+ stored = append(stored, assistantMessage{Assets: assets, RunIDs: runIDs, Activity: activityEvents, StartedAt: &startedAt, CreatedAt: time.Now().UTC(), SpeakerName: reply.SpeakerName, SpeakerAgentID: reply.SpeakerAgentID, Model: replyModel, Usage: turnUsage.snapshot(), Role: "assistant", Content: jsonObject(gin.H{"message": reply.Message, "drafts": reply.Drafts}), Attachments: reply.Images, GenerationID: assistantControlScopeFrom(modelCtx).GenerationID})conversation := assistantConversation{Shared: shared, ID: req.SessionID, ProjectID: req.ProjectID, Model: req.Model, Effort: req.Effort, Executor: req.Executor, RunID: req.RunID, Messages: stored}if toolSession != nil {conversation.WorkspaceRunID = toolSession.conversationWorkspace()@@ -1214,9 +1228,11 @@ type assistantCLIRequest struct {OnUsage func(domain.TokenUsage)}-func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.User, onEvent func(assistantStreamEvent)) (string, string, error) {+func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.User, onEvent func(assistantStreamEvent)) (output string, returnedSessionID string, returnedErr error) {req.Model = assistantRequestModel(req.Executor, req.Model)engine, engineModel := assistantModelEngine(req.Model)+ attempt := assistantDiagnosticsFrom(ctx).begin(engine, engineModel, req.Resume, user)+ defer func() { attempt.finish(returnedErr) }()if engine != assistantEngineCodeBuddy && (req.ReportOnly || (!req.Native && !req.ReviewOnly)) {return "", "", errAssistantEngineUnsupported}@@ -1225,6 +1241,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Ulog.Printf("assistant CLI resolve failed: %v", err)return "", "", err}+ attempt.configure(bin, req)root := req.SessionRootif root == "" {root = assistantSessionRoot(user.ID)@@ -1299,7 +1316,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.UmissingText := "No conversation found with session ID: " + inv.sessionRefvar handle func(string)sink := func(event domain.TelemetryEvent) {+ attempt.process(event)if event.Name == "process.stderr" {+ attempt.stderr(event.Message)if line := strings.TrimSpace(event.Message); line != "" {missingSession = missingSession || strings.Contains(line, missingText)stderrTail = append(stderrTail, line)@@ -1312,6 +1331,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Uif event.Name != "process.stdout" {return}+ attempt.protocol(event.Message)if inv.translate == nil {handle(event.Message)return@@ -1322,6 +1342,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U}handle = func(line string) {line = strings.TrimSpace(line)+ attempt.tools(line)if failure := assistantCLIStreamFailure(line); failure != nil {streamError = failure}@@ -1362,7 +1383,12 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U}}}+ attempt.phase("execution")_, err = runtime.ExecuteLocalCommand(ctx, workspace, command, inv.credentials, sink)+ attempt.exited(err)+ if err == nil {+ attempt.phase("protocol")+ }if req.OnUsage != nil && assistantUsageReported(usage) {req.OnUsage(usage)}@@ -1390,7 +1416,11 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U}out, err := decodeAssistantCLIResult(final, resultError, err, stderrTail)if err != nil {- log.Printf("assistant CLI session=%s: %s", sessionID, redactAssistantSecrets(err.Error(), user))+ diagnosticID := ""+ if attempt != nil {+ diagnosticID = attempt.id+ }+ log.Printf("assistant CLI diagnostic=%s session=%s: %s", diagnosticID, sessionID, sanitizeAssistantDiagnostic(err.Error(), user, 4096))return "", sessionID, err}return out, sessionID, nildiff --git a/internal/httpapi/assistant_diagnostic_environment.go b/internal/httpapi/assistant_diagnostic_environment.gonew file mode 100644index 00000000..c7508b8e--- /dev/null+++ b/internal/httpapi/assistant_diagnostic_environment.go@@ -0,0 +1,126 @@+package httpapi++import (+ "encoding/json"+ "net/url"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "runtime/debug"+ "strings"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/managedcli"+)++var assistantDiagnosticInstance = domain.AssistantDiagnosticEnvironment{+ PlatformVersion: "development", GoVersion: runtime.Version(), OS: runtime.GOOS, Arch: runtime.GOARCH,+ InstanceID: "api-" + newAssistantSessionID(), InstanceStartedAt: time.Now().UTC(),+}++func assistantDiagnosticEnvironment() domain.AssistantDiagnosticEnvironment {+ e := assistantDiagnosticInstance+ if info, ok := debug.ReadBuildInfo(); ok {+ if info.Main.Version != "" {+ e.PlatformVersion = info.Main.Version+ }+ for _, item := range info.Settings {+ switch item.Key {+ case "vcs.revision":+ e.Revision = item.Value+ case "vcs.modified":+ modified := item.Value == "true"+ e.Modified = &modified+ }+ }+ }+ return e+}++var diagnosticVersion = regexp.MustCompile(`^v?[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$`)++// Read installation metadata rather than launching a second CLI process. A+// version probe can itself hang or mutate a continuation cache. The native+// handshake can fill the version later when installation metadata is absent.+func assistantDiagnosticCLIVersion(engine, bin string) (version, source string) {+ if root := strings.TrimSpace(os.Getenv("AGENTFLOW_MANAGED_CLI_ROOT")); root != "" {+ if inventory, err := managedcli.ReadInventory(root); err == nil {+ if install, ok := inventory[engine]; ok && install.Binary == bin && diagnosticVersion.MatchString(install.Version) {+ return install.Version, "managed_inventory"+ }+ }+ }+ packages := map[string]string{"codex": "@openai/codex", "codebuddy": "@tencent-ai/codebuddy-code", "claude-code": "@anthropic-ai/claude-code"}+ resolved, err := filepath.EvalSymlinks(bin)+ if err == nil && packages[engine] != "" {+ for dir, depth := filepath.Dir(resolved), 0; depth < 5; dir, depth = filepath.Dir(dir), depth+1 {+ info, err := os.Stat(filepath.Join(dir, "package.json"))+ if err != nil || info.Size() > 64<<10 {+ continue+ }+ raw, err := os.ReadFile(filepath.Join(dir, "package.json"))+ var pkg struct{ Name, Version string }+ if err == nil && json.Unmarshal(raw, &pkg) == nil && pkg.Name == packages[engine] && diagnosticVersion.MatchString(pkg.Version) {+ return pkg.Version, "package_metadata"+ }+ }+ }+ return "", "not_reported"+}++func (a *assistantDiagnosticAttempt) configure(bin string, req assistantCLIRequest) {+ if a == nil {+ return+ }+ engine, _ := assistantModelEngine(assistantRequestModel(req.Executor, req.Model))+ version, source := assistantDiagnosticCLIVersion(engine, bin)+ endpoint, protocol := "", "stream-json"+ switch engine {+ case "codex":+ endpoint, protocol = a.user.CodexBaseURL, "responses / app-server JSON-RPC"+ if endpoint == "" {+ endpoint = "https://api.openai.com/v1"+ }+ case "claude-code":+ endpoint, protocol = a.user.ClaudeCodeBaseURL, "messages / stream-json"+ if endpoint == "" {+ endpoint = "https://api.anthropic.com"+ }+ case "codebuddy":+ // The CLI selects this endpoint internally. Do not guess a hostname.+ env := strings.TrimSpace(a.user.CodeBuddyInternetEnvironment)+ if env == "" {+ env = "default"+ }+ endpoint = "CLI-managed (" + env + ")"+ default:+ credential := a.user.AgentCLICredentials[engine]+ endpoint, protocol = credential.BaseURL, credential.Protocol+ }+ // Gateways may put a key in the path (/v1/<key>/…); host is enough to+ // tell which service the CLI talked to.+ if u, err := url.Parse(endpoint); err == nil && u.Host != "" {+ endpoint = (&url.URL{Scheme: u.Scheme, Host: u.Host}).String()+ }+ binarySource := "discovered"+ key := "AGENTFLOW_" + strings.ToUpper(strings.ReplaceAll(engine, "-", "_")) + "_BIN"+ if engine == "claude-code" {+ key = "AGENTFLOW_CLAUDE_BIN"+ }+ if strings.TrimSpace(os.Getenv(key)) == bin {+ binarySource = "explicit_override"+ } else if source == "managed_inventory" {+ binarySource = "managed_inventory"+ } else if root := strings.TrimSpace(os.Getenv("AGENTFLOW_MANAGED_CLI_ROOT")); root != "" && strings.HasPrefix(bin, filepath.Clean(root)+string(filepath.Separator)) {+ binarySource = "managed_inventory"+ }+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ attempt.CLIVersion, attempt.VersionSource = version, source+ attempt.BinarySource = binarySource+ attempt.Endpoint = sanitizeAssistantDiagnostic(endpoint, a.user, 300)+ attempt.Protocol = sanitizeAssistantDiagnostic(protocol, a.user, 80)+ attempt.Effort = sanitizeAssistantDiagnostic(req.Effort, a.user, 40)+ })+}diff --git a/internal/httpapi/assistant_diagnostic_evidence.go b/internal/httpapi/assistant_diagnostic_evidence.gonew file mode 100644index 00000000..5f3a047c--- /dev/null+++ b/internal/httpapi/assistant_diagnostic_evidence.go@@ -0,0 +1,413 @@+package httpapi++import (+ "encoding/json"+ "fmt"+ "log"+ "regexp"+ "strconv"+ "strings"+ "time"++ "agentflow/internal/domain"+)++const diagnosticTimelineLimit = 160++// Keep the beginning and tail. Repeated warnings must not evict the first+// failure, the initial configuration, or the process's start.+func (d *assistantDiagnosticsCollector) appendTimelineLocked(e domain.AssistantDiagnosticEvent) {+ d.timelineSequence+++ e.Sequence = d.timelineSequence+ if e.At.IsZero() {+ e.At = time.Now().UTC()+ }+ if len(d.report.Timeline) == diagnosticTimelineLimit {+ d.report.Timeline = append(d.report.Timeline[:24], d.report.Timeline[25:]...)+ d.dropLocked("timeline", 1)+ }+ d.report.Timeline = append(d.report.Timeline, e)+}++func (d *assistantDiagnosticsCollector) dropLocked(kind string, n int) {+ d.report.Truncated = true+ if d.report.Dropped == nil {+ d.report.Dropped = map[string]int{}+ }+ d.report.Dropped[kind] += n+}++func (d *assistantDiagnosticsCollector) platform(kind, message string, user domain.User) {+ if d == nil {+ return+ }+ e := domain.AssistantDiagnosticEvent{Kind: kind, Source: "platform", Message: sanitizeAssistantDiagnostic(message, user, 2048)}+ d.mu.Lock()+ d.appendTimelineLocked(e)+ id := d.report.GenerationID+ d.mu.Unlock()+ log.Printf("assistant diagnostic=%s instance=%s event=%s: %s", id, assistantDiagnosticInstance.InstanceID, kind, e.Message)+}++// The first explicit cause wins: a process killed after a cancellation must+// not replace the reason that caused that cancellation.+func (d *assistantDiagnosticsCollector) terminate(code, message string, user domain.User) {+ if d == nil {+ return+ }+ message = sanitizeAssistantDiagnostic(message, user, 2048)+ d.mu.Lock()+ if d.report.Termination != nil {+ d.mu.Unlock()+ return+ }+ now := time.Now().UTC()+ d.report.Termination = &domain.AssistantDiagnosticTermination{At: now, Code: code, Source: "platform", Message: message}+ d.appendTimelineLocked(domain.AssistantDiagnosticEvent{At: now, Source: "platform", Kind: "generation.termination", Code: code, Message: message})+ id := d.report.GenerationID+ d.mu.Unlock()+ log.Printf("assistant diagnostic=%s instance=%s termination=%s: %s", id, assistantDiagnosticInstance.InstanceID, code, message)+}++func (a *assistantDiagnosticAttempt) process(event domain.TelemetryEvent) {+ if a == nil {+ return+ }+ now := time.Now().UTC()+ if !event.Timestamp.IsZero() {+ now = event.Timestamp+ }+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ if attempt.Process == nil {+ attempt.Process = &domain.AssistantDiagnosticProcess{State: "not_started"}+ }+ p := attempt.Process+ switch event.Name {+ case "process.started":+ p.PID, _ = event.Attributes["pid"].(int)+ p.State, p.StartedAt = "running", &now+ case "process.start_failed":+ p.State, p.FinishedAt = "start_failed", &now+ case "process.finished":+ if p.State != "start_failed" {+ p.State = "exited"+ }+ p.FinishedAt = &now+ p.Signal, _ = event.Attributes["signal"].(string)+ p.UserCPUMs, _ = event.Attributes["userCpuMs"].(int64)+ p.SystemCPUMs, _ = event.Attributes["systemCpuMs"].(int64)+ if code, ok := event.Attributes["exitCode"].(int); ok {+ attempt.ExitCode = &code+ }+ if incomplete, _ := event.Attributes["outputIncomplete"].(bool); incomplete {+ a.d.dropLocked("processOutputIncomplete", 1)+ }+ case "process.stdout":+ p.StdoutLines+++ if p.FirstStdoutAt == nil {+ p.FirstStdoutAt = &now+ }+ p.LastStdoutAt = &now+ case "process.stderr":+ p.StderrLines+++ if p.FirstStderrAt == nil {+ p.FirstStderrAt = &now+ }+ p.LastStderrAt = &now+ }+ if event.Name != "process.stdout" && event.Name != "process.stderr" {+ // process.started.Message contains argv and is intentionally discarded.+ e := domain.AssistantDiagnosticEvent{At: now, Source: "process", Kind: event.Name, AttemptID: a.id}+ if event.Name == "process.start_failed" {+ e.Message = sanitizeAssistantDiagnostic(event.Message, a.user, 1024)+ }+ if event.Name == "process.finished" && p.Signal != "" {+ e.Message = "signal: " + p.Signal+ }+ a.d.appendTimelineLocked(e)+ }+ })+}++var (+ diagnosticRequestID = regexp.MustCompile(`(?i)\b(?:request[ _-]?id|x-request-id)\s*[=:]\s*["']?([A-Za-z0-9_.:/-]{4,160})`)+ diagnosticTraceID = regexp.MustCompile(`(?i)\b(?:trace[ _-]?id|x-trace-id)\s*[=:]\s*["']?([A-Za-z0-9_.:/-]{4,160})`)+ diagnosticHTTPStatus = regexp.MustCompile(`(?i)\b(?:HTTP(?:/[0-9.]+)?\s+|status(?:\s+code)?[\s:=]+)([1-5][0-9]{2})\b`)+)++func diagnosticTextMetadata(e *domain.AssistantDiagnosticEvent) {+ if match := diagnosticRequestID.FindStringSubmatch(e.Message); e.RequestID == "" && len(match) > 1 {+ e.RequestID = match[1]+ }+ if match := diagnosticTraceID.FindStringSubmatch(e.Message); e.TraceID == "" && len(match) > 1 {+ e.TraceID = match[1]+ }+ if match := diagnosticHTTPStatus.FindStringSubmatch(e.Message); e.StatusCode == 0 && len(match) > 1 {+ e.StatusCode, _ = strconv.Atoi(match[1])+ }+}++func isPlaceholderRetryEvent(e *domain.AssistantDiagnosticEvent) bool {+ if e == nil {+ return false+ }+ return e.RequestID == "" && strings.HasPrefix(strings.TrimSpace(e.Message), "Reconnecting...")+}++func (a *assistantDiagnosticAttempt) recordEvent(e domain.AssistantDiagnosticEvent) {+ e.Source, e.AttemptID = "cli", a.id+ diagnosticTextMetadata(&e)+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ isErr := strings.Contains(e.Kind, "error") || strings.Contains(e.Kind, "fail") || e.StatusCode >= 400+ if isErr && (attempt.FirstError == nil || (isPlaceholderRetryEvent(attempt.FirstError) && !isPlaceholderRetryEvent(&e))) {+ first := e+ attempt.FirstError = &first+ }+ if len(attempt.Events) == 40 {+ attempt.Events = append(attempt.Events[:8], attempt.Events[9:]...)+ a.d.dropLocked("protocolEvents", 1)+ }+ attempt.Events = append(attempt.Events, e)+ a.d.appendTimelineLocked(e)+ })+}++func (d *assistantDiagnosticsCollector) toolStart(source, id, name, parent, attemptID string, user domain.User) string {+ if d == nil {+ return ""+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ if id == "" {+ d.toolSequence+++ id = fmt.Sprintf("gateway/%d", d.toolSequence)+ }+ id = sanitizeAssistantDiagnostic(id, user, 160)+ for i := range d.report.Tools {+ t := &d.report.Tools[i]+ if t.ID == id && t.Source == source && t.AttemptID == attemptID {+ if name != "" {+ t.Name = sanitizeAssistantDiagnostic(name, user, 120)+ }+ return id+ }+ }+ if len(d.report.Tools) >= 80 {+ drop := -1+ for i, t := range d.report.Tools {+ if t.Status == "completed" {+ drop = i+ break+ }+ }+ if drop == -1 {+ drop = 0+ }+ d.report.Tools = append(d.report.Tools[:drop], d.report.Tools[drop+1:]...)+ d.dropLocked("tools", 1)+ }+ now := time.Now().UTC()+ name = sanitizeAssistantDiagnostic(name, user, 120)+ d.report.Tools = append(d.report.Tools, domain.AssistantDiagnosticTool{ID: id, AttemptID: attemptID, Source: source, Name: name, ParentID: sanitizeAssistantDiagnostic(parent, user, 160), Status: "running", StartedAt: now})+ d.appendTimelineLocked(domain.AssistantDiagnosticEvent{At: now, Source: source, Kind: "tool.started", AttemptID: attemptID, ToolID: id, Tool: name})+ return id+}++func (d *assistantDiagnosticsCollector) toolEnd(source, id, attemptID, message string, failed bool, exitCode *int, user domain.User) {+ if d == nil {+ return+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ for i := len(d.report.Tools) - 1; i >= 0; i-- {+ t := &d.report.Tools[i]+ if t.ID != id || t.Source != source || t.AttemptID != attemptID || t.FinishedAt != nil {+ continue+ }+ now := time.Now().UTC()+ t.FinishedAt, t.ExitCode, t.Status = &now, exitCode, "completed"+ e := domain.AssistantDiagnosticEvent{At: now, Source: source, Kind: "tool.completed", AttemptID: attemptID, ToolID: id, Tool: t.Name}+ if failed {+ t.Status, e.Kind = "failed", "tool.failed"+ t.Error = sanitizeAssistantDiagnostic(message, user, 1024)+ if t.Error == "" {+ t.Error = "工具返回失败标记,未提供错误详情"+ }+ e.Message = t.Error+ diagnosticTextMetadata(&e)+ t.StatusCode, t.RequestID, t.TraceID = e.StatusCode, e.RequestID, e.TraceID+ }+ d.appendTimelineLocked(e)+ return+ }+}++// Only failing tool responses contribute text. Successful outputs, arguments,+// commands, model prose and reasoning are never retained by this collector.+func diagnosticErrorText(raw json.RawMessage) string {+ if len(raw) > 256<<10 {+ raw = raw[:256<<10]+ }+ var text string+ if json.Unmarshal(raw, &text) == nil {+ return truncateRunes(text, 2048)+ }+ var blocks []struct{ Type, Text string }+ if json.Unmarshal(raw, &blocks) == nil {+ for _, b := range blocks {+ if b.Type == "text" {+ text += b.Text + "\n"+ if len(text) > 8192 {+ break+ }+ }+ }+ return truncateRunes(strings.TrimSpace(text), 2048)+ }+ var detail struct{ Message, Error string }+ if json.Unmarshal(raw, &detail) == nil {+ return truncateRunes(strings.TrimSpace(detail.Message+" "+detail.Error), 2048)+ }+ return ""+}++func (a *assistantDiagnosticAttempt) tools(line string) {+ if a == nil || len(line) > 256<<10 {+ return+ }+ var event struct {+ Type string `json:"type"`+ Parent string `json:"parent_tool_use_id"`+ Message struct {+ Content []struct {+ Type, ID, Name string+ ToolUseID string `json:"tool_use_id"`+ IsError bool `json:"is_error"`+ Content json.RawMessage `json:"content"`+ } `json:"content"`+ } `json:"message"`+ Event struct {+ Type string+ ContentBlock struct{ Type, ID, Name string } `json:"content_block"`+ } `json:"event"`+ }+ if json.Unmarshal([]byte(line), &event) != nil {+ return+ }+ if event.Type == "stream_event" && event.Event.Type == "content_block_start" && event.Event.ContentBlock.Type == "tool_use" {+ b := event.Event.ContentBlock+ a.d.toolStart("cli", b.ID, b.Name, event.Parent, a.id, a.user)+ }+ for _, b := range event.Message.Content {+ if event.Type == "assistant" && b.Type == "tool_use" && b.ID != "" {+ a.d.toolStart("cli", b.ID, b.Name, event.Parent, a.id, a.user)+ }+ if event.Type == "user" && b.Type == "tool_result" && b.ToolUseID != "" {+ message := ""+ if b.IsError {+ message = diagnosticErrorText(b.Content)+ }+ a.d.toolEnd("cli", b.ToolUseID, a.id, message, b.IsError, nil, a.user)+ }+ }+}++func (a *assistantDiagnosticAttempt) nativeMetadata(raw map[string]any) {+ get := func(v map[string]any, key string) string { value, _ := v[key].(string); return value }+ params, _ := raw["params"].(map[string]any)+ result, _ := raw["result"].(map[string]any)+ version := ""+ for _, key := range []string{"claude_code_version", "codebuddy_version", "cliVersion"} {+ if value := get(raw, key); diagnosticVersion.MatchString(value) {+ version = value+ }+ }+ // Codex initialize returns a userAgent; extract only the version, not host+ // descriptions or other fields from the initialization response.+ if agent := get(result, "userAgent"); strings.Contains(agent, "codex") {+ if match := regexp.MustCompile(`\b[0-9]+\.[0-9]+\.[0-9]+\b`).FindString(agent); match != "" {+ version = match+ }+ }+ method, kind := get(raw, "method"), get(raw, "type")+ eventSub, _ := raw["event"].(map[string]any)+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ if version != "" {+ attempt.CLIVersion, attempt.VersionSource = version, "native_handshake"+ }+ for _, key := range []string{"session_id", "sessionId", "sessionID", "conversation_id"} {+ if id := get(raw, key); id != "" {+ attempt.NativeSessionID = sanitizeAssistantDiagnostic(id, a.user, 160)+ }+ }+ if id := get(params, "threadId"); id != "" {+ attempt.NativeSessionID = sanitizeAssistantDiagnostic(id, a.user, 160)+ }+ if thread, ok := result["thread"].(map[string]any); ok && get(thread, "id") != "" {+ attempt.NativeSessionID = sanitizeAssistantDiagnostic(get(thread, "id"), a.user, 160)+ }+ if turn, ok := params["turn"].(map[string]any); ok && get(turn, "id") != "" {+ attempt.NativeTurnID = sanitizeAssistantDiagnostic(get(turn, "id"), a.user, 160)+ }+ milestone := ""+ dedupe := false+ switch {+ case kind == "system" && get(raw, "subtype") == "init" || get(result, "userAgent") != "" || get(raw, "event") == "init":+ milestone, dedupe = "cli.initialized", true+ case method == "turn/started" || kind == "turn_start":+ milestone = "model.turn_started"+ case method == "item/agentMessage/delta" || method == "item/reasoning/summaryTextDelta" || method == "item/reasoning/textDelta" ||+ (kind == "stream_event" && get(eventSub, "type") == "content_block_delta") || kind == "model.streaming" || kind == "message_update":+ milestone, dedupe = "model.first_output_delta", true+ case method == "turn/completed":+ milestone = "model.turn_finished"+ case kind == "result" || kind == "final" || kind == "agent_end":+ milestone = "protocol.result_received"+ }+ if milestone != "" {+ if dedupe {+ for _, existing := range a.d.report.Timeline {+ if existing.AttemptID == a.id && existing.Kind == milestone {+ return+ }+ }+ }+ a.d.appendTimelineLocked(domain.AssistantDiagnosticEvent{Source: "cli", Kind: milestone, AttemptID: a.id})+ }+ })+ if method != "item/started" && method != "item/completed" {+ return+ }+ item, _ := params["item"].(map[string]any)+ id, name := get(item, "id"), ""+ switch get(item, "type") {+ case "mcpToolCall":+ name = "mcp__" + get(item, "server") + "__" + get(item, "tool")+ case "commandExecution":+ name = "Bash"+ case "webSearch":+ name = "WebSearch"+ }+ if id == "" || name == "" {+ return+ }+ a.d.toolStart("cli", id, name, "", a.id, a.user)+ if method == "item/completed" {+ var exitCode *int+ if n, ok := item["exitCode"].(float64); ok {+ code := int(n)+ exitCode = &code+ }+ status := get(item, "status")+ failed := status == "failed" || status == "declined" || item["error"] != nil || exitCode != nil && *exitCode != 0+ message := ""+ if failed {+ data, _ := json.Marshal(item["error"])+ message = diagnosticErrorText(data)+ if message == "" && exitCode != nil {+ message = fmt.Sprintf("工具进程退出码 %d", *exitCode)+ }+ }+ a.d.toolEnd("cli", id, a.id, message, failed, exitCode, a.user)+ }+}diff --git a/internal/httpapi/assistant_diagnostics.go b/internal/httpapi/assistant_diagnostics.gonew file mode 100644index 00000000..251c1599--- /dev/null+++ b/internal/httpapi/assistant_diagnostics.go@@ -0,0 +1,478 @@+package httpapi++import (+ "context"+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/url"+ "os/exec"+ "regexp"+ "sort"+ "strings"+ "sync"+ "time"++ "agentflow/internal/domain"+ "github.com/gin-gonic/gin"+)++type assistantDiagnosticsKey struct{}++type assistantDiagnosticsCollector struct {+ mu sync.Mutex+ report domain.AssistantDiagnostics+ sequence int+ timelineSequence int+ toolSequence int+ // persisted fingerprints the evidence last written by a running+ // checkpoint, so unchanged evidence is not rewritten every tick.+ persisted [sha256.Size]byte+ persistedAt time.Time+}++// assistantDiagnosticsRewriteInterval bounds how long a running turn's stored+// evidence may go without a rewrite; it must stay well below the 45s after+// which a silent row is reported as CHECKPOINT_LOST.+const assistantDiagnosticsRewriteInterval = 10 * time.Second++func newAssistantDiagnosticsCollector(g domain.AssistantGeneration) *assistantDiagnosticsCollector {+ environment := assistantDiagnosticEnvironment()+ d := &assistantDiagnosticsCollector{report: domain.AssistantDiagnostics{Version: 2, GenerationID: g.ID, SessionID: g.SessionID, StartedAt: g.StartedAt, Status: g.Status, Environment: &environment, Attempts: []domain.AssistantCLIAttempt{}}}+ d.appendTimelineLocked(domain.AssistantDiagnosticEvent{At: g.StartedAt, Source: "platform", Kind: "generation.started"})+ return d+}++func assistantDiagnosticsFrom(ctx context.Context) *assistantDiagnosticsCollector {+ d, _ := ctx.Value(assistantDiagnosticsKey{}).(*assistantDiagnosticsCollector)+ return d+}++func (d *assistantDiagnosticsCollector) snapshot(g domain.AssistantGeneration) domain.AssistantDiagnostics {+ d.mu.Lock()+ defer d.mu.Unlock()+ d.report.Status, d.report.UpdatedAt = g.Status, time.Now().UTC()+ if g.Failure != nil || g.Status == "cancelled" || g.Status == "completed" {+ d.report.Failure = g.Failure+ }+ // Deep copy bounded slices so a checkpoint never races with process output.+ raw, _ := json.Marshal(d.report)+ var out domain.AssistantDiagnostics+ _ = json.Unmarshal(raw, &out)+ domain.AnalyzeAssistantDiagnostics(&out)+ return out+}++// checkpointSnapshot returns the report for a running checkpoint and whether it+// must be written: evidence changed, or the rewrite interval elapsed.+func (d *assistantDiagnosticsCollector) checkpointSnapshot(g domain.AssistantGeneration) (domain.AssistantDiagnostics, bool) {+ report := d.snapshot(g)+ stable := report+ stable.UpdatedAt, stable.LastCheckpointAt = time.Time{}, nil+ raw, _ := json.Marshal(stable)+ sum := sha256.Sum256(raw)+ d.mu.Lock()+ defer d.mu.Unlock()+ now := time.Now()+ if g.Status == "running" && sum == d.persisted && now.Sub(d.persistedAt) < assistantDiagnosticsRewriteInterval {+ return report, false+ }+ d.persisted, d.persistedAt = sum, now+ return report, true+}++func (d *assistantDiagnosticsCollector) fail(ctx context.Context, err error, user domain.User) domain.AssistantFailure {+ f := classifyAssistantFailure(ctx, err)+ if d == nil {+ return f+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ // Unless the error itself names the cause, prefer the structured provider+ // failure captured before translation over keywords in the stderr tail:+ // the newest error event is the one that ended the turn.+ specific := false+ if err != nil && ctx.Err() == nil {+ _, specific = classifyAssistantFailureParts(domain.AssistantFailure{Code: "GENERATION_FAILED"}, err)+ }+ if !specific && (assistantFailureGeneric(f.Code) || f.Phase == "provider" || f.Phase == "connection") {+ if candidate, ok := d.structuredFailureLocked(ctx); ok {+ f = candidate+ }+ }+ if f.Code == "AUTHENTICATION_FAILED" && len(d.report.Attempts) > 0 {+ engine := d.report.Attempts[len(d.report.Attempts)-1].Engine+ if engine != assistantEngineCodeBuddy {+ f.Message = fmt.Sprintf("%s 请求鉴权失败,请检查个人配置后重试", assistantEngineLabel(engine))+ }+ }+ d.report.Failure = &f+ if err != nil {+ d.report.Error = sanitizeAssistantDiagnostic(err.Error(), user, 4096)+ }+ d.appendTimelineLocked(domain.AssistantDiagnosticEvent{Kind: "generation.failed", Source: "platform", Code: f.Code, Phase: f.Phase, Message: d.report.Error})+ return f+}++// structuredFailureLocked classifies the newest CLI error event, falling back+// to its HTTP status when the provider text matches no known wording.+func (d *assistantDiagnosticsCollector) structuredFailureLocked(ctx context.Context) (domain.AssistantFailure, bool) {+ for i := len(d.report.Attempts) - 1; i >= 0; i-- {+ attempt := d.report.Attempts[i]+ candidates := append([]domain.AssistantDiagnosticEvent{}, attempt.Events...)+ if attempt.FirstError != nil {+ candidates = append([]domain.AssistantDiagnosticEvent{*attempt.FirstError}, candidates...)+ }+ for j := len(candidates) - 1; j >= 0; j-- {+ e := candidates[j]+ if e.Kind == "provider.metadata" || !(e.StatusCode >= 400 || strings.Contains(e.Kind, "error") || strings.Contains(e.Kind, "fail")) {+ continue+ }+ candidate := classifyAssistantFailure(ctx, fmt.Errorf("%s %s", e.Code, e.Message))+ if assistantFailureGeneric(candidate.Code) && e.StatusCode >= 400 {+ candidate = classifyAssistantFailure(ctx, fmt.Errorf("http %d", e.StatusCode))+ if assistantFailureGeneric(candidate.Code) && e.StatusCode == http.StatusNotFound {+ candidate = classifyAssistantFailure(ctx, errors.New("model_not_found"))+ }+ }+ if !assistantFailureGeneric(candidate.Code) {+ return candidate, true+ }+ }+ }+ return domain.AssistantFailure{}, false+}++func (d *assistantDiagnosticsCollector) failureForMessage(message string) *domain.AssistantFailure {+ if d == nil {+ return nil+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ if d.report.Failure == nil || d.report.Failure.Message != message {+ d.report.Failure = &domain.AssistantFailure{Code: "GENERATION_FAILED", Phase: "orchestration", Message: message, Suggestion: "下载诊断信息交给管理员排查;重试前请检查已执行的操作。"}+ }+ f := *d.report.Failure+ return &f+}++type assistantDiagnosticAttempt struct {+ d *assistantDiagnosticsCollector+ id string+ user domain.User+}++func (d *assistantDiagnosticsCollector) termination() *domain.AssistantDiagnosticTermination {+ if d == nil {+ return nil+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ if d.report.Termination == nil {+ return nil+ }+ copy := *d.report.Termination+ return ©+}++func (d *assistantDiagnosticsCollector) currentAttemptID() string {+ if d == nil {+ return ""+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ for i := len(d.report.Attempts) - 1; i >= 0; i-- {+ if d.report.Attempts[i].Status == "running" {+ return d.report.Attempts[i].ID+ }+ }+ if n := len(d.report.Attempts); n > 0 {+ return d.report.Attempts[n-1].ID+ }+ return ""+}++func (d *assistantDiagnosticsCollector) begin(engine, model string, resume bool, user domain.User) *assistantDiagnosticAttempt {+ if d == nil {+ return nil+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ d.sequence+++ id := fmt.Sprintf("%s/%d", d.report.GenerationID, d.sequence)+ if len(d.report.Attempts) >= 16 {+ d.report.Attempts = d.report.Attempts[1:]+ d.dropLocked("attempts", 1)+ }+ d.report.Attempts = append(d.report.Attempts, domain.AssistantCLIAttempt{ID: id, Engine: engine, Model: sanitizeAssistantDiagnostic(model, user, 200), Resume: resume, StartedAt: time.Now().UTC(), Phase: "setup", Status: "running"})+ d.appendTimelineLocked(domain.AssistantDiagnosticEvent{Source: "platform", Kind: "cli.preparing", AttemptID: id, Phase: "setup"})+ return &assistantDiagnosticAttempt{d: d, id: id, user: user}+}++func (a *assistantDiagnosticAttempt) update(fn func(*domain.AssistantCLIAttempt)) {+ if a == nil {+ return+ }+ a.d.mu.Lock()+ defer a.d.mu.Unlock()+ for i := range a.d.report.Attempts {+ if a.d.report.Attempts[i].ID == a.id {+ fn(&a.d.report.Attempts[i])+ return+ }+ }+}++func (a *assistantDiagnosticAttempt) phase(phase string) {+ a.update(func(attempt *domain.AssistantCLIAttempt) { attempt.Phase = phase })+}++func (a *assistantDiagnosticAttempt) finish(err error) {+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ now := time.Now().UTC()+ attempt.FinishedAt = &now+ attempt.Status = "completed"+ if err != nil {+ attempt.Status = "failed"+ attempt.Error = sanitizeAssistantDiagnostic(err.Error(), a.user, 4096)+ if len([]rune(attempt.Error)) > 4096 {+ a.d.report.Truncated = true+ }+ if errors.Is(err, context.Canceled) {+ attempt.Status = "cancelled"+ }+ }+ a.d.appendTimelineLocked(domain.AssistantDiagnosticEvent{At: now, Source: "platform", Kind: "cli." + attempt.Status, AttemptID: a.id, Phase: attempt.Phase, Message: attempt.Error})+ })+}++// Process exit and generation outcome differ: a zero exit may have no result.+func (a *assistantDiagnosticAttempt) exited(err error) {+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ if err == nil {+ code := 0+ attempt.ExitCode = &code+ return+ }+ var exit *exec.ExitError+ if errors.As(err, &exit) {+ code := exit.ExitCode()+ attempt.ExitCode = &code+ }+ })+}++func (a *assistantDiagnosticAttempt) stderr(line string) {+ if a == nil {+ return+ }+ rawLine := line+ line = sanitizeAssistantDiagnostic(line, a.user, 1024)+ if strings.TrimSpace(line) == "" {+ return+ }+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ if len([]rune(rawLine)) > 1024 {+ a.d.dropLocked("stderrCharacters", len([]rune(rawLine))-1024)+ }+ if len(attempt.FirstStderr) < 8 {+ attempt.FirstStderr = append(attempt.FirstStderr, line)+ }+ attempt.Stderr = append(attempt.Stderr, line)+ if len(attempt.Stderr) > 20 {+ attempt.Stderr = attempt.Stderr[1:]+ a.d.dropLocked("stderrLines", 1)+ }+ })+ var entry struct {+ Level string `json:"level"`+ Target string `json:"target"`+ Fields struct {+ Message string `json:"message"`+ SamplingError string `json:"sampling_error"`+ } `json:"fields"`+ }+ if json.Unmarshal([]byte(rawLine), &entry) == nil && (entry.Level == "ERROR" || entry.Fields.SamplingError != "") {+ // Benign Codex streaming order logs stay in raw stderr but must not mask real errors.+ if entry.Fields.SamplingError == "" && entry.Target == "codex_core::util" && strings.Contains(entry.Fields.Message, "without active item") {+ return+ }+ kind := "cli.stderr.error"+ message := entry.Fields.Message+ if entry.Fields.SamplingError != "" {+ kind = "cli.stderr.sampling_error"+ if message != "" {+ message += ": " + entry.Fields.SamplingError+ } else {+ message = entry.Fields.SamplingError+ }+ }+ e := domain.AssistantDiagnosticEvent{At: time.Now().UTC(), Kind: kind, Message: sanitizeAssistantDiagnostic(message, a.user, 1024)}+ diagnosticTextMetadata(&e)+ record := true+ a.update(func(attempt *domain.AssistantCLIAttempt) {+ if len(attempt.Events) > 0 {+ last := attempt.Events[len(attempt.Events)-1]+ record = last.Message != e.Message || last.RequestID != e.RequestID+ }+ })+ if record {+ a.recordEvent(e)+ }+ }+}++// Inspect only protocol metadata containers. Never keep assistant text, tool+// input/output, headers, config, argv or the original stdout JSON.+func (a *assistantDiagnosticAttempt) protocol(line string) {+ if a == nil {+ return+ }+ if len(line) > 256<<10 {+ a.update(func(*domain.AssistantCLIAttempt) { a.d.report.Truncated = true })+ return+ }+ var raw map[string]any+ if json.Unmarshal([]byte(line), &raw) != nil {+ return+ }+ a.nativeMetadata(raw)+ e := domain.AssistantDiagnosticEvent{At: time.Now().UTC()}+ var inspect func(map[string]any, int)+ inspect = func(v map[string]any, depth int) {+ if depth > 5 {+ return+ }+ for _, key := range []string{"type", "method"} {+ if s, _ := v[key].(string); s != "" && (strings.Contains(s, "error") || strings.Contains(s, "failed") || strings.Contains(s, "retry") || strings.Contains(s, "warning")) {+ e.Kind = sanitizeAssistantDiagnostic(s, a.user, 120)+ }+ }+ for _, field := range []struct {+ key string+ dest *string+ }{{"requestId", &e.RequestID}, {"request_id", &e.RequestID}, {"traceId", &e.TraceID}, {"trace_id", &e.TraceID}, {"errorCode", &e.Code}, {"providerErrorCode", &e.Code}, {"errorPhase", &e.Phase}} {+ if s, _ := v[field.key].(string); s != "" {+ *field.dest = sanitizeAssistantDiagnostic(s, a.user, 160)+ }+ }+ if s, _ := v["code"].(string); s != "" && e.Code == "" {+ e.Code = sanitizeAssistantDiagnostic(s, a.user, 160)+ }+ for _, key := range []string{"statusCode", "status_code", "httpStatusCode"} {+ if n, ok := v[key].(float64); ok && n >= 100 && n <= 599 {+ e.StatusCode = int(n)+ }+ }+ for _, key := range []string{"retryable", "willRetry"} {+ if b, ok := v[key].(bool); ok {+ value := b+ e.Retryable = &value+ }+ }+ for _, key := range []string{"payload", "params", "data", "error", "attribution", "turn", "codexErrorInfo", "httpConnectionFailed", "responseStreamDisconnected", "responseStreamConnectionFailed"} {+ if nested, ok := v[key].(map[string]any); ok {+ if key == "error" {+ e.Kind = "provider.error"+ }+ inspect(nested, depth+1)+ }+ }+ if e.Kind != "" {+ for _, key := range []string{"message", "providerErrorMessage", "error"} {+ if s, _ := v[key].(string); s != "" {+ e.Message = sanitizeAssistantDiagnostic(s, a.user, 1024)+ }+ }+ }+ }+ inspect(raw, 0)+ diagnosticTextMetadata(&e)+ if e.Kind == "" && e.RequestID == "" && e.TraceID == "" && e.StatusCode == 0 {+ return+ }+ if e.Kind == "" {+ e.Kind = "provider.metadata"+ }+ a.recordEvent(e)+}++var (+ diagnosticANSI = regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]`)+ diagnosticPEM = regexp.MustCompile(`(?s)-----BEGIN [^-]*PRIVATE KEY-----.*?(?:-----END [^-]*PRIVATE KEY-----|$)`)+ diagnosticBearer = regexp.MustCompile(`(?i)\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+`)+ diagnosticSecret = regexp.MustCompile(`(?i)((?:["']?(?:[a-z0-9_-]*(?:api[_-]?key|auth[_-]?token|access[_-]?token|refresh[_-]?token|password|passwd|client[_-]?secret)|authorization|cookie|set-cookie|token|secret)["']?)\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)`)+ diagnosticKey = regexp.MustCompile(`\b(?:sk-[A-Za-z0-9_-]{8,}|ghp_[A-Za-z0-9]+|github_pat_[A-Za-z0-9_]+|glpat-[A-Za-z0-9_-]+)\b`)+ diagnosticURL = regexp.MustCompile(`https?://[^\s<>"']+`)+ diagnosticPath = regexp.MustCompile(`(?:/(?:Users|home|root|tmp|private|var|data|workspace|workspaces|opt|srv)/|[A-Za-z]:\\)[^\s"'<>;,|]+`)+)++func sanitizeAssistantDiagnostic(text string, user domain.User, limit int) string {+ secrets := []string{user.CodeBuddyAPIKey, user.CodexAPIKey, user.ClaudeCodeAPIKey, user.GitToken, user.GongfengRefreshToken}+ for _, credential := range user.AgentCLICredentials {+ secrets = append(secrets, credential.APIKey)+ }+ sort.Slice(secrets, func(i, j int) bool { return len(secrets[i]) > len(secrets[j]) })+ for _, secret := range secrets {+ if secret != "" {+ text = strings.ReplaceAll(text, secret, "<redacted>")+ }+ }+ text = diagnosticANSI.ReplaceAllString(text, "")+ text = diagnosticPEM.ReplaceAllString(text, "<redacted private key>")+ text = diagnosticBearer.ReplaceAllString(text, "$1 <redacted>")+ text = diagnosticSecret.ReplaceAllString(text, "${1}<redacted>")+ text = diagnosticKey.ReplaceAllString(text, "<redacted>")+ text = diagnosticURL.ReplaceAllStringFunc(text, func(raw string) string {+ u, err := url.Parse(raw)+ if err != nil {+ return "<redacted URL>"+ }+ u.User, u.RawQuery, u.Fragment = nil, "", ""+ // Session MCP paths can contain authentication tokens.+ if strings.Contains(u.Path, "/mcp/") {+ u.Path, u.RawPath = "/mcp/<redacted>", ""+ }+ return u.String()+ })+ text = diagnosticPath.ReplaceAllString(text, "<path>")+ return truncateRunes(text, limit)+}++func (h *assistantHandlers) generationDiagnostics(c *gin.Context) {+ user, ok := h.requestUser(c.Request, true)+ if !ok {+ c.JSON(401, gin.H{"error": "请先登录"})+ return+ }+ // Like attachments outside the transcript, error excerpts require project+ // membership. Public project-conversation links expose only the safe summary.+ ownerID, _, err := h.conversationScope(c, c.Param("id"), "", "", user.ID)+ if err != nil {+ c.JSON(403, gin.H{"error": err.Error()})+ return+ }+ id := c.Param("generationId")+ report, ok := h.repo.AssistantDiagnostics(ownerID, c.Param("id"), id)+ if !ok {+ c.JSON(404, gin.H{"error": "该轮次没有可用的诊断记录"})+ return+ }+ if value, live := assistantLiveGenerations.Load(id); live {+ l := value.(*assistantLiveGeneration)+ if l.diagnostics != nil {+ report = l.diagnostics()+ }+ }+ c.Header("Cache-Control", "no-store")+ if c.Query("download") == "1" {+ data, _ := json.MarshalIndent(report, "", " ")+ c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="loopforge-diagnostics-%s.json"`, url.PathEscape(report.GenerationID)))+ c.Header("X-Content-Type-Options", "nosniff")+ c.Data(200, "application/json; charset=utf-8", data)+ return+ }+ c.JSON(200, report)+}diff --git a/internal/httpapi/assistant_diagnostics_checkpoint_test.go b/internal/httpapi/assistant_diagnostics_checkpoint_test.gonew file mode 100644index 00000000..55eeb11a--- /dev/null+++ b/internal/httpapi/assistant_diagnostics_checkpoint_test.go@@ -0,0 +1,106 @@+package httpapi++import (+ "testing"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/runtime"+)++// checkpointRunningGeneration renews the lease every tick but rewrites the+// stored diagnostic payload only when the evidence changed.+func TestAssistantCheckpointRunningGenerationHeartbeatsUnchangedEvidence(t *testing.T) {+ st := cvAStore(t)+ h := &assistantHandlers{deps: &deps{repo: st}}+ const owner = 31+ if err := st.PutAssistantSession(owner, domain.AssistantSession{ID: "ckpt-session"}); err != nil {+ t.Fatal(err)+ }+ g := domain.AssistantGeneration{ID: "ckpt-turn", SessionID: "ckpt-session", UserID: owner, Status: "running", StartedAt: time.Now().UTC()}+ if err := st.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ payload := func() string {+ t.Helper()+ var raw []byte+ if err := st.DB.Table("assistant_diagnostics").Select("payload").Where("generation_id = ?", g.ID).Row().Scan(&raw); err != nil {+ t.Fatal(err)+ }+ return string(raw)+ }+ leaseAt := func() time.Time {+ t.Helper()+ var at time.Time+ if err := st.DB.Table("assistant_generations").Select("updated_at").Where("generation_id = ?", g.ID).Row().Scan(&at); err != nil {+ t.Fatal(err)+ }+ return at+ }++ d := newAssistantDiagnosticsCollector(g)+ d.platform("cli.preparing", "first evidence", domain.User{})+ if err := h.checkpointRunningGeneration(g, d); err != nil {+ t.Fatal(err)+ }+ first := payload()+ firstLease := leaseAt()++ time.Sleep(5 * time.Millisecond)+ if err := h.checkpointRunningGeneration(g, d); err != nil {+ t.Fatal(err)+ }+ if got := payload(); got != first {+ t.Fatal("unchanged evidence rewrote the diagnostic payload")+ }+ if !leaseAt().After(firstLease) {+ t.Fatal("heartbeat did not renew the generation lease")+ }++ d.platform("cli.started", "second evidence", domain.User{})+ if err := h.checkpointRunningGeneration(g, d); err != nil {+ t.Fatal(err)+ }+ stored, ok := st.AssistantDiagnostics(owner, g.SessionID, g.ID)+ if !ok || payload() == first || len(stored.Timeline) < 2 || stored.Timeline[len(stored.Timeline)-1].Message != "second evidence" {+ t.Fatalf("changed evidence not written: %+v", stored.Timeline)+ }++ // Without a collector the checkpoint still writes (a default report).+ if err := h.checkpointRunningGeneration(g, nil); err != nil {+ t.Fatal(err)+ }+ g.Status = "completed"+ if err := h.checkpointRunningGeneration(g, d); err != nil {+ t.Fatal(err)+ }+ if err := h.checkpointRunningGeneration(g, d); err == nil {+ t.Fatal("checkpoint accepted a finished generation")+ }+}++// Generic agent CLIs read their endpoint from AgentCLICredentials; a key+// embedded in its path, userinfo or query must not reach the report.+func TestAssistantDiagnosticAgentCLIEndpointKeepsOnlySchemeAndHost(t *testing.T) {+ g := domain.AssistantGeneration{ID: "agent-cli-endpoint", SessionID: "s", Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ user := domain.User{AgentCLICredentials: map[string]domain.AgentCLICredential{+ runtime.AgentCLIKimi: {BaseURL: "https://u:[email protected]/v1/path-secret-value?key=q#f", Protocol: "openai"},+ runtime.AgentCLIDeepSeek: {BaseURL: "not a url"},+ }}+ a := d.begin(runtime.AgentCLIKimi, "model", false, user)+ a.configure("/nonexistent/kimi", assistantCLIRequest{Model: runtime.AgentCLIKimi + ":model"})+ b := d.begin(runtime.AgentCLIDeepSeek, "model", false, user)+ b.configure("/nonexistent/dsh", assistantCLIRequest{Model: runtime.AgentCLIDeepSeek + ":model"})+ report := d.snapshot(g)+ if len(report.Attempts) != 2 {+ t.Fatalf("attempts = %+v", report.Attempts)+ }+ if got := report.Attempts[0]; got.Endpoint != "https://kimi-gateway.example" || got.Protocol != "openai" {+ t.Fatalf("agent CLI endpoint kept path or credentials: %+v", got)+ }+ // A value without a host is not a URL and is reported as configured.+ if got := report.Attempts[1].Endpoint; got != "not a url" {+ t.Fatalf("hostless endpoint = %q", got)+ }+}diff --git a/internal/httpapi/assistant_diagnostics_test.go b/internal/httpapi/assistant_diagnostics_test.gonew file mode 100644index 00000000..46f3381e--- /dev/null+++ b/internal/httpapi/assistant_diagnostics_test.go@@ -0,0 +1,266 @@+package httpapi++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+ "github.com/gin-gonic/gin"+)++func TestAssistantDiagnosticsCaptureNativeFailureAndExit(t *testing.T) {+ dir := t.TempDir()+ bin := filepath.Join(dir, "codebuddy")+ script := `#!/bin/sh+echo 'Authorization: Bearer header-private-value' >&2+echo 'OPENAI_API_KEY=known-private-value password="unknown-password" /Users/example/private/config.json' >&2+echo '{"type":"error","error":{"message":"rate limit reached","code":"rate_limit","statusCode":429,"requestId":"request-example","traceId":"trace-example","retryable":true}}'+exit 7+`+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin)+ g := domain.AssistantGeneration{ID: "diagnostic-turn", SessionID: "diagnostic-session", Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ ctx := context.WithValue(context.Background(), assistantDiagnosticsKey{}, d)+ user := domain.User{ID: 1, CodeBuddyAPIKey: "known-private-value"}+ _, _, err := runAssistantCLI(ctx, assistantCLIRequest{Prompt: "private prompt must never be exported", SessionRoot: dir}, user, nil)+ if err == nil {+ t.Fatal("nonzero CLI was accepted")+ }+ f := d.fail(ctx, err, user)+ g.Failure, g.Status = &f, "failed"+ report := d.snapshot(g)+ if f.Code != "RATE_LIMITED" || len(report.Attempts) != 1 {+ t.Fatalf("wrong failure: %+v", report)+ }+ a := report.Attempts[0]+ if a.ExitCode == nil || *a.ExitCode != 7 || a.FinishedAt == nil || a.Status != "failed" || len(a.Events) != 1 {+ t.Fatalf("lost process outcome: %+v", a)+ }+ e := a.Events[0]+ if e.RequestID != "request-example" || e.TraceID != "trace-example" || e.StatusCode != 429 || e.Retryable == nil || !*e.Retryable {+ t.Fatalf("lost native IDs: %+v", e)+ }+ raw, _ := json.Marshal(report)+ for _, secret := range []string{"known-private-value", "header-private-value", "unknown-password", "/Users/example", "private prompt must never be exported", "--print"} {+ if bytes.Contains(raw, []byte(secret)) {+ t.Fatalf("diagnostics leaked %q: %s", secret, raw)+ }+ }+ // Readers must receive immutable snapshots, even while another attempt runs.+ d.begin("codebuddy", "second-model", true, user).stderr("new output")+ if len(report.Attempts) != 1 || len(report.Attempts[0].Stderr) != 2 {+ t.Fatal("snapshot changed after another attempt")+ }+}++func TestAssistantDiagnosticSanitizationAndBounds(t *testing.T) {+ user := domain.User{GitToken: "git-secret", GongfengRefreshToken: "refresh-secret", AgentCLICredentials: map[string]domain.AgentCLICredential{"zcode": {APIKey: "agent-secret"}}}+ pemBlock := "-----BEGIN " + "PRIVATE KEY-----\nprivate-key-content\n-----END " + "PRIVATE KEY-----"+ input := `{"api_key":"unrecognized-key","Authorization":"Bearer unknown-bearer","password":"unknown-pass"}+https://username:[email protected]/v1?signature=url-secret#fragment-secret+git-secret refresh-secret agent-secret sk-abcdefghijklmnopqrstuvwxyz+` + pemBlock + `+/home/user/.config/private.json C:\Users\user\private.json`+ out := sanitizeAssistantDiagnostic(input, user, 8192)+ for _, secret := range []string{"unrecognized-key", "unknown-bearer", "unknown-pass", "url-pass", "url-secret", "fragment-secret", "git-secret", "refresh-secret", "agent-secret", "sk-abc", "private-key-content", "/home/user", "C:\\Users"} {+ if strings.Contains(out, secret) {+ t.Fatalf("leaked %q: %s", secret, out)+ }+ }+ g := domain.AssistantGeneration{ID: "bounded", Status: "running"}+ d := newAssistantDiagnosticsCollector(g)+ for i := 0; i < 20; i++ {+ a := d.begin("codebuddy", "model", false, user)+ for j := 0; j < 80; j++ {+ a.stderr(strings.Repeat("x", 2048))+ a.protocol(`{"type":"error","error":{"message":"sample failure","requestId":"req-example"},"input":{"password":"never keep tool input"}}`)+ }+ }+ report := d.snapshot(g)+ if len(report.Attempts) != 16 || !report.Truncated {+ t.Fatal("attempt archive is not bounded")+ }+ for _, a := range report.Attempts {+ if len(a.Stderr) > 20 || len(a.Events) > 40 {+ t.Fatal("attempt is not bounded")+ }+ }+ raw, _ := json.Marshal(report)+ if bytes.Contains(raw, []byte("never keep tool input")) {+ t.Fatal("retained tool input")+ }+}++func TestAssistantDiagnosticDownloadChecksSessionAndOwner(t *testing.T) {+ t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")+ h, owner := workbenchFixture(t)+ if err := h.repo.PutAssistantSession(owner.ID, domain.AssistantSession{ID: "diag-session", ProjectID: "workbench"}); err != nil {+ t.Fatal(err)+ }+ g := domain.AssistantGeneration{ID: "diag-one", SessionID: "diag-session", UserID: owner.ID, Status: "running", StartedAt: time.Now().UTC()}+ if err := h.repo.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ d := newAssistantDiagnosticsCollector(g)+ f := d.fail(context.Background(), errors.New("network interrupted"), owner)+ g.Status, g.Failure = "failed", &f+ if err := h.repo.CheckpointAssistantGeneration(g, d.snapshot(g)); err != nil {+ t.Fatal(err)+ }+ request := func(user domain.User, session string) (int, string, string) {+ c, w := workbenchContext(user, "GET", "/diagnostics?download=1", bytes.NewBuffer(nil))+ c.Params = gin.Params{{Key: "id", Value: session}, {Key: "generationId", Value: g.ID}}+ h.generationDiagnostics(c)+ return w.Code, w.Body.String(), w.Header().Get("Content-Disposition")+ }+ status, body, disposition := request(owner, g.SessionID)+ if status != 200 || !strings.Contains(disposition, "attachment;") || !strings.Contains(body, "NETWORK_ERROR") {+ t.Fatalf("download failed: %d %s %s", status, disposition, body)+ }+ if err := h.repo.PutUser(domain.User{LoginName: "diag-outsider"}); err != nil {+ t.Fatal(err)+ }+ outsider, _ := h.repo.UserByLoginName("diag-outsider")+ if status, _, _ := request(outsider, g.SessionID); status < 400 {+ t.Fatal("other user downloaded private diagnostics")+ }+ if status, _, _ := request(owner, "different-session"); status < 400 {+ t.Fatal("generation ID bypassed session scope")+ }+}++func TestAssistantDiagnosticClassifiesProviderMetadataBeforeTranslation(t *testing.T) {+ g := domain.AssistantGeneration{ID: "native", Status: "running"}+ d := newAssistantDiagnosticsCollector(g)+ a := d.begin("zcode", "model", false, domain.User{})+ data, err := os.ReadFile("../runtime/testdata/zcode-0.17.1-stream-401-sample.ndjson")+ if err != nil {+ t.Fatal(err)+ }+ for _, line := range strings.Split(string(data), "\n") {+ a.protocol(line)+ }+ f := d.fail(context.Background(), errors.New("exit status 1"), domain.User{})+ if f.Code != "AUTHENTICATION_FAILED" || strings.Contains(f.Message, "CodeBuddy") {+ t.Fatalf("wrong provider failure: %+v", f)+ }+ g.Status, g.Failure = "failed", &f+ report := d.snapshot(g)+ raw, _ := json.Marshal(report)+ if !bytes.Contains(raw, []byte("ece088ae-92ca-43a2-ae2d-d8ef1ac86680")) || !bytes.Contains(raw, []byte("864e141b-aa26-4c64-9d32-759185219185")) {+ t.Fatal("dropped native request/trace ID")+ }+ if bytes.Contains(raw, []byte("requestHeaders")) || bytes.Contains(raw, []byte("baseURL")) {+ t.Fatal("retained provider configuration or headers")+ }+}++func TestAssistantDiagnosticFirstErrorIgnoresBenignNoiseAndUpgradesPlaceholder(t *testing.T) {+ g := domain.AssistantGeneration{ID: "first-error-turn", SessionID: "s1", Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ a := d.begin("codex", "hy4", false, domain.User{CodexAPIKey: "secret-codex-key"})+ a.stderr(`{"timestamp":"2026-11-13T07:14:22Z","level":"ERROR","fields":{"message":"ReasoningSummaryDelta without active item"},"target":"codex_core::util"}`)+ if snap := d.snapshot(g); len(snap.Attempts[0].Events) != 0 || snap.Attempts[0].FirstError != nil {+ t.Fatalf("benign codex delta warning polluted structured error events: %+v", snap.Attempts[0])+ }+ a.protocol(`{"method":"error","params":{"willRetry":true,"error":{"message":"Reconnecting... 1/5"}}}`)+ a.stderr(`{"timestamp":"2026-11-13T07:14:23Z","level":"WARN","fields":{"message":"stream disconnected - retrying","sampling_error":"unexpected status 401 Unauthorized: Invalid token (request id: req-real-401), url: https://api.example.com/v1/responses"},"target":"codex_core::responses_retry"}`)+ for i := 0; i < 45; i++ {+ a.stderr("trailing warning line")+ a.protocol(`{"method":"error","params":{"willRetry":true,"error":{"message":"Reconnecting... later"}}}`)+ }+ f := d.fail(context.Background(), errors.New("exit status 1"), domain.User{})+ g.Status, g.Failure = "failed", &f+ snap := d.snapshot(g)+ first := snap.Attempts[0].FirstError+ if first == nil || first.StatusCode != 401 || first.RequestID != "req-real-401" {+ t.Fatalf("FirstError did not upgrade to substantive root cause: %+v", first)+ }+ if f.Code != "AUTHENTICATION_FAILED" {+ t.Fatalf("expected fallback classification to use FirstError after event rotation, got %+v", f)+ }+ if len(snap.Attempts[0].FirstStderr) != 8 || snap.Dropped["stderrLines"] == 0 || snap.Dropped["protocolEvents"] == 0 {+ t.Fatalf("expected head stderr and drop counters, got firstStderr=%d dropped=%v", len(snap.Attempts[0].FirstStderr), snap.Dropped)+ }+}++func TestAssistantDiagnosticCapturesGatewayToolLifecycleAndRedactsSuccess(t *testing.T) {+ h, u := workbenchFixture(t)+ u.GitToken = "private-git-token"+ g := domain.AssistantGeneration{ID: "gateway-diag", SessionID: "gateway-sess", UserID: u.ID, Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ attempt := d.begin("codex", "gpt-5.6", false, u)+ ctx := context.WithValue(context.Background(), assistantDiagnosticsKey{}, d)+ sess, files, err := startAgentToolSession(ctx, u, "workbench", AgentToolAssistant, assistantExecModeForApproval(AssistantApprovalConfirm), "", nil, nil, t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ defer sess.Close()+ defer files.Cleanup()++ gw := &agentToolGateway{deps: h.deps}+ _ = gw.handleRPC(ctx, sess, agentToolRPCRequest{JSONRPC: "2.0", ID: 1, Method: "initialize"})+ _ = gw.handleRPC(ctx, sess, agentToolRPCRequest{JSONRPC: "2.0", ID: 2, Method: "tools/list"})+ okParams, _ := json.Marshal(map[string]any{"name": "workbench_tool_schema", "arguments": map[string]any{"name": "projects_get", "secretArg": "never-log-tool-arg"}})+ okResp := gw.handleRPC(ctx, sess, agentToolRPCRequest{JSONRPC: "2.0", ID: 3, Method: "tools/call", Params: okParams})+ if okResp.Error != nil {+ t.Fatalf("unexpected gateway error: %+v", okResp.Error)+ }+ failParams, _ := json.Marshal(map[string]any{"name": "agentflow__issues_delete", "arguments": map[string]any{"path": map[string]any{"id": "1"}}})+ _ = gw.handleRPC(ctx, sess, agentToolRPCRequest{JSONRPC: "2.0", ID: 4, Method: "tools/call", Params: failParams})+ attempt.finish(nil)++ g.Status = "completed"+ report := d.snapshot(g)+ if len(report.Tools) != 2 {+ t.Fatalf("expected 2 gateway tools, got %+v", report.Tools)+ }+ if report.Tools[0].Status != "completed" || report.Tools[0].Error != "" || report.Tools[0].AttemptID != attempt.id {+ t.Fatalf("unexpected successful tool record: %+v", report.Tools[0])+ }+ if report.Tools[1].Status != "failed" || !strings.Contains(report.Tools[1].Error, "unknown tool") {+ t.Fatalf("missing failed gateway tool reason: %+v", report.Tools[1])+ }+ raw, _ := json.Marshal(report)+ if bytes.Contains(raw, []byte("never-log-tool-arg")) || bytes.Contains(raw, []byte("inputSchema")) || bytes.Contains(raw, []byte("private-git-token")) {+ t.Fatalf("gateway diagnostics leaked arguments, successful output, or secret: %s", raw)+ }+ if !bytes.Contains(raw, []byte("mcp.gateway_initialized")) || !bytes.Contains(raw, []byte("mcp.tools_listed")) {+ t.Fatalf("missing gateway timeline milestones: %s", raw)+ }+}++func TestAssistantDiagnosticRecordsUserCancellationTermination(t *testing.T) {+ h, u := workbenchFixture(t)+ entered := make(chan struct{}, 1)+ h.generate = func(ctx context.Context, _ string, _ domain.User) (string, error) {+ entered <- struct{}{}+ <-ctx.Done()+ return "", ctx.Err()+ }+ c, rec := workbenchContext(u, "POST", "/api/assistant/generations", bytes.NewBufferString(`{"projectId":"workbench","sessionId":"cancel-diag-chat","messages":[{"role":"user","content":"测试停止归因"}]}`))+ h.startGeneration(c)+ if rec.Code != 202 {+ t.Fatalf("start: %d %s", rec.Code, rec.Body.String())+ }+ <-entered+ g, _ := h.repo.AssistantGeneration(u.ID, "cancel-diag-chat")+ if err := h.repo.CancelAssistantGeneration(u.ID, "cancel-diag-chat", g.ID); err != nil {+ t.Fatal(err)+ }+ waitGeneration(t, h, u.ID, "cancel-diag-chat", func(gen domain.AssistantGeneration) bool { return gen.Status == "cancelled" })+ report, ok := h.repo.AssistantDiagnostics(u.ID, "cancel-diag-chat", g.ID)+ if !ok || report.Termination == nil || report.Termination.Code != "USER_CANCELLED" {+ t.Fatalf("expected USER_CANCELLED in persisted diagnostics, got %+v", report)+ }+}diff --git a/internal/httpapi/assistant_direct_generation.go b/internal/httpapi/assistant_direct_generation.goindex 8f555427..ac3ba1b6 100644--- a/internal/httpapi/assistant_direct_generation.go+++ b/internal/httpapi/assistant_direct_generation.go@@ -10,12 +10,13 @@ import (// Synchronous shared chat must occupy the same durable slot as /generations.// Otherwise a second process can save a pending turn while the first CLI writes// the shared transcript. A local file lock additionally fences stale writers.-func (h *assistantHandlers) claimDirectSharedGeneration(ctx context.Context, req assistantRequest, ownerID int64, actor domain.User, cancel context.CancelFunc) (domain.AssistantGeneration, func(bool), error) {+func (h *assistantHandlers) claimDirectSharedGeneration(ctx context.Context, req assistantRequest, ownerID int64, actor domain.User, cancel context.CancelFunc) (domain.AssistantGeneration, *assistantDiagnosticsCollector, func(bool), error) {g := domain.AssistantGeneration{ID: newAssistantSessionID(), SessionID: req.SessionID, UserID: ownerID, ActorID: actor.ID, ActorName: actor.LoginName, ProjectID: req.ProjectID, Status: "running", StartedAt: time.Now().UTC()}pending := assistantConversation{ID: req.SessionID, Shared: true, ProjectID: req.ProjectID, Model: req.Model, Effort: req.Effort, RunID: req.RunID, Messages: req.Messages}if err := h.repo.BeginAssistantGeneration(g, pending); err != nil {- return g, nil, err+ return g, nil, nil, err}+ diagnostics := newAssistantDiagnosticsCollector(g)untrack := inflightTasks.Add()stop, done := make(chan struct{}), make(chan struct{})go func() {@@ -30,18 +31,30 @@ func (h *assistantHandlers) claimDirectSharedGeneration(ctx context.Context, reqreturncase <-ticker.C:current, ok := h.repo.AssistantGeneration(ownerID, req.SessionID)- if !ok || current.ID != g.ID || current.Status != "running" || current.CancelRequested {+ if !ok || current.ID != g.ID {+ diagnostics.terminate("GENERATION_SUPERSEDED", "当前生成记录已被替换或移除", actor)cancel()return}- if err := h.repo.CheckpointAssistantGeneration(g); err != nil {+ if current.Status != "running" {+ diagnostics.terminate("GENERATION_STATUS_CHANGED", "生成状态已变更为 "+current.Status, actor)+ cancel()+ return+ }+ if current.CancelRequested {+ diagnostics.terminate("USER_CANCELLED", "用户主动停止了本轮生成", actor)+ cancel()+ return+ }+ if err := h.checkpointRunningGeneration(g, diagnostics); err != nil {+ diagnostics.terminate("CHECKPOINT_FAILED", "保存生成检查点失败:"+err.Error(), actor)cancel()return}}}}()- return g, func(completed bool) {+ return g, diagnostics, func(completed bool) {defer untrack()close(stop)<-done@@ -54,6 +67,12 @@ func (h *assistantHandlers) claimDirectSharedGeneration(ctx context.Context, reqg.Status = "cancelled"}}- _ = h.repo.CheckpointAssistantGeneration(g)+ if g.Status == "failed" {+ g.Failure = diagnostics.snapshot(g).Failure+ if g.Failure != nil {+ g.Error = g.Failure.Message+ }+ }+ _ = h.repo.CheckpointAssistantGeneration(g, diagnostics.snapshot(g))}, nil}diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.goindex aa479378..421ccb75 100644--- a/internal/httpapi/assistant_engine_cli.go+++ b/internal/httpapi/assistant_engine_cli.go@@ -60,7 +60,11 @@ func assistantEngineConfigDir(engine string) string {// well-known install locations, then a CLI installed from a failed conversation.func resolveAssistantEngineBin(engine string) (string, error) {if engine == assistantEngineCodeBuddy {- return resolveCodeBuddyBin()+ bin, err := resolveCodeBuddyBin()+ if err != nil && (strings.Contains(err.Error(), "未找到") || strings.Contains(err.Error(), "尚未安装")) {+ return "", assistantCLIMissingError{engine: engine, binary: "codebuddy"}+ }+ return bin, err}binary, override, managed := "codex", "AGENTFLOW_CODEX_BIN", "codex"if engine == assistantEngineClaude {diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.goindex dcb2e92f..5890d589 100644--- a/internal/httpapi/assistant_failure.go+++ b/internal/httpapi/assistant_failure.go@@ -5,8 +5,12 @@ import ("encoding/json""errors""net/http"+ "os"+ "os/exec"+ "regexp""strings"+ "agentflow/internal/domain""agentflow/internal/runtime")@@ -58,23 +62,115 @@ func assistantCLIStreamFailure(line string) error {return nil}-// Only return fixed user-facing messages: CLI errors and stderr may contain-// credentials or internal paths and must never be copied into the response.+// Summaries use fixed wording; sanitized provider details are available in the+// diagnostic report instead of interpolating arbitrary stderr into the UI.func assistantGenerationFailure(ctx context.Context, err error) (int, string) {+ failure := classifyAssistantFailure(ctx, err)+ status := http.StatusBadGatewayif ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {- return http.StatusGatewayTimeout, "生成已取消或超时,请重试"+ status = http.StatusGatewayTimeout+ }+ return status, failure.Message+}++func classifyAssistantFailure(ctx context.Context, err error) domain.AssistantFailure {+ f := domain.AssistantFailure{Code: "GENERATION_FAILED", Phase: "execution", Message: "AI 助手生成失败,具体原因见诊断信息", Suggestion: "下载诊断信息交给管理员排查;重试前请检查已执行的操作。"}+ if err == nil {+ return f+ }+ if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {+ f.Code, f.Message = "EXECUTION_TIMEOUT", "生成已取消或超时,请重试"+ return f+ }+ if ctx.Err() != nil || errors.Is(err, context.Canceled) {+ f.Code, f.Message = "EXECUTION_CANCELLED", "生成已取消或超时,请重试"+ return f}if errors.Is(err, runtime.ErrMaxTurns) || assistantCLIMaxTurns(err.Error()) {- return http.StatusBadGateway, "AI 助手已达到执行轮数上限,未能完成回答,请重试"+ f.Code, f.Message = "EXECUTION_LIMIT", "AI 助手已达到执行轮数上限,未能完成回答,请重试"+ return f+ }+ var missing assistantCLIMissingError+ if errors.As(err, &missing) {+ f.Code, f.Phase, f.Message, f.Suggestion = "CLI_NOT_INSTALLED", "setup", missing.Error(), "请管理员检查执行器的安装与配置。"+ return f+ }+ // The process error usually carries the CLI's stderr tail. Classify the+ // error itself first so unrelated stderr words (an earlier retry warning,+ // sandbox notices) cannot outrank the real cause; stderr is the fallback.+ f, _ = classifyAssistantFailureParts(f, err)+ return f+}++// assistantFailureGeneric reports codes that only say "the CLI failed" and+// leave room for a more specific cause from stderr or structured events.+func assistantFailureGeneric(code string) bool {+ return code == "GENERATION_FAILED" || code == "CLI_EXIT_NONZERO" || code == "MISSING_RESULT"+}++// classifyAssistantFailureParts classifies the error text before its stderr+// tail first; specific reports whether that part alone named the cause.+func classifyAssistantFailureParts(f domain.AssistantFailure, err error) (domain.AssistantFailure, bool) {+ head, tail, _ := strings.Cut(err.Error(), "; stderr=")+ c := classifyAssistantFailureText(f, err, head)+ if !assistantFailureGeneric(c.Code) || tail == "" {+ return c, !assistantFailureGeneric(c.Code)+ }+ if t := classifyAssistantFailureText(f, err, tail); !assistantFailureGeneric(t.Code) {+ return t, false}- message := strings.ToLower(err.Error())- if strings.Contains(message, "unauthorized") || strings.Contains(message, "invalid api key") || strings.Contains(message, "api key expired") || strings.Contains(message, "invalid credential") || strings.Contains(message, "status code 401") || strings.Contains(message, "http 401") {- return http.StatusBadGateway, "CodeBuddy 凭据无效或已过期,请检查个人配置后重试"+ return c, false+}++var assistantModelMissingRe = regexp.MustCompile("(?i)\\bmodel\\s+[`'\"]?[^\\s`'\"]*[`'\"]?\\s*(?:does not exist|not found|is not available)")++func classifyAssistantFailureText(f domain.AssistantFailure, err error, text string) domain.AssistantFailure {+ message := strings.ToLower(text)+ has := func(parts ...string) bool {+ for _, p := range parts {+ if strings.Contains(message, p) {+ return true+ }+ }+ return false}- if errors.Is(err, errAssistantMissingResult) {- return http.StatusBadGateway, "AI 助手生成中断,未返回完整回答,请重试"+ switch {+ case has("insufficient_quota", "quota exceeded", "credit balance", "billing", "额度不足", "余额不足"):+ f.Code, f.Phase, f.Message, f.Suggestion = "QUOTA_EXCEEDED", "provider", "模型服务额度不足,无法继续生成", "请检查模型服务的余额或额度。"+ case has("rate limit", "rate_limit", "too many requests", "http 429", "status 429", "status code 429", "status=429"):+ f.Code, f.Phase, f.Message, f.Suggestion = "RATE_LIMITED", "provider", "模型服务请求过于频繁(429)", "请稍后再试,或检查模型服务的限流配置。"+ case errors.Is(err, errAssistantCredentialRejected), has("unauthorized", "invalid api key", "invalid_api_key", "invalid token", "api key expired", "invalid credential", "http 401", "status 401", "status code 401", "status=401", "authentication_error"):+ f.Code, f.Phase, f.Message, f.Suggestion = "AUTHENTICATION_FAILED", "provider", "CodeBuddy 凭据无效或已过期,请检查个人配置后重试", "请检查所用 CLI 的 API Key 和 Base URL。"+ var credential assistantCredentialError+ if errors.As(err, &credential) {+ f.Message = credential.Error()+ }+ if err == errAssistantCredentialRejected {+ f.Message = err.Error()+ }+ case has("forbidden", "http 403", "status 403", "status code 403", "status=403"):+ f.Code, f.Phase, f.Message, f.Suggestion = "PERMISSION_DENIED", "provider", "模型服务拒绝访问(403)", "请检查 API Key 的权限及模型访问范围。"+ case has("context_length", "context window", "maximum context", "prompt is too long", "too many tokens"):+ f.Code, f.Phase, f.Message, f.Suggestion = "CONTEXT_LIMIT_EXCEEDED", "provider", "对话内容超过模型的上下文上限", "请缩短输入、开启新对话,或使用上下文更大的模型。"+ case has("model_not_found", "model not found", "unknown model", "model does not exist") || assistantModelMissingRe.MatchString(text):+ f.Code, f.Phase, f.Message, f.Suggestion = "MODEL_UNAVAILABLE", "provider", "所选模型不存在或当前账号无权使用", "请检查模型名称和访问权限,或切换模型。"+ case has("upstream unavailable", "service unavailable", "bad gateway", "gateway timeout", "http 502", "http 503", "http 504", "status 502", "status 503", "status 504", "status code 502", "status code 503", "status code 504", "overloaded", "servers are currently busy"):+ f.Code, f.Phase, f.Message, f.Suggestion = "UPSTREAM_UNAVAILABLE", "provider", "模型服务暂时不可用", "请稍后再试,或切换模型服务。"+ case has("connection refused", "connection reset", "connection closed", "network interrupted", "network error", "network_error", "no such host", "dial tcp", "tls handshake", "tls: ", "i/o timeout", "broken pipe", "stream disconnected", "econnreset", "econnrefused", "unexpected eof"):+ f.Code, f.Phase, f.Message, f.Suggestion = "NETWORK_ERROR", "connection", "CLI 与模型服务连接失败或连接中断", "请检查模型服务地址、网络与代理配置。"+ default:+ var exit *exec.ExitError+ var path *os.PathError+ switch {+ case errors.As(err, &path), errors.Is(err, exec.ErrNotFound):+ f.Code, f.Phase, f.Message, f.Suggestion = "CLI_START_FAILED", "setup", "CLI 启动或初始化失败", "请管理员检查 CLI 的安装、目录与文件权限。"+ case errors.Is(err, errAssistantMissingResult):+ f.Code, f.Phase, f.Message = "MISSING_RESULT", "protocol", "AI 助手生成中断,未返回完整回答,请重试"+ case errors.As(err, &exit), has("exit status"):+ f.Code, f.Message = "CLI_EXIT_NONZERO", "CLI 异常退出,未完成本轮回复"+ }}- return http.StatusBadGateway, assistantGenerationFailedMessage+ return f}// assistantGenerationFailedMessage is the generic generation failure. A CLIdiff --git a/internal/httpapi/assistant_failure_priority_test.go b/internal/httpapi/assistant_failure_priority_test.gonew file mode 100644index 00000000..59a9aca9--- /dev/null+++ b/internal/httpapi/assistant_failure_priority_test.go@@ -0,0 +1,95 @@+package httpapi++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "agentflow/internal/domain"+)++func TestAssistantFailureClassifiesErrorBeforeStderrNoise(t *testing.T) {+ for _, tc := range []struct {+ name string+ err error+ want string+ }{+ {"auth error with earlier rate-limit warning in stderr", fmt.Errorf("unexpected status 401 Unauthorized: invalid api key; stderr=WARN rate limit reached, retrying | bubblewrap: forbidden"), "AUTHENTICATION_FAILED"},+ {"stderr only fallback", fmt.Errorf("%w; stderr=HTTP 503 service unavailable", errors.New("exit status 1")), "UPSTREAM_UNAVAILABLE"},+ {"openai model name in 404", errors.New("unexpected status 404 Not Found: The model `nope` does not exist"), "MODEL_UNAVAILABLE"},+ {"quoted model name", errors.New(`The model "gpt-x" does not exist or you do not have access to it`), "MODEL_UNAVAILABLE"},+ {"plain exit", errors.New("exit status 1"), "CLI_EXIT_NONZERO"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := classifyAssistantFailure(context.Background(), tc.err).Code; got != tc.want {+ t.Fatalf("code=%s want %s", got, tc.want)+ }+ })+ }+}++func TestAssistantDiagnosticPrefersNewestStructuredErrorOverStderrText(t *testing.T) {+ g := domain.AssistantGeneration{ID: "structured-turn", SessionID: "s", Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ a := d.begin("codex", "model", false, domain.User{})+ a.recordEvent(domain.AssistantDiagnosticEvent{Kind: "provider.error", Message: "rate limit reached, retrying", StatusCode: 429})+ a.recordEvent(domain.AssistantDiagnosticEvent{Kind: "provider.error", Message: "invalid api key", StatusCode: 401})+ err := fmt.Errorf("%w; stderr=WARN rate limit reached, retrying", errors.New("exit status 1"))+ if f := d.fail(context.Background(), err, domain.User{}); f.Code != "AUTHENTICATION_FAILED" {+ t.Fatalf("stderr retry warning outranked the final 401: %+v", f)+ }++ d = newAssistantDiagnosticsCollector(g)+ a = d.begin("codex", "model", false, domain.User{})+ a.recordEvent(domain.AssistantDiagnosticEvent{Kind: "provider.error", Message: "Not Found", StatusCode: 404})+ if f := d.fail(context.Background(), errors.New("exit status 1"), domain.User{}); f.Code != "MODEL_UNAVAILABLE" {+ t.Fatalf("provider 404 not mapped: %+v", f)+ }++ // A cause named by the error itself stays authoritative.+ d = newAssistantDiagnosticsCollector(g)+ a = d.begin("codex", "model", false, domain.User{})+ a.recordEvent(domain.AssistantDiagnosticEvent{Kind: "provider.error", Message: "rate limit", StatusCode: 429})+ if f := d.fail(context.Background(), errors.New("prompt is too long"), domain.User{}); f.Code != "CONTEXT_LIMIT_EXCEEDED" {+ t.Fatalf("explicit error overridden: %+v", f)+ }+}++func TestAssistantDiagnosticEndpointKeepsOnlySchemeAndHost(t *testing.T) {+ g := domain.AssistantGeneration{ID: "endpoint-turn", SessionID: "s", Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ user := domain.User{CodexBaseURL: "https://user:[email protected]/v1/path-secret-value/openai?key=q#f"}+ a := d.begin("codex", "model", false, user)+ a.configure("/nonexistent/codex", assistantCLIRequest{Model: "codex:model"})+ report := d.snapshot(g)+ if len(report.Attempts) != 1 || report.Attempts[0].Endpoint != "https://gateway.example.com" {+ t.Fatalf("endpoint kept path or credentials: %+v", report.Attempts)+ }+}++func TestAssistantDiagnosticCheckpointSkipsUnchangedEvidence(t *testing.T) {+ g := domain.AssistantGeneration{ID: "checkpoint-turn", SessionID: "s", Status: "running", StartedAt: time.Now().UTC()}+ d := newAssistantDiagnosticsCollector(g)+ if _, write := d.checkpointSnapshot(g); !write {+ t.Fatal("first checkpoint was skipped")+ }+ if _, write := d.checkpointSnapshot(g); write {+ t.Fatal("unchanged evidence rewritten")+ }+ d.platform("cli.preparing", "preparing", domain.User{})+ if _, write := d.checkpointSnapshot(g); !write {+ t.Fatal("changed evidence skipped")+ }+ d.mu.Lock()+ d.persistedAt = time.Now().Add(-assistantDiagnosticsRewriteInterval)+ d.mu.Unlock()+ if _, write := d.checkpointSnapshot(g); !write {+ t.Fatal("rewrite interval not honored")+ }+ g.Status = "failed"+ if _, write := d.checkpointSnapshot(g); !write {+ t.Fatal("final checkpoint skipped")+ }+}diff --git a/internal/httpapi/assistant_failure_test.go b/internal/httpapi/assistant_failure_test.goindex 50663496..7bfb8649 100644--- a/internal/httpapi/assistant_failure_test.go+++ b/internal/httpapi/assistant_failure_test.go@@ -28,7 +28,7 @@ func TestAssistantCLIReportsTerminalFailuresWithoutResult(t *testing.T) {{"structured auth event", `{"type":"error","error":{"message":"Invalid API key: test-private-key"}}`, "凭据无效或已过期"},{"auth result", `{"type":"result","is_error":true,"result":"Unauthorized: test-private-key"}`, "凭据无效或已过期"},{"missing result", `{"type":"assistant","message":{"content":[{"type":"text","text":"正在检查代码"}]}}`, "未返回完整回答"},- {"other event", `{"type":"error","error":"upstream unavailable: test-private-key"}`, "生成失败,请稍后重试"},+ {"other event", `{"type":"error","error":"upstream unavailable: test-private-key"}`, "模型服务暂时不可用"},} {t.Run(tc.name, func(t *testing.T) {dir := t.TempDir()@@ -71,7 +71,7 @@ func TestPrivateAssistantReportsExecutionFailureWithoutReplayingTools(t *testing{"max turns", "执行轮数上限", runtime.ErrMaxTurns},{"missing result", "未返回完整回答", errAssistantMissingResult},{"credentials", "凭据无效或已过期", errors.New("HTTP 401: test-only")},- {"process", "生成失败,请稍后重试", errors.New("network interrupted: test-only")},+ {"process", "连接失败或连接中断", errors.New("network interrupted: test-only")},} {t.Run(tc.name, func(t *testing.T) {h, actor := workbenchFixture(t)@@ -137,7 +137,7 @@ func TestFailedSharedGenerationSnapshotKeepsCauseAndRetryHistory(t *testing.T) {{"max turns", "执行轮数上限", runtime.ErrMaxTurns},{"missing terminal result", "未返回完整回答", errAssistantMissingResult},{"credentials", "凭据无效或已过期", errors.New("HTTP 401: test-only")},- {"process", "生成失败,请稍后重试", errors.New("exit status 1; stderr=network interrupted test-only")},+ {"process", "连接失败或连接中断", errors.New("exit status 1; stderr=network interrupted test-only")},} {t.Run(tc.name, func(t *testing.T) {h, actor, _, _, session := sharedWorkbenchFixture(t)@@ -177,16 +177,23 @@ func TestFailedSharedGenerationSnapshotKeepsCauseAndRetryHistory(t *testing.T) {t.Fatalf("wrong persisted failure: %s", w.Body.String())}saved, _ := h.repo.AssistantSession(actor.ID, session.ID)- if last := saved.Messages[len(saved.Messages)-1]; last.Role != "user" || last.AuthorID != actor.ID {- t.Fatalf("retry history lost its accepted user: %+v", last)+ if user := saved.Messages[len(saved.Messages)-2]; user.Role != "user" || user.AuthorID != actor.ID {+ t.Fatalf("retry history lost its accepted user: %+v", user)+ }+ failed := saved.Messages[len(saved.Messages)-1]+ if failed.GenerationID != snapshot.ID || failed.Failure == nil {+ t.Fatalf("failure has no durable diagnostic reference: %+v", failed)}h.generate = func(context.Context, string, domain.User) (string, error) { return "核查完成", nil }- start(saved.Messages)+ start(append(saved.Messages, assistantMessage{Role: "user", Content: "请重试"}))wait("completed")saved, _ = h.repo.AssistantSession(actor.ID, session.ID)- if len(saved.Messages) != len(messages)+1 || saved.Messages[len(saved.Messages)-1].Role != "assistant" {+ if len(saved.Messages) != len(messages)+3 || saved.Messages[len(saved.Messages)-1].Role != "assistant" {t.Fatalf("retry duplicated the user turn or lost the answer: %+v", saved.Messages)}+ if report, ok := h.repo.AssistantDiagnostics(actor.ID, session.ID, snapshot.ID); !ok || report.Status != "failed" || report.Failure == nil {+ t.Fatalf("retry overwrote diagnostics: %+v", report)+ }})}}diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.goindex 16468db2..7790e9af 100644--- a/internal/httpapi/assistant_generation.go+++ b/internal/httpapi/assistant_generation.go@@ -258,6 +258,13 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistdefer cancel()rec := newAssistantGenerationRecorder(g)defer rec.close()+ ctx = context.WithValue(ctx, assistantDiagnosticsKey{}, rec.diagnostics)+ diagUser, _ := h.repo.User(g.UserID)+ if actor != nil && actor.ID != 0 && actor.ID != g.UserID {+ if u, ok := h.repo.User(actor.ID); ok {+ diagUser = u+ }+ }sink := rec.sinkstopped := make(chan struct{})done := make(chan struct{})@@ -272,6 +279,7 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistcase <-ticker.C:if req.workspaceToken != "" {if err := h.engine.RenewConversationWorkspaceUse(req.RunID, req.workspaceToken); err != nil {+ rec.diagnostics.terminate("WORKSPACE_LEASE_LOST", "会话工作区续租失败:"+err.Error(), diagUser)cancel()}}@@ -281,10 +289,23 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistrec.g.Steer = old.Steerrec.mu.Unlock()}- if !ok || old.ID != g.ID || old.Status != "running" || old.CancelRequested {+ if !ok || old.ID != g.ID {+ rec.diagnostics.terminate("GENERATION_SUPERSEDED", "当前生成记录已被替换或移除", diagUser)+ cancel()+ } else if old.Status != "running" {+ rec.diagnostics.terminate("GENERATION_STATUS_CHANGED", "生成状态已变更为 "+old.Status, diagUser)+ cancel()+ } else if old.CancelRequested {+ if old.Steer != nil {+ rec.diagnostics.terminate("USER_STEER", "用户在生成途中发送新指令转向下一轮", diagUser)+ } else {+ rec.diagnostics.terminate("USER_CANCELLED", "用户主动停止了本轮生成", diagUser)+ }cancel()}- if err := h.repo.CheckpointAssistantGeneration(rec.snapshot()); err != nil {+ snapshot := rec.snapshot()+ if err := h.checkpointRunningGeneration(snapshot, rec.diagnostics); err != nil {+ rec.diagnostics.terminate("CHECKPOINT_FAILED", "保存生成检查点失败:"+err.Error(), diagUser)cancel()}}@@ -294,7 +315,9 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistfunc() {defer func() {if recover() != nil {- sink("error", gin.H{"error": "生成异常中断,请重试"})+ rec.diagnostics.terminate("SERVER_PANIC", "服务端处理生成时发生未捕获异常", diagUser)+ failure := &domain.AssistantFailure{Code: "INTERNAL_ERROR", Phase: "server", Message: "生成异常中断,请重试", Suggestion: "请携带诊断编号联系管理员排查服务端日志。"}+ sink("error", gin.H{"error": failure.Message, "failure": failure})}}()body, _ := json.Marshal(req)@@ -323,10 +346,12 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assist}if writer.status >= 400 && g.Error == "" {var result struct {- Error string `json:"error"`+ Error string `json:"error"`+ Failure *domain.AssistantFailure `json:"failure"`}_ = json.Unmarshal(writer.body.Bytes(), &result)g.Error = result.Error+ g.Failure = result.Failure}if len(g.Reply) > 0 {g.Status = "completed"@@ -336,10 +361,20 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistg.Error = "生成未完成,请重试"}if ctx.Err() != nil {- g.Status = "cancelled"- g.Error = "生成已停止"+ if term := rec.diagnostics.termination(); term != nil && term.Code == "WORKSPACE_LEASE_LOST" {+ g.Status = "failed"+ g.Error = "会话工作区续租失败,生成已中断"+ g.Failure = &domain.AssistantFailure{Code: "WORKSPACE_LEASE_LOST", Phase: "server", Message: g.Error, Suggestion: "检查已执行操作及工作区状态后再重试;可下载诊断信息排查。"}+ } else {+ g.Status = "cancelled"+ g.Error = "生成已停止"+ g.Failure = nil+ }}}+ if g.Status == "failed" && g.Failure == nil {+ g.Failure = rec.diagnostics.failureForMessage(g.Error)+ }rec.g = gg = rec.snapshotLocked()steer := g.Steer@@ -360,7 +395,7 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assiststeer = nil}}- if err := h.repo.CheckpointAssistantGeneration(g); err != nil {+ if err := h.repo.CheckpointAssistantGeneration(g, rec.diagnostics.snapshot(g)); err != nil {fmt.Printf("assistant generation checkpoint failed: %T\n", err)}rec.live.publish()diff --git a/internal/httpapi/assistant_generation_recorder.go b/internal/httpapi/assistant_generation_recorder.goindex 3a198828..5e6cf5a0 100644--- a/internal/httpapi/assistant_generation_recorder.go+++ b/internal/httpapi/assistant_generation_recorder.go@@ -12,19 +12,21 @@ import (// its generation record and publishes them to live SSE readers. Chat turns and// scheduled runs share it so both stream to the conversation page the same way.type assistantGenerationRecorder struct {- mu sync.Mutex- g domain.AssistantGeneration- sequence int- eventBytes int- projection assistantStreamProjection- live *assistantLiveGeneration+ mu sync.Mutex+ g domain.AssistantGeneration+ sequence int+ eventBytes int+ projection assistantStreamProjection+ live *assistantLiveGeneration+ diagnostics *assistantDiagnosticsCollector}// newAssistantGenerationRecorder registers g as live; call close when the// turn's final state has been checkpointed.func newAssistantGenerationRecorder(g domain.AssistantGeneration) *assistantGenerationRecorder {- r := &assistantGenerationRecorder{g: g, live: &assistantLiveGeneration{changed: make(chan struct{})}}+ r := &assistantGenerationRecorder{g: g, live: &assistantLiveGeneration{changed: make(chan struct{})}, diagnostics: newAssistantDiagnosticsCollector(g)}r.live.read = r.snapshot+ r.live.diagnostics = func() domain.AssistantDiagnostics { return r.diagnostics.snapshot(r.snapshot()) }assistantLiveGenerations.Store(g.ID, r.live)return r}@@ -70,10 +72,12 @@ func (r *assistantGenerationRecorder) sink(kind string, value any) {r.g.WorkspaceWarning = fmt.Sprint(value)case "error":var e struct {- Error string `json:"error"`+ Error string `json:"error"`+ Failure *domain.AssistantFailure `json:"failure"`}_ = json.Unmarshal(raw, &e)r.g.Error = e.Error+ r.g.Failure = e.Failure}}@@ -83,3 +87,17 @@ func (r *assistantGenerationRecorder) activity() []domain.AssistantActivityEventdefer r.mu.Unlock()return r.projection.activity.snapshot()}++// checkpointRunningGeneration renews a running turn's lease every tick but+// rewrites its diagnostic payload only when the evidence changed or the+// rewrite interval elapsed.+func (h *assistantHandlers) checkpointRunningGeneration(g domain.AssistantGeneration, d *assistantDiagnosticsCollector) error {+ if d == nil {+ return h.repo.CheckpointAssistantGeneration(g)+ }+ report, write := d.checkpointSnapshot(g)+ if !write {+ return h.repo.HeartbeatAssistantGeneration(g)+ }+ return h.repo.CheckpointAssistantGeneration(g, report)+}diff --git a/internal/httpapi/assistant_live.go b/internal/httpapi/assistant_live.goindex b2148fd4..417a8c5d 100644--- a/internal/httpapi/assistant_live.go+++ b/internal/httpapi/assistant_live.go@@ -90,9 +90,10 @@ func assistantDraftMessagePrefix(raw string) string {}type assistantLiveGeneration struct {- mu sync.Mutex- changed chan struct{}- read func() domain.AssistantGeneration+ mu sync.Mutex+ changed chan struct{}+ read func() domain.AssistantGeneration+ diagnostics func() domain.AssistantDiagnostics}var assistantLiveGenerations sync.Mapdiff --git a/internal/httpapi/assistant_title.go b/internal/httpapi/assistant_title.goindex be8c6c42..281ef276 100644--- a/internal/httpapi/assistant_title.go+++ b/internal/httpapi/assistant_title.go@@ -105,7 +105,7 @@ func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerIDtitle, err = summarizeAssistantTitle(runCtx, user, model, prompt, shared)}if err != nil || strings.TrimSpace(title) == "" {- log.Printf("assistant title summary skipped session=%s: %v", sessionID, redactAssistantSecrets(fmt.Sprint(err), user))+ log.Printf("assistant title summary skipped session=%s: %s", sessionID, sanitizeAssistantDiagnostic(fmt.Sprint(err), user, 4096))return}if err := h.repo.SetAssistantSessionGeneratedTitle(ownerID, sessionID, title); err != nil {diff --git a/internal/httpapi/assistant_unfinished.go b/internal/httpapi/assistant_unfinished.goindex 5e35bf2d..c4fb0b3d 100644--- a/internal/httpapi/assistant_unfinished.go+++ b/internal/httpapi/assistant_unfinished.go@@ -21,19 +21,24 @@ const ()// turnTranscriptMessage builds the transcript entry for a turn that ended-// without a stored reply. A turn that produced nothing visible is not kept.+// without a stored reply. Failures also keep a diagnostic reference when the+// CLI produced no visible output, so starting another turn cannot hide them.func turnTranscriptMessage(g domain.AssistantGeneration, model string, stopped bool) (domain.AssistantMessage, bool) {- if g.Stream == nil {+ if g.Stream == nil && g.Failure == nil {return domain.AssistantMessage{}, false}- activity := g.Stream.Activity- text := assistantVisibleReply(g.Stream.Answer, activity)- if !transcriptWorthKeeping(text, activity) {+ var activity []domain.AssistantActivityEvent+ var text string+ if g.Stream != nil {+ activity = g.Stream.Activity+ text = assistantVisibleReply(g.Stream.Answer, activity)+ }+ if !transcriptWorthKeeping(text, activity) && g.Failure == nil {return domain.AssistantMessage{}, false}payload := map[string]any{"message": text, "drafts": []any{}}started := g.StartedAt- message := domain.AssistantMessage{Role: "assistant", Activity: activity, StartedAt: &started, CreatedAt: time.Now().UTC(), Model: strings.TrimSpace(model)}+ message := domain.AssistantMessage{Role: "assistant", Activity: activity, StartedAt: &started, CreatedAt: time.Now().UTC(), Model: strings.TrimSpace(model), GenerationID: g.ID, Failure: g.Failure}if stopped {payload["stopped"] = truemessage.Unfinished = strings.TrimSpace(g.Error)diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 8c6677c5..698788b6 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -302,6 +302,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servg.POST("/api/assistant/chat", asst.chat)g.POST("/api/assistant/generations", asst.startGeneration)g.GET("/api/assistant/sessions/:id/generation", asst.generation)+ g.GET("/api/assistant/sessions/:id/generations/:generationId/diagnostics", asst.generationDiagnostics)g.POST("/api/assistant/sessions/:id/generation/cancel", asst.generation)g.POST("/api/assistant/sessions/:id/generation/steer", asst.steerGeneration)g.POST("/api/assistant/sessions/:id/proposals", asst.decideProposal)diff --git a/internal/repo/assistant.go b/internal/repo/assistant.goindex 4ddfc28c..65dab309 100644--- a/internal/repo/assistant.go+++ b/internal/repo/assistant.go@@ -425,6 +425,9 @@ func (r *AssistantRepo) DeleteAssistantSession(userID int64, id string) error {if err := tx.Where("session_id = ?", id).Delete(&assistantSessionReadRow{}).Error; err != nil {return err}+ if err := tx.Where("session_id = ? AND user_id = ?", id, userID).Delete(&assistantDiagnosticsRow{}).Error; err != nil {+ return err+ }return tx.Where("session_id = ? AND user_id = ?", id, userID).Delete(&assistantGenerationRow{}).Error})}diff --git a/internal/repo/assistant_cli_notice.go b/internal/repo/assistant_cli_notice.goindex 00ff62c8..540a338e 100644--- a/internal/repo/assistant_cli_notice.go+++ b/internal/repo/assistant_cli_notice.go@@ -50,10 +50,15 @@ func (r *AssistantRepo) replaceGenerationCLIFailure(engine, missing, generic, nereturn err}g := decodeGeneration(row)- if !cliFailureMatches(g.Error, missing, generic, sameEngine) {+ msg := g.Error+ if msg == "" && g.Failure != nil {+ msg = g.Failure.Message+ }+ if !cliFailureMatches(msg, missing, generic, sameEngine) && !(sameEngine && g.Failure != nil && g.Failure.Code == "GENERATION_FAILED") {return nil}g.Error = next+ g.Failure = nilreturn tx.Model(&assistantGenerationRow{}).Where("session_id = ? AND generation_id = ?", row.SessionID, row.GenerationID).Update("payload", mustJSON(g)).Error})if err != nil {@@ -135,10 +140,14 @@ func cliFailureMatches(text, missing, generic string, sameEngine bool) bool {func rewriteCLIFailureMessages(item *domain.AssistantSession, missing, generic, next string, sameEngine bool) bool {changed := falsefor i := range item.Messages {- if !cliFailureMatches(item.Messages[i].Unfinished, missing, generic, sameEngine) {+ m := &item.Messages[i]+ matched := cliFailureMatches(m.Unfinished, missing, generic, sameEngine) ||+ (m.Failure != nil && (cliFailureMatches(m.Failure.Message, missing, generic, sameEngine) || (sameEngine && m.Failure.Code == "GENERATION_FAILED")))+ if !matched {continue}- item.Messages[i].Unfinished = next+ m.Unfinished = next+ m.Failure = nilchanged = true}return changeddiff --git a/internal/repo/assistant_diagnostics.go b/internal/repo/assistant_diagnostics.gonew file mode 100644index 00000000..240b4153--- /dev/null+++ b/internal/repo/assistant_diagnostics.go@@ -0,0 +1,97 @@+package repo++import (+ "encoding/json"+ "errors"+ "time"++ "agentflow/internal/domain"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++// Separate from the current-generation slot: a retry must not replace the+// previous turn's evidence. Access always includes both owner and session.+type assistantDiagnosticsRow struct {+ GenerationID string `gorm:"primaryKey;size:64"`+ SessionID string `gorm:"size:64;index:idx_assistant_diagnostics_session"`+ UserID int64 `gorm:"index:idx_assistant_diagnostics_session"`+ Payload []byte `gorm:"type:json"`+ UpdatedAt time.Time+}++func (assistantDiagnosticsRow) TableName() string { return "assistant_diagnostics" }++func initialAssistantDiagnostics(g domain.AssistantGeneration) domain.AssistantDiagnostics {+ return domain.AssistantDiagnostics{Version: 2, GenerationID: g.ID, SessionID: g.SessionID, Status: g.Status, StartedAt: g.StartedAt, UpdatedAt: time.Now().UTC(), Failure: g.Failure, Attempts: []domain.AssistantCLIAttempt{}}+}++func checkpointAssistantDiagnostics(tx *gorm.DB, g domain.AssistantGeneration, reports []domain.AssistantDiagnostics) error {+ now := time.Now().UTC()+ if len(reports) > 0 {+ // The caller owns the full report, so nothing needs to be read back:+ // one upsert replaces the previous checkpoint.+ report := reports[0]+ report.LastCheckpointAt = &now+ report.GenerationID, report.SessionID = g.ID, g.SessionID+ report.Status, report.Failure, report.UpdatedAt = g.Status, g.Failure, now+ domain.AnalyzeAssistantDiagnostics(&report)+ row := assistantDiagnosticsRow{GenerationID: g.ID, SessionID: g.SessionID, UserID: g.UserID, Payload: mustJSON(report), UpdatedAt: now}+ return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "generation_id"}}, DoUpdates: clause.AssignmentColumns([]string{"payload", "updated_at"})}).Create(&row).Error+ }+ var row assistantDiagnosticsRow+ err := tx.Where("generation_id = ? AND session_id = ? AND user_id = ?", g.ID, g.SessionID, g.UserID).Take(&row).Error+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {+ return err+ }+ report := initialAssistantDiagnostics(g)+ if err == nil {+ _ = json.Unmarshal(row.Payload, &report)+ if report.LastCheckpointAt == nil && !row.UpdatedAt.IsZero() {+ prev := row.UpdatedAt.UTC()+ report.LastCheckpointAt = &prev+ }+ }+ if g.Status == "interrupted" && report.Termination == nil {+ report.Termination = &domain.AssistantDiagnosticTermination{At: now, Code: "CHECKPOINT_LOST", Source: "platform", Message: "超过 45 秒未收到运行实例心跳,生成已中断"}+ seq := len(report.Timeline) + 1+ if len(report.Timeline) > 0 && report.Timeline[len(report.Timeline)-1].Sequence >= seq {+ seq = report.Timeline[len(report.Timeline)-1].Sequence + 1+ }+ report.Timeline = append(report.Timeline, domain.AssistantDiagnosticEvent{At: now, Sequence: seq, Source: "platform", Kind: "generation.termination", Code: "CHECKPOINT_LOST", Message: report.Termination.Message})+ }+ report.GenerationID, report.SessionID = g.ID, g.SessionID+ report.Status, report.Failure, report.UpdatedAt = g.Status, g.Failure, now+ domain.AnalyzeAssistantDiagnostics(&report)+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return tx.Create(&assistantDiagnosticsRow{GenerationID: g.ID, SessionID: g.SessionID, UserID: g.UserID, Payload: mustJSON(report), UpdatedAt: now}).Error+ }+ return tx.Model(&row).Updates(map[string]any{"payload": mustJSON(report), "updated_at": now}).Error+}++func (r *AssistantRepo) AssistantDiagnostics(userID int64, sessionID, generationID string) (domain.AssistantDiagnostics, bool) {+ var row assistantDiagnosticsRow+ if err := r.DB.Where("user_id = ? AND session_id = ? AND generation_id = ?", userID, sessionID, generationID).Take(&row).Error; err != nil {+ return domain.AssistantDiagnostics{}, false+ }+ var report domain.AssistantDiagnostics+ if json.Unmarshal(row.Payload, &report) != nil {+ return domain.AssistantDiagnostics{}, false+ }+ if report.Status == "running" && !row.UpdatedAt.IsZero() && time.Since(row.UpdatedAt) > 45*time.Second {+ now := time.Now().UTC()+ report.Status = "interrupted"+ if report.LastCheckpointAt == nil {+ prev := row.UpdatedAt.UTC()+ report.LastCheckpointAt = &prev+ }+ if report.Termination == nil {+ report.Termination = &domain.AssistantDiagnosticTermination{At: now, Code: "CHECKPOINT_LOST", Source: "platform", Message: "超过 45 秒未收到运行实例心跳,生成已中断"}+ }+ if report.Failure == nil {+ report.Failure = &domain.AssistantFailure{Code: "EXECUTION_INTERRUPTED", Phase: "server", Message: "服务端生成已中断,请检查已执行操作后重试", Suggestion: "检查已执行操作后再重试;可下载诊断信息交给管理员排查。"}+ }+ }+ domain.AnalyzeAssistantDiagnostics(&report)+ return report, true+}diff --git a/internal/repo/assistant_diagnostics_read_test.go b/internal/repo/assistant_diagnostics_read_test.gonew file mode 100644index 00000000..86fa65f6--- /dev/null+++ b/internal/repo/assistant_diagnostics_read_test.go@@ -0,0 +1,78 @@+package repo++import (+ "testing"+ "time"++ "agentflow/internal/domain"+)++func TestAssistantDiagnosticsReadRefreshesStaleRunningReport(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ const owner = 21+ if err := s.PutAssistantSession(owner, domain.AssistantSession{ID: "diag-read"}); err != nil {+ t.Fatal(err)+ }+ g := domain.AssistantGeneration{ID: "diag-read-1", SessionID: "diag-read", UserID: owner, Status: "running", StartedAt: time.Now().UTC()}+ if err := s.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ report := domain.AssistantDiagnostics{Version: 2, GenerationID: g.ID, SessionID: g.SessionID, Status: "running", StartedAt: g.StartedAt,+ Attempts: []domain.AssistantCLIAttempt{{ID: g.ID + "/1", CLIVersion: "1", Process: &domain.AssistantDiagnosticProcess{PID: 5, State: "running"}}}}+ if err := s.CheckpointAssistantGeneration(g, report); err != nil {+ t.Fatal(err)+ }++ fresh, ok := s.AssistantDiagnostics(owner, g.SessionID, g.ID)+ if !ok || fresh.Status != "running" || fresh.Termination != nil || fresh.Failure != nil || fresh.Assessment == nil || fresh.Assessment.Outcome != "pending" {+ t.Fatalf("fresh running report must stay live: %+v", fresh)+ }++ // Read the diagnostics directly (without refreshing the generation slot+ // first): the read path itself must notice the missing heartbeat.+ stale := time.Now().Add(-46 * time.Second).UTC()+ if err := s.DB.Exec("UPDATE assistant_diagnostics SET payload = ?, updated_at = ? WHERE generation_id = ?",+ mustJSON(domain.AssistantDiagnostics{Version: 2, GenerationID: g.ID, SessionID: g.SessionID, Status: "running", StartedAt: g.StartedAt}), stale, g.ID).Error; err != nil {+ t.Fatal(err)+ }+ got, ok := s.AssistantDiagnostics(owner, g.SessionID, g.ID)+ if !ok {+ t.Fatal("stale diagnostics missing")+ }+ if got.Status != "interrupted" || got.Termination == nil || got.Termination.Code != "CHECKPOINT_LOST" || got.Termination.Source != "platform" {+ t.Fatalf("stale report not interrupted: %+v", got)+ }+ if got.Failure == nil || got.Failure.Code != "EXECUTION_INTERRUPTED" || got.Failure.Phase != "server" {+ t.Fatalf("stale report failure = %+v", got.Failure)+ }+ if got.LastCheckpointAt == nil || got.LastCheckpointAt.Sub(stale).Abs() > time.Second {+ t.Fatalf("lastCheckpointAt must fall back to the row heartbeat %v, got %v", stale, got.LastCheckpointAt)+ }+ if got.Assessment == nil || got.Assessment.Outcome != "termination_recorded" {+ t.Fatalf("stale report assessment = %+v", got.Assessment)+ }++ // Existing termination, failure and checkpoint evidence is never replaced.+ kept := time.Now().Add(-10 * time.Minute).UTC().Truncate(time.Second)+ original := domain.AssistantDiagnostics{Version: 2, GenerationID: g.ID, SessionID: g.SessionID, Status: "running", LastCheckpointAt: &kept,+ Termination: &domain.AssistantDiagnosticTermination{Code: "USER_STEER", Message: "用户改了方向"},+ Failure: &domain.AssistantFailure{Code: "NETWORK_ERROR", Message: "网络连接中断"}}+ if err := s.DB.Exec("UPDATE assistant_diagnostics SET payload = ?, updated_at = ? WHERE generation_id = ?", mustJSON(original), stale, g.ID).Error; err != nil {+ t.Fatal(err)+ }+ got, ok = s.AssistantDiagnostics(owner, g.SessionID, g.ID)+ if !ok || got.Status != "interrupted" || got.Termination.Code != "USER_STEER" || got.Failure.Code != "NETWORK_ERROR" || !got.LastCheckpointAt.Equal(kept) {+ t.Fatalf("stale refresh overwrote recorded evidence: %+v", got)+ }++ if err := s.DB.Exec("UPDATE assistant_diagnostics SET payload = ? WHERE generation_id = ?", []byte("{not json"), g.ID).Error; err != nil {+ t.Fatal(err)+ }+ if _, ok := s.AssistantDiagnostics(owner, g.SessionID, g.ID); ok {+ t.Fatal("corrupt payload must not be returned")+ }+}diff --git a/internal/repo/assistant_diagnostics_test.go b/internal/repo/assistant_diagnostics_test.gonew file mode 100644index 00000000..d6564408--- /dev/null+++ b/internal/repo/assistant_diagnostics_test.go@@ -0,0 +1,114 @@+package repo++import (+ "testing"+ "time"++ "agentflow/internal/domain"+)++func TestAssistantDiagnosticsSurviveRetryAndDeleteWithSession(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ const owner = 11+ if err := s.PutAssistantSession(owner, domain.AssistantSession{ID: "diagnostic-history"}); err != nil {+ t.Fatal(err)+ }+ g := domain.AssistantGeneration{ID: "first-diagnostic", SessionID: "diagnostic-history", UserID: owner, Status: "running", StartedAt: time.Now().UTC()}+ if err := s.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ g.Status = "failed"+ g.Failure = &domain.AssistantFailure{Code: "NETWORK_ERROR", Message: "网络连接中断"}+ report := initialAssistantDiagnostics(g)+ report.Error = "connection reset"+ report.Attempts = []domain.AssistantCLIAttempt{{ID: "first/1", Engine: "codebuddy"}}+ if err := s.CheckpointAssistantGeneration(g, report); err != nil {+ t.Fatal(err)+ }+ first := g+ g.ID, g.Status, g.Failure = "second-diagnostic", "running", nil+ if err := s.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ if err := s.CheckpointAssistantGeneration(first, report); err == nil {+ t.Fatal("stale checkpoint was allowed")+ }+ stored, ok := s.AssistantDiagnostics(owner, g.SessionID, first.ID)+ if !ok || stored.Status != "failed" || stored.Failure.Code != "NETWORK_ERROR" || len(stored.Attempts) != 1 || stored.Error != "connection reset" {+ t.Fatalf("retry replaced failure: %+v", stored)+ }+ if _, ok := s.AssistantDiagnostics(owner+1, g.SessionID, first.ID); ok {+ t.Fatal("owner scope bypassed")+ }+ if _, ok := s.AssistantDiagnostics(owner, "wrong-session", first.ID); ok {+ t.Fatal("session scope bypassed")+ }+ g.Status = "completed"+ if err := s.CheckpointAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ if err := s.DeleteAssistantSession(owner, g.SessionID); err != nil {+ t.Fatal(err)+ }+ if _, ok := s.AssistantDiagnostics(owner, g.SessionID, first.ID); ok {+ t.Fatal("deleted conversation left diagnostic data")+ }+}++func TestAssistantDiagnosticsStaleRunningTurnsRefreshToCheckpointLost(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ const owner = 12+ if err := s.PutAssistantSession(owner, domain.AssistantSession{ID: "stale-diag-session"}); err != nil {+ t.Fatal(err)+ }+ started := time.Now().Add(-2 * time.Minute).UTC()+ g := domain.AssistantGeneration{ID: "stale-turn-1", SessionID: "stale-diag-session", UserID: owner, Status: "running", StartedAt: started}+ if err := s.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ partial := domain.AssistantDiagnostics{+ Version: 2,+ GenerationID: g.ID,+ SessionID: g.SessionID,+ Status: "running",+ StartedAt: started,+ Environment: &domain.AssistantDiagnosticEnvironment{PlatformVersion: "test", InstanceID: "api-crashed"},+ Attempts: []domain.AssistantCLIAttempt{{ID: "stale-turn-1/1", Engine: "codex", CLIVersion: "0.163.0", Status: "running", Process: &domain.AssistantDiagnosticProcess{PID: 99, State: "running"}}},+ Tools: []domain.AssistantDiagnosticTool{{ID: "gateway/1", Source: "gateway", Name: "tapd__bugs_list", Status: "running", StartedAt: started}},+ }+ if err := s.CheckpointAssistantGeneration(g, partial); err != nil {+ t.Fatal(err)+ }+ expired := time.Now().Add(-time.Minute).UTC()+ if err := s.DB.Exec("UPDATE assistant_generations SET updated_at = ? WHERE session_id = ?", expired, g.SessionID).Error; err != nil {+ t.Fatal(err)+ }+ if err := s.DB.Exec("UPDATE assistant_diagnostics SET updated_at = ? WHERE generation_id = ?", expired, g.ID).Error; err != nil {+ t.Fatal(err)+ }+ gotGen, ok := s.AssistantGeneration(owner, g.SessionID)+ if !ok || gotGen.Status != "interrupted" {+ t.Fatalf("expected interrupted generation, got %+v", gotGen)+ }+ report, ok := s.AssistantDiagnostics(owner, g.SessionID, g.ID)+ if !ok {+ t.Fatal("missing diagnostics after interruption")+ }+ if report.Status != "interrupted" || report.Termination == nil || report.Termination.Code != "CHECKPOINT_LOST" {+ t.Fatalf("expected CHECKPOINT_LOST termination, got %+v", report)+ }+ if len(report.Tools) != 1 || report.Tools[0].Status != "unfinished" {+ t.Fatalf("lost pre-crash tool evidence: %+v", report.Tools)+ }+ if report.Assessment == nil || report.LastCheckpointAt == nil {+ t.Fatalf("missing assessment or lastCheckpointAt: %+v", report)+ }+}diff --git a/internal/repo/assistant_diagnostics_upsert_test.go b/internal/repo/assistant_diagnostics_upsert_test.gonew file mode 100644index 00000000..066b48a2--- /dev/null+++ b/internal/repo/assistant_diagnostics_upsert_test.go@@ -0,0 +1,61 @@+package repo++import (+ "testing"+ "time"++ "agentflow/internal/domain"+)++func TestAssistantDiagnosticsCheckpointUpsertAndHeartbeat(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ const owner = 21+ if err := s.PutAssistantSession(owner, domain.AssistantSession{ID: "upsert-session"}); err != nil {+ t.Fatal(err)+ }+ g := domain.AssistantGeneration{ID: "upsert-turn", SessionID: "upsert-session", UserID: owner, Status: "running", StartedAt: time.Now().UTC()}+ if err := s.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ report := initialAssistantDiagnostics(g)+ report.Attempts = []domain.AssistantCLIAttempt{{ID: "upsert-turn/1", Engine: "codex"}}+ for i := 0; i < 2; i++ {+ if err := s.CheckpointAssistantGeneration(g, report); err != nil {+ t.Fatal(err)+ }+ }+ var before assistantDiagnosticsRow+ if err := s.DB.Where("generation_id = ?", g.ID).Take(&before).Error; err != nil {+ t.Fatal(err)+ }+ var count int64+ s.DB.Model(&assistantDiagnosticsRow{}).Where("generation_id = ?", g.ID).Count(&count)+ if count != 1 {+ t.Fatalf("upsert created %d rows", count)+ }+ if err := s.HeartbeatAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ var after assistantDiagnosticsRow+ if err := s.DB.Where("generation_id = ?", g.ID).Take(&after).Error; err != nil {+ t.Fatal(err)+ }+ if string(after.Payload) != string(before.Payload) {+ t.Fatal("heartbeat rewrote the diagnostic payload")+ }+ stored, ok := s.AssistantDiagnostics(owner, g.SessionID, g.ID)+ if !ok || stored.Status != "running" || len(stored.Attempts) != 1 || stored.LastCheckpointAt == nil {+ t.Fatalf("checkpoint lost: %+v", stored)+ }+ g.Status = "completed"+ if err := s.HeartbeatAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ if err := s.HeartbeatAssistantGeneration(g); err == nil {+ t.Fatal("heartbeat accepted a finished generation")+ }+}diff --git a/internal/repo/assistant_generations.go b/internal/repo/assistant_generations.goindex 2b364c9a..96d9b589 100644--- a/internal/repo/assistant_generations.go+++ b/internal/repo/assistant_generations.go@@ -46,7 +46,14 @@ func (r *AssistantRepo) AssistantGeneration(userID int64, sessionID string) (domg := decodeGeneration(row)g.Status = "interrupted"g.Error = "服务端生成已中断,请检查已执行操作后重试"- _ = r.DB.Model(&assistantGenerationRow{}).Where("session_id = ? AND generation_id = ? AND status = ? AND updated_at = ?", sessionID, row.GenerationID, "running", row.UpdatedAt).Updates(map[string]any{"status": g.Status, "payload": mustJSON(g)}).Error+ g.Failure = &domain.AssistantFailure{Code: "EXECUTION_INTERRUPTED", Phase: "server", Message: g.Error, Suggestion: "检查已执行操作后再重试;可下载诊断信息交给管理员排查。"}+ _ = r.DB.Transaction(func(tx *gorm.DB) error {+ res := tx.Model(&assistantGenerationRow{}).Where("session_id = ? AND generation_id = ? AND status = ? AND updated_at = ?", sessionID, row.GenerationID, "running", row.UpdatedAt).Updates(map[string]any{"status": g.Status, "payload": mustJSON(g)})+ if res.Error != nil || res.RowsAffected != 1 {+ return res.Error+ }+ return checkpointAssistantDiagnostics(tx, g, nil)+ })if err := r.DB.Where("session_id = ? AND user_id = ?", sessionID, userID).Take(&row).Error; err != nil {return domain.AssistantGeneration{}, false}@@ -95,15 +102,32 @@ func (r *AssistantRepo) BeginAssistantGeneration(g domain.AssistantGeneration, pif old.Status == "running" {return fmt.Errorf("此会话正在生成,请等待完成或停止")}- return tx.Model(&old).Updates(map[string]any{"generation_id": g.ID, "status": "running", "cancel_requested": false, "payload": mustJSON(g), "updated_at": time.Now().UTC(), "finished_at": nil}).Error+ if err := tx.Model(&old).Updates(map[string]any{"generation_id": g.ID, "status": "running", "cancel_requested": false, "payload": mustJSON(g), "updated_at": time.Now().UTC(), "finished_at": nil}).Error; err != nil {+ return err+ }+ return checkpointAssistantDiagnostics(tx, g, nil)}if !errors.Is(err, gorm.ErrRecordNotFound) {return err}- return tx.Create(&assistantGenerationRow{SessionID: g.SessionID, UserID: g.UserID, GenerationID: g.ID, Status: "running", Payload: mustJSON(g), UpdatedAt: time.Now().UTC()}).Error+ if err := tx.Create(&assistantGenerationRow{SessionID: g.SessionID, UserID: g.UserID, GenerationID: g.ID, Status: "running", Payload: mustJSON(g), UpdatedAt: time.Now().UTC()}).Error; err != nil {+ return err+ }+ return checkpointAssistantDiagnostics(tx, g, nil)})}-func (r *AssistantRepo) CheckpointAssistantGeneration(g domain.AssistantGeneration) error {+func (r *AssistantRepo) CheckpointAssistantGeneration(g domain.AssistantGeneration, diagnostics ...domain.AssistantDiagnostics) error {+ return r.checkpointAssistantGeneration(g, true, diagnostics)+}++// HeartbeatAssistantGeneration records a running checkpoint whose diagnostic+// evidence has not changed since it was last stored, so the diagnostic payload+// is not rewritten.+func (r *AssistantRepo) HeartbeatAssistantGeneration(g domain.AssistantGeneration) error {+ return r.checkpointAssistantGeneration(g, false, nil)+}++func (r *AssistantRepo) checkpointAssistantGeneration(g domain.AssistantGeneration, withDiagnostics bool, diagnostics []domain.AssistantDiagnostics) error {return r.DB.Transaction(func(tx *gorm.DB) error {var row assistantGenerationRowerr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("session_id = ? AND user_id = ? AND generation_id = ? AND status = ?", g.SessionID, g.UserID, g.ID, "running").Take(&row).Error@@ -127,7 +151,10 @@ func (r *AssistantRepo) CheckpointAssistantGeneration(g domain.AssistantGeneratiif res.RowsAffected != 1 {return fmt.Errorf("生成状态已变化")}- return nil+ if !withDiagnostics {+ return nil+ }+ return checkpointAssistantDiagnostics(tx, g, diagnostics)})}diff --git a/internal/repo/models.go b/internal/repo/models.goindex 71b26a75..70773c1b 100644--- a/internal/repo/models.go+++ b/internal/repo/models.go@@ -710,7 +710,7 @@ func allModels() []any {runPreviewRow{}, previewSessionRow{}, previewBlobRow{}, WorkspaceCheckpoint{}, workspaceCheckpointChunk{},mrDeliveryStateRow{}, definitionRevisionRow{},runnerRow{}, runnerTaskRow{}, runnerTaskEventRow{}, userRunnerPrefRow{},- assistantSessionRow{}, assistantTaskRow{}, assistantGenerationRow{}, assistantSessionReadRow{}, assistantPreferenceRow{},+ assistantSessionRow{}, assistantTaskRow{}, assistantGenerationRow{}, assistantSessionReadRow{}, assistantPreferenceRow{}, assistantDiagnosticsRow{},chatRoomRow{}, chatMessageRow{},requirementSpaceRow{}, spaceMemberRow{}, spaceArtifactRow{}, spaceArtifactRevisionRow{}, spaceThreadRow{},engineInstanceRow{},diff --git a/internal/runtime/process.go b/internal/runtime/process.goindex be8b69d2..66923fc6 100644--- a/internal/runtime/process.go+++ b/internal/runtime/process.go@@ -8,6 +8,7 @@ import ("os/exec""strings""sync"+ "syscall""time")@@ -16,9 +17,6 @@ const processWaitDelay = time.Secondfunc runCommand(cmd *exec.Cmd, sink EventSink) (string, error) {var buf bytes.Buffervar mu sync.Mutex- if sink != nil {- sink(domain.TelemetryEvent{Category: "process", Name: "process.started", Phase: "start", Message: compactCommand(cmd.Args)})- }stdout := &processWriter{output: &buf, mu: &mu, sink: sink, name: "process.stdout", level: "info"}stderr := &processWriter{output: &buf, mu: &mu, sink: sink, name: "process.stderr", level: "error"}cmd.Stdout, cmd.Stderr = stdout, stderr@@ -28,7 +26,21 @@ func runCommand(cmd *exec.Cmd, sink EventSink) (string, error) {// at 100ms a busy host (CI running Go and JS tests together) dropped the// tail of a 50KB failure log, which is the part users need.cmd.WaitDelay = processWaitDelay- err := cmd.Run()+ // Start launches the stdout/stderr copy goroutines. Hold the writers' lock+ // until process.started is delivered so the sink stays serialized and the+ // event always precedes the first output line.+ mu.Lock()+ err := cmd.Start()+ if err == nil && sink != nil {+ sink(domain.TelemetryEvent{Category: "process", Name: "process.started", Timestamp: time.Now().UTC(), Phase: "start", Message: compactCommand(cmd.Args), Attributes: map[string]any{"pid": cmd.Process.Pid}})+ }+ mu.Unlock()+ if err == nil {+ err = cmd.Wait()+ } else if sink != nil {+ sink(domain.TelemetryEvent{Category: "process", Name: "process.start_failed", Timestamp: time.Now().UTC(), Phase: "start", Level: "error", Message: err.Error()})+ }+ outputIncomplete := errors.Is(err, exec.ErrWaitDelay)if errors.Is(err, exec.ErrWaitDelay) {err = nil}@@ -39,7 +51,18 @@ func runCommand(cmd *exec.Cmd, sink EventSink) (string, error) {if err != nil {level = "error"}- sink(domain.TelemetryEvent{Category: "process", Name: "process.finished", Phase: phase, Level: level, Message: commandResult(err)})+ attrs := map[string]any{"outputIncomplete": outputIncomplete}+ if state := cmd.ProcessState; state != nil {+ attrs["pid"], attrs["exitCode"] = state.Pid(), state.ExitCode()+ attrs["userCpuMs"], attrs["systemCpuMs"] = state.UserTime().Milliseconds(), state.SystemTime().Milliseconds()+ if status, ok := state.Sys().(interface {+ Signaled() bool+ Signal() syscall.Signal+ }); ok && status.Signaled() {+ attrs["signal"] = status.Signal().String()+ }+ }+ sink(domain.TelemetryEvent{Category: "process", Name: "process.finished", Timestamp: time.Now().UTC(), Phase: phase, Level: level, Message: commandResult(err), Attributes: attrs})}return buf.String(), err}diff --git a/internal/runtime/process_events_test.go b/internal/runtime/process_events_test.gonew file mode 100644index 00000000..fe96e0b2--- /dev/null+++ b/internal/runtime/process_events_test.go@@ -0,0 +1,23 @@+package runtime++import (+ "os/exec"+ "testing"++ "agentflow/internal/domain"+)++// The sink is not goroutine-safe on purpose: runCommand must serialize every+// callback, including process.started, against the output copy goroutines.+func TestRunCommandSerializesStartedBeforeOutput(t *testing.T) {+ for i := 0; i < 20; i++ {+ var names []string+ sink := func(e domain.TelemetryEvent) { names = append(names, e.Name) }+ if _, err := runCommand(exec.Command("sh", "-c", "echo a; echo b 1>&2; echo c"), sink); err != nil {+ t.Fatal(err)+ }+ if len(names) < 5 || names[0] != "process.started" || names[len(names)-1] != "process.finished" {+ t.Fatalf("events out of order: %v", names)+ }+ }+}diff --git a/migrations/029_assistant_diagnostics.sql b/migrations/029_assistant_diagnostics.sqlnew file mode 100644index 00000000..7ca20eeb--- /dev/null+++ b/migrations/029_assistant_diagnostics.sql@@ -0,0 +1,11 @@+-- Optional manual additive DDL. Startup AutoMigrate also adds this table.+-- Diagnostic records survive retries and are deleted with their conversation.+CREATE TABLE IF NOT EXISTS assistant_diagnostics (+ generation_id VARCHAR(64) NOT NULL,+ session_id VARCHAR(64) NOT NULL,+ user_id BIGINT NOT NULL,+ payload JSON,+ updated_at DATETIME(3),+ PRIMARY KEY (generation_id),+ INDEX idx_assistant_diagnostics_session (session_id, user_id)+) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;