From 832ba356c711decedd042a9f790183a34b4f579f Mon Sep 17 00:00:00 2001
From: Zhang Wenyue <35551877+yefuyou@users.noreply.github.com>
Date: Sat, 21 Nov 2026 20:35:01 +0800
Subject: [PATCH 1/3] [feat] agent: export read-only conversation trace reports
(#421)
Add a Markdown report export across all executed turns, with bounded event metadata and linked generation-job status. Omit raw model prompts and tool payloads.
---
src/canvas/AssistantTracePage.tsx | 35 +++++++-
src/canvas/assistant-trace.css | 5 ++
src/canvas/traceExport.ts | 133 ++++++++++++++++++++++++++++++
src/i18n/messages/en-US/trace.ts | 3 +
src/i18n/messages/zh-CN/trace.ts | 3 +
tests/traceExport.test.ts | 64 ++++++++++++++
6 files changed, 240 insertions(+), 3 deletions(-)
create mode 100644 src/canvas/traceExport.ts
create mode 100644 tests/traceExport.test.ts
diff --git a/src/canvas/AssistantTracePage.tsx b/src/canvas/AssistantTracePage.tsx
index a07a40e85..2e0f5fa82 100644
--- a/src/canvas/AssistantTracePage.tsx
+++ b/src/canvas/AssistantTracePage.tsx
@@ -7,6 +7,7 @@ import { traceCategory, isThinkingTokenEstimate, readableTraceValue } from "./tr
import { initialTurn, normalizeTrace, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "./traceTurns.ts";
import { readTurnJobs, turnJobView, type TurnJob } from "./traceJobs.ts";
+import { conversationTraceReport } from "./traceExport.ts";
import "./assistant-trace.css";
@@ -297,14 +298,36 @@ const STATUS_KEYS: Record = {
stopped: "trace.turn.status.stopped", interrupted: "trace.turn.status.interrupted",
};
-function ConversationTrace({ project, target, turns }: {
- project: string; target: string; turns: ConversationTurn[];
+function ConversationTrace({ project, conversationId, target, turns }: {
+ project: string; conversationId: string; target: string; turns: ConversationTurn[];
}) {
const t = useT();
const [open, setOpen] = useState>(() => new Set());
const [loaded, setLoaded] = useState>(() => new Set());
const placed = useRef(false);
const initial = initialTurn(turns, target);
+ const [exporting, setExporting] = useState(false);
+ const [exportError, setExportError] = useState(false);
+ async function exportReport() {
+ if (exporting) return;
+ setExporting(true);
+ setExportError(false);
+ try {
+ const markdown = await conversationTraceReport(project, conversationId, turns);
+ const url = URL.createObjectURL(new Blob([markdown], { type: "text/markdown;charset=utf-8" }));
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = "opendirector-trace-" + conversationId + ".md";
+ document.body.append(link);
+ link.click();
+ link.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
+ } catch {
+ setExportError(true);
+ } finally {
+ setExporting(false);
+ }
+ }
function toggle(id: string, value: boolean) {
setOpen((previous) => {
@@ -327,6 +350,12 @@ function ConversationTrace({ project, target, turns }: {
return (
<>
+
+
+ {exportError && {t("trace.export.failed")}}
+
}
{conversation === undefined ? {t("trace.loading")}
: wide ? (
-
+
) : (
)}
diff --git a/src/canvas/assistant-trace.css b/src/canvas/assistant-trace.css
index 6d612878c..7d04cf4bc 100644
--- a/src/canvas/assistant-trace.css
+++ b/src/canvas/assistant-trace.css
@@ -100,3 +100,8 @@
.cw-trace-turn > summary { grid-template-columns: auto minmax(0, 1fr); }
.cw-trace-turn-meta { grid-column: 1 / -1; }
}
+
+.cw-trace-export { display: flex; align-items: center; gap: 12px; padding: 8px 20px; }
+.cw-trace-export button { padding: 6px 12px; border: 1px solid #4d5d6d; border-radius: 4px; background: #303c48; color: #d6e8f7; font: inherit; cursor: pointer; }
+.cw-trace-export button:disabled { cursor: wait; opacity: .6; }
+.cw-trace-export span[role="alert"] { color: #f0a3a3; }
diff --git a/src/canvas/traceExport.ts b/src/canvas/traceExport.ts
new file mode 100644
index 000000000..b690d2bd3
--- /dev/null
+++ b/src/canvas/traceExport.ts
@@ -0,0 +1,133 @@
+/** Read-only, user-initiated report of conversation trace metadata and safe event summaries. */
+import { normalizeTrace, traceRuntime, traceSources, type ConversationTurn } from "./traceTurns.ts";
+
+const MAX_LOG_CHARS = 1_000_000;
+const MAX_EVENTS_PER_SOURCE = 400;
+const EVENT_PATTERN = /^[A-Za-z][A-Za-z0-9_.:/-]{0,72}$/;
+const JOB_STATES = new Set(["queued", "running", "succeeded", "failed", "cancelled", "interrupted"]);
+
+type TraceEvent = { kind: string; status?: string };
+type SourceReport = { name: string; state: "available" | "missing" | "unavailable"; events: TraceEvent[]; truncated: boolean };
+type JobReport = { id: string; status: string; adopted: boolean };
+type TurnReport = { turn: ConversationTurn; sources: SourceReport[]; jobs: JobReport[] | null };
+
+const record = (value: unknown): Record =>
+ value && typeof value === "object" && !Array.isArray(value) ? value as Record : {};
+const eventCode = (value: unknown): string | null =>
+ typeof value === "string" && EVENT_PATTERN.test(value) ? value : null;
+
+/** Extract event codes and fixed states only; never include prompts, arguments, outputs or raw JSON. */
+export function traceEventSummary(body: string): { events: TraceEvent[]; truncated: boolean } {
+ const clipped = body.length > MAX_LOG_CHARS;
+ const lines = body.slice(0, MAX_LOG_CHARS).split("\n");
+ if (clipped) lines.pop(); // Last line may contain incomplete JSON.
+ const events: TraceEvent[] = [];
+ let truncated = clipped;
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ let parsed: unknown;
+ try { parsed = JSON.parse(line); } catch { continue; }
+ const outer = record(parsed);
+ const native = record(outer.native);
+ const part = record(native.part);
+ const item = record(native.item);
+ const state = record(part.state);
+ const kind = eventCode(native.event_type) ?? eventCode(native.type) ??
+ eventCode(outer.event) ?? eventCode(outer.type);
+ if (!kind) continue;
+ const rawStatus = state.status ?? item.status;
+ const status = eventCode(rawStatus);
+ events.push(status ? { kind, status } : { kind });
+ if (events.length >= MAX_EVENTS_PER_SOURCE) { truncated = true; break; }
+ }
+ return { events, truncated };
+}
+
+const inline = (value: string): string =>
+ value.replace(/\s+/g, " ").replace(/[\\\`*_{}\[\]()#+.!|>]/g, "\\$&");
+
+async function sourceReport(fetcher: typeof fetch, base: string, turn: ConversationTurn, source: string): Promise {
+ try {
+ const response = await fetcher(base + "/traces/" + encodeURIComponent(turn.id) + "/" + encodeURIComponent(source),
+ { headers: { "X-OpenDirector-Request": "1" } });
+ if (response.status === 404) return { name: source, state: "missing", events: [], truncated: false };
+ if (!response.ok) return { name: source, state: "unavailable", events: [], truncated: false };
+ const body = await response.text();
+ const normalized = normalizeTrace(source, body.slice(0, MAX_LOG_CHARS));
+ const summary = traceEventSummary(normalized);
+ return { name: source, state: "available", events: summary.events,
+ truncated: summary.truncated || body.length > MAX_LOG_CHARS };
+ } catch {
+ return { name: source, state: "unavailable", events: [], truncated: false };
+ }
+}
+
+async function jobReport(fetcher: typeof fetch, base: string, turn: ConversationTurn): Promise {
+ try {
+ const response = await fetcher(base + "/turns/" + encodeURIComponent(turn.id) + "/jobs",
+ { headers: { "X-OpenDirector-Request": "1" } });
+ if (!response.ok) return null;
+ const raw: unknown = await response.json();
+ if (!Array.isArray(raw)) return null;
+ return raw.flatMap((entry: unknown) => {
+ const job = record(entry);
+ if (typeof job.jobId !== "string") return [];
+ return [{ id: job.jobId, status: typeof job.status === "string" && JOB_STATES.has(job.status)
+ ? job.status : "unknown", adopted: job.adopted === true }];
+ });
+ } catch {
+ return null;
+ }
+}
+
+/** Every turn is fetched independently, including collapsed turns; no project writes or provider calls. */
+export async function conversationTraceReport(project: string, conversationId: string, turns: ConversationTurn[],
+ fetcher: typeof fetch = fetch, generatedAt = new Date().toISOString()): Promise {
+ const base = "/api/creation/projects/" + encodeURIComponent(project) + "/assistant";
+ const reports: TurnReport[] = [];
+ for (const turn of turns) {
+ const sources = traceSources(traceRuntime(turn.runtime)).filter((name) => name !== "model");
+ const [logs, jobs] = await Promise.all([
+ Promise.all(sources.map((source) => sourceReport(fetcher, base, turn, source))),
+ jobReport(fetcher, base, turn),
+ ]);
+ reports.push({ turn, sources: logs, jobs });
+ }
+ const lines = [
+ "# OpenDirector Agent Trace Report", "",
+ "- Project ID: " + inline(project),
+ "- Conversation ID: " + inline(conversationId),
+ "- Generated at: " + inline(generatedAt), "",
+ "> This is a read-only execution summary. Raw model requests, prompts, tool arguments/results and asset data are not exported. Review user request previews and identifiers before sharing.", "",
+ ];
+ for (const { turn, sources, jobs } of reports) {
+ lines.push("## Turn " + turn.number, "",
+ "- Turn ID: " + inline(turn.id),
+ "- Request preview: " + inline(turn.text),
+ "- Runtime: " + inline(turn.runtime),
+ "- Model: " + inline(turn.model ?? "not recorded"),
+ "- Status: " + inline(turn.status) + (turn.status === "streaming" ? " (partial snapshot)" : ""), "",
+ "### Trace events (metadata only)", "");
+ for (const source of sources) {
+ lines.push("#### " + inline(source.name), "");
+ if (source.state !== "available") {
+ lines.push("- Trace " + (source.state === "missing" ? "not recorded" : "unavailable"), "");
+ } else if (!source.events.length) {
+ lines.push("- No readable events", "");
+ } else {
+ for (const event of source.events)
+ lines.push("- " + inline(event.kind) + (event.status ? " (" + inline(event.status) + ")" : ""));
+ if (source.truncated) lines.push("- Event list truncated at the report limit");
+ lines.push("");
+ }
+ }
+ lines.push("### Linked generation jobs", "");
+ if (jobs === null) lines.push("- Job data unavailable");
+ else if (!jobs.length) lines.push("- No linked jobs");
+ else for (const job of jobs)
+ lines.push("- " + inline(job.id) + ": " + inline(job.status) +
+ (job.adopted ? " (adopted)" : " (not adopted)"));
+ lines.push("");
+ }
+ return lines.join("\n") + "\n";
+}
diff --git a/src/i18n/messages/en-US/trace.ts b/src/i18n/messages/en-US/trace.ts
index 115e1762f..7a254b306 100644
--- a/src/i18n/messages/en-US/trace.ts
+++ b/src/i18n/messages/en-US/trace.ts
@@ -35,6 +35,9 @@ export const trace = {
"trace.jobs.adopted": "Adopted",
"trace.jobs.notAdopted": "Not adopted",
"trace.jobs.cancelRequested": "Cancel requested",
+ "trace.export.button": "Export report (.md)",
+ "trace.export.working": "Preparing report…",
+ "trace.export.failed": "Could not export the trace report. Please retry.",
"trace.conversationTitle": "Conversation trace",
"trace.turns.nav": "Turns",
"trace.turns.empty": "This conversation has no executed turns.",
diff --git a/src/i18n/messages/zh-CN/trace.ts b/src/i18n/messages/zh-CN/trace.ts
index 6a43d6adf..1ea11f622 100644
--- a/src/i18n/messages/zh-CN/trace.ts
+++ b/src/i18n/messages/zh-CN/trace.ts
@@ -35,6 +35,9 @@ export const trace = {
"trace.jobs.adopted": "已采用",
"trace.jobs.notAdopted": "未采用",
"trace.jobs.cancelRequested": "已请求取消",
+ "trace.export.button": "导出轨迹报告(.md)",
+ "trace.export.working": "正在生成报告…",
+ "trace.export.failed": "导出轨迹报告失败,请重试。",
"trace.conversationTitle": "对话轨迹",
"trace.turns.nav": "轮次",
"trace.turns.empty": "该对话还没有已执行的轮次。",
diff --git a/tests/traceExport.test.ts b/tests/traceExport.test.ts
new file mode 100644
index 000000000..2ad510964
--- /dev/null
+++ b/tests/traceExport.test.ts
@@ -0,0 +1,64 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { conversationTraceReport, traceEventSummary } from "../src/canvas/traceExport.ts";
+import type { ConversationTurn } from "../src/canvas/traceTurns.ts";
+
+const turn = (id: string, number: number, runtime = "default", status: ConversationTurn["status"] = "complete"): ConversationTurn =>
+ ({ id, number, text: "Review [report]", runtime, model: "example", status });
+
+test("export omits raw model data, arguments, tool output and credential-like content", async () => {
+ const secret = "provider_secret_not_for_report";
+ const summary = traceEventSummary([
+ JSON.stringify({ event: "model.request", payload: { messages: [{ content: secret }] } }),
+ JSON.stringify({ native: { type: "tool_call", part: { state: { status: "completed" }, input: secret } } }),
+ JSON.stringify({ native: { type: "tool_call_update", item: { status: "failed", aggregated_output: secret } } }),
+ ].join("\n"));
+ assert.deepEqual(summary.events, [
+ { kind: "model.request" }, { kind: "tool_call", status: "completed" }, { kind: "tool_call_update", status: "failed" },
+ ]);
+ assert.ok(!JSON.stringify(summary).includes(secret));
+});
+
+test("all turns including collapsed ones export with their own runtime and linked job status", async () => {
+ const paths: string[] = [];
+ const fetcher: typeof fetch = async (input) => {
+ const path = String(input);
+ paths.push(path);
+ if (path.includes("/turns/a/jobs"))
+ return Response.json([{ jobId: "job-1", status: "running", adopted: false }]);
+ if (path.includes("/turns/b/jobs"))
+ return Response.json([{ jobId: "job-2", status: "failed", adopted: false }]);
+ if (path.endsWith("/traces/a/opencode"))
+ return new Response('{"event":"model.request","payload":{"messages":[{"content":"password"}]}}\n', { status: 200 });
+ if (path.endsWith("/traces/b/codex"))
+ return new Response('{"type":"turn.started"}\n', { status: 200 });
+ return new Response("", { status: 404 });
+ };
+ const result = await conversationTraceReport("project", "conversation",
+ [turn("a", 1), turn("b", 2, "codex", "streaming")], fetcher, "2026-11-21T00:00:00Z");
+ assert.match(result, /## Turn 1/);
+ assert.match(result, /## Turn 2/);
+ assert.match(result, /job-1: running \(not adopted\)/);
+ assert.match(result, /job-2: failed \(not adopted\)/);
+ assert.match(result, /partial snapshot/);
+ assert.ok(!result.includes("password"));
+ assert.deepEqual(paths.filter((p) => p.includes("/traces/")).sort(),
+ ["/api/creation/projects/project/assistant/traces/a/opencode", "/api/creation/projects/project/assistant/traces/b/codex"]);
+});
+
+test("missing and failed logs remain explicit without invented events", async () => {
+ const fetcher: typeof fetch = async (url) =>
+ String(url).endsWith("/jobs") ? new Response("", { status: 503 }) : new Response("", { status: 404 });
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)], fetcher);
+ assert.match(result, /Trace not recorded/);
+ assert.match(result, /Job data unavailable/);
+ assert.doesNotMatch(result, /No linked jobs/);
+});
+
+test("untrusted metadata cannot inject Markdown headings or list entries", async () => {
+ const fetcher: typeof fetch = async (url) =>
+ String(url).endsWith("/jobs") ? Response.json([]) : new Response("", { status: 404 });
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)], fetcher);
+ assert.ok(result.includes("Review \\[report\\]"));
+ assert.ok(!result.includes("Review [report]"));
+});
From 67d253734b6b6d72b287cd5e8e66c251643db6c3 Mon Sep 17 00:00:00 2001
From: Zhang Wenyue <35551877+yefuyou@users.noreply.github.com>
Date: Sat, 21 Nov 2026 20:37:26 +0800
Subject: [PATCH 2/3] [fix] agent: escape HTML in exported trace report text
---
src/canvas/traceExport.ts | 3 ++-
tests/traceExport.test.ts | 2 +-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/canvas/traceExport.ts b/src/canvas/traceExport.ts
index b690d2bd3..f57c19a21 100644
--- a/src/canvas/traceExport.ts
+++ b/src/canvas/traceExport.ts
@@ -44,7 +44,8 @@ export function traceEventSummary(body: string): { events: TraceEvent[]; truncat
}
const inline = (value: string): string =>
- value.replace(/\s+/g, " ").replace(/[\\\`*_{}\[\]()#+.!|>]/g, "\\$&");
+ value.replace(/&/g, "&").replace(//g, ">")
+ .replace(/\s+/g, " ").replace(/[\\\`*_{}\[\]()#+.!|]/g, "\\ value.replace(/\s+/g, " ").replace(/[\\\`*_{}\[\]()#+.!|>]/g, "\\$&");");
async function sourceReport(fetcher: typeof fetch, base: string, turn: ConversationTurn, source: string): Promise {
try {
diff --git a/tests/traceExport.test.ts b/tests/traceExport.test.ts
index 2ad510964..99da62693 100644
--- a/tests/traceExport.test.ts
+++ b/tests/traceExport.test.ts
@@ -59,6 +59,6 @@ test("untrusted metadata cannot inject Markdown headings or list entries", async
const fetcher: typeof fetch = async (url) =>
String(url).endsWith("/jobs") ? Response.json([]) : new Response("", { status: 404 });
const result = await conversationTraceReport("p", "c", [turn("a", 1)], fetcher);
- assert.ok(result.includes("Review \\[report\\]"));
+ assert.ok(result.includes("Review <secret> \\[report\\]"));
assert.ok(!result.includes("Review [report]"));
});
From 70b39b417488dc2e92c740e554a73089995c3766 Mon Sep 17 00:00:00 2001
From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
Date: Sat, 21 Nov 2026 13:36:02 +0000
Subject: [PATCH 3/3] [fix] agent: repair the broken escape expression in trace
export
Restore the Markdown escape replace after the HTML entity escaping so the file parses again (TS1005/TS1127).
---
src/canvas/traceExport.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/canvas/traceExport.ts b/src/canvas/traceExport.ts
index f57c19a21..37998ad1e 100644
--- a/src/canvas/traceExport.ts
+++ b/src/canvas/traceExport.ts
@@ -45,7 +45,7 @@ export function traceEventSummary(body: string): { events: TraceEvent[]; truncat
const inline = (value: string): string =>
value.replace(/&/g, "&").replace(//g, ">")
- .replace(/\s+/g, " ").replace(/[\\\`*_{}\[\]()#+.!|]/g, "\\ value.replace(/\s+/g, " ").replace(/[\\\`*_{}\[\]()#+.!|>]/g, "\\$&");");
+ .replace(/\s+/g, " ").replace(/[\\`*_{}\[\]()#+.!|]/g, "\\$&");
async function sourceReport(fetcher: typeof fetch, base: string, turn: ConversationTurn, source: string): Promise {
try {