diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml
index 938024f25..a338cc60c 100644
--- a/.github/workflows/release-checks.yml
+++ b/.github/workflows/release-checks.yml
@@ -311,6 +311,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_original_export.mjs
- name: Print isolated service logs on failure
if: failure()
run: |
diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md
index 5189d2628..27d903a38 100644
--- a/docs/architecture/agent-runtime.md
+++ b/docs/architecture/agent-runtime.md
@@ -106,6 +106,12 @@ CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不
## 对话轨迹页 / Conversation trace page
-轨迹页 `/?traceProject=…&conversation=…&turn=…` 在一页内按顺序列出一个对话的全部已执行轮次,每轮可独立展开,展开时才读取该轮日志与关联 Job。轮次索引来自只读接口 `GET .../assistant/conversations/{conversation_id}/trace`,它解析当前对话、已归档对话和 `reusedCreateIds` 别名,只返回轮次元数据(序号、用户输入摘要、运行时、状态),不读取日志正文,不激活对话,不获取编辑租约。轮次由持久化的身份关系确定:用户消息与 id 为 `uuid5(用户消息 id, 'assistant')` 的助手消息成对才算已执行的一轮;没有该助手记录的用户消息(例如排队中、未执行)不出现。每轮使用自己记录的运行时选择日志源和解析器,仅 Default(opencode)显示模型原始请求。`GET .../traces/{turn_id}/conversation` 供旧的单轮链接查找所属对话;找不到时保持原单轮页面。
+轨迹页 `/?traceProject=…&conversation=…&turn=…` 在一页内按顺序列出一个对话的全部已执行轮次,每轮可独立展开,展开时才读取该轮日志与关联 Job;“下载原始轨迹”是用户显式触发的例外,见下。轮次索引来自只读接口 `GET .../assistant/conversations/{conversation_id}/trace`,它解析当前对话、已归档对话和 `reusedCreateIds` 别名,只返回轮次元数据(序号、用户输入摘要、运行时、状态),不读取日志正文,不激活对话,不获取编辑租约。轮次由持久化的身份关系确定:用户消息与 id 为 `uuid5(用户消息 id, 'assistant')` 的助手消息成对才算已执行的一轮;没有该助手记录的用户消息(例如排队中、未执行)不出现。每轮使用自己记录的运行时选择日志源和解析器,仅 Default(opencode)显示模型原始请求。`GET .../traces/{turn_id}/conversation` 供旧的单轮链接查找所属对话;找不到时保持原单轮页面。
-English summary: the trace page lists every executed turn of a conversation, expanded one at a time, and reads a turn's logs and linked Jobs only when it is opened. The turn index comes from the read-only `GET .../assistant/conversations/{conversation_id}/trace`, which resolves current, archived and aliased (`reusedCreateIds`) conversation ids and returns metadata only (number, input summary, runtime, status). It never reads log bodies, activates a conversation or takes a lease. A turn is a user message paired with the assistant message whose id is `uuid5(user id, 'assistant')`, so queued or never executed user messages are not listed. Each turn uses its own recorded runtime for the log source and parser, and raw model requests are offered for the Default (opencode) runtime only. `GET .../traces/{turn_id}/conversation` lets old single-turn links find their conversation; when none is found the single-turn page remains.
+English summary: the trace page lists every executed turn of a conversation, expanded one at a time, and reads a turn's logs and linked Jobs only when it is opened; the user-triggered original trace download is the one exception (below). The turn index comes from the read-only `GET .../assistant/conversations/{conversation_id}/trace`, which resolves current, archived and aliased (`reusedCreateIds`) conversation ids and returns metadata only (number, input summary, runtime, status). It never reads log bodies, activates a conversation or takes a lease. A turn is a user message paired with the assistant message whose id is `uuid5(user id, 'assistant')`, so queued or never executed user messages are not listed. Each turn uses its own recorded runtime for the log source and parser, and raw model requests are offered for the Default (opencode) runtime only. `GET .../traces/{turn_id}/conversation` lets old single-turn links find their conversation; when none is found the single-turn page remains.
+
+### 原始轨迹归档 / Original trace archive
+
+“下载原始轨迹”由前端完成,不新增或修改后端接口,复用 `src/canvas/zipArchive.ts` 的 `createZip()`(`compress: false`,保留原始字节)与 `downloadFile()`。流程:先重新请求 `GET .../conversations/{conversation_id}/trace`,任何轮次为 `streaming` 即拒绝;随后对每轮按其运行时逐个请求 `GET .../traces/{turn_id}/{source}`(404 记为 `missing`,其他非 2xx、超时、响应提前结束、超限一律失败),读完后再次校验轮次状态,不一致则失败。任何失败都不产出 ZIP。因此归档是逐来源读取的结果,不是跨文件原子快照,`manifest.json` 的 `snapshot` 字段如实说明。容量上限为 64 MiB,含每个条目的本地头、中央目录项、结束记录和 manifest,没有单文件上限,超限时错误指出轮次与来源。每个请求和整个导出都有超时,用户可取消,读取流在失败、超限、取消时被取消并释放。内容不脱敏,`model.jsonl` 原样包含;`manifest.json` 区分 Job 为空(`jobs: []`)与查询失败(`jobs: null`、`jobsStatus: "unavailable"`)。
+
+English summary: the download is built in the frontend with no backend change, reusing `createZip()` (`compress: false`, original bytes) and `downloadFile()`. It re-fetches the conversation trace index and refuses when any turn is `streaming`, reads each source sequentially (404 becomes `missing`; any other non-2xx, timeout, early end or cap overrun fails), then re-checks turn status and fails on any difference. No failure produces a ZIP, and the archive is explicitly a per-source read, not an atomic snapshot across files (`manifest.json` says so). The 64 MiB cap covers raw bytes plus ZIP headers, central directory, end record and manifest; there is no per-file cap, and an overrun names the turn and source. Requests and the whole export are time-bounded, the user can cancel, and streams are cancelled and released on failure, overrun or cancel. Content is not redacted (`model.jsonl` included). The manifest separates no linked Jobs (`jobs: []`) from a failed lookup (`jobs: null`, `jobsStatus: "unavailable"`).
diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md
index 0e9cc762e..328b650c3 100644
--- a/docs/guides/user-guide.md
+++ b/docs/guides/user-guide.md
@@ -156,6 +156,14 @@ Use **New conversation** at the top of the panel to start a separate chat. **Con
Asset generation may continue after the reply ends. Check its progress in **Generation history**.
+### Download the original trace
+
+Open the conversation trace page and choose **Download original trace (.zip)** to save the raw per-turn log files for local debugging. The ZIP holds one `manifest.json` and, under `turn-NNNN/`, the unmodified `.jsonl` log of each source (the Default runtime also includes `model.jsonl`, the model requests). Nothing is redacted, so the files can contain credentials, prompts, tool inputs and outputs and private paths. A confirmation appears first; review the files before sharing them.
+
+- The archive is read source by source and is not an atomic snapshot across files. It is only built when no turn is running, and turn status is checked again at click time and after reading. While a turn is running the button is disabled; wait for it to finish.
+- A source file that does not exist is listed as `missing` in `manifest.json`. A failed Jobs lookup is recorded as `jobsStatus: "unavailable"`, which differs from a turn that has no linked Jobs (`jobs: []`).
+- The total is capped at 64 MiB including ZIP overhead. If a read fails, times out, ends early, or goes over the cap, the page names the turn and source and no ZIP is saved. You can cancel while it is preparing.
+
## Edit images, video, and audio
Select a node, then choose an action from its toolbar.
diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md
index fcb1992a8..43aa920c7 100644
--- a/docs/guides/user-guide.zh-CN.md
+++ b/docs/guides/user-guide.zh-CN.md
@@ -156,6 +156,14 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制
素材生成可能在回复结束后继续进行,可在“生成历史”查看进度。
+### 下载原始轨迹
+
+在对话轨迹页选择“下载原始轨迹(.zip)”,可保存各轮次的原始日志文件,供本地排障。ZIP 内含一个 `manifest.json`,以及 `turn-NNNN/` 目录下各来源未经修改的 `.jsonl` 日志(Default 运行时另含记录模型请求的 `model.jsonl`)。内容不做脱敏,可能包含密钥、提示词、工具输入输出和私有路径。下载前会先弹出确认,分享前请自行检查文件内容。
+
+- 压缩包是逐个来源读取的归档,不是跨文件的原子快照。仅在没有轮次执行时才会生成;点击时和读取结束后都会重新校验轮次状态。有轮次正在执行时按钮不可用,请等待结束。
+- 不存在的来源文件在 `manifest.json` 中标记为 `missing`。Job 查询失败记为 `jobsStatus: "unavailable"`,与没有关联 Job(`jobs: []`)不同。
+- 总大小(含 ZIP 开销)上限为 64 MiB。读取失败、超时、响应提前结束或超限时,页面会指出轮次和来源,且不保存任何 ZIP。准备过程中可以取消。
+
## 编辑图片、视频和音频
选中节点,通过工具栏选择所需操作。
diff --git a/src/canvas/AssistantTracePage.tsx b/src/canvas/AssistantTracePage.tsx
index a07a40e85..7f57bedf5 100644
--- a/src/canvas/AssistantTracePage.tsx
+++ b/src/canvas/AssistantTracePage.tsx
@@ -7,6 +7,8 @@ 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 { downloadFile } from "./assets.ts";
+import { conversationTraceArchive, TraceExportError } from "./traceExport.ts";
import "./assistant-trace.css";
@@ -297,14 +299,51 @@ 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(null);
+ const exportAbort = useRef(null);
+ const running = turns.some((item) => item.status === "streaming");
+ useEffect(() => () => exportAbort.current?.abort(), []);
+ function exportMessage(error: unknown): string | null {
+ if (!(error instanceof TraceExportError)) return t("trace.export.failed");
+ const { turn, source, status, limit } = error.detail;
+ const params = { turn: turn ?? "-", source: source ?? "-", status: status ?? "-",
+ limit: limit ? Math.round(limit / 1048576) : 0 };
+ switch (error.code) {
+ case "aborted": return null;
+ case "running": return t("trace.export.error.running", params);
+ case "tooLarge": return t("trace.export.error.tooLarge", params);
+ case "tooManyFiles": return t("trace.export.error.tooManyFiles", params);
+ case "timeout": return t("trace.export.error.timeout", params);
+ case "changed": return t("trace.export.error.changed", params);
+ case "incomplete": return t("trace.export.error.incomplete", params);
+ default: return t("trace.export.error.read", params);
+ }
+ }
+ async function exportArchive() {
+ if (exporting || running || !window.confirm(t("trace.export.warning"))) return;
+ const controller = new AbortController();
+ exportAbort.current = controller;
+ setExporting(true);
+ setExportError(null);
+ try {
+ const archive = await conversationTraceArchive(project, conversationId, { signal: controller.signal });
+ downloadFile(archive, "opendirector-trace-" + conversationId + ".zip");
+ } catch (error) {
+ setExportError(exportMessage(error));
+ } finally {
+ exportAbort.current = null;
+ setExporting(false);
+ }
+ }
function toggle(id: string, value: boolean) {
setOpen((previous) => {
@@ -327,6 +366,14 @@ function ConversationTrace({ project, target, turns }: {
return (
<>
+
+ void exportArchive()}>
+ {t(exporting ? "trace.export.working" : "trace.export.button")}
+
+ {exporting && exportAbort.current?.abort()}>{t("trace.export.cancel")} }
+ {running && !exporting && {t("trace.export.blockedRunning")} }
+ {exportError && {exportError} }
+
{turns.map((item) => (
{turn}
}
{conversation === undefined ? {t("trace.loading")}
: wide ? (
-
+
) : (
)}
diff --git a/src/canvas/assistant-trace.css b/src/canvas/assistant-trace.css
index 6d612878c..8913b8ca0 100644
--- a/src/canvas/assistant-trace.css
+++ b/src/canvas/assistant-trace.css
@@ -100,3 +100,9 @@
.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: not-allowed; opacity: .6; }
+.cw-trace-export span[role="status"] { color: #e4c88a; }
+.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..90da0032c
--- /dev/null
+++ b/src/canvas/traceExport.ts
@@ -0,0 +1,247 @@
+/** Exact-byte, user-triggered archive of per-turn raw trace files. No normalization or redaction.
+ * Sources are read one at a time, so the archive is not an atomic snapshot: it is only produced
+ * when no turn is running before and after the reads, and any inconsistency fails the export. */
+import { createZip, type ZipEntry } from "./zipArchive.ts";
+import { traceRuntime, traceSources, type ConversationTurn } from "./traceTurns.ts";
+
+/** Total budget for raw bytes plus ZIP headers, central directory and manifest. */
+export const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
+const MAX_FILES = 512;
+const REQUEST_TIMEOUT_MS = 60_000;
+const TOTAL_TIMEOUT_MS = 10 * 60_000;
+const SOURCES = new Set(["opencode", "model", "codex", "claude", "jiuwenswarm", "deepseek"]);
+const encoder = new TextEncoder();
+
+export type TraceExportErrorCode =
+ | "running" | "tooLarge" | "tooManyFiles" | "read" | "incomplete" | "changed" | "timeout" | "aborted";
+
+/** Failure with enough structure for the UI to name the turn and source involved. */
+export type TraceExportDetail = {
+ turn?: number; source?: string; status?: number; limit?: number; cause?: unknown };
+
+export class TraceExportError extends Error {
+ readonly code: TraceExportErrorCode;
+ readonly detail: TraceExportDetail;
+ constructor(code: TraceExportErrorCode, detail: TraceExportDetail = {}) {
+ super("Trace export failed: " + code
+ + (detail.turn ? " turn " + detail.turn : "") + (detail.source ? " " + detail.source : "")
+ + (detail.status ? " HTTP " + detail.status : ""));
+ this.name = "TraceExportError";
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+export type TraceExportOptions = {
+ fetcher?: typeof fetch;
+ generatedAt?: string;
+ signal?: AbortSignal;
+ /** Bound for one request including its body. */
+ requestTimeoutMs?: number;
+ /** Bound for the whole export. */
+ totalTimeoutMs?: number;
+ /** Raw data and archive overhead cap. */
+ maxArchiveBytes?: number;
+};
+
+type SourceEntry = { source: string; file?: string; bytes?: number; status: "included" | "missing" | "unsupported" };
+type JobEntry = { jobId: string; status: string; adopted: boolean };
+type ManifestTurn = {
+ id: string; number: number; runtime: string; status: string;
+ sources: SourceEntry[]; jobs: JobEntry[] | null; jobsStatus: "ok" | "unavailable";
+};
+
+const HEADERS = { "X-OpenDirector-Request": "1" };
+
+/** Reject as soon as the signal aborts, even if the underlying fetcher ignores it. */
+function guard(work: Promise, signal: AbortSignal): Promise {
+ if (signal.aborted) return Promise.reject(signal.reason);
+ return new Promise((resolve, reject) => {
+ const onAbort = () => reject(signal.reason);
+ signal.addEventListener("abort", onAbort, { once: true });
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
+ });
+}
+
+/** Per-request signal that aborts on timeout (request or remaining total) or the caller's signal. */
+function requestScope(outer: AbortSignal, timeoutMs: number, turn?: number, source?: string) {
+ const controller = new AbortController();
+ const forward = () => controller.abort(outer.reason);
+ if (outer.aborted) forward(); else outer.addEventListener("abort", forward, { once: true });
+ const timer = setTimeout(() => controller.abort(new TraceExportError("timeout", { turn, source })), timeoutMs);
+ return {
+ signal: controller.signal,
+ done() { clearTimeout(timer); outer.removeEventListener("abort", forward); },
+ };
+}
+
+async function discard(response: Response): Promise {
+ await response.body?.cancel().catch(() => undefined);
+}
+
+/** Read bytes, not text; cancel the stream on any failure so no response is left open. */
+async function readBytes(response: Response, limit: number, cap: number, signal: AbortSignal,
+ turn: number, source: string): Promise {
+ const tooLarge = () => new TraceExportError("tooLarge", { turn, source, limit: cap });
+ const header = response.headers.get("content-length");
+ const declared = header !== null && /^\d+$/.test(header) ? Number(header) : undefined;
+ if (declared !== undefined && declared > limit) { await discard(response); throw tooLarge(); }
+ if (!response.body) {
+ const value = new Uint8Array(await guard(response.arrayBuffer(), signal));
+ if (value.byteLength > limit) throw tooLarge();
+ if (declared !== undefined && value.byteLength !== declared)
+ throw new TraceExportError("incomplete", { turn, source });
+ return value;
+ }
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ let finished = false;
+ try {
+ while (true) {
+ const { done, value } = await guard(reader.read(), signal);
+ if (done) { finished = true; break; }
+ size += value.byteLength;
+ if (size > limit) throw tooLarge();
+ chunks.push(value);
+ }
+ if (declared !== undefined && size !== declared) throw new TraceExportError("incomplete", { turn, source });
+ } catch (error) {
+ if (error instanceof TraceExportError) throw error;
+ if (signal.aborted) throw signal.reason;
+ throw new TraceExportError("incomplete", { turn, source, cause: error });
+ } finally {
+ if (!finished) await Promise.resolve(reader.cancel()).catch(() => undefined);
+ reader.releaseLock();
+ }
+ const result = new Uint8Array(size);
+ let cursor = 0;
+ for (const chunk of chunks) { result.set(chunk, cursor); cursor += chunk.byteLength; }
+ return result;
+}
+
+async function fetchTurns(fetcher: typeof fetch, base: string, id: string,
+ signal: AbortSignal): Promise {
+ const response = await guard(fetcher(base + "/conversations/" + encodeURIComponent(id) + "/trace",
+ { headers: HEADERS, signal }), signal);
+ if (!response.ok) {
+ await discard(response);
+ throw new TraceExportError("read", { source: "trace index", status: response.status });
+ }
+ const body = await guard(response.json(), signal) as { turns?: unknown };
+ if (!Array.isArray(body.turns)) throw new TraceExportError("read", { source: "trace index" });
+ return body.turns as ConversationTurn[];
+}
+
+/** An unavailable Jobs lookup is recorded as `jobs: null`; a lookup with no Jobs is `[]`. */
+async function linkedJobs(fetcher: typeof fetch, base: string, id: string,
+ signal: AbortSignal): Promise {
+ try {
+ const response = await guard(fetcher(base + "/turns/" + encodeURIComponent(id) + "/jobs",
+ { headers: HEADERS, signal }), signal);
+ if (!response.ok) { await discard(response); return null; }
+ const payload: unknown = await guard(response.json(), signal);
+ if (!Array.isArray(payload)) return null;
+ return payload.flatMap((entry: unknown) => {
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
+ const value = entry as Record;
+ if (typeof value.jobId !== "string") return [];
+ return [{ jobId: value.jobId, status: typeof value.status === "string" ? value.status : "unknown",
+ adopted: value.adopted === true }];
+ });
+ } catch (error) {
+ if (signal.aborted) throw signal.reason;
+ return null;
+ }
+}
+
+const archiveOverhead = (path: string) => 30 + 46 + 2 * encoder.encode(path).length;
+const END_RECORD = 22;
+
+function assertIdle(turns: ConversationTurn[]): void {
+ const running = turns.find((turn) => turn.status === "streaming");
+ if (running) throw new TraceExportError("running", { turn: running.number });
+}
+
+/**
+ * Re-checks turn status, then reads every source as-is. Missing (404) logs appear in the
+ * manifest; any other failure, size overrun, timeout or cancellation aborts the whole export
+ * and no archive is returned. All turns are included, regardless of which UI panels are expanded.
+ */
+export async function conversationTraceArchive(project: string, conversationId: string,
+ options: TraceExportOptions = {}): Promise {
+ const fetcher = options.fetcher ?? ((...args: Parameters) => fetch(...args));
+ const limit = options.maxArchiveBytes ?? MAX_ARCHIVE_BYTES;
+ const requestTimeout = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
+ const generatedAt = options.generatedAt ?? new Date().toISOString();
+ const base = "/api/creation/projects/" + encodeURIComponent(project) + "/assistant";
+ const started = Date.now();
+ const total = options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS;
+ const outer = options.signal ?? new AbortController().signal;
+ const mapAbort = (error: unknown) => {
+ if (error instanceof TraceExportError) return error;
+ return outer.aborted ? new TraceExportError("aborted") : error;
+ };
+ const scoped = async (turn: number | undefined, source: string | undefined,
+ work: (signal: AbortSignal) => Promise): Promise => {
+ const remaining = total - (Date.now() - started);
+ if (remaining <= 0) throw new TraceExportError("timeout", { turn, source });
+ const scope = requestScope(outer, Math.min(requestTimeout, remaining), turn, source);
+ try { return await work(scope.signal); } catch (error) { throw mapAbort(error); } finally { scope.done(); }
+ };
+
+ const turns = await scoped(undefined, "trace index", (signal) => fetchTurns(fetcher, base, conversationId, signal));
+ assertIdle(turns);
+ const files: ZipEntry[] = [];
+ const manifestTurns: ManifestTurn[] = [];
+ let used = END_RECORD + archiveOverhead("manifest.json");
+ for (const [index, turn] of turns.entries()) {
+ const sources: SourceEntry[] = [];
+ const directory = "turn-" + String(index + 1).padStart(4, "0") + "/";
+ for (const source of traceSources(traceRuntime(turn.runtime))) {
+ if (!SOURCES.has(source)) { sources.push({ source, status: "unsupported" }); continue; }
+ const path = directory + source + ".jsonl";
+ if (files.length >= MAX_FILES) throw new TraceExportError("tooManyFiles", { turn: turn.number, source });
+ const bytes = await scoped(turn.number, source, async (signal) => {
+ let response: Response;
+ try {
+ response = await guard(fetcher(base + "/traces/" + encodeURIComponent(turn.id) + "/" +
+ encodeURIComponent(source), { headers: HEADERS, signal }), signal);
+ } catch (error) {
+ if (signal.aborted) throw signal.reason;
+ throw new TraceExportError("read", { turn: turn.number, source, cause: error });
+ }
+ if (response.status === 404) { await discard(response); return undefined; }
+ if (!response.ok) {
+ await discard(response);
+ throw new TraceExportError("read", { turn: turn.number, source, status: response.status });
+ }
+ return readBytes(response, limit - used - archiveOverhead(path), limit, signal, turn.number, source);
+ });
+ if (!bytes) { sources.push({ source, status: "missing" }); continue; }
+ files.push({ path, data: bytes, compress: false });
+ used += bytes.byteLength + archiveOverhead(path);
+ sources.push({ source, file: path, bytes: bytes.byteLength, status: "included" });
+ }
+ const jobs = await scoped(turn.number, "jobs", (signal) => linkedJobs(fetcher, base, turn.id, signal));
+ manifestTurns.push({ id: turn.id, number: turn.number, runtime: turn.runtime, status: turn.status,
+ sources, jobs, jobsStatus: jobs === null ? "unavailable" : "ok" });
+ }
+
+ // Sources were read one by one: refuse an archive if the turns changed or started running meanwhile.
+ const after = await scoped(undefined, "trace index", (signal) => fetchTurns(fetcher, base, conversationId, signal));
+ assertIdle(after);
+ const key = (list: ConversationTurn[]) => JSON.stringify(list.map((turn) => [turn.id, turn.status]));
+ if (key(after) !== key(turns)) throw new TraceExportError("changed");
+
+ const manifest = encoder.encode(JSON.stringify({
+ format: "opendirector-original-trace-archive", version: 1,
+ projectId: project, conversationId, exportedAt: generatedAt,
+ snapshot: "Each source file was read separately after confirming no turn was running, and turn status was re-checked afterwards. This is not an atomic snapshot across files.",
+ warning: "Original trace data may include credentials, prompts, tool inputs/outputs and private paths. Review before sharing.",
+ turns: manifestTurns,
+ }, null, 2) + "\n");
+ if (used + manifest.length > limit)
+ throw new TraceExportError("tooLarge", { source: "manifest.json", limit });
+ return createZip([{ path: "manifest.json", data: manifest, compress: false }, ...files], new Date(generatedAt));
+}
diff --git a/src/i18n/messages/en-US/trace.ts b/src/i18n/messages/en-US/trace.ts
index 115e1762f..5f7002f55 100644
--- a/src/i18n/messages/en-US/trace.ts
+++ b/src/i18n/messages/en-US/trace.ts
@@ -35,6 +35,19 @@ export const trace = {
"trace.jobs.adopted": "Adopted",
"trace.jobs.notAdopted": "Not adopted",
"trace.jobs.cancelRequested": "Cancel requested",
+ "trace.export.button": "Download original trace (.zip)",
+ "trace.export.working": "Preparing trace archive…",
+ "trace.export.warning": "Original trace logs may contain secrets, prompts, tool arguments, model responses and private paths. Download for local debugging only and review before sharing. Continue?",
+ "trace.export.failed": "Could not download original traces. No partial archive was saved.",
+ "trace.export.cancel": "Cancel",
+ "trace.export.blockedRunning": "A turn is still running. Wait for it to finish before downloading original traces.",
+ "trace.export.error.running": "Turn {turn} is still running. Wait for it to finish, then download again. No archive was saved.",
+ "trace.export.error.tooLarge": "The original traces exceed the {limit} MiB archive limit (including ZIP overhead). Stopped at turn {turn}, source {source}. No archive was saved.",
+ "trace.export.error.tooManyFiles": "Too many trace files to archive. Stopped at turn {turn}, source {source}. No archive was saved.",
+ "trace.export.error.timeout": "Reading original traces timed out at turn {turn}, source {source}. No archive was saved.",
+ "trace.export.error.changed": "The conversation changed while its traces were being read. Try again. No archive was saved.",
+ "trace.export.error.incomplete": "The response for turn {turn}, source {source} ended early or the file changed while reading. No archive was saved.",
+ "trace.export.error.read": "Could not read turn {turn}, source {source} (HTTP {status}). No archive was saved.",
"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..51ded508a 100644
--- a/src/i18n/messages/zh-CN/trace.ts
+++ b/src/i18n/messages/zh-CN/trace.ts
@@ -35,6 +35,19 @@ export const trace = {
"trace.jobs.adopted": "已采用",
"trace.jobs.notAdopted": "未采用",
"trace.jobs.cancelRequested": "已请求取消",
+ "trace.export.button": "下载原始轨迹(.zip)",
+ "trace.export.working": "正在打包原始轨迹…",
+ "trace.export.warning": "原始轨迹可能包含密钥、提示词、工具参数、模型响应和私有路径。仅供本地排障,分享前请检查文件内容。继续下载?",
+ "trace.export.failed": "原始轨迹下载失败,未保存不完整压缩包。",
+ "trace.export.cancel": "取消",
+ "trace.export.blockedRunning": "有轮次仍在执行。请等待执行结束后再下载原始轨迹。",
+ "trace.export.error.running": "第 {turn} 轮仍在执行。请等待结束后重新下载,未保存任何压缩包。",
+ "trace.export.error.tooLarge": "原始轨迹超过 {limit} MiB 的压缩包上限(含 ZIP 开销)。在第 {turn} 轮、来源 {source} 处停止,未保存任何压缩包。",
+ "trace.export.error.tooManyFiles": "轨迹文件过多无法打包。在第 {turn} 轮、来源 {source} 处停止,未保存任何压缩包。",
+ "trace.export.error.timeout": "读取第 {turn} 轮、来源 {source} 的原始轨迹超时,未保存任何压缩包。",
+ "trace.export.error.changed": "读取轨迹期间对话发生变化,请重试,未保存任何压缩包。",
+ "trace.export.error.incomplete": "第 {turn} 轮、来源 {source} 的响应提前结束或文件在读取时发生变化,未保存任何压缩包。",
+ "trace.export.error.read": "无法读取第 {turn} 轮、来源 {source}(HTTP {status}),未保存任何压缩包。",
"trace.conversationTitle": "对话轨迹",
"trace.turns.nav": "轮次",
"trace.turns.empty": "该对话还没有已执行的轮次。",
diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json
index 5301eee5d..a4fcbb666 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_original_export.mjs",
+ "fixture": true,
+ "previewSafe": true,
+ "lanes": [
+ "gate"
+ ],
+ "note": "Bilingual original Trace ZIP archive download on assistant fixture services; only linked Jobs are stubbed."
+ },
{
"file": "assistant_run_navigation.mjs",
"fixture": true,
diff --git a/tests/browser/trace_original_export.mjs b/tests/browser/trace_original_export.mjs
new file mode 100644
index 000000000..c2168674f
--- /dev/null
+++ b/tests/browser/trace_original_export.mjs
@@ -0,0 +1,452 @@
+/** Original Trace archive export (#421): real UI click, real ZIP 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 { createHash } from "node:crypto";
+import { spawnSync } from "node:child_process";
+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
+// raw traces are intentionally sensitive; fixtures contain only synthetic sentinels.
+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 = {
+ [turns[0].id + ".model.jsonl"]: line({ event: "model.request", payload: { messages: [{ content: system }], apiKey: key } }),
+ // 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);
+if (evidence) {
+ // Source copies (as written on disk) so standard tools can compare hashes with the archive.
+ await mkdir(join(evidence, "sources"), { recursive: true });
+ for (const [name, content] of Object.entries(logs)) {
+ const index = turns.findIndex((turn) => name.startsWith(turn.id + "."));
+ await writeFile(join(evidence, "sources", "turn-" + String(index + 1).padStart(4, "0") + "-" + name.slice(turns[index].id.length + 1)), 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}`;
+/** Read the archive the way unzip does: EOCD, then the central directory, never by scanning local headers. */
+function unpack(zip) {
+ const files = new Map();
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
+ const eocd = zip.length - 22;
+ assert.equal(view.getUint32(eocd, true), 0x06054b50, "ZIP end record exists");
+ const count = view.getUint16(eocd + 10, true);
+ const size = view.getUint32(eocd + 12, true);
+ const offset = view.getUint32(eocd + 16, true);
+ assert.equal(offset + size, eocd, "central directory ends at the end record");
+ let at = offset;
+ for (let index = 0; index < count; index++) {
+ assert.equal(view.getUint32(at, true), 0x02014b50, "central header");
+ assert.equal(view.getUint16(at + 10, true), 0, "ZIP file uses STORE");
+ const length = view.getUint32(at + 20, true);
+ const nameLength = view.getUint16(at + 28, true);
+ const local = view.getUint32(at + 42, true);
+ assert.equal(view.getUint32(local, true), 0x04034b50, "local header at central offset");
+ const name = zip.subarray(at + 46, at + 46 + nameLength).toString("utf8");
+ const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
+ files.set(name, zip.subarray(start, start + length));
+ at += 46 + nameLength + view.getUint16(at + 30, true) + view.getUint16(at + 32, true);
+ }
+ assert.equal(at, eocd, "central directory size matches its entries");
+ return files;
+}
+/** Standard tools, when installed, must also accept the downloaded file. */
+function standardTools(path) {
+ const tools = [
+ ["python3", ["-c", "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.testzip() is None", path]],
+ ["unzip", ["-tq", path]],
+ ];
+ const ran = [];
+ for (const [command, args] of tools) {
+ const result = spawnSync(command, args, { encoding: "utf8" });
+ if (result.error?.code === "ENOENT") continue;
+ assert.equal(result.status, 0, command + ": " + result.stdout + result.stderr);
+ ran.push(command);
+ }
+ return ran;
+}
+const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
+
+const labels = {
+ "zh-CN": { exportButton: "下载原始轨迹(.zip)", failed: "原始轨迹下载失败,未保存不完整压缩包。",
+ running: "有轮次仍在执行。请等待执行结束后再下载原始轨迹。",
+ runningError: /第 2 轮仍在执行/, tooLarge: /64 MiB.*第 1 轮、来源 model/, read403: /第 2 轮、来源 codex(HTTP 403)/,
+ empty: "该对话还没有已执行的轮次。", title: "对话轨迹" },
+ "en-US": { exportButton: "Download original trace (.zip)",
+ failed: "Could not download original traces. No partial archive was saved.",
+ running: "A turn is still running. Wait for it to finish before downloading original traces.",
+ runningError: /Turn 2 is still running/, tooLarge: /64 MiB archive limit.*turn 1, source model/, read403: /turn 2, source codex \(HTTP 403\)/,
+ 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);
+ page.on("dialog", (dialog) => dialog.accept()); // Accept the sensitive raw-data warning explicitly.
+ 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 exportArchive(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(),
+ ]);
+ 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)), "model requests are included");
+ assert.ok(!during.some((entry) => /\/stop$|\/events$|\/resume|\/cancel|\/turns$/.test(entry)));
+ assert.equal(download.suggestedFilename(), "opendirector-trace-" + conversationId + ".zip");
+ const path = await download.path();
+ assert.ok(path);
+ const tools = standardTools(path);
+ if (evidence) {
+ await mkdir(evidence, { recursive: true });
+ await writeFile(join(evidence, "download-" + Date.now() + ".zip"), await readFile(path));
+ await writeFile(join(evidence, "standard-tools.txt"), "ran: " + tools.join(", ") + "\n", { flag: "a" });
+ }
+ return unpack(await readFile(path));
+ }
+ function assertArchive(files) {
+ const manifest = JSON.parse(files.get("manifest.json").toString("utf8"));
+ assert.equal(manifest.format, "opendirector-original-trace-archive");
+ assert.equal(manifest.projectId, projectId);
+ assert.equal(manifest.conversationId, conversationId);
+ assert.equal(manifest.turns.length, 4);
+ const names = [...files.keys()];
+ assert.deepEqual(names, ["manifest.json", "turn-0001/model.jsonl", "turn-0001/opencode.jsonl",
+ "turn-0002/codex.jsonl", "turn-0004/codex.jsonl"]);
+ assert.ok(manifest.warning.includes("credentials"));
+ assert.equal(manifest.turns[0].jobs[0].jobId, jobIds.succeeded);
+ assert.equal(manifest.turns[1].jobs[0].status, "failed");
+ assert.equal(manifest.turns[2].jobs[0].status, "running");
+ assert.equal(manifest.turns[2].sources[0].status, "missing");
+ assert.equal(manifest.turns[3].jobs, null);
+ assert.equal(manifest.turns[3].jobsStatus, "unavailable", "failed Jobs lookup is not an empty list");
+ assert.equal(manifest.turns[0].jobsStatus, "ok");
+ assert.match(manifest.snapshot, /not an atomic snapshot/);
+ assert.equal(manifest.turns[0].sources[0].source, "model");
+ for (const [file, content] of Object.entries(logs)) {
+ const index = turns.findIndex((turn) => file.startsWith(turn.id + "."));
+ const name = "turn-" + String(index + 1).padStart(4, "0") + "/" +
+ file.slice(turns[index].id.length + 1);
+ assert.equal(files.get(name)?.toString("utf8"), content, "raw byte-for-byte preservation: " + file);
+ }
+ const raw = [...files.values()].map((value) => value.toString("utf8")).join("\n");
+ for (const sentinel of SECRETS)
+ assert.ok(raw.includes(sentinel), "raw diagnostic content preserved: " + sentinel);
+ assert.ok(raw.includes("not json "), "invalid JSONL lines must not be discarded");
+ }
+ 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 archive 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 files = await exportArchive(page, seen, text);
+ assertArchive(files);
+ 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) await writeFile(join(evidence, "manifest-" + locale + ".json"), files.get("manifest.json"));
+
+ // 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();
+ assertArchive(await exportArchive(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();
+ }
+ }
+
+ // Blocked, refused and oversized exports: explicit message, no download, no partial ZIP.
+ const indexRoute = /\/assistant\/conversations\/[^/]+\/trace$/;
+ async function withStatus(page, state) {
+ await page.route(indexRoute, async (route) => {
+ try {
+ const response = await route.fetch();
+ const body = await response.json();
+ if (state.streaming) body.turns[1].status = "streaming";
+ await route.fulfill({ response, json: body });
+ } catch {
+ // The page navigated away or closed while this poll was in flight.
+ }
+ });
+ }
+ for (const locale of ["zh-CN", "en-US"]) {
+ const text = labels[locale];
+ const { context, page, seen } = await openContext(locale);
+ try {
+ const downloads = [];
+ page.on("download", (download) => downloads.push(download));
+ const state = { streaming: true };
+ await withStatus(page, state);
+ const button = page.getByRole("button", { name: text.exportButton, exact: true });
+
+ // A streaming turn in the conversation disables the button and says why.
+ await page.goto(tracePage(`conversation=${conversationId}&turn=${turns[0].id}`));
+ await page.getByText(text.running, { exact: true }).waitFor();
+ assert.equal(await button.isDisabled(), true);
+
+ // Stale page state: the page shows the conversation as idle, the server now says streaming.
+ state.streaming = false;
+ await page.goto(tracePage(`conversation=${conversationId}&turn=${turns[0].id}`));
+ await button.waitFor();
+ await page.waitForFunction(() => !document.body.textContent.includes("still running") && !document.body.textContent.includes("仍在执行"));
+ assert.equal(await button.isEnabled(), true);
+ state.streaming = true;
+ const before = seen.requests.length;
+ await button.click();
+ await page.getByRole("alert").filter({ hasText: text.runningError }).waitFor();
+ assert.ok(!seen.requests.slice(before).some((entry) => /\/traces\/[^/]+\/(model|opencode|codex)$/.test(entry)),
+ "no log is read once the recheck sees a running turn");
+ state.streaming = false;
+
+ // 403 on one source aborts the whole export.
+ await page.route(new RegExp(`/traces/${turns[1].id}/codex$`), (route) =>
+ route.fulfill({ status: 403, body: "denied" }));
+ await button.click();
+ await page.getByRole("alert").filter({ hasText: text.read403 }).waitFor();
+ await page.unroute(new RegExp(`/traces/${turns[1].id}/codex$`));
+
+ // Over the 64 MiB total: names turn 1 and source model.
+ const huge = Buffer.alloc(65 * 1024 * 1024, 0x61);
+ const modelUrl = new RegExp(`/traces/${turns[0].id}/model$`);
+ await page.route(modelUrl, (route) => route.fulfill({ status: 200, body: huge }));
+ await button.click();
+ await page.getByRole("alert").filter({ hasText: text.tooLarge }).waitFor();
+ await page.unroute(modelUrl);
+ assert.equal(await button.isEnabled(), true);
+ await sleep(300);
+ assert.equal(downloads.length, 0, "failures never produce a download");
+ assertReadOnly(seen);
+ } finally {
+ await context.close();
+ }
+ }
+
+ // A single 48 MiB source exports under the 64 MiB total, byte for byte (route-intercepted response).
+ {
+ const text = labels["en-US"];
+ const { context, page, seen } = await openContext("en-US");
+ try {
+ const big = Buffer.alloc(48 * 1024 * 1024);
+ for (let index = 0; index < big.length; index += 7) big[index] = (index >> 3) & 0x7f | 0x20;
+ for (let index = 0; index < big.length; index += 1000) big[index] = 0x0a;
+ await page.route(new RegExp(`/traces/${turns[1].id}/codex$`), (route) =>
+ route.fulfill({ status: 200, body: big }));
+ await page.goto(tracePage(`conversation=${conversationId}&turn=${turns[1].id}`));
+ const files = await exportArchive(page, seen, text);
+ const entry = files.get("turn-0002/codex.jsonl");
+ assert.equal(entry.length, big.length);
+ assert.equal(sha256(entry), sha256(big));
+ assert.equal(files.get("turn-0001/opencode.jsonl")?.toString("utf8"), logs[turns[0].id + ".opencode.jsonl"]);
+ assertReadOnly(seen);
+ } 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("original trace ZIP archive: ok");
diff --git a/tests/traceExport.test.ts b/tests/traceExport.test.ts
new file mode 100644
index 000000000..35fe32c04
--- /dev/null
+++ b/tests/traceExport.test.ts
@@ -0,0 +1,281 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import test from "node:test";
+import { conversationTraceArchive, TraceExportError, type TraceExportErrorCode } from "../src/canvas/traceExport.ts";
+import type { ConversationTurn } from "../src/canvas/traceTurns.ts";
+import { parseZip } from "./traceZip.ts";
+
+const encoder = new TextEncoder();
+const MiB = 1024 * 1024;
+const turn = (id: string, number: number, runtime: string = "default",
+ status: ConversationTurn["status"] = "complete"): ConversationTurn =>
+ ({ id, number, text: "A request", runtime, model: "test", status });
+const sha = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
+
+type Log = Uint8Array | null | number | (() => Response);
+type Setup = {
+ turns: ConversationTurn[];
+ /** Index responses after the first one (default: unchanged). */
+ later?: ConversationTurn[][];
+ logs?: Record;
+ jobs?: (turnId: string) => Response;
+};
+/** Fake API: trace index, per-source logs (bytes, 404 for null, status number, or custom) and Jobs. */
+function api(setup: Setup, calls: string[] = []): typeof fetch {
+ let indexCalls = 0;
+ return async (input, init) => {
+ const url = String(input);
+ calls.push(url);
+ assert.equal((init?.headers as Record)?.["X-OpenDirector-Request"], "1");
+ if (url.endsWith("/trace")) {
+ const turns = indexCalls === 0 ? setup.turns : setup.later?.[indexCalls - 1] ?? setup.turns;
+ indexCalls++;
+ return Response.json({ conversationId: "c", turns });
+ }
+ if (url.endsWith("/jobs"))
+ return setup.jobs?.(url.split("/").at(-2)!) ?? Response.json([{ jobId: "job-1", status: "failed", adopted: false }]);
+ const log = Object.entries(setup.logs ?? {}).find(([suffix]) => url.endsWith(suffix))?.[1];
+ if (log === undefined || log === null) return new Response(null, { status: 404 });
+ if (typeof log === "number") return new Response("denied", { status: log });
+ if (typeof log === "function") return log();
+ return new Response(log as Uint8Array);
+ };
+}
+async function zipOf(blob: Blob) { return parseZip(new Uint8Array(await blob.arrayBuffer())); }
+async function failure(work: Promise, code: TraceExportErrorCode): Promise {
+ const error = await work.then(() => undefined, (cause: unknown) => cause);
+ assert.ok(error instanceof TraceExportError, String(error));
+ assert.equal(error.code, code, error.message);
+ return error;
+}
+/** Response whose body is a hand-made reader so cancel/release calls can be observed. */
+function spyResponse(read: () => Promise>, headers: Record = {}) {
+ const spy = { cancelled: 0, released: 0 };
+ const response = {
+ ok: true, status: 200, headers: new Headers(headers),
+ body: { getReader: () => ({ read, cancel: async () => { spy.cancelled++; }, releaseLock: () => { spy.released++; } }),
+ cancel: async () => undefined },
+ } as unknown as Response;
+ return { spy, response };
+}
+
+test("central directory offset, size and entry count are valid and independent of the writer", async () => {
+ const model = encoder.encode('{"prompt":"sk-demo-sensitive"}\n');
+ const runtime = encoder.encode('not-json\n{"tool":{"output":"秘密"}}\n{"unfinished":');
+ const blob = await conversationTraceArchive("project", "c", {
+ generatedAt: "2026-11-25T00:00:00Z",
+ fetcher: api({ turns: [turn("a", 1), turn("b", 2, "codex")],
+ logs: { "/a/model": model, "/a/opencode": runtime, "/b/codex": new Uint8Array() } }),
+ });
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ const { entries, cdOffset, cdSize } = parseZip(bytes);
+ assert.deepEqual(entries.map((entry) => entry.name),
+ ["manifest.json", "turn-0001/model.jsonl", "turn-0001/opencode.jsonl", "turn-0002/codex.jsonl"]);
+ const eocd = new DataView(bytes.buffer, bytes.byteLength - 22);
+ assert.equal(eocd.getUint16(10, true), 4, "entry count");
+ assert.equal(eocd.getUint32(12, true), cdSize);
+ assert.equal(eocd.getUint32(16, true), cdOffset);
+ assert.equal(cdOffset + cdSize + 22, bytes.byteLength);
+ const files = new Map(entries.map((entry) => [entry.name, entry.data]));
+ assert.deepEqual(files.get("turn-0001/model.jsonl"), model);
+ assert.deepEqual(files.get("turn-0001/opencode.jsonl"), runtime);
+ assert.equal(files.get("turn-0002/codex.jsonl")?.length, 0);
+ assert.equal(blob.type, "application/zip");
+});
+
+test("manifest lists sources, byte counts, snapshot semantics and job lookup state", async () => {
+ const { entries } = await zipOf(await conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1), turn("b", 2, "codex"), turn("c", 3, "claude"), turn("d", 4, "../../secret")],
+ logs: { "/a/model": encoder.encode("m\n"), "/a/opencode": encoder.encode("raw\n"),
+ "/b/codex": encoder.encode("x\n"), "/c/claude": null },
+ jobs: (id) => id === "a" ? Response.json([]) : id === "b" ? Response.json([{ jobId: "job-1", status: "failed", adopted: false }])
+ : new Response("boom", { status: 500 }) }),
+ }));
+ const manifest = JSON.parse(new TextDecoder().decode(entries[0]!.data));
+ assert.equal(manifest.format, "opendirector-original-trace-archive");
+ assert.match(manifest.snapshot, /not an atomic snapshot/);
+ assert.ok(manifest.warning.includes("credentials"));
+ assert.deepEqual(manifest.turns[0].sources, [
+ { source: "model", file: "turn-0001/model.jsonl", bytes: 2, status: "included" },
+ { source: "opencode", file: "turn-0001/opencode.jsonl", bytes: 4, status: "included" }]);
+ assert.deepEqual([manifest.turns[0].jobs, manifest.turns[0].jobsStatus], [[], "ok"], "no linked jobs");
+ assert.equal(manifest.turns[1].jobs[0].jobId, "job-1");
+ assert.deepEqual([manifest.turns[2].jobs, manifest.turns[2].jobsStatus], [null, "unavailable"], "lookup failed");
+ assert.deepEqual(manifest.turns[2].sources, [{ source: "claude", status: "missing" }]);
+ assert.equal(manifest.turns[3].sources[0].status, "unsupported");
+});
+
+test("48 MiB single source is exported byte for byte under the 64 MiB total cap", async () => {
+ const big = new Uint8Array(48 * MiB);
+ for (let index = 0; index < big.length; index += 4099) big[index] = (index * 31) & 0xff;
+ const { entries } = await zipOf(await conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": big } }),
+ }));
+ const file = entries.find((entry) => entry.name === "turn-0001/codex.jsonl")!;
+ assert.equal(file.size, 48 * MiB);
+ assert.equal(sha(file.data), sha(big));
+});
+
+test("total cap includes ZIP overhead: raw bytes that fit alone still fail with turn and source", async () => {
+ const raw = encoder.encode("x".repeat(1000));
+ const fits = api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": raw } });
+ await conversationTraceArchive("p", "c", { fetcher: fits, maxArchiveBytes: 4096 });
+ const error = await failure(conversationTraceArchive("p", "c", { fetcher: fits, maxArchiveBytes: 1100 }), "tooLarge");
+ assert.deepEqual([error.detail.turn, error.detail.source], [1, "codex"], "limit allows the raw bytes but not the headers");
+});
+
+test("second source over the cumulative cap names its turn, with chunked and declared lengths", async () => {
+ const chunk = new Uint8Array(600);
+ const stream = (reader: { cancelled: number }) => () => new Response(new ReadableStream({
+ pull(controller) { controller.enqueue(chunk); }, cancel() { reader.cancelled++; } }));
+ const chunked = { cancelled: 0 };
+ const error = await failure(conversationTraceArchive("p", "c", {
+ maxArchiveBytes: 2000,
+ fetcher: api({ turns: [turn("a", 1, "codex"), turn("b", 2, "claude")],
+ logs: { "/a/codex": chunk, "/b/claude": stream(chunked) } }),
+ }), "tooLarge");
+ assert.deepEqual([error.detail.turn, error.detail.source], [2, "claude"]);
+ assert.equal(chunked.cancelled, 1, "unbounded stream was cancelled");
+ const declared = spyResponse(async () => ({ done: true, value: undefined }), { "content-length": String(70 * MiB) });
+ let bodyCancelled = 0;
+ (declared.response.body as { cancel: () => Promise }).cancel = async () => { bodyCancelled++; };
+ const second = await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": () => declared.response } }),
+ }), "tooLarge");
+ assert.equal(second.detail.source, "codex");
+ assert.equal(bodyCancelled, 1, "oversized declared length cancels the body without reading it");
+ assert.match(second.message, /tooLarge turn 1 codex/);
+});
+
+for (const status of [403, 500]) {
+ test(`HTTP ${status} on a source fails the export and names turn and source`, async () => {
+ const error = await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex"), turn("b", 2, "claude")],
+ logs: { "/a/codex": encoder.encode("ok\n"), "/b/claude": status } }),
+ }), "read");
+ assert.deepEqual([error.detail.turn, error.detail.source, error.detail.status], [2, "claude", status]);
+ });
+}
+
+test("404 marks only that source missing", async () => {
+ const { entries } = await zipOf(await conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "opencode")], logs: { "/a/model": null, "/a/opencode": encoder.encode("r\n") } }),
+ }));
+ const manifest = JSON.parse(new TextDecoder().decode(entries[0]!.data));
+ assert.equal(manifest.turns[0].sources[0].status, "missing");
+ assert.deepEqual(entries.map((entry) => entry.name), ["manifest.json", "turn-0001/opencode.jsonl"]);
+});
+
+test("a stream cut short of its Content-Length is an error, never a shorter file", async () => {
+ let sent = false;
+ const short = spyResponse(async () => sent ? { done: true, value: undefined }
+ : (sent = true, { done: false, value: new Uint8Array(10) }), { "content-length": "100" });
+ const error = await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": () => short.response } }),
+ }), "incomplete");
+ assert.deepEqual([error.detail.turn, error.detail.source], [1, "codex"]);
+});
+
+test("a network error mid-stream fails the export and cancels and releases the reader", async () => {
+ let reads = 0;
+ const broken = spyResponse(async () => {
+ if (reads++ === 0) return { done: false, value: new Uint8Array(10) };
+ throw new TypeError("terminated");
+ });
+ await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": () => broken.response } }),
+ }), "incomplete");
+ assert.deepEqual(broken.spy, { cancelled: 1, released: 1 });
+});
+
+test("a stalled request times out with turn and source", async () => {
+ const stalled: typeof fetch = async (input, init) => {
+ const url = String(input);
+ if (url.endsWith("/trace")) return Response.json({ conversationId: "c", turns: [turn("a", 1, "codex")] });
+ return new Promise(() => { void init; }); // ignores the signal on purpose
+ };
+ const error = await failure(conversationTraceArchive("p", "c", { fetcher: stalled, requestTimeoutMs: 20 }), "timeout");
+ assert.deepEqual([error.detail.turn, error.detail.source], [1, "codex"]);
+});
+
+test("a stalled body times out and releases the reader", async () => {
+ const stalled = spyResponse(() => new Promise(() => {}));
+ const error = await failure(conversationTraceArchive("p", "c", {
+ requestTimeoutMs: 20,
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": () => stalled.response } }),
+ }), "timeout");
+ assert.equal(error.detail.source, "codex");
+ assert.deepEqual(stalled.spy, { cancelled: 1, released: 1 });
+});
+
+test("the whole export is bounded as well as each request", async () => {
+ const slow: typeof fetch = async (input) => {
+ const url = String(input);
+ if (url.endsWith("/trace")) return Response.json({ conversationId: "c", turns: [turn("a", 1, "codex"), turn("b", 2, "codex")] });
+ if (url.endsWith("/jobs")) return Response.json([]);
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ return new Response("x\n");
+ };
+ await failure(conversationTraceArchive("p", "c", { fetcher: slow, requestTimeoutMs: 1000, totalTimeoutMs: 45 }), "timeout");
+});
+
+test("cancelling releases the reader and reports aborted", async () => {
+ const stalled = spyResponse(() => new Promise(() => {}));
+ const controller = new AbortController();
+ const pending = conversationTraceArchive("p", "c", {
+ signal: controller.signal,
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": () => stalled.response } }),
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ controller.abort();
+ await failure(pending, "aborted");
+ assert.deepEqual(stalled.spy, { cancelled: 1, released: 1 });
+ await failure(conversationTraceArchive("p", "c", { signal: controller.signal, fetcher: api({ turns: [] }) }), "aborted");
+});
+
+test("a running turn blocks export before any source is read", async () => {
+ const calls: string[] = [];
+ const error = await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex"), turn("b", 2, "codex", "streaming")] }, calls),
+ }), "running");
+ assert.equal(error.detail.turn, 2);
+ assert.ok(!calls.some((url) => url.includes("/traces/")), calls.join("\n"));
+});
+
+test("the click-time recheck uses the server's current status, not what the page showed", async () => {
+ // The page believed every turn was complete; the index now reports the latest as streaming.
+ await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex", "streaming")], logs: { "/a/codex": encoder.encode("x\n") } }),
+ }), "running");
+});
+
+test("a turn that starts running or changes during the reads rejects the export", async () => {
+ const logs = { "/a/codex": encoder.encode("x\n") };
+ await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], later: [[turn("a", 1, "codex", "streaming")]], logs }),
+ }), "running");
+ await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], later: [[turn("a", 1, "codex"), turn("b", 2, "codex")]], logs }),
+ }), "changed");
+ await failure(conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], later: [[turn("a", 1, "codex", "stopped")]], logs }),
+ }), "changed");
+});
+
+test("a failing trace index is an error naming the index", async () => {
+ const error = await failure(conversationTraceArchive("p", "c", {
+ fetcher: async () => new Response("nope", { status: 403 }),
+ }), "read");
+ assert.deepEqual([error.detail.source, error.detail.status], ["trace index", 403]);
+});
+
+test("the independent ZIP parser rejects the old writer's EOCD defect (central directory size + 12)", async () => {
+ const blob = await conversationTraceArchive("p", "c", {
+ fetcher: api({ turns: [turn("a", 1, "codex")], logs: { "/a/codex": encoder.encode("x\n") } }),
+ });
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ parseZip(bytes);
+ const view = new DataView(bytes.buffer, bytes.byteLength - 22);
+ view.setUint32(12, view.getUint32(12, true) + 12, true);
+ assert.throws(() => parseZip(bytes), /does not end at EOCD/);
+});
diff --git a/tests/traceZip.ts b/tests/traceZip.ts
new file mode 100644
index 000000000..6bb952cdc
--- /dev/null
+++ b/tests/traceZip.ts
@@ -0,0 +1,54 @@
+/** Independent ZIP reader for tests: walks EOCD and the central directory the way unzip and
+ * Python zipfile do. It shares no code with the writer under test. */
+import { Buffer } from "node:buffer";
+
+export type CentralEntry = {
+ name: string; method: number; crc: number; compressedSize: number; size: number;
+ localOffset: number; data: Uint8Array;
+};
+
+function crc32(bytes: Uint8Array): number {
+ let crc = 0xffffffff;
+ for (let index = 0; index < bytes.length; index++) {
+ crc ^= bytes[index]!;
+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+export function parseZip(zip: Uint8Array): { entries: CentralEntry[]; cdOffset: number; cdSize: number } {
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
+ const fail = (message: string): never => { throw new Error("invalid ZIP: " + message); };
+ const eocd = zip.byteLength - 22;
+ if (eocd < 0 || view.getUint32(eocd, true) !== 0x06054b50) fail("no EOCD at end of file");
+ const count = view.getUint16(eocd + 10, true);
+ if (view.getUint16(eocd + 8, true) !== count) fail("entry counts differ");
+ const cdSize = view.getUint32(eocd + 12, true);
+ const cdOffset = view.getUint32(eocd + 16, true);
+ if (view.getUint16(eocd + 20, true) !== 0) fail("unexpected comment");
+ if (cdOffset + cdSize !== eocd) fail(`central directory ${cdOffset}+${cdSize} does not end at EOCD ${eocd}`);
+ const entries: CentralEntry[] = [];
+ let at = cdOffset;
+ for (let index = 0; index < count; index++) {
+ if (view.getUint32(at, true) !== 0x02014b50) fail("bad central header " + index);
+ const nameLength = view.getUint16(at + 28, true);
+ const extra = view.getUint16(at + 30, true) + view.getUint16(at + 32, true);
+ const entry = {
+ name: Buffer.from(zip.subarray(at + 46, at + 46 + nameLength)).toString("utf8"),
+ method: view.getUint16(at + 10, true), crc: view.getUint32(at + 16, true),
+ compressedSize: view.getUint32(at + 20, true), size: view.getUint32(at + 24, true),
+ localOffset: view.getUint32(at + 42, true),
+ };
+ const local = entry.localOffset;
+ if (view.getUint32(local, true) !== 0x04034b50) fail("central offset misses local header: " + entry.name);
+ const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
+ const data = zip.subarray(start, start + entry.compressedSize);
+ if (start + entry.compressedSize > cdOffset) fail("entry data overlaps central directory: " + entry.name);
+ if (entry.method !== 0 || entry.compressedSize !== entry.size) fail("not STORE: " + entry.name);
+ if (crc32(data) !== entry.crc) fail("CRC mismatch: " + entry.name);
+ entries.push({ ...entry, data });
+ at += 46 + nameLength + extra;
+ }
+ if (at !== eocd) fail("central directory size does not match its entries");
+ return { entries, cdOffset, cdSize };
+}