diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index f9d4e52fa..b311d8f03 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -4,6 +4,8 @@ from dataclasses import dataclass, replace import json import logging +from os import fstat +from os.path import join, normpath from pathlib import Path import threading import time @@ -12,8 +14,8 @@ from uuid import UUID, uuid4, uuid5 from anyio import CancelScope -from fastapi import APIRouter, Header -from fastapi.responses import FileResponse, JSONResponse, StreamingResponse +from fastapi import APIRouter, Header, Query +from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse from pydantic import BaseModel, ConfigDict, Field, JsonValue from opendirector.agent.catalog import model_choices @@ -35,6 +37,7 @@ Runtime = RuntimeId +TRACE_CHUNK_BYTES = 512 * 1024 def _assistant_request(config): """Admission uses the same output ceiling as the configured model gateway.""" @@ -486,11 +489,13 @@ def agent_routes(projects, generation, configs, provider=None, *, active=None) - conversations = Conversations(projects) runtimes = AgentRuntimes(projects, generation, configs, provider) + def running_turn(project_id: UUID) -> UUID | None: + running = active.get(project_id) + return running.turn if running is not None and running.task is not None and not running.task.done() else None + @router.get('/conversations/{conversation_id}/trace') def conversation_trace(project_id: UUID, conversation_id: UUID): - running = active.get(project_id) - live = running.turn if running is not None and running.task is not None and not running.task.done() else None - return conversations.trace(project_id, conversation_id, live) + return conversations.trace(project_id, conversation_id, running_turn(project_id)) @router.get('/traces/{turn_id}/conversation') def trace_conversation(project_id: UUID, turn_id: UUID): @@ -509,12 +514,43 @@ def trace_input(project_id: UUID, turn_id: UUID): @router.get('/traces/{turn_id}/{source}') def trace(project_id: UUID, turn_id: UUID, - source: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'model']): + source: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'model'], + cursor: Annotated[str | None, Query(pattern=r'^(?:[0-9]+:[0-9]+:[0-9]+)?$', max_length=64)] = None): folder = child(conversations.path(project_id), 'agent-runs') - file = child(folder, f'{turn_id}.{source}.jsonl') - if not file.is_file(): + filename = normpath(join(folder, f'{turn_id}.{source}.jsonl')) + if not filename.startswith(join(folder, '')): raise ProjectError('轨迹文件不存在。', 404) - return FileResponse(file, media_type='text/plain', headers={'Cache-Control': 'no-store'}) + file = Path(filename) + if file.is_symlink(): + raise ProjectError('项目内部文件不能是符号链接。', 409) + headers = {'Cache-Control': 'no-store'} + if cursor is None: + if not file.is_file(): + raise ProjectError('轨迹文件不存在。', 404) + return FileResponse(file, media_type='text/plain', headers=headers) + + # Sample liveness before reading. If a turn finishes during this read, + # the client will still check again and receive every final byte. + headers['X-Trace-Running'] = '1' if running_turn(project_id) == turn_id else '0' + if not file.is_file(): + return Response(status_code=404, headers=headers) + try: + with file.open('rb') as stream: + stat = fstat(stream.fileno()) + identity = f'{stat.st_dev}:{stat.st_ino}' + previous, _, position = cursor.rpartition(':') + offset = int(position) if position else 0 + if cursor and (previous != identity or offset > stat.st_size): + headers['X-Trace-Reset'] = '1' + offset = 0 + stream.seek(offset) + data = stream.read(min(TRACE_CHUNK_BYTES, stat.st_size - offset)) + except FileNotFoundError: + return Response(status_code=404, headers=headers) + next_offset = offset + len(data) + headers['X-Trace-Cursor'] = f'{identity}:{next_offset}' + headers['X-Trace-More'] = '1' if next_offset < stat.st_size else '0' + return Response(content=data, media_type='text/plain', headers=headers) @router.get('/turns/{turn_id}/jobs') def turn_jobs(project_id: UUID, turn_id: UUID): diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index c8c2447a9..1d38e48f7 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -118,8 +118,12 @@ CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不 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. +轨迹浏览使用 `GET .../traces/{turn_id}/{source}?cursor=…` 按字节读取追加日志。空游标从头开始,之后使用响应返回的游标;每个响应最多读取 512 KiB。浏览器跨响应保留未完成的 UTF-8 和 JSONL 记录,并增量合并同一消息或工具调用。回合结束后,浏览器读完剩余字节即停止轮询。无游标的同一路径继续提供原始文件。 + +The trace viewer reads append-only log bytes from `GET .../traces/{turn_id}/{source}?cursor=…`. An empty cursor starts at the beginning, and each response returns the next cursor and at most 512 KiB. The browser carries incomplete UTF-8 and JSONL records across responses and merges updates to the same message or tool call. It stops polling after the turn ends and the remaining bytes have been read. The same route serves the original file when the cursor is omitted. + ### 原始轨迹归档 / 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"`)。 +“下载原始轨迹”由前端读取原始文件并生成,复用 `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"`). +English summary: the download reads original files and builds the archive in the frontend, 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/development/lessons.md b/docs/development/lessons.md index a706d3b93..20e3ea60f 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -28,6 +28,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Check:** As relevant to the change, inspect persisted object identities, references, and execution inputs after conversion or recovery. Reopen the project or reconnect to the run when needed, and verify the actual result. - **Preview follow-up:** [PR #465](https://github.com/ThinkFlowLab/OpenDirector/pull/465) initially opened the project for a prompt rewrite, which could contend with the browser's edit lease. A rewrite reads the saved snapshot and has no durable job to recover. Verify it can finish under a separate session and that a browser disconnect closes the server-side request. - **Async projection follow-up:** PR #193's structured-editor CI failure prompted a real-browser delayed-read regression. An older background projection could finish after an acknowledged editor save and restore an obsolete CAS basis, making the next save/publication fail. Recheck the editor transaction and captured snapshot at completion before installing either changed or apparently identical content. Keep publication versions fixed, test the actual save/retry/provenance path with a deterministic interleaving, and retain the original CI failure rather than treating a longer timeout or a rerun as its explanation. +- **Publication lock follow-up:** [#562](https://github.com/ThinkFlowLab/OpenDirector/pull/562) exposed task polling failing during publication. [#539](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/46222060697/job/141218914874) exposed the same contention in upload staging before a timeline save. While a same-project publication is paused after journaling, exercise task reads and upload staging through HTTP. Staging uses its own handle lock and still validates the edit lease. Asset registration and timeline saves continue to use the project write rules. / **发布锁补充:** 在同一工程写入日志后暂停发布,经 HTTP 检查工具任务读取与素材暂存。暂存使用独立的句柄锁并验证编辑租约,素材登记和时间线保存仍走工程写入规则。 - **Media representation follow-up:** [Issue #282](https://github.com/ThinkFlowLab/OpenDirector/issues/282) exposed copy/export paths that read displayed pixels and archive imports that displayed unsupported original bytes. A browser preview and an original asset need distinct read paths while retaining the same asset identity. Verify original bytes through download, fresh publication, cross-project paste fallback and archive round trips, including the first display after import. [PR #287 review](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5857373679) also exposed missing MIME-extension mappings and a fallback that could name preview PNG bytes as HEIC. Carry the expected original type into readers, reject a missing original, and check timeline/FCPXML packages as well as canvas archives. - **Upload acknowledgement follow-up:** Investigating [PR #287's camera sample](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5868923062) reproduced a failed preview being swallowed into a successfully saved empty generation item. Require a usable preview before completing a HEIF import, and assert the failure leaves the original registered without creating an empty item. Slow uploads also crossed the first save acknowledgement: default expansion and model display labels were mistaken for user edits. Compare effective settings while retaining actual content, model, frame-selection and lock conflicts; exercise upload into a newly created node and its reference composer before the first save finishes. diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index b2885c368..81707ee89 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -125,7 +125,10 @@ def lock(self, project_id, handle): def _scope(self, db, project_id, session, trusted=False): self.projects._recover() - path, manifest = self.projects._find(db, project_id) + # Staging writes to a separately locked upload handle. The catalog + # transaction protects project moves and the lease, while a live + # publication can leave us on the last complete manifest. + path, manifest = self.projects._find(None, project_id) if not trusted: self.projects._lease(db, project_id, path, session) return self.projects._current(db, project_id, path, manifest).snapshot diff --git a/src/canvas/AssistantTracePage.tsx b/src/canvas/AssistantTracePage.tsx index b410a75f5..16825208b 100644 --- a/src/canvas/AssistantTracePage.tsx +++ b/src/canvas/AssistantTracePage.tsx @@ -1,12 +1,13 @@ import { useT } from "../i18n/I18nProvider"; import type { MessageKey } from "../i18n/types"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { memo, useEffect, useMemo, useRef, useState } from "react"; import { traceCategory, isThinkingTokenEstimate, readableTraceValue } from "./traceCategory.ts"; import { turnTiming, TURN_STATUS_KEYS } from "./turnTiming.ts"; -import { initialTurn, normalizeTrace, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "./traceTurns.ts"; +import { initialTurn, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "./traceTurns.ts"; +import { createTraceCursor, type TraceSnapshot } from "./traceCursor.ts"; import { readTurnJobs, turnJobView, type TurnJob } from "./traceJobs.ts"; import { downloadFile } from "./assets.ts"; import { conversationTraceArchive, TraceExportError } from "./traceExport.ts"; @@ -45,54 +46,55 @@ const labels: Record = { event: "trace.role.event", reasoning: "trace.role.reasoning", }; -function TraceRow({ kind, summary, value }: { +const TraceRow = memo(function TraceRow({ kind, summary, value }: { kind: string; summary: string; value: unknown; }) { const t = useT(); + const [open, setOpen] = useState(false); return ( -
+
setOpen(event.currentTarget.open)}> {t(labels[kind] ?? "trace.role.event")} - {summary} + {summary.slice(0, 512)} -
{typeof value === "string" ? value : JSON.stringify(value, null, 2)}
+ {open &&
{typeof value === "string" ? value : JSON.stringify(readableTraceValue(value), null, 2)}
}
); -} +}); -function TraceEntries({ traces, rawModel }: { traces: string[]; rawModel: boolean }) { +const TraceEntries = memo(function TraceEntries({ traces, rawModel }: { + traces: readonly (TraceSnapshot | undefined)[]; rawModel: boolean; +}) { const t = useT(); const entries = useMemo(() => { - const parsed = traces.flatMap((trace, sourceIndex) => { - let timestamp = 0; - return trace.split("\n").flatMap((line, index) => { - if (!line.trim()) return []; - let record: TraceRecord | null; - try { - record = readableTraceValue(JSON.parse(line)) as TraceRecord | null; - } catch { - record = null; - } - if (isThinkingTokenEstimate(record?.native)) return []; - if (record?.native?.type === "assistant" && record.native.message?.content?.length === 0) return []; - timestamp = record?.native?.timestamp ?? - (record?.timestamp === undefined ? timestamp : record.timestamp * 1000); - return [{ line, record, timestamp, key: `${sourceIndex}:${index}` }]; - }); - }).sort((a, b) => a.timestamp - b.timestamp); + const sources = rawModel ? traces.slice(0, 1) : traces; + const parsed = sources.flatMap((trace, sourceIndex) => { + let timestamp = 0; + return trace?.rows.flatMap((value, index) => { + const line = typeof value === "string" ? value : ""; + const record = value && typeof value === "object" ? value as TraceRecord : null; + if (!record && !line) return []; + if (isThinkingTokenEstimate(record?.native)) return []; + if (record?.native?.type === "assistant" && record.native.message?.content?.length === 0) return []; + timestamp = record?.native?.timestamp ?? + (record?.timestamp === undefined ? timestamp : record.timestamp * 1000); + return [{ line, record, timestamp, key: `${sourceIndex}:${trace.generation}:${index}` }]; + }) ?? []; + }).sort((a, b) => a.timestamp - b.timestamp); const reasoning = new Map(); - return parsed.filter((entry) => { - if (entry.record?.event !== "model.reasoning") return true; + return parsed.flatMap((entry) => { + if (entry.record?.event !== "model.reasoning") return [entry]; const identity = `${entry.record.requestId}:${entry.record.choiceIndex ?? 0}`; const previous = reasoning.get(identity); if (previous?.record) { previous.record.text = (previous.record.text ?? "") + (entry.record.text ?? ""); - return false; + return []; } - reasoning.set(identity, entry); - return true; + const merged = { ...entry, record: { ...entry.record } }; + reasoning.set(identity, merged); + return [merged]; }); - }, [traces]); + }, [traces, rawModel]); let request = 0; const seenInputs = new Set(); const seenReasoning = new Set(); @@ -112,7 +114,7 @@ function TraceEntries({ traces, rawModel }: { traces: string[]; rawModel: boolea const thoughts = (payload.messages ?? []).flatMap((message, index) => { const text = message.reasoning_content?.trim(); if (!text || message.role !== "assistant") return []; - const identity = JSON.stringify(message); + const identity = JSON.stringify(readableTraceValue(message)); if (seenReasoning.has(identity)) return []; seenReasoning.add(identity); if (hasStreamedReasoning || firstModelRequest || titleRequest) return []; @@ -121,7 +123,7 @@ function TraceEntries({ traces, rawModel }: { traces: string[]; rawModel: boolea if (!titleRequest) firstModelRequest = false; const inputs = titleRequest ? [] : (payload.messages ?? []).flatMap((message, index) => { if (!["system", "developer"].includes(message.role)) return []; - const identity = JSON.stringify(message); + const identity = JSON.stringify(readableTraceValue(message)); if (seenInputs.has(identity)) return []; seenInputs.add(identity); const content = typeof message.content === "string" ? message.content : identity; @@ -129,7 +131,7 @@ function TraceEntries({ traces, rawModel }: { traces: string[]; rawModel: boolea summary={t("trace.systemPrompt")} value={content} />]; }); - const toolsKey = payload.tools?.length ? JSON.stringify(payload.tools) : undefined; + const toolsKey = payload.tools?.length ? JSON.stringify(readableTraceValue(payload.tools)) : undefined; if (toolsKey && !seenInputs.has(toolsKey)) { seenInputs.add(toolsKey); inputs.push(; }); -} +}); function TraceJobs({ jobs }: { jobs: TurnJob[] }) { const t = useT(); @@ -212,17 +214,18 @@ function TurnTrace({ project, turn, runtime, live }: { project: string; turn: string; runtime: string; live: boolean; }) { const [input, setInput] = useState(null); - const [traces, setTraces] = useState([]); + const [traces, setTraces] = useState([]); const [showModel, setShowModel] = useState(false); const rawModel = runtime === "opencode" && showModel; const [status, setStatus] = useState(null); + const [waiting, setWaiting] = useState(live); const [jobs, setJobs] = useState([]); const t = useT(); useEffect(() => { const controller = new AbortController(); const [projectPath, turnPath] = [project, turn].map(encodeURIComponent); - const sources = traceSources(runtime); + const sources = traceSources(runtime).map(createTraceCursor); setInput(null); const traceUrl = `/api/creation/projects/${projectPath}/assistant/traces/${turnPath}`; const options = { headers: { "X-OpenDirector-Request": "1" }, signal: controller.signal }; @@ -235,27 +238,36 @@ function TurnTrace({ project, turn, runtime, live }: { setTraces([]); setJobs([]); let timer: number | undefined; + let polling = live; async function refresh() { + let delay = 750; try { - if (live && document.hidden) return; - const jobsRequest = fetch(`/api/creation/projects/${projectPath}/assistant/turns/${turnPath}/jobs`, options) - .then(readTurnJobs, () => [] as TurnJob[]); - const snapshots = await Promise.all(sources.map(async (name) => { - const response = await fetch(`${traceUrl}/${encodeURIComponent(name)}`, options); - const body = response.ok ? await response.text() : ""; - return { status: response.status, body: normalizeTrace(name, body) }; - })); - const nextJobs = await jobsRequest; - const status = snapshots.some((item) => item.status === 200) ? 200 : snapshots[0].status; + if (polling && document.hidden) return; + const snapshots = await Promise.all(sources.map((source) => source.read(traceUrl, options, live) + .catch(() => null))); if (controller.signal.aborted) return; - setStatus(status); - setJobs((previous) => JSON.stringify(previous) === JSON.stringify(nextJobs) ? previous : nextJobs); - const bodies = snapshots.map((item) => item.body); - setTraces((previous) => bodies.every((body, index) => body === previous[index]) ? previous : bodies); - } catch { - if (!controller.signal.aborted) setStatus(0); + setWaiting(snapshots.some((item) => item?.follow)); + const available = snapshots.some((item) => item?.status === 200); + if (available) setStatus(200); + else setStatus((previous) => previous === 200 && snapshots.includes(null) ? previous + : snapshots.every((item) => item?.status === 404) ? 404 : 0); + setTraces((previous) => { + const rows = snapshots.map((item, index) => item?.snapshot ?? previous[index]); + return rows.every((body, index) => body === previous[index]) ? previous : rows; + }); + const more = snapshots.some((item) => item?.more); + polling = more || snapshots.some((item) => item?.follow) || (polling && snapshots.includes(null)); + if (more) { + delay = 0; + return; + } + const nextJobs = await fetch(`/api/creation/projects/${projectPath}/assistant/turns/${turnPath}/jobs`, options) + .then(readTurnJobs, () => null); + if (!controller.signal.aborted && nextJobs) { + setJobs((previous) => JSON.stringify(previous) === JSON.stringify(nextJobs) ? previous : nextJobs); + } } finally { - if (live && !controller.signal.aborted) timer = window.setTimeout(refresh, 750); + if (polling && !controller.signal.aborted) timer = window.setTimeout(refresh, delay); } } void refresh(); @@ -279,14 +291,14 @@ function TurnTrace({ project, turn, runtime, live }: { )} {!rawModel && input !== null && } {status === 200 ? ( - rawModel && !traces[0]?.trim() ? ( + rawModel && !traces[0]?.rows.length ? (

{t("trace.noModelRequests")}

) : ( - + ) ) : (

{status === null ? t("trace.loading") : - status === 404 && live ? t("trace.waiting") : + status === 404 && waiting ? t("trace.waiting") : status === 404 ? t("trace.notFound") : t("trace.loadFailed")}

)} @@ -392,8 +404,7 @@ function ConversationTrace({ project, conversationId, target, turns }: { {loaded.has(item.id) && ( - + )}
))} @@ -453,7 +464,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams {conversation === undefined ?

{t("trace.loading")}

: wide ? ( ) : ( - + )} ); diff --git a/src/canvas/claudeTrace.ts b/src/canvas/claudeTrace.ts index f82936d7f..655b3e3ff 100644 --- a/src/canvas/claudeTrace.ts +++ b/src/canvas/claudeTrace.ts @@ -16,45 +16,48 @@ type RecordValue = { type ToolRow = { native: { type: "tool_use"; part: { tool: string; state: { status: string; input?: unknown; output?: unknown } } }; callId: string }; /** Claude's outer role describes the envelope; each block supplies its display semantics. */ -export function normalizeClaudeTrace(trace: string): string { +export function createClaudeTraceProjection() { const rows: unknown[] = []; - const tools = new Map(); - for (const line of trace.split("\n")) { - if (!line.trim()) continue; - let record: RecordValue; - try { record = JSON.parse(line); } catch { continue; } - if (!record || typeof record !== "object") continue; - const native = record.native; - const blocks = native?.message?.content; - if (!Array.isArray(blocks) || !["assistant", "user"].includes(native?.type ?? "")) { - rows.push(record); - continue; - } - for (const block of blocks) { - if (block.type === "tool_use" || block.type === "tool_result") { - const id = block.type === "tool_use" ? block.id : block.tool_use_id; - if (!id) { rows.push({ ...record, native: { ...native, message: { ...native?.message, content: [block] } } }); continue; } - let row = tools.get(id); - if (!row) { - row = { native: { type: "tool_use", part: { tool: block.name ?? id, state: { status: "in_progress" } } }, callId: id }; - rows.push(row); - tools.set(id, row); - } - if (block.type === "tool_use") { - row.native.part.tool = block.name ?? id; - row.native.part.state.input = block.input; - } else { - row.native.part.state.status = block.is_error ? "failed" : "completed"; - row.native.part.state.output = block.content; + const tools = new Map(); + function append(lines: string[]) { + for (const line of lines) { + if (!line.trim()) continue; + let record: RecordValue; + try { record = JSON.parse(line); } catch { continue; } + if (!record || typeof record !== "object") continue; + const native = record.native; + const blocks = native?.message?.content; + if (!Array.isArray(blocks) || !["assistant", "user"].includes(native?.type ?? "")) { + rows.push(record); + continue; + } + for (const block of blocks) { + if (block.type === "tool_use" || block.type === "tool_result") { + const id = block.type === "tool_use" ? block.id : block.tool_use_id; + if (!id) { rows.push({ ...record, native: { ...native, message: { ...native?.message, content: [block] } } }); continue; } + const previous = tools.get(id); + const state: ToolRow["native"]["part"]["state"] = previous ? { ...previous.row.native.part.state } : { status: "in_progress" }; + if (block.type === "tool_use") { + state.input = block.input; + } else { + state.status = block.is_error ? "failed" : "completed"; + state.output = block.content; + } + const row: ToolRow = { native: { type: "tool_use", part: { + tool: previous?.row.native.part.tool ?? block.name ?? id, state, + } }, callId: id }; + const index = previous?.index ?? rows.length; + rows[index] = row; + tools.set(id, { row, index }); + } else if (block.type === "text" && block.text) { + rows.push({ native: { type: "text", role: native?.message?.role ?? native?.type, part: { text: block.text } } }); + } else if (block.type === "thinking" && block.thinking) { + rows.push({ native: { type: "reasoning", part: { text: block.thinking } } }); + } else if (block.type !== "redacted_thinking" && block.type !== "encrypted_thinking") { + rows.push({ ...record, native: { ...native, message: { ...native?.message, content: [block] } } }); } - } else if (block.type === "text" && block.text) { - rows.push({ native: { type: "text", role: native?.message?.role ?? native?.type, part: { text: block.text } } }); - } else if (block.type === "thinking" && block.thinking) { - rows.push({ native: { type: "reasoning", part: { text: block.thinking } } }); - } else if (block.type !== "redacted_thinking" && block.type !== "encrypted_thinking") { - rows.push({ ...record, native: { ...native, message: { ...native?.message, content: [block] } } }); } } } - return rows.map(row => JSON.stringify(row)).join("\n"); + return { rows, append }; } diff --git a/src/canvas/codexTrace.ts b/src/canvas/codexTrace.ts index 0d2b8d14f..5331162e8 100644 --- a/src/canvas/codexTrace.ts +++ b/src/canvas/codexTrace.ts @@ -6,29 +6,31 @@ type CodexRecord = { }; /** Replace lifecycle updates in place so commands stay readable and stable during polling. */ -export function normalizeCodexTrace(trace: string): string { +export function createCodexTraceProjection() { const rows: CodexRecord[] = []; const identities = new Map(); - for (const line of trace.split("\n")) { - if (!line.trim()) continue; - let record: CodexRecord; - try { record = JSON.parse(line); } catch { continue; } - if (!record || typeof record !== "object") continue; - const type = record.native?.type; - if (type === "thread.started" || type === "turn.started") continue; - const item = record.native?.item; - const identity = item?.id && type?.startsWith("item.") ? `item:${item.id}` - : record.type === "tool" && record.id ? `tool:${record.id}` : undefined; - const index = identity ? identities.get(identity) : undefined; - if (index !== undefined) { - const previous = rows[index]; - rows[index] = { ...previous, ...record, - ...(record.native ? { native: { ...previous.native, ...record.native, - ...(item ? { item: { ...previous.native?.item, ...item } } : {}) } } : {}) }; - } else { - if (identity) identities.set(identity, rows.length); - rows.push(record); + function append(lines: string[]) { + for (const line of lines) { + if (!line.trim()) continue; + let record: CodexRecord; + try { record = JSON.parse(line); } catch { continue; } + if (!record || typeof record !== "object") continue; + const type = record.native?.type; + if (type === "thread.started" || type === "turn.started") continue; + const item = record.native?.item; + const identity = item?.id && type?.startsWith("item.") ? `item:${item.id}` + : record.type === "tool" && record.id ? `tool:${record.id}` : undefined; + const index = identity ? identities.get(identity) : undefined; + if (index !== undefined) { + const previous = rows[index]; + rows[index] = { ...previous, ...record, + ...(record.native ? { native: { ...previous.native, ...record.native, + ...(item ? { item: { ...previous.native?.item, ...item } } : {}) } } : {}) }; + } else { + if (identity) identities.set(identity, rows.length); + rows.push(record); + } } } - return rows.map(row => JSON.stringify(row)).join("\n"); + return { rows, append }; } diff --git a/src/canvas/deepseekTrace.ts b/src/canvas/deepseekTrace.ts index e98a3c12c..2cbf07d39 100644 --- a/src/canvas/deepseekTrace.ts +++ b/src/canvas/deepseekTrace.ts @@ -41,76 +41,93 @@ function textContent(content: unknown): string { } /** Project ACP updates into trace rows while retaining their original records. */ -export function normalizeDeepseekTrace(trace: string): string { +export function createDeepseekTraceProjection() { const rows: (DisplayRecord | AcpRecord)[] = []; - const messages = new Map(); - const calls = new Map(); - let plan: DisplayRecord | undefined; - for (const line of trace.split("\n")) { - if (!line.trim()) continue; - let record: AcpRecord; - try { - record = JSON.parse(line) as AcpRecord; - } catch { - // A live snapshot may end midway through a JSONL record. - continue; + const messages = new Map(); + const calls = new Map(); + let plan: number | undefined; + function append(lines: string[]) { + const changed = new Map(); + function edit(index: number | undefined, create: () => DisplayRecord) { + const current = index === undefined ? undefined : changed.get(index); + if (current) return current; + const previous = index === undefined ? undefined : rows[index]; + const row = previous && "raw" in previous ? { + ...previous, raw: previous.raw.slice(), + native: { ...previous.native, part: { ...previous.native.part } }, + } : create(); + const position = index ?? rows.length; + rows[position] = row; + changed.set(position, row); + return row; } - if (!record.native?.jsonrpc) { - rows.push(record); - continue; - } - const update = record.native.params?.update; - if (!update) { - if (record.native.error) { - rows.push({ timestamp: record.timestamp, native: { type: "error", - part: { text: JSON.stringify(record.native.error) } }, raw: [record] }); - } else if (record.native.result?.stopReason) { - rows.push({ timestamp: record.timestamp, native: { type: "step_finish", - part: { reason: record.native.result.stopReason } }, raw: [record] }); + + for (const line of lines) { + if (!line.trim()) continue; + let record: AcpRecord; + try { + record = JSON.parse(line) as AcpRecord; + } catch { + // Ignore malformed JSONL lines. + continue; } - continue; - } - const kind = update.sessionUpdate; - if (kind === "agent_thought_chunk" || kind === "agent_message_chunk") { - const text = textContent(update.content); - if (!text) continue; - const type = kind === "agent_thought_chunk" ? "reasoning" : "text"; - const identity = update.messageId ? type + ":" + update.messageId : undefined; - const last = rows.at(-1); - let row = identity ? messages.get(identity) : - last && "raw" in last && last.native.type === type ? last : undefined; - if (!row) { - row = { timestamp: record.timestamp, native: { type, part: { text: "" } }, raw: [] }; - rows.push(row); - if (identity) messages.set(identity, row); + if (!record || typeof record !== "object") continue; + if (!record.native?.jsonrpc) { + rows.push(record); + continue; } - row.native.part.text += text; - row.raw.push(record); - } else if ((kind === "tool_call" || kind === "tool_call_update") && update.toolCallId) { - let row = calls.get(update.toolCallId); - if (!row) { - row = { timestamp: record.timestamp, native: { type: "tool_use", - part: { tool: update.title ?? update.toolCallId, state: { status: "in_progress" } } }, raw: [] }; - rows.push(row); - calls.set(update.toolCallId, row); + const update = record.native.params?.update; + if (!update) { + if (record.native.error) { + rows.push({ timestamp: record.timestamp, native: { type: "error", + part: { text: JSON.stringify(record.native.error) } }, raw: [record] }); + } else if (record.native.result?.stopReason) { + rows.push({ timestamp: record.timestamp, native: { type: "step_finish", + part: { reason: record.native.result.stopReason } }, raw: [record] }); + } + continue; } - if (update.title !== undefined) row.native.part.tool = update.title; - row.native.part.state = { - ...row.native.part.state, - status: update.status ?? row.native.part.state!.status, - ...(update.rawInput === undefined ? {} : { input: update.rawInput }), - ...(update.content === undefined ? {} : { output: update.content }), - ...(update.rawOutput === undefined ? {} : { output: update.rawOutput }), - }; - row.raw.push(record); - } else if (kind === "plan") { - if (!plan) { - plan = { timestamp: record.timestamp, native: { type: "plan", part: {} }, raw: [] }; - rows.push(plan); + const kind = update.sessionUpdate; + if (kind === "agent_thought_chunk" || kind === "agent_message_chunk") { + const text = textContent(update.content); + if (!text) continue; + const type = kind === "agent_thought_chunk" ? "reasoning" : "text"; + const identity = update.messageId ? type + ":" + update.messageId : undefined; + const last = rows.at(-1); + const index = identity ? messages.get(identity) : + last && "raw" in last && last.native.type === type ? rows.length - 1 : undefined; + const row = edit(index, () => ({ + timestamp: record.timestamp, native: { type, part: { text: "" } }, raw: [], + })); + if (identity && index === undefined) messages.set(identity, rows.length - 1); + row.native.part.text += text; + row.raw.push(record); + } else if ((kind === "tool_call" || kind === "tool_call_update") && update.toolCallId) { + const index = calls.get(update.toolCallId); + const row = edit(index, () => ({ + timestamp: record.timestamp, native: { type: "tool_use", part: { + tool: update.title ?? update.toolCallId, state: { status: "in_progress" }, + } }, raw: [], + })); + if (index === undefined) calls.set(update.toolCallId, rows.length - 1); + if (update.title !== undefined) row.native.part.tool = update.title; + row.native.part.state = { + ...row.native.part.state, + status: update.status ?? row.native.part.state!.status, + ...(update.rawInput === undefined ? {} : { input: update.rawInput }), + ...(update.content === undefined ? {} : { output: update.content }), + ...(update.rawOutput === undefined ? {} : { output: update.rawOutput }), + }; + row.raw.push(record); + } else if (kind === "plan") { + const row = edit(plan, () => ({ + timestamp: record.timestamp, native: { type: "plan", part: {} }, raw: [], + })); + plan ??= rows.length - 1; + row.native.part.text = (update.entries ?? []).map((entry) => entry.content + " · " + entry.status).join("\n"); + row.raw.push(record); } - plan.native.part.text = (update.entries ?? []).map((entry) => entry.content + " · " + entry.status).join("\n"); - plan.raw.push(record); } } - return rows.map((row) => JSON.stringify(row)).join("\n"); + return { rows, append }; } diff --git a/src/canvas/piTrace.ts b/src/canvas/piTrace.ts index 3bdf3e489..01265f32e 100644 --- a/src/canvas/piTrace.ts +++ b/src/canvas/piTrace.ts @@ -42,68 +42,85 @@ const contentText = (value: PiMessage["content"] | undefined) => * records collapse into one row per call. pi reports a retried attempt as an ordinary * `message_end` with `stopReason: 'error'`, so only the settled `agent_end` fails the turn. */ -export function normalizePiTrace(trace: string): string { - const rows: Row[] = []; - const calls = new Map(); - for (const line of trace.split("\n")) { - if (!line.trim()) continue; - let record: PiRecord; - try { record = JSON.parse(line); } catch { continue; } - const event = record?.native; - if (!event || typeof event !== "object") continue; - const timestamp = event.message?.timestamp; - const row = (part: Part, type: string, role?: string) => { - const created: Row = { native: { type, part, ...(role ? { role } : {}), ...(timestamp === undefined ? {} : { timestamp }) } }; - rows.push(created); - return created; - }; - if (LIFECYCLE.has(event.type ?? "")) continue; - if (event.type === "message_end") { - const message = event.message; - if (message?.role === "user") { - const text = contentText(message.content); - if (text.trim()) row({ text }, "text", "user"); +export function createPiTraceProjection() { + const rows: (PiRecord | Row)[] = []; + const calls = new Map(); + + function updateCall(call: { index: number; row: Row }, state: Part["state"], durationMs?: number) { + const native = call.row.native; + call.row = { native: { ...native, part: { ...native.part, state }, + ...(durationMs === undefined ? {} : { durationMs }) } }; + rows[call.index] = call.row; + } + + function append(lines: string[]) { + for (const line of lines) { + if (!line.trim()) continue; + let record: PiRecord; + try { record = JSON.parse(line); } catch { continue; } + const event = record?.native; + if (!event || typeof event !== "object") continue; + const timestamp = event.message?.timestamp; + const addRow = (part: Part, type: string, role?: string) => { + const created: Row = { native: { type, part, ...(role ? { role } : {}), ...(timestamp === undefined ? {} : { timestamp }) } }; + const index = rows.push(created) - 1; + return { index, row: created }; + }; + if (LIFECYCLE.has(event.type ?? "")) continue; + if (event.type === "message_end") { + const message = event.message; + if (message?.role === "user") { + const text = contentText(message.content); + if (text.trim()) addRow({ text }, "text", "user"); + continue; + } + if (message?.role !== "assistant" || message.stopReason === "error") continue; + for (const block of Array.isArray(message.content) ? message.content : []) { + if (block?.type === "text" && block.text?.trim()) addRow({ text: block.text }, "text", "assistant"); + else if (block?.type === "thinking" && block.thinking?.trim()) addRow({ text: block.thinking }, "reasoning"); + // Tool calls are reported by their execution records, so the call is shown once. + } continue; } - if (message?.role !== "assistant" || message.stopReason === "error") continue; - for (const block of Array.isArray(message.content) ? message.content : []) { - if (block?.type === "text" && block.text?.trim()) row({ text: block.text }, "text", "assistant"); - else if (block?.type === "thinking" && block.thinking?.trim()) row({ text: block.thinking }, "reasoning"); - // Tool calls are reported by their execution records, so the call is shown once. + if (event.type === "agent_end") { + const assistant = (event.messages ?? []).filter((message) => message?.role === "assistant"); + const settled = assistant.at(-1)?.errorMessage; + if (settled) addRow({ text: settled }, "error"); + else if (assistant.at(-1)?.stopReason === "error") rows.push(record); + continue; } - continue; - } - if (event.type === "agent_end") { - const assistant = (event.messages ?? []).filter((message) => message?.role === "assistant"); - const settled = assistant.at(-1)?.errorMessage; - if (settled) row({ text: settled }, "error"); - else if (assistant.at(-1)?.stopReason === "error") rows.push(record as Row); - continue; - } - if (event.type === "tool_execution_start") { - const call = row({ tool: event.toolName ?? event.toolCallId ?? "", state: { status: "in_progress", input: event.args } }, "tool_use"); - if (event.toolCallId) calls.set(event.toolCallId, call); - continue; - } - if (event.type === "tool_execution_update") { - const state = calls.get(event.toolCallId ?? "")?.native.part.state; - const output = contentText(event.partialResult?.content); - if (state?.status === "in_progress" && output) state.output = output; - continue; - } - if (event.type === "tool_execution_end") { - const known = calls.get(event.toolCallId ?? ""); - const call = known ?? row({ tool: event.toolName ?? event.toolCallId ?? "", state: { status: "in_progress" } }, "tool_use"); - if (event.toolCallId) calls.set(event.toolCallId, call); - call.native.part.state = { - status: event.isError ? "failed" : "completed", - ...(call.native.part.state?.input === undefined ? {} : { input: call.native.part.state.input }), - output: contentText(event.result?.content), - }; - if (event.durationMs !== undefined) call.native.durationMs = event.durationMs; - continue; + if (event.type === "tool_execution_start") { + const call = addRow({ tool: event.toolName ?? event.toolCallId ?? "", state: { status: "in_progress", input: event.args } }, "tool_use"); + if (event.toolCallId) calls.set(event.toolCallId, call); + continue; + } + if (event.type === "tool_execution_update") { + const call = calls.get(event.toolCallId ?? ""); + const state = call?.row.native.part.state; + const output = contentText(event.partialResult?.content); + if (call && state?.status === "in_progress" && output) updateCall(call, { ...state, output }); + continue; + } + if (event.type === "tool_execution_end") { + const known = calls.get(event.toolCallId ?? ""); + const call = known ?? addRow({ tool: event.toolName ?? event.toolCallId ?? "", state: { status: "in_progress" } }, "tool_use"); + if (event.toolCallId) calls.set(event.toolCallId, call); + const input = call.row.native.part.state?.input; + updateCall(call, { + status: event.isError ? "failed" : "completed", + ...(input === undefined ? {} : { input }), + output: contentText(event.result?.content), + }, event.durationMs); + continue; + } + rows.push(record); } - rows.push(record as Row); } - return rows.map((row) => JSON.stringify(row)).join("\n"); + return { rows, append }; +} + +export function normalizePiTrace(trace: string): string { + const projection = createPiTraceProjection(); + projection.append(trace.split("\n")); + return projection.rows.map((row) => JSON.stringify(row)).join("\n"); } diff --git a/src/canvas/traceCursor.ts b/src/canvas/traceCursor.ts new file mode 100644 index 000000000..95234d017 --- /dev/null +++ b/src/canvas/traceCursor.ts @@ -0,0 +1,76 @@ +import { createClaudeTraceProjection } from "./claudeTrace.ts"; +import { createCodexTraceProjection } from "./codexTrace.ts"; +import { createDeepseekTraceProjection } from "./deepseekTrace.ts"; +import { createPiTraceProjection } from "./piTrace.ts"; + +function rawProjection() { + const rows: unknown[] = []; + return { + rows, + append(lines: string[]) { + for (const line of lines) { + if (!line.trim()) continue; + try { rows.push(JSON.parse(line)); } catch { rows.push(line); } + } + }, + }; +} + +function projectionFor(source: string) { + switch (source) { + case "claude": return createClaudeTraceProjection(); + case "codex": return createCodexTraceProjection(); + case "deepseek": return createDeepseekTraceProjection(); + case "pi": return createPiTraceProjection(); + default: return rawProjection(); + } +} + +export type TraceSnapshot = { + generation: number; + rows: readonly unknown[]; +}; + +export function createTraceCursor(source: string) { + let cursor = ""; + let decoder = new TextDecoder(); + let pending = ""; + let projection = projectionFor(source); + let snapshot: TraceSnapshot = { generation: 0, rows: [] }; + + async function read(url: string, options: RequestInit, live: boolean) { + const response = await fetch(`${url}/${encodeURIComponent(source)}?cursor=${encodeURIComponent(cursor)}`, options); + const running = response.headers.get("X-Trace-Running"); + if ((running !== "0" && running !== "1") || (!response.ok && response.status !== 404)) { + throw new Error("Trace unavailable"); + } + const next = response.headers.get("X-Trace-Cursor"); + if (response.ok && next === null) throw new Error("Missing trace cursor"); + const more = response.headers.get("X-Trace-More") === "1"; + const follow = live && running === "1"; + const bytes = response.ok ? await response.arrayBuffer() : undefined; + if (options.signal?.aborted) throw new Error("Trace read aborted"); + + const reset = response.headers.get("X-Trace-Reset") === "1" || (!response.ok && cursor !== ""); + if (reset) { + decoder = new TextDecoder(); + pending = ""; + projection = projectionFor(source); + snapshot = { generation: snapshot.generation + 1, rows: [] }; + } + cursor = next ?? ""; + if (bytes) { + const stream = more || follow; + const lines = decoder.decode(bytes, { stream }).split("\n"); + lines[0] = pending + lines[0]; + pending = stream ? lines.pop() ?? "" : ""; + if (lines.some((line) => line.trim())) { + projection.append(lines); + snapshot = { ...snapshot, rows: projection.rows.slice() }; + } + } + return { status: response.status, more, follow, snapshot }; + } + + return { read }; +} diff --git a/src/canvas/traceTurns.ts b/src/canvas/traceTurns.ts index 2899824a7..d3f0c36fb 100644 --- a/src/canvas/traceTurns.ts +++ b/src/canvas/traceTurns.ts @@ -1,9 +1,4 @@ /** Turn index of a conversation on the Trace page, and the per-turn runtime choices. */ -import { normalizeClaudeTrace } from "./claudeTrace.ts"; -import { normalizeCodexTrace } from "./codexTrace.ts"; -import { normalizeDeepseekTrace } from "./deepseekTrace.ts"; -import { normalizePiTrace } from "./piTrace.ts"; - export type ConversationTurn = { id: string; number: number; @@ -29,15 +24,6 @@ export const runtimeName = (runtime: string) => RUNTIME_NAMES[runtime] ?? runtim /** Log sources read for a runtime. Only opencode records raw model requests. */ export const traceSources = (runtime: string) => runtime === "opencode" ? ["model", runtime] : [runtime]; -/** Each runtime keeps its own log format; the page never applies one runtime's parser to another turn. */ -export function normalizeTrace(source: string, body: string): string { - return source === "deepseek" ? normalizeDeepseekTrace(body) - : source === "codex" ? normalizeCodexTrace(body) - : source === "claude" ? normalizeClaudeTrace(body) - : source === "pi" ? normalizePiTrace(body) - : body; -} - /** The linked turn if the conversation lists it, otherwise the latest turn. */ export function initialTurn(turns: ConversationTurn[], target: string): string { return turns.some((item) => item.id === target) ? target : turns.at(-1)?.id ?? ""; diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 97021655d..72d6d8096 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -82,7 +82,7 @@ "lanes": [ "gate" ], - "note": "Bilingual original Trace ZIP archive download on assistant fixture services; only linked Jobs are stubbed." + "note": "Bilingual original Trace ZIP export and 64 MiB live trace transfer gate on assistant fixture services." }, { "file": "assistant_run_navigation.mjs", diff --git a/tests/browser/trace_original_export.mjs b/tests/browser/trace_original_export.mjs index c2168674f..e762d666c 100644 --- a/tests/browser/trace_original_export.mjs +++ b/tests/browser/trace_original_export.mjs @@ -8,7 +8,7 @@ * 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 { appendFile, mkdir, open, readdir, readFile, rename, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createHash } from "node:crypto"; import { spawnSync } from "node:child_process"; @@ -446,6 +446,123 @@ try { await context.close(); } } + // Follow a real active turn through the paged trace API and its final write. + { + const activeTurn = crypto.randomUUID(); + const log = join(directory, "agent-runs", `${activeTurn}.codex.jsonl`); + const cursorPath = `/traces/${activeTurn}/codex`; + const chunkBytes = 512 * 1024; + const logBytes = 64 * 1024 * 1024; + const { context, page, seen } = await openContext("en-US"); + await api("/creation-test-assistant-gate", { open: false }); + let turnResponse; + try { + turnResponse = await fetch(base + "/api" + assistant + "/turns", { + method: "POST", headers, + body: JSON.stringify({ id: activeTurn, conversationId: emptyId, text: "Live trace fixture", runtime: "codex", modelId }), + }); + assert.equal(turnResponse.status, 200); + const index = await api(`${assistant}/conversations/${emptyId}/trace`); + assert.equal(index.turns.at(-1).status, "streaming"); + + const reads = []; + page.on("response", (response) => { + const url = new URL(response.url()); + if (!url.pathname.endsWith(cursorPath)) return; + const headers = response.headers(); + reads.push({ + cursor: url.searchParams.get("cursor"), + status: response.status(), + bytes: Number(headers["content-length"] ?? 0), + }); + }); + const missing = page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith(cursorPath) && response.status() === 404); + await page.goto(tracePage(`conversation=${emptyId}&turn=${activeTurn}&runtime=codex&live=1`)); + await missing; + + // Split this record across responses. The live append below also splits a UTF-8 character. + const prefix = '{"padding":"'; + const padding = "x".repeat(chunkBytes - 1 - prefix.length); + const initial = prefix + padding + '场","native":{"type":"item.started","item":' + + '{"id":"cmd","type":"command_execution","command":"inspect 场景","status":"in_progress"}}}\n'; + // Use complete, hidden lifecycle records to model a large log with large + // individual records. Publish the fixture only after all 64 MiB are on disk. + const lifecycle = (bytes) => { + const prefix = '{"native":{"type":"thread.started"},"padding":"'; + const suffix = '"}\n'; + return prefix + "x".repeat(bytes - prefix.length - suffix.length) + suffix; + }; + const block = lifecycle(2 * chunkBytes); + const file = await open(log + ".fixture", "w"); + try { + let remaining = logBytes - Buffer.byteLength(initial); + while (remaining >= block.length) { + await file.writeFile(block); + remaining -= block.length; + } + await file.writeFile(lifecycle(remaining)); + await file.writeFile(initial); + } finally { + await file.close(); + } + await rename(log + ".fixture", log); + const row = page.locator(".cw-trace-row").filter({ has: page.getByText("inspect 场景", { exact: true }) }); + await row.getByText("Running", { exact: true }).waitFor(); + await row.locator("summary").click(); + await row.getByText("Waiting for output", { exact: false }).waitFor(); + + const delta = line({ native: { type: "item.completed", item: { + id: "cmd", type: "command_execution", status: "completed", exit_code: 0, + aggregated_output: "场景检查完成", + } } }); + const partial = Buffer.from(delta); + const split = partial.indexOf(Buffer.from("场")) + 1; + const observed = (bytes, running) => page.waitForResponse((response) => { + const url = new URL(response.url()); + const headers = response.headers(); + return url.pathname.endsWith(cursorPath) && url.searchParams.has("cursor") + && Number(headers["content-length"]) === bytes && headers["x-trace-running"] === running; + }); + + await observed(0, "1"); + + const firstDelta = observed(split, "1"); + await appendFile(log, partial.subarray(0, split)); + await firstDelta; + assert.equal(await row.getByText("Running", { exact: true }).isVisible(), true); + + const flushed = observed(partial.length - split, "0"); + // Pause the next browser request until the final bytes are written and the turn is done. + let resumeRead; + const finished = new Promise((resolve) => { resumeRead = resolve; }); + await page.route(new RegExp(cursorPath + "\\?"), async (route) => { + await finished; + await route.continue(); + }); + try { + await appendFile(log, partial.subarray(split)); + await api("/creation-test-assistant-gate", { open: true }); + await turnResponse.text(); + } finally { + resumeRead(); + } + await flushed; + await row.getByText("场景检查完成", { exact: true }).waitFor(); + assert.equal(await row.getByText("Completed", { exact: true }).count(), 1); + await page.locator(`#turn-${activeTurn} .is-turn-complete`).waitFor(); + const terminalReads = reads.length; + await sleep(2200); + assert.equal(reads.length, terminalReads, "terminal turn must stop reading its log"); + assert.equal(reads.filter((read) => read.status === 200 && read.cursor === "").length, 1); + assert.ok(reads.every((read) => read.cursor !== null && read.bytes <= chunkBytes)); + assert.equal(reads.reduce((sum, read) => sum + read.bytes, 0), logBytes + Buffer.byteLength(delta)); + assertReadOnly(seen); + } finally { + await api("/creation-test-assistant-gate", { open: true }); + await context.close(); + } + } } finally { await browser.close(); } diff --git a/tests/claudeTrace.test.ts b/tests/claudeTrace.test.ts index 852516696..826fa4820 100644 --- a/tests/claudeTrace.test.ts +++ b/tests/claudeTrace.test.ts @@ -1,23 +1,33 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { normalizeClaudeTrace } from "../src/canvas/claudeTrace.ts"; -const parse = (records: unknown[]) => normalizeClaudeTrace(records.map(record => JSON.stringify(record)).join("\n")).split("\n").filter(Boolean).map(line => JSON.parse(line)); +import { createClaudeTraceProjection } from "../src/canvas/claudeTrace.ts"; +function parse(records: unknown[]) { + const projection = createClaudeTraceProjection(); + for (const record of records) projection.append([JSON.stringify(record)]); + return projection.rows; +} const message = (type: string, content: unknown[]) => ({ native: { type, message: { role: type, content } } }); test("assistant tool_use is a tool and user tool_result updates the same call", () => { const rows = parse([message("assistant", [{ type: "tool_use", id: "call1", name: "Bash", input: { command: "pwd && ls -la" } }]), message("user", [{ type: "tool_result", tool_use_id: "call1", content: "/work", is_error: false }])]); assert.equal(rows.length, 1); - assert.equal(rows[0].native.type, "tool_use"); - assert.equal(rows[0].native.part.tool, "Bash"); - assert.deepEqual(rows[0].native.part.state, { status: "completed", input: { command: "pwd && ls -la" }, output: "/work" }); + assert.deepEqual(rows[0], { native: { type: "tool_use", part: { + tool: "Bash", state: { status: "completed", input: { command: "pwd && ls -la" }, output: "/work" }, + } }, callId: "call1" }); }); test("mixed Claude content retains text, reasoning and separate parallel tool identities", () => { const rows = parse([message("assistant", [{ type: "text", text: "Working" }, { type: "thinking", thinking: "Plan", signature: "opaque" }, { type: "tool_use", id: "a", name: "Bash", input: {} }, { type: "tool_use", id: "b", name: "Bash", input: {} }]), message("user", [{ type: "tool_result", tool_use_id: "b", content: "Error", is_error: true }])]); - assert.deepEqual(rows.map(row => row.native.type), ["text", "reasoning", "tool_use", "tool_use"]); - assert.equal(rows[2].native.part.state.status, "in_progress"); - assert.equal(rows[3].native.part.state.status, "failed"); + assert.equal(rows.length, 4); + assert.partialDeepStrictEqual(rows, [ + { native: { type: "text" } }, + { native: { type: "reasoning" } }, + { native: { type: "tool_use", part: { state: { status: "in_progress" } } } }, + { native: { type: "tool_use", part: { state: { status: "failed" } } } }, + ]); assert.ok(!JSON.stringify(rows).includes("opaque")); - assert.equal(normalizeClaudeTrace('{"native":'), ""); + const projection = createClaudeTraceProjection(); + projection.append(['{"native":']); + assert.deepEqual(projection.rows, []); }); diff --git a/tests/codexTrace.test.ts b/tests/codexTrace.test.ts index 8ee5d1b5b..300eb10d6 100644 --- a/tests/codexTrace.test.ts +++ b/tests/codexTrace.test.ts @@ -1,15 +1,19 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { normalizeCodexTrace } from "../src/canvas/codexTrace.ts"; -const parse = (records: unknown[]) => normalizeCodexTrace(records.map(record => JSON.stringify(record)).join("\n")).split("\n").filter(Boolean).map(line => JSON.parse(line)); +import { createCodexTraceProjection } from "../src/canvas/codexTrace.ts"; +function parse(records: unknown[]) { + const projection = createCodexTraceProjection(); + for (const record of records) projection.append([JSON.stringify(record)]); + return projection.rows; +} test("Codex command updates merge in place and retain command, output and failure", () => { const start = { native: { type: "item.started", item: { id: "a", type: "command_execution", command: "pwd", status: "in_progress" } } }; - assert.equal(parse([start])[0].native.item.status, "in_progress"); + assert.equal(parse([start])[0].native?.item?.status, "in_progress"); const rows = parse([start, { native: { type: "item.completed", item: { id: "b", type: "agent_message", text: "Working" } } }, { native: { type: "item.completed", item: { id: "a", aggregated_output: "Permission denied", exit_code: 1, status: "failed" } } }]); assert.equal(rows.length, 2); - assert.deepEqual(rows[0].native.item, { id: "a", type: "command_execution", command: "pwd", status: "failed", aggregated_output: "Permission denied", exit_code: 1 }); - assert.equal(rows[1].native.item.text, "Working"); + assert.deepEqual(rows[0].native?.item, { id: "a", type: "command_execution", command: "pwd", status: "failed", aggregated_output: "Permission denied", exit_code: 1 }); + assert.equal(rows[1].native?.item?.text, "Working"); }); test("Codex hides lifecycle noise but preserves errors and merges CLI receipts", () => { const rows = parse([{ native: { type: "thread.started" } }, { native: { type: "turn.started" } }, @@ -19,6 +23,8 @@ test("Codex hides lifecycle noise but preserves errors and merges CLI receipts", assert.equal(rows.length, 2); assert.equal(rows[0].name, "project show"); assert.deepEqual(rows[0].result, { ok: true }); - assert.equal(rows[1].native.item.message, "API failure"); - assert.equal(normalizeCodexTrace('{"native":'), ""); + assert.equal(rows[1].native?.item?.message, "API failure"); + const projection = createCodexTraceProjection(); + projection.append(['{"native":']); + assert.deepEqual(projection.rows, []); }); diff --git a/tests/deepseekTrace.test.ts b/tests/deepseekTrace.test.ts index 94ed608b7..cac91e5e0 100644 --- a/tests/deepseekTrace.test.ts +++ b/tests/deepseekTrace.test.ts @@ -1,14 +1,15 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { normalizeDeepseekTrace } from "../src/canvas/deepseekTrace.ts"; +import { createDeepseekTraceProjection } from "../src/canvas/deepseekTrace.ts"; function update(value: object) { return { native: { jsonrpc: "2.0", method: "session/update", params: { update: value } } }; } -function normalize(records: object[]) { - return normalizeDeepseekTrace(records.map((value) => JSON.stringify(value)).join("\n")) - .split("\n").filter(Boolean).map((line) => JSON.parse(line)); +function project(records: object[]) { + const projection = createDeepseekTraceProjection(); + for (const record of records) projection.append([JSON.stringify(record)]); + return projection.rows; } test("ACP chunks form separate assistant and thinking rows by message identity", () => { @@ -18,7 +19,10 @@ test("ACP chunks form separate assistant and thinking rows by message identity", update({ sessionUpdate: "agent_message_chunk", messageId: "a", content: { type: "text", text: "Working." } }), update({ sessionUpdate: "agent_thought_chunk", messageId: "b", content: { type: "text", text: "Next step." } }), ]; - const rows = normalize(records); + const rows = project(records).map((row) => { + assert.ok("raw" in row); + return row; + }); assert.deepEqual(rows.map((row) => [row.native.type, row.native.part.text]), [ ["reasoning", "Inspect the project."], ["text", "Working."], ["reasoning", "Next step."], ]); @@ -28,22 +32,25 @@ test("ACP chunks form separate assistant and thinking rows by message identity", test("tool updates preserve arguments and update one row for each parallel call", () => { const start = (toolCallId: string) => update({ sessionUpdate: "tool_call", toolCallId, title: "bash", status: "in_progress", rawInput: { command: toolCallId } }); - const running = normalize([start("a"), start("b")]); - assert.equal(running[0].native.part.state.status, "in_progress"); - const rows = normalize([start("a"), start("b"), update({ + const running = project([start("a"), start("b")]); + assert.partialDeepStrictEqual(running[0], { native: { part: { state: { status: "in_progress" } } } }); + const rows = project([start("a"), start("b"), update({ sessionUpdate: "tool_call_update", toolCallId: "a", status: "completed", content: [{ type: "content", content: { type: "text", text: "Done" } }], })]); assert.equal(rows.length, 2); - assert.equal(rows[0].native.part.state.status, "completed"); - assert.deepEqual(rows[0].native.part.state.input, { command: "a" }); - assert.equal(rows[0].raw.length, 2); - assert.equal(rows[1].native.part.state.status, "in_progress"); + assert.partialDeepStrictEqual(rows, [ + { native: { part: { state: { status: "completed", input: { command: "a" } } } } }, + { native: { part: { state: { status: "in_progress" } } } }, + ]); + const first = rows[0]; + assert.ok("raw" in first); + assert.equal(first.raw.length, 2); }); test("transport handshakes and usage stay out of the activity list while CLI receipts remain", () => { const receipt = { type: "tool", name: "opendirector project show", status: "complete" }; - const rows = normalize([ + const rows = project([ { native: { jsonrpc: "2.0", id: 1, result: { protocolVersion: 1 } } }, update({ sessionUpdate: "usage_update", used: 123, size: 1000 }), receipt, @@ -51,5 +58,5 @@ test("transport handshakes and usage stay out of the activity list while CLI rec ]); assert.equal(rows.length, 2); assert.deepEqual(rows[0], receipt); - assert.equal(rows[1].native.part.reason, "end_turn"); + assert.partialDeepStrictEqual(rows[1], { native: { part: { reason: "end_turn" } } }); }); diff --git a/tests/test_assistant_conversation_trace.py b/tests/test_assistant_conversation_trace.py index a7dd53a04..05904913e 100644 --- a/tests/test_assistant_conversation_trace.py +++ b/tests/test_assistant_conversation_trace.py @@ -115,6 +115,56 @@ def test_turn_resolves_to_its_own_conversation_including_archived(assistant): assert client.get(path + '/conversations').json()['activeId'] == second +@pytest.mark.parametrize('source', ['deepseek', 'pi']) +def test_trace_cursor_reads_appended_bytes_and_preserves_original_export(assistant, tmp_path, source): + client, path, _ = assistant + conversation = client.get(path).json()['conversationId'] + send(client, path, conversation, '轨迹') + turn = client.get(f'{path}/conversations/{conversation}/trace').json()['turns'][0]['id'] + url = f'{path}/traces/{turn}/{source}' + file = conversation_file(tmp_path).parent / f'{turn}.{source}.jsonl' + first = '{"text":"第一条"}\n'.encode() + second = '{"text":"第二条"}\n'.encode() + file.write_bytes(first) + + initial = client.get(url, params={'cursor': ''}) + assert initial.content == first + assert initial.headers['X-Trace-Running'] == '0' + cursor = initial.headers['X-Trace-Cursor'] + assert client.get(url, params={'cursor': cursor}).content == b'' + + with file.open('ab') as stream: + stream.write(second) + assert client.get(url, params={'cursor': cursor}).content == second + assert client.get(url).content == first + second + + replacement = file.with_suffix('.new') + replacement.write_bytes(second + first) + replacement.replace(file) + reset = client.get(url, params={'cursor': cursor}) + assert reset.headers['X-Trace-Reset'] == '1' + assert reset.content == second + first + + +@pytest.mark.parametrize('params', [{}, {'cursor': ''}], ids=['export', 'cursor']) +def test_trace_rejects_symlink(assistant, tmp_path, params): + client, path, _ = assistant + conversation = client.get(path).json()['conversationId'] + send(client, path, conversation, '轨迹') + target = tmp_path / 'outside.jsonl' + target.write_text('{"text":"outside"}\n') + turn = uuid4() + folder = conversation_file(tmp_path).parent + try: + (folder / f'{turn}.deepseek.jsonl').symlink_to(target) + except OSError: + pytest.skip('Cannot create symbolic links on this host') + + response = client.get(f'{path}/traces/{turn}/deepseek', params=params) + assert response.status_code == 409 + assert target.read_text() == '{"text":"outside"}\n' + + class Clock: """Deterministic stand-in for the agent module's time source.""" def __init__(self): diff --git a/tests/test_creation_api.py b/tests/test_creation_api.py index da70064cf..f0833fb01 100644 --- a/tests/test_creation_api.py +++ b/tests/test_creation_api.py @@ -691,3 +691,37 @@ def test_canvas_owner_survives_expiry_and_server_restart_until_takeover(api, mon assert other.post(path + '/commands', json=rename(command), headers=editor).status_code == 409 assert other.delete('/api/creation/sessions/' + preview).is_success assert other.post(path + '/open-canvas', headers={**allow_preview, **editor}).json()['editing'] == {'mode': 'edit'} + + +def test_uploads_can_be_staged_during_project_publication(api, monkeypatch): + from concurrent.futures import ThreadPoolExecutor + from threading import Event + + client, _ = api + path, command, _ = create(client) + assert client.post(path + '/open').status_code == 200 + publishing, resume = Event(), Event() + + def pause(self, stage): + if stage == 'bundle_written': + publishing.set() + assert resume.wait(10) + + monkeypatch.setattr(CreationProjects, '_checkpoint', pause) + change = dict(type='asset.writeText', commandId=str(uuid4()), projectId=command['projectId'], + payload=dict(name='Published.txt', text='content')) + upload = f'{path}/uploads/{uuid4()}' + with ThreadPoolExecutor(max_workers=1) as pool: + pending = pool.submit(client.post, path + '/commands', json=change) + try: + assert publishing.wait(5) + response = client.put(upload, content=b'upload content', headers={'X-Asset-Name': 'upload.bin'}) + assert response.status_code == 200, response.text + assert response.json()['status'] == 'ready' + assert client.get(upload).json() == response.json() + denied = client.get(upload, headers={'X-OpenDirector-Session': str(uuid4())}) + assert denied.status_code == 409 and denied.json()['code'] == 'session_expired' + assert not pending.done() + finally: + resume.set() + assert pending.result(timeout=5).json()['status'] == 'applied' diff --git a/tests/traceCursor.test.ts b/tests/traceCursor.test.ts new file mode 100644 index 000000000..a3f6b7070 --- /dev/null +++ b/tests/traceCursor.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createTraceCursor } from "../src/canvas/traceCursor.ts"; + +test("a live DeepSeek cursor merges split updates, retains snapshots and drains at completion", async (context) => { + function event(sessionUpdate: string, text: string) { + return JSON.stringify({ native: { jsonrpc: "2.0", params: { update: { + sessionUpdate, messageId: "a", content: { type: "text", text }, + } } } }) + "\n"; + } + const initial = Buffer.from(event("agent_message_chunk", "先检查")); + const delta = Buffer.from(event("agent_message_chunk", "场景。")); + const split = delta.indexOf(Buffer.from("场")) + 1; + const responses = [ + new Response(initial, { headers: { "X-Trace-Cursor": "1:2:100", "X-Trace-Running": "1" } }), + new Response(delta.subarray(0, split), { headers: { "X-Trace-Cursor": "1:2:200", "X-Trace-Running": "1" } }), + new Response(delta.subarray(split), { headers: { "X-Trace-Cursor": "1:2:300", "X-Trace-Running": "0" } }), + ]; + const fetch = context.mock.method(globalThis, "fetch", async () => responses.shift()); + const cursor = createTraceCursor("deepseek"); + const initialRead = await cursor.read("/traces/turn", {}, true); + const partialRead = await cursor.read("/traces/turn", {}, true); + const terminal = await cursor.read("/traces/turn", {}, true); + assert.equal(partialRead.snapshot, initialRead.snapshot); + assert.equal(partialRead.follow, true); + assert.equal(terminal.follow, false); + assert.equal(terminal.more, false); + assert.equal(initialRead.snapshot.rows.length, 1); + assert.equal(terminal.snapshot.rows.length, 1); + assert.partialDeepStrictEqual(initialRead.snapshot.rows[0], { native: { part: { text: "先检查" } } }); + assert.partialDeepStrictEqual(terminal.snapshot.rows[0], { native: { part: { text: "先检查场景。" } } }); + assert.deepEqual(fetch.mock.calls.map((call) => call.arguments[0]), [ + "/traces/turn/deepseek?cursor=", "/traces/turn/deepseek?cursor=1%3A2%3A100", + "/traces/turn/deepseek?cursor=1%3A2%3A200", + ]); +}); + +test("a Pi cursor updates one tool row across chunks without mutating earlier snapshots", async (context) => { + const responses = [ + new Response(JSON.stringify({ native: { + type: "tool_execution_start", toolCallId: "call-1", toolName: "read", args: { path: "scene.txt" }, + } }) + "\n", { headers: { "X-Trace-Cursor": "1:2:100", "X-Trace-Running": "1" } }), + new Response(JSON.stringify({ native: { + type: "tool_execution_end", toolCallId: "call-1", + result: { content: [{ type: "text", text: "scene" }] }, + } }) + "\n", { headers: { "X-Trace-Cursor": "1:2:200", "X-Trace-Running": "0" } }), + ]; + context.mock.method(globalThis, "fetch", async () => responses.shift()); + const cursor = createTraceCursor("pi"); + const initial = await cursor.read("/traces/turn", {}, true); + const final = await cursor.read("/traces/turn", {}, true); + assert.equal(final.snapshot.rows.length, 1); + assert.partialDeepStrictEqual(initial.snapshot.rows[0], { + native: { type: "tool_use", part: { state: { status: "in_progress" } } }, + }); + assert.partialDeepStrictEqual(final.snapshot.rows[0], { + native: { type: "tool_use", part: { tool: "read", state: { + status: "completed", input: { path: "scene.txt" }, output: "scene", + } } }, + }); +}); diff --git a/tests/traceTurns.test.ts b/tests/traceTurns.test.ts index efd5462fc..c6322bed3 100644 --- a/tests/traceTurns.test.ts +++ b/tests/traceTurns.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { initialTurn, normalizeTrace, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "../src/canvas/traceTurns.ts"; +import { initialTurn, runtimeName, traceRuntime, traceSources, type ConversationTurn } from "../src/canvas/traceTurns.ts"; const turn = (id: string, number: number, runtime = "default"): ConversationTurn => ({ id, number, text: id, runtime, model: null, status: "complete" }); @@ -13,13 +13,6 @@ test("each turn reads its own runtime's log sources", () => { assert.equal(runtimeName("unknown"), "unknown"); }); -test("normalizers are selected by the turn's source, other sources pass through", () => { - const body = '{"event":"model.request"}\n'; - assert.equal(normalizeTrace("opencode", body), body); - assert.equal(normalizeTrace("model", body), body); - assert.notEqual(normalizeTrace("codex", '{"type":"thread.started"}\n'), undefined); -}); - test("linked turn is opened, otherwise the latest", () => { const turns = [turn("a", 1), turn("b", 2, "codex"), turn("c", 3, "deepseek")]; assert.equal(initialTurn(turns, "a"), "a");