Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/release-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
35 changes: 32 additions & 3 deletions src/canvas/AssistantTracePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -297,14 +298,36 @@ const STATUS_KEYS: Record<ConversationTurn["status"], MessageKey> = {
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<Set<string>>(() => new Set());
const [loaded, setLoaded] = useState<Set<string>>(() => 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) => {
Expand All @@ -327,6 +350,12 @@ function ConversationTrace({ project, target, turns }: {

return (
<>
<div className="cw-trace-export">
<button type="button" disabled={exporting || turns.length === 0} onClick={() => void exportReport()}>
{t(exporting ? "trace.export.working" : "trace.export.button")}
</button>
{exportError && <span role="alert">{t("trace.export.failed")}</span>}
</div>
<nav className="cw-trace-turnnav" aria-label={t("trace.turns.nav")}>
{turns.map((item) => (
<button key={item.id} type="button" aria-pressed={open.has(item.id)}
Expand Down Expand Up @@ -405,7 +434,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
{!wide && <p><code>{turn}</code></p>}
</header>
{conversation === undefined ? <p role="status">{t("trace.loading")}</p> : wide ? (
<ConversationTrace project={project} target={turn} turns={conversation.turns} />
<ConversationTrace project={project} conversationId={conversation.id} target={turn} turns={conversation.turns} />
) : (
<TurnTrace project={project} turn={turn} runtime={runtime} live={live} />
)}
Expand Down
5 changes: 5 additions & 0 deletions src/canvas/assistant-trace.css
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
155 changes: 155 additions & 0 deletions src/canvas/traceExport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/** 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<string, unknown> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
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(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
.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<SourceReport> {
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 { 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 };
}
}

async function jobReport(fetcher: typeof fetch, base: string, turn: ConversationTurn): Promise<JobReport[] | null> {
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<string> {
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";
}
3 changes: 3 additions & 0 deletions src/i18n/messages/en-US/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
3 changes: 3 additions & 0 deletions src/i18n/messages/zh-CN/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": "该对话还没有已执行的轮次。",
Expand Down
9 changes: 9 additions & 0 deletions tests/browser/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading