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/5] [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/5] [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/5] [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 {
From bd7f033cebb4434b94f7e6063ecf3857bacd308c Mon Sep 17 00:00:00 2001
From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
Date: Mon, 23 Nov 2026 09:52:36 +0000
Subject: [PATCH 4/5] [fix] agent: bound trace report log reads to the
character limit
---
src/canvas/traceExport.ts | 31 ++++++++++++---
tests/traceExport.test.ts | 80 +++++++++++++++++++++++++++++++++++++++
2 files changed, 106 insertions(+), 5 deletions(-)
diff --git a/src/canvas/traceExport.ts b/src/canvas/traceExport.ts
index 37998ad1e..310b1a7ba 100644
--- a/src/canvas/traceExport.ts
+++ b/src/canvas/traceExport.ts
@@ -47,17 +47,38 @@ const inline = (value: string): string =>
value.replace(/&/g, "&").replace(//g, ">")
.replace(/\s+/g, " ").replace(/[\\`*_{}\[\]()#+.!|]/g, "\\$&");
+/** Reads at most MAX_LOG_CHARS characters (plus one chunk) and cancels the stream once the limit is exceeded. */
+async function readBoundedText(response: Response): Promise<{ text: string; clipped: boolean }> {
+ if (!response.body) {
+ const text = await response.text();
+ return { text: text.slice(0, MAX_LOG_CHARS), clipped: text.length > MAX_LOG_CHARS };
+ }
+ const reader = response.body.getReader(), decoder = new TextDecoder();
+ let text = "";
+ try {
+ while (text.length <= MAX_LOG_CHARS) {
+ const { done, value } = await reader.read();
+ if (done) { text += decoder.decode(); break; }
+ text += decoder.decode(value, { stream: true });
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ }
+ if (text.length <= MAX_LOG_CHARS) return { text, clipped: false };
+ // Drop the cut-off last line so a partial record is never normalized.
+ const head = text.slice(0, MAX_LOG_CHARS);
+ return { text: head.slice(0, head.lastIndexOf("\n") + 1), clipped: true };
+}
+
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 };
+ const { text, clipped } = await readBoundedText(response);
+ const summary = traceEventSummary(normalizeTrace(source, text));
+ return { name: source, state: "available", events: summary.events, truncated: summary.truncated || clipped };
} catch {
return { name: source, state: "unavailable", events: [], truncated: false };
}
diff --git a/tests/traceExport.test.ts b/tests/traceExport.test.ts
index 99da62693..721fc45e3 100644
--- a/tests/traceExport.test.ts
+++ b/tests/traceExport.test.ts
@@ -62,3 +62,83 @@ test("untrusted metadata cannot inject Markdown headings or list entries", async
assert.ok(result.includes("Review <secret> \\[report\\]"));
assert.ok(!result.includes("Review [report]"));
});
+
+const MAX = 1_000_000;
+const jobsOrLog = (log: (path: string) => Response): typeof fetch => async (input) => {
+ const path = String(input);
+ return path.endsWith("/jobs") ? Response.json([]) : log(path);
+};
+const SECRETS = ["SENTINEL_PROMPT", "SENTINEL_ARGS", "SENTINEL_RESULT", "sk-DEMOSECRET123456"];
+const secretLine = JSON.stringify({ event: "model.request", payload: { prompt: SECRETS[0], arguments: SECRETS[1],
+ result: SECRETS[2], apiKey: SECRETS[3] } });
+
+test("a very large log is read only up to the limit plus one chunk and marked truncated", async () => {
+ const line = JSON.stringify({ event: "tool_call", pad: "x".repeat(990) }) + "\n";
+ const chunk = new TextEncoder().encode(line.repeat(100));
+ let pulled = 0, cancelled = false;
+ const stream = new ReadableStream({
+ pull(controller) { pulled += chunk.byteLength; controller.enqueue(chunk); },
+ cancel() { cancelled = true; },
+ }, { highWaterMark: 0 });
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)],
+ jobsOrLog(() => new Response(stream, { status: 200 })));
+ assert.ok(cancelled);
+ assert.ok(pulled > MAX && pulled <= MAX + chunk.byteLength, "pulled " + pulled);
+ assert.match(result, /Event list truncated/);
+ assert.match(result, /- tool\\_call/);
+});
+
+test("a line cut at the limit does not produce a bogus event", async () => {
+ const full = JSON.stringify({ event: "good.event" }) + "\n";
+ const cutLine = JSON.stringify({ event: "cut.event" });
+ const filler = JSON.stringify({ event: "x", pad: "y".repeat(MAX - full.length - 20) }) + "\n";
+ // Line "cut.event" starts before the limit but ends after it.
+ const body = full + filler + cutLine + "\n" + cutLine;
+ assert.ok(body.length > MAX);
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)],
+ jobsOrLog(() => new Response(body, { status: 200 })));
+ assert.match(result, /good\\.event/);
+ assert.doesNotMatch(result, /cut\\.event/);
+ assert.match(result, /Event list truncated/);
+});
+
+test("invalid JSON lines are skipped without failing", async () => {
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)],
+ jobsOrLog(() => new Response('not json\n{"event":"ok.event"\n{"event":"fine"}\n{', { status: 200 })));
+ assert.match(result, /- fine/);
+ assert.doesNotMatch(result, /ok\\.event/);
+ assert.doesNotMatch(result, /unavailable/);
+});
+
+test("stream errors and rejected fetches are reported as unavailable", async () => {
+ const failing = new ReadableStream({
+ start(controller) { controller.enqueue(new TextEncoder().encode('{"event":"a"}\n')); },
+ pull(controller) { controller.error(new Error("network")); },
+ }, { highWaterMark: 0 });
+ const streamed = await conversationTraceReport("p", "c", [turn("a", 1)],
+ jobsOrLog(() => new Response(failing, { status: 200 })));
+ assert.match(streamed, /Trace unavailable/);
+ assert.match(streamed, /## Turn 1/);
+ const rejected: typeof fetch = async (input) => {
+ if (String(input).endsWith("/jobs")) return Response.json([]);
+ throw new TypeError("offline");
+ };
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)], rejected);
+ assert.match(result, /Trace unavailable/);
+});
+
+test("an empty response is available with no readable events", async () => {
+ const result = await conversationTraceReport("p", "c", [turn("a", 1)],
+ jobsOrLog(() => new Response("", { status: 200 })));
+ assert.match(result, /No readable events/);
+ assert.doesNotMatch(result, /unavailable|not recorded/);
+});
+
+test("sentinel secrets in logs never reach the report, including when clipped", async () => {
+ const body = (secretLine + "\n").repeat(Math.ceil(MAX / secretLine.length) + 5);
+ for (const text of [secretLine + "\n", body]) {
+ const result = await conversationTraceReport("p", "c", [turn("a", 1), turn("b", 2, "codex")],
+ jobsOrLog(() => new Response(text, { status: 200 })));
+ for (const secret of SECRETS) assert.ok(!result.includes(secret), secret);
+ }
+});
From cb3c537bd7f732368cd981b58c4f247df247effd Mon Sep 17 00:00:00 2001
From: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
Date: Mon, 23 Nov 2026 09:58:08 +0000
Subject: [PATCH 5/5] [test] agent: add real-browser trace report download test
to the PR gate
---
.github/workflows/release-checks.yml | 1 +
tests/browser/manifest.json | 9 +
tests/browser/trace_report_export.mjs | 315 ++++++++++++++++++++++++++
3 files changed, 325 insertions(+)
create mode 100644 tests/browser/trace_report_export.mjs
diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml
index a51af74e4..e6e5ff979 100644
--- a/.github/workflows/release-checks.yml
+++ b/.github/workflows/release-checks.yml
@@ -290,6 +290,7 @@ jobs:
curl --silent --fail "$CREATION_WEB_URL/" >/dev/null
node tests/browser/bilingual_defaults.mjs
node tests/browser/assistant_auxiliary_panels.mjs
+ node tests/browser/trace_report_export.mjs
- name: Print isolated service logs on failure
if: failure()
run: |
diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json
index 345d6b701..772132d1e 100644
--- a/tests/browser/manifest.json
+++ b/tests/browser/manifest.json
@@ -70,6 +70,15 @@
],
"note": "Controls the model-stub gate; runs on its own fixture services."
},
+ {
+ "file": "trace_report_export.mjs",
+ "fixture": true,
+ "previewSafe": true,
+ "lanes": [
+ "gate"
+ ],
+ "note": "Conversation Trace report download in both locales on the assistant fixture services. Linked Jobs are answered by page.route; every other request reaches the real API."
+ },
{
"file": "assistant_run_navigation.mjs",
"fixture": true,
diff --git a/tests/browser/trace_report_export.mjs b/tests/browser/trace_report_export.mjs
new file mode 100644
index 000000000..43b967f4f
--- /dev/null
+++ b/tests/browser/trace_report_export.mjs
@@ -0,0 +1,315 @@
+/** Conversation Trace report export (#421): real UI click, real browser download.
+ * Run against creation_server.py --assistant-fixture; no model or provider is called.
+ *
+ * Real: project, conversation, turns (fixture agent, runtimes default and codex),
+ * trace log files on disk, the Trace page and the browser download.
+ * Fixture: linked Jobs. The fixture agent cannot create Jobs with Agent lineage,
+ * so only GET .../assistant/turns//jobs is answered by page.route. Job lineage
+ * itself is covered by tests/test_agent_job_lineage.py.
+ */
+import assert from "node:assert/strict";
+import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { launchBrowser } from "./engine.mjs";
+
+const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179";
+const evidence = process.env.TRACE_EXPORT_EVIDENCE_DIR;
+const headers = {
+ "X-OpenDirector-Request": "1",
+ "X-OpenDirector-Session": crypto.randomUUID(),
+ "Content-Type": "application/json",
+};
+async function api(path, body) {
+ const response = await fetch(base + "/api" + path, {
+ headers,
+ ...(body ? { method: "POST", body: JSON.stringify(body) } : {}),
+ });
+ assert.ok(response.ok, path + ": " + (await response.clone().text()));
+ return response.json();
+}
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const health = await api("/creation-test-health");
+assert.equal(health.isolated, true);
+assert.equal(health.assistantFixture, true);
+await api("/creation-test-assistant-gate", { open: true });
+
+const unique = crypto.randomUUID().slice(0, 8);
+const projectId = crypto.randomUUID();
+await api(`/creation/projects/${projectId}/commands`, {
+ projectId,
+ commandId: crypto.randomUUID(),
+ type: "project.create",
+ payload: { name: `Trace export ${unique}` },
+});
+await api(`/creation/projects/${projectId}/open`, {});
+const assistant = `/creation/projects/${projectId}/assistant`;
+const modelId = (await api("/model-configs")).find((model) => model.kind === "agent").id;
+
+// Four executed turns with two runtimes. No prompt text here is a secret: the
+// report may show the request preview by design.
+const specs = [
+ { runtime: "default", text: `Plan the opening shot ${unique}` },
+ { runtime: "codex", text: `Render the second scene ${unique}` },
+ { runtime: "default", text: `Add the closing title ${unique}` },
+ { runtime: "codex", text: `Review the final cut ${unique}` },
+];
+const turns = [];
+for (const spec of specs) {
+ const id = crypto.randomUUID();
+ const response = await fetch(base + "/api" + assistant + "/turns", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ id, text: spec.text, runtime: spec.runtime, modelId }),
+ });
+ assert.equal(response.status, 200, await response.clone().text());
+ await response.text();
+ turns.push({ ...spec, id });
+}
+const conversation = await api(assistant);
+const conversationId = conversation.conversationId;
+const indexed = await api(`${assistant}/conversations/${conversationId}/trace`);
+assert.deepEqual(
+ indexed.turns.map((turn) => [turn.id, turn.runtime, turn.status]),
+ turns.map((turn) => [turn.id, turn.runtime, "complete"]),
+);
+
+// Seed trace logs next to the project (the server and this script share a machine).
+const projects = join(health.root, "projects");
+let directory;
+for (const name of await readdir(projects)) {
+ try {
+ const info = JSON.parse(await readFile(join(projects, name, "project.json"), "utf8"));
+ if (info.id === projectId) directory = join(projects, name);
+ } catch {}
+}
+assert.ok(directory, "project directory must be found under the isolated root");
+const SECRETS = [
+ "SENTINEL_PROMPT_" + unique,
+ "SENTINEL_SYSTEM_" + unique,
+ "SENTINEL_TOOL_ARGS_" + unique,
+ "SENTINEL_TOOL_RESULT_" + unique,
+ "sk-DEMO" + unique + "KEYVALUE",
+];
+const [prompt, system, args, result, key] = SECRETS;
+const line = (value) => JSON.stringify(value) + "\n";
+const logs = {
+ // opencode-style log for turn 1
+ [`${turns[0].id}.opencode.jsonl`]:
+ line({ event: "session.start", message: system }) +
+ line({ native: { type: "tool", part: { state: { status: "completed", input: { path: args, apiKey: key }, output: result } } } }) +
+ line({ event: "assistant.message", text: prompt }),
+ // codex-style log for turn 2
+ [`${turns[1].id}.codex.jsonl`]:
+ line({ native: { type: "thread.started" } }) +
+ line({ native: { type: "item.completed", item: { id: "i1", type: "command_execution", status: "completed", command: args, aggregated_output: result } } }) +
+ line({ native: { type: "item.completed", item: { id: "i2", type: "agent_message", status: "failed", text: prompt } } }),
+ // turn 3 has no log at all. Turn 4: partial and invalid JSON lines around one valid event.
+ [`${turns[3].id}.codex.jsonl`]:
+ "not json " + key + "\n" +
+ line({ native: { type: "item.started", item: { id: "p1", status: "in_progress", command: args } } }) +
+ `{"native":{"type":"item.completed","item":{"command":"${result}`,
+};
+await mkdir(join(directory, "agent-runs"), { recursive: true });
+for (const [name, content] of Object.entries(logs))
+ await writeFile(join(directory, "agent-runs", name), content);
+
+const jobIds = {
+ succeeded: `job-succeeded-${unique}`,
+ failed: `job-failed-${unique}`,
+ running: `job-running-${unique}`,
+};
+const jobPayload = {
+ [turns[0].id]: [{ jobId: jobIds.succeeded, status: "succeeded", adopted: true }],
+ [turns[1].id]: [{ jobId: jobIds.failed, status: "failed", adopted: false }],
+ [turns[2].id]: [{ jobId: jobIds.running, status: "running", adopted: false }],
+};
+const failingJobs = turns[3].id;
+
+const tracePage = (query) =>
+ `${base}/?traceProject=${projectId}&${query}`;
+const unescape = (text) => text.replace(/\\([\\`*_{}[\]()#+.!|])/g, "$1");
+const section = (report, number) => {
+ const found = report.split(/^## /m).find((part) => part.startsWith(`Turn ${number}\n`));
+ assert.ok(found, `Turn ${number} section`);
+ return unescape(found);
+};
+
+const labels = {
+ "zh-CN": { exportButton: "导出轨迹报告(.md)", failed: "导出轨迹报告失败,请重试。",
+ empty: "该对话还没有已执行的轮次。", title: "对话轨迹" },
+ "en-US": { exportButton: "Export report (.md)", failed: "Could not export the trace report. Please retry.",
+ empty: "This conversation has no executed turns.", title: "Conversation trace" },
+};
+
+const browser = await launchBrowser();
+try {
+ async function openContext(locale) {
+ const context = await browser.newContext({ locale, viewport: { width: 1280, height: 900 }, acceptDownloads: true });
+ await context.addInitScript((value) => {
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ localStorage.setItem("opendirector.locale.v1", value);
+ }, locale);
+ const page = await context.newPage();
+ page.setDefaultTimeout(15000);
+ const seen = { errors: [], requests: [] };
+ page.on("pageerror", (error) => seen.errors.push(error.message));
+ page.on("request", (request) => {
+ if (request.url().startsWith(base)) seen.requests.push(`${request.method()} ${new URL(request.url()).pathname}`);
+ });
+ await page.route(/\/assistant\/turns\/[^/]+\/jobs(?:\?.*)?$/, (route) => {
+ if (route.request().method() !== "GET") return route.continue();
+ const turn = new URL(route.request().url()).pathname.split("/").at(-2);
+ if (turn === failingJobs) return route.fulfill({ status: 500, json: { detail: "Jobs fixture failure" } });
+ return route.fulfill({ json: jobPayload[turn] ?? [] });
+ });
+ return { context, page, seen };
+ }
+ async function exportReport(page, seen, text) {
+ const before = seen.requests.length;
+ const [download] = await Promise.all([
+ page.waitForEvent("download"),
+ page.getByRole("button", { name: text.exportButton, exact: true }).click(),
+ ]);
+ // The click itself performs only GETs (trace logs and job lists).
+ const during = seen.requests.slice(before);
+ assert.ok(during.length > 0 && during.every((entry) => entry.startsWith("GET ")), JSON.stringify(during));
+ assert.ok(!during.some((entry) => /\/traces\/[^/]+\/model$/.test(entry)), "raw model requests not fetched");
+ assert.ok(!during.some((entry) => /\/stop$|\/events$|\/resume|\/cancel|\/turns$/.test(entry)));
+ assert.equal(download.suggestedFilename(), `opendirector-trace-${conversationId}.md`);
+ const path = await download.path();
+ assert.ok(path, "download must be saved");
+ return readFile(path, "utf8");
+ }
+ function assertReport(report) {
+ assert.match(report, /^# OpenDirector Agent Trace Report/);
+ assert.ok(report.includes(projectId) && report.includes(conversationId));
+ // Every executed turn is present, not only the expanded one.
+ for (const [index, turn] of turns.entries()) {
+ const part = section(report, index + 1);
+ assert.ok(part.includes(`Turn ID: ${turn.id}`), `turn ${index + 1} id`);
+ assert.ok(part.includes(`Runtime: ${turn.runtime}`), `turn ${index + 1} runtime`);
+ assert.ok(part.includes("Status: complete"), `turn ${index + 1} status`);
+ assert.ok(part.includes(turn.text), `turn ${index + 1} request preview`);
+ }
+ const [one, two, three, four] = [1, 2, 3, 4].map((number) => section(report, number));
+ assert.ok(one.includes("#### opencode") && !one.includes("#### codex"));
+ assert.ok(two.includes("#### codex") && !two.includes("#### opencode"));
+ assert.ok(!report.includes("#### model"), "raw model requests are not exported");
+ // Event kinds and statuses only.
+ assert.match(one, /- session\.start\n/);
+ assert.match(one, /- tool \(completed\)/);
+ assert.match(one, /- assistant\.message\n/);
+ assert.match(two, /- item\.completed \(completed\)/);
+ assert.match(two, /- item\.completed \(failed\)/);
+ // Linked Jobs.
+ assert.match(one, new RegExp(`${jobIds.succeeded}: succeeded \\(adopted\\)`));
+ assert.match(two, new RegExp(`${jobIds.failed}: failed \\(not adopted\\)`));
+ assert.match(three, new RegExp(`${jobIds.running}: running \\(not adopted\\)`));
+ assert.ok(three.includes("Trace not recorded"), "missing log");
+ assert.ok(four.includes("Job data unavailable"), "failed job request");
+ assert.match(four, /- item\.started \(in_progress\)/);
+ assert.ok(!/- item\.completed/.test(four), "a cut line must not create an event");
+ // No raw content or credentials.
+ for (const secret of SECRETS) assert.ok(!report.includes(secret), `report leaks ${secret}`);
+ assert.ok(!/sk-DEMO/.test(report));
+ }
+ function assertReadOnly(seen) {
+ assert.deepEqual(seen.errors, []);
+ // Navigating away makes the app shell release its editing-session lease (DELETE
+ // /api/creation/sessions/, src/backend/api.ts). That is page lifecycle, not export.
+ const writes = seen.requests.filter((entry) => !entry.startsWith("GET ") &&
+ !/^DELETE \/api\/creation\/sessions\/[0-9a-f-]+$/.test(entry));
+ assert.deepEqual(writes, [], "export must not write or call providers");
+ }
+
+ for (const locale of ["zh-CN", "en-US"]) {
+ const text = labels[locale];
+ const { context, page, seen } = await openContext(locale);
+ try {
+ // Only turn 2 is expanded; the report still covers all four turns.
+ await page.goto(tracePage(`conversation=${conversationId}&turn=${turns[1].id}`));
+ await page.getByRole("heading", { name: text.title, exact: true }).waitFor();
+ const button = page.getByRole("button", { name: text.exportButton, exact: true });
+ await button.waitFor();
+ assert.equal(await button.isEnabled(), true);
+ await page.locator(`#turn-${turns[1].id}[open]`).waitFor();
+ assert.equal(await page.locator("details[open]").count(), 1);
+ if (evidence) {
+ await mkdir(evidence, { recursive: true });
+ await page.screenshot({ path: join(evidence, `trace-page-${locale}.png`), fullPage: true });
+ }
+ const report = await exportReport(page, seen, text);
+ assertReport(report);
+ assert.equal(await button.isEnabled(), true, "button is usable again");
+ assert.equal(await page.getByRole("alert").count(), 0);
+ assert.equal(await page.locator("details[open]").count(), 1, "export does not expand turns");
+ if (evidence) {
+ const viewer = await context.newPage();
+ await viewer.setContent(`${report
+ .replace(/&/g, "&").replace(/`);
+ await viewer.screenshot({ path: join(evidence, `report-${locale}.png`), fullPage: true });
+ await viewer.close();
+ }
+
+ // An old single-turn link for a listed turn resolves to the conversation and exports.
+ await page.goto(`${base}/?traceProject=${projectId}&turn=${turns[2].id}&runtime=opencode`);
+ await page.getByRole("heading", { name: text.title, exact: true }).waitFor();
+ assertReport(await exportReport(page, seen, text));
+
+ // An unknown turn keeps the single-turn page, which has no export button.
+ const unknown = crypto.randomUUID();
+ await page.goto(`${base}/?traceProject=${projectId}&turn=${unknown}&runtime=opencode`);
+ await page.locator("code", { hasText: unknown }).waitFor();
+ assert.equal(await page.getByRole("button", { name: text.exportButton, exact: true }).count(), 0);
+ assertReadOnly(seen);
+ } finally {
+ await context.close();
+ }
+ }
+
+ // Export failure shows an alert and leaves the button usable.
+ {
+ const text = labels["en-US"];
+ const { context, page, seen } = await openContext("en-US");
+ try {
+ await page.addInitScript(() => {
+ URL.createObjectURL = () => {
+ throw new Error("blocked for test");
+ };
+ });
+ await page.goto(tracePage(`conversation=${conversationId}&turn=${turns[0].id}`));
+ const button = page.getByRole("button", { name: text.exportButton, exact: true });
+ await button.waitFor();
+ let downloaded = false;
+ page.on("download", () => (downloaded = true));
+ await button.click();
+ await page.getByRole("alert").filter({ hasText: text.failed }).waitFor();
+ assert.equal(await button.isEnabled(), true);
+ await sleep(300);
+ assert.equal(downloaded, false);
+ assert.deepEqual(seen.errors.filter((message) => !message.includes("blocked for test")), []);
+ } finally {
+ await context.close();
+ }
+ }
+
+ // An empty conversation (a new one behind the executed one) disables export.
+ const emptyId = crypto.randomUUID();
+ await api(`${assistant}/conversations`, { id: emptyId });
+ for (const locale of ["zh-CN", "en-US"]) {
+ const text = labels[locale];
+ const { context, page, seen } = await openContext(locale);
+ try {
+ await page.goto(tracePage(`conversation=${emptyId}`));
+ await page.getByText(text.empty, { exact: true }).waitFor();
+ assert.equal(await page.getByRole("button", { name: text.exportButton, exact: true }).isDisabled(), true);
+ assertReadOnly(seen);
+ } finally {
+ await context.close();
+ }
+ }
+} finally {
+ await browser.close();
+}
+console.log("trace report export: ok");