fix(tracing): trace waterfall + summary prompt + chat tab all lose data after each agent turn

Merged
SA
6mo ago
+749-36

Closes #896.

Follow-up to #867. Fixes the trace lifecycle and rendering bugs that survived #867's concurrency hardening because they live at a different layer of the system.

What this fixes

#BugFix
1session.status === "idle" handler in worker.ts called endTrace + sessionTraces.delete after every turn. idle is a per-turn busy→idle transition, not session-end. Next event hit a cache miss, Trace.create() + startTrace snapshotted an empty 1-span file, clobbering the rich on-disk trace.Handler removed. Trace lives as long as the worker has the session in sessionTraces. Finalization on shutdown + MAX_TRACES eviction only.
2getOrCreateTrace cache-miss path never rehydrated from disk — worker restart / eviction always overwrote the existing trace.New Trace.rehydrateFromFile(sessionId) restores spans / metadata / counters / clears root endTime. getOrCreateTrace prefers it before falling back to startTrace.
3worker.setWorkspace was not idempotent → spurious calls cleared sessionTraces.Track currentWorkspaceID at module scope; early-return on unchanged value.
4routes/session/index.tsx workspaceID effect re-ran on every session() signal change.createEffect(on(() => session()?.workspaceID, ...)) so SolidJS dirty-tracks only workspaceID.
5Prompt never captured. Three event handlers in worker.ts could feed metadata.prompt: (a) the user-role message.updated handler only fired if info.summary.title || info.summary.body was populated, which doesn't happen on the first turn; (b) the text-part branch of message.part.updated gated on part.time?.end, which user-input parts never have set; (c) the session.updated handler called setTitle(info.title) with one argument only, never touching prompt. Codex review caught a second risk: dropping the time.end gate while keeping setTitle(text, text) would regress the auto-generated session title to raw user input, because setTitle(t, p) mutates both fields.New Trace.setPrompt(prompt) that only mutates metadata.prompt. The user-text branch of message.part.updated drops the time.end precondition and calls setPrompt(text) instead of setTitle(text, text).
6Chat tab could only render metadata.prompt (singular) at the top + assistant generations. Every user message after the first was dropped from the viewer.New Trace.logUserMessage(text) pushes a kind: "user-message" span. The user-text branch of message.part.updated also calls it for each user-identified text. Viewer chat-view rebuilt to interleave user-message and generation spans in startTime order. Backward compatible with traces that lack user-message spans.

Why #867 didn't catch these

PR #867 closed M2 (snapshot-debounce dropping events) and M3 (FileExporter racing flushSync). Both are intra-Trace-instance concurrency — within one Trace object's state machine. The reproducers in tracing-rename-race.test.ts and tracing-display-crash.test.ts all hold one instance for the test's lifetime and exercise crash/burst conditions against that instance.

The bugs in this PR are at three other layers:

  • Cross-instance lifecycle (rows 1–4): when one Trace gets destroyed and a new one is constructed for the same sessionID. The on-disk file clobber happens via the new instance's first snapshot, not from any race within an old one.
  • Worker event-handler layer / data feed (row 5): what gets fed into the Trace from the bus event stream. Orthogonal to persistence correctness.
  • Viewer renderer + data model (row 6): how the viewer's chat tab iterates spans. A correct persistence layer can still ship a 1-span trace if upstream feeds 1 span.

Beyond the layer mismatch, the per-turn idle handler (row 1) was intentional code — the original comment read "Finalize trace when session reaches idle (completed)". It was a semantic misunderstanding of what idle means at the event level (per-turn vs session-end), not a concurrency bug, so #867's reproducer matrix wouldn't have surfaced it. And no existing test exercises the full event-stream-to-trace-file path across multiple busy → idle cycles, so the cross-turn nature was invisible to CI.

Independent of #867's scope

Every bug fixed here predates #867 (the prior trace-corruption PR). Listing
this explicitly so reviewers can see this PR is orthogonal work — not a
follow-up cleaning up regressions #867 introduced.

Bug fixed in this PROriginEvidence
1. Per-turn session.status === "idle" destroying the Trace (worker.ts)Predates #867git log -S 'status === "idle"' -- worker.ts → introduced by #183 ("feat: replace Langfuse with local-first tracing system"), the original local-tracing PR. Predates #867 by months.
2. getOrCreateTrace no disk rehydration (worker.ts)Predates #867Same #183 PR introduced getOrCreateTrace without rehydration. #867 never touched worker.ts.
3. setWorkspace not idempotent (worker.ts)Predates #867Same as above — #867 never touched worker.ts.
4. SolidJS effect re-firing on every signal change (routes/session/index.tsx)Predates #867#867 never touched the TSX route at all.
5. Prompt-capture broken (worker.ts)Predates #867All three relevant event handlers (message.updated user-role branch, message.part.updated text branch, session.updated) live in worker.ts, never touched by #867.
6. User messages not first-class in trace data model (tracing.ts kind union, viewer.ts chat-view)Predates #867#867 modified tracing.ts but only added M2/M3 concurrency fixes — did NOT change the kind union, did NOT touch viewer.ts (zero changes to the viewer file in the #867 commits).

Tests

  • test/cli/tui/worker-trace-clearing.test.ts — source-grep contract tests: no-idle-clobber, rehydrate-before-startTrace, setPrompt-not-setTitle, Trace.setPrompt purity.
  • test/altimate/tracing-rehydrate.test.ts — behavioral tests for rehydrateFromFile (preserve spans/metadata/counters, reject missing/mismatched/malformed, clear endTime on rehydrate) and logUserMessage (chronological ordering).

47 affected tests pass. Typecheck clean. 35 existing tracing tests (tracing-display-crash, tracing-rename-race) pass unchanged.

Verification on a live build

Built locally as 0.0.0-fix/trace-clearing-on-workspace-set-202606051512. Confirmed against a real multi-turn TUI session that:

  • The trace file now persists across busy → idle transitions (5+ spans, full metadata, real counter values where v0.8.3 produced a 1-span / metadata: {} / null-summary file).
  • After a fresh rebuild with the rendering fix, multi-turn chat tab interleaves each user message with its assistant response in chronological order instead of showing only the last user prompt.

Out of scope

  • Higher-fidelity integration test for cross-turn trace correctness. The source-grep + behavioral tests here lock the contracts but don't drive synthetic session.status idle events through the real worker event loop. Tracked separately as a follow-up.
  • The user-role message.updated handler in worker.ts still calls setTitle(title, title) with summary.title || summary.body. Same setTitle(x, x) shape Codex caught for the user-text branch in this PR; if the title-agent's summary update lands after session.updated, it can overwrite metadata.prompt with the title-agent's text instead of the user's actual input. Smaller surface than the bug fixed here; not addressed in this PR.

🤖 Generated with Claude Code


Summary by cubic

Fixes trace lifecycle bugs that overwrote traces after each turn and preserves trace identity across restarts. Also makes the chat tab show multi-turn conversations, improves prompt capture (skipping synthetic parts), and prevents duplicate top-level prompts for long messages.

  • Bug Fixes

    • Removed per-turn finalize on session.status === "idle"; traces persist across turns and only finalize on shutdown or eviction.
    • Added Trace.rehydrateFromFile(sessionId) and call it before startTrace on cache miss; preserves spans/metadata/counters/traceId, normalizes session ID, clears root endTime, and marks any open generation spans as “interrupted” to keep structure.
    • Made setWorkspace idempotent via currentWorkspaceID; UI effect now uses on(() => session()?.workspaceID, ...) so it fires only on real changes, preventing sessionTraces clearing.
    • Captured prompts via Trace.setPrompt(prompt) and dropped the time.end gate for user text; never call setTitle(text, text) and skip synthetic/ignored text parts so prompts stay accurate.
    • Logged user messages with Trace.logUserMessage(text) and updated the viewer to interleave user-message and generation spans by time; falls back to metadata.prompt when needed and dedupes using the shared USER_MESSAGE_INPUT_MAX_CHARS cap to avoid duplicate long prompts.
  • Refactors

    • Made Trace.rehydrateFromFile async and awaited it in getOrCreateTrace and stream handlers to avoid blocking the event loop on cache misses; tests updated accordingly.
    • Migrated tracing-rehydrate tests to the tmpdir() fixture for consistency.
    • Tightened worker-trace-clearing test regex to be scope-bounded, ensuring the synthetic/ignored gate and setPrompt/logUserMessage checks apply to the correct branch.
    • Removed redundant specs/trace-bugs-followup-867.md to avoid duplicated documentation.

Summary by CodeRabbit

  • New Features

    • Multi-turn chat with explicit per-turn user-message tracking and improved session recovery from disk
  • Bug Fixes

    • Deduplicated prompt bubbles in the chat view and preserved in-progress traces across turns (prevents lost/overwritten history)
    • Reduced unnecessary workspace restarts to avoid clearing cached traces
  • Tests

    • Added tests covering session rehydration, user-message recording, and trace-retention behaviors