CodeNomad/dev-docs/TRANSCRIPT.md
Pascal André b9aa5f3b02
fix(ui): simplify high contrast to one channel curve (#1570)
I replace role-specific high-contrast rules with one sRGB channel curve
(1.3 contrast, mirrored pivots), preserving the palette's colored text
and original filled-button ink.

I keep Contrast Auto/On/Off, corrected light-palette surfaces and one
shared active-toggle tint; the result was visually approved.

I verified typechecking, 86 focused unit tests, 31 help checks across
ten languages and focused browser regressions.
2026-11-17 16:26:27 +01:00

23 KiB

Transcript rendering

Agent conventions

  • Mermaid fences (mermaid/mmd) use only @mermaid-js/tiny, loaded on demand and excluded from PWA precaching. lib/markdown.ts publishes a per-render token/encoded-source/completeness sidecar from actual fenced tokens alongside cached HTML; raw HTML cannot supply that provenance. markdown-mermaid.tsx consumes the sidecar and retains source for unfinished or display-truncated fences and while streaming. Source/diagram choices remain local to the Markdown owner; copy/wrap keep the native source. mermaid-renderer.ts serializes bounded renders in one opaque allow-scripts iframe with network-disabled CSP; returned SVGs are image documents rather than host HTML. Keep 50,000-character/500-edge input limits, a 2M-character SVG ceiling and the initialization/render deadlines, including late-import fencing. MermaidDiagram is shared with .mmd file previews; invalid/unsupported/oversized content keeps an actionable source fallback. Regression coverage: tests/browser/mermaid.test.ts.

  • Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. A prompt delivered from the session inbox takes the position the native message page owns: the SDK's session.inbox.delivered moves the prompt's row to the reducer's tail, so a delivery that relocates a row which is not the reducer's last owes an authoritative page read — invalidated and finished like a settlement read, shared with any in-flight read and superseded only by a newer admitted execution, and published through the instance layer's frame gates (active session, latest window) exactly as live events' projections are. The outstanding read is a retirement barrier, and a verified reconnect carries the demand: after the seeded page lands, the repair resumes immediately instead of trailing behind the quiet reconciliation. No client-side ordering state survives the delivery: the reducer itself is healed, so reconnect seeding and authoritative replacement carry the corrected order. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys.

  • The message-content popup and Chat settings share components/transcript-visibility.ts and the semantic icons from components/message-content-icons.ts; tool presentation metadata lives independently of renderers in components/tool-call/tool-presentation.ts. Popup styles live in styles/components/transcript-filters.css. Popup rows show a requested state at once and keep it until the save carrying it settles. Each save re-renders the transcript, so a drag sweep (dev-docs/UI_CONVENTIONS.md) saves its rows once, on release (afterSweep). Saves run in order, each built from the preferences the previous one returned; a batch of rows is sealed as it joins the queue, so a later click never jumps ahead of a preset change nor rides along with a sweep still held.

  • Transcript presets are Nothing (hides every row, including all tools), Minimal, Balanced and Everything (TRANSCRIPT_PRESETS); saved Detailed choices load as Custom with their effective tool column. Chat settings shows the four as buttons above the table of exact default states; the popup shows the same choice as a native select under its title, where a disabled Custom entry appears only after a manual row change. Escape closes an open list before the popup. Preset names are localized in every locale; covered by tests/browser/transcript-presets.test.ts.

  • Status Tokens are independent of message token visibility. The non-interactive renderStatus slot keeps the session input/output/cost chips in the header in both states; collapsed they form one ellipsized line, expanded they include reasoning and wrap beside the heading. Expanded content holds descendant-inclusive totals below the header. Keep the layout in styles/panels/status-tokens.css.

  • Message token disclosures keep one row in both states: collapsed shows the input/output/cost summary chips on a single ellipsized line; expanded swaps the same row to all six chips beside the chevron, which wrap onto further lines when narrow instead of truncating (expansion exists to read every value). Messages and Status share components/usage-metric-chips.tsx and styles/components/usage-metrics.css; message row geometry lives in styles/messaging/message-usage.css.

  • Tool-result images retain native state.content and render through the shared components/tool-call/output-images.tsx surface, including MCP and specialized tools. Keep image bytes out of text projections (copy/search/speech); image styles live in styles/messaging/tool-call/images.css.

  • Transcript pages carry large tool images by reference: the UI's native message list reads (lib/sdk-manager.ts) and history windows (fetchHistoryWindow) send the x-codenomad-media: deferred opt-in (server/src/opencode/session-media-contract.ts), and the server replaces each tool image data URI over INLINE_MEDIA_LIMIT (32 KiB) with a /api/workspaces/<id>/session-media/<session>/<message>/<part>/<index>/<sha256> path (opencode/session-media.ts). toolImageSource resolves that path on the API base, so the lazy <img> loads only shown images; routes/session-media.ts serves the bytes of the owned session's native message, pinned by the digest and refused at or after an undo boundary, as an immutable sandboxed image. Single-message reads (session.message.get: pruning revisions, previews), live events, user attachments and requests without the opt-in stay whole, so revisions hash native content.

  • Markdown images of local file paths (C:/…, file://, absolute or relative POSIX paths) cannot load in the renderer. lib/markdown.ts renders them as their alt text in a span.markdown-local-image, and components/markdown.tsx swaps the label for an <img> with the source of a completed tool image of the same path already in the session's loaded messages (lib/markdown-local-images.ts: the image's file name or its single-image tool's filePath; Windows paths compare case-insensitively, a relative path must match one known path's end). Only blocks containing such a label read and track the session's tool parts. Never fetch local paths through a backend route for this; an unmatched path keeps its alt text.

  • Code Mode reads native metadata.toolCalls in tool-call/renderers/execute-data.ts; keep call-list styling in styles/messaging/tool-call/execute.css, with native image/output ownership in the shared tool shell. A completed object or array result arrives as compact JSON (with optional Warnings:/Logs: blocks): executeOutputForRender displays it indented within size and nesting-depth bounds, while copy keeps the native text; strings, errors and other output use the shared rendering.

  • Subagent cards (tool-call/renderers/task.tsx) treat a completed call whose metadata.status is running as a background launch acknowledgement, never as its result. tool-call/renderers/subagent-report.ts shows instead the child's latest hidden synthetic <subagent sessionID state …> report delivered to that call: created at or after the call's execution start (time.ran, else its creation) and before the next call continuing the same child, chosen by creation time then message id (never list position), with its state: a running tag means the child still owns background work. Every idle period reports, so a call continued before any report joins the next period that reports. The card header's status indicator and duration follow the child session's state across its whole delivery range (latestChildState, exposed through the renderer getHeaderStatus hook): running from the launch acknowledgement until the child's newest round reports terminally, and a later call continuing the same child returns every card of that child to running until the newest round reports; the duration ends at the settling report's delivery time. That override is display-only: settlement reads and the settled-session refresh (hasUnsettledToolRow, hasStrandedFinishedRoundTool, refreshSettledSessionMessages) read only part statuses, which a background launch settles at once — never wire them to the overridden status, or a parent session's end would keep re-reading while its background child owns the work; reports arrive as event-stream synthetic messages, or with the authoritative page on reconnect. The deferred body mount releases while that state is live or failed, but its birth check keeps reading the part's own status: an overridden status must first evaluate inside a tracked render, never in untracked setup, or its memo freezes on a transient store state. Renderer contexts read instanceId/sessionId through getters — a card row can be reused across a session switch, and a captured plain string would keep reading the previous session's transcript. One index of reports and call times per parent-session revision serves every card; it is owned by the message store and tied to the session's message-id list, so eviction, reload or store replacement rebuild it. A call stored with its result in the tool output (earlier runtimes) shows that output. Covered by subagent-report.test.ts and tests/browser/task-copy.test.ts.

  • A shell call the user interrupted fails with its output so far followed by metadata.notice, flagged metadata.interrupted. tool-call/renderers/bash-data.ts renders the part before the notice like a finished call's output and the shell's getErrorText hook shows only the notice under the error label; other failures keep the whole error. Covered by bash-data.test.ts and tests/browser/tool-images.test.ts.

  • Native websearch text is parsed conservatively by tool-call/renderers/websearch-data.ts; unknown/oversized responses use the shared raw renderer. Recognized provider-consent Forms retain the generic schema/answer path, with layout in styles/messaging/tool-call/websearch.css.

  • Session lifecycle features use OpenCode V2's published signals: one session.execution.{succeeded,failed,interrupted} per busy period (lib/native-execution-events.ts) and session.retry.scheduled for provider backoff. The schema-declared session.idle/session.status are never published; never wire a feature only to them. A terminal event is a hint until session.active confirms settlement, which alone announces "A session finished", only for root sessions ending in success, failure or an inactivity stop. Transcript reducers retire at settlement, deferred while prompts stay parked in their inbox or a user shell or unsettled tool call still needs reconciling there. A tool part still streaming (rendered "pending") once a settlement drained has lost its called transition: session.tool.success reduces solely from the running status (a later failed can still settle it). Symmetrically, admission drops a session.tool.called whose newest matching part already holds a terminal status: the reducer would overwrite the settled state wholesale (flipping completed tool images back to "running" until a settlement read healed them); native tool IDs are unique per step, so a legitimate call never lands on a settled part. The SDK reducer already answers a terminal event whose transcript holds a streaming or running tool by invalidating and re-reading messages, but that refresh is dropped while the stream is not connected and never publishes its result; the terminal event therefore finishes the read itself (finishOpenCodeDataEvent: one message.sync that shares the SDK's in-flight read when connected and starts it when not) and projects the reconciled page, which keeps the display window's membership. Only a newer admitted execution suppresses that publication — same-round activity such as a late terminal tool event must not leave the repair unpublished. Non-event settlement evidence finishes the same read through the same fence: the liveness activity read observing that a run the UI still believed working has settled (observeNonEventSettlement, reported by session-api), and an authoritative inbox sync that drops an item the reducer admitted (a delivery or cancellation without events, whose user message may never be admitted either). A tool still streaming or running in a finished round once a later session.step.started reduced (reconcileStrandedRoundTools, hooked after both the direct emit and the queued replay, where the scan runs at the task boundary between replay chunks) lost its terminal event mid-execution: the loop feeds every tool result back before it continues, so waiting for the settlement read would keep its spinner live through later rounds (and a quickly following execution would suppress that repair). That reconcile and every settlement read share one in-flight reconciliation per transcript (settlementReadPending); covered by opencode-data-settlement.test.ts. Token/cost lines (components/message-usage.tsx) appear once per agent message: the row of an assistant message's final text (the one carrying "delete tools and reasoning") renders, once that message has native usage, the sum (sumMessageUsage) of its own usage and of every message holding a tool or reasoning part that cleanup selects (technicalCleanupParts). Reuse that selection rather than a separate projection. The line renders inside the content row, so it never shifts <Index> items or splits a technical group (whose Delete needs two tools); tool-only steps get no line. A message whose text is followed by tools also counts in the next message's line, as its tools belong to that selection. Sums cover the loaded transcript window only, like cleanup. Capture real streams with scripts/test-session-lifecycle-native.mjs.

  • Native transcript events reduce only through stores/opencode-data.ts (never add another partial-part reducer), which publishes bounded snapshots through hydrateMessages (message-v2/instance-store.ts); these per-event re-projections must not invalidate unchanged messages: hydrateMessages reuses the resident MessageRecord object whenever content, explicit timestamps and prompt-display metadata are unchanged, and an identical whole snapshot returns before any store write or session-revision bump. Part/info comparisons use allocation-free structural equality (partDataEqual), never JSON.stringify. The SDK reduce mutates rows in place, so reference identity can never prove a session unchanged — never add a reference-anchored projection skip. A session's reducer is replaced (authoritative resync after an overflow, rotation failure or reconnect; pruning invalidation) only through replaceTranscriptEntry, which bumps the transcript's entryRevision; reactive readers of the reducer, such as the inbox behind queued badges (getOpenCodeSessionInbox), track it so they rebind instead of keeping the disposed reducer's last state (opencode-inbox-rebinding.test.ts, tests/browser/session-rendering.test.ts).

  • Event-driven projections coalesce to the frame level through stores/opencode-projection-frame.ts: events still reduce synchronously and in order, but the projection into the message store runs at most once per animation frame per session, always from the reducer's newest state (a bounded timer while the window is hidden, since hidden windows pause animation frames; environments without a frame scheduler keep the previous synchronous projection). Store readers lag at most one frame. Session selection writes (writeSessionSelection) and visibility transitions flush pending pages; transcript eviction and instance teardown cancel them; destructive events (session.deleted, session.inbox.cancelled, session.revert.committed) and forced authoritative publications still project synchronously and subsume the pending frame. Projections and stream invalidation gate on watched transcripts — the active session plus any child session whose task renderer keeps its transcript visible (stores/session-transcript-visibility.ts): watched children project streamed steps like the active session instead of dropping their loaded page per event, while an event admitted while its session was watched but no longer watched at frame time invalidates the loaded page so the next activation reads authoritatively. Covered by opencode-projection-frame.test.ts, session-child-transcript-watch.test.ts and tests/browser/streaming-projection.test.ts.

  • Reducer page reads (the SDK's message.sync through the message.list proxy in createDataEntry) flush buffered compaction text, snapshot the session's live rows, fetch, flush again and answer with the page merged against that snapshot (stores/opencode-data-read-merge.ts), so buffered text is reduced exactly once: the page is the base and keeps its cursor, a live row new or changed since the snapshot keeps its live version (a row changed only in its root time.completed, which SDK step boundaries stamp, takes the page's version) except for its identified content parts, such as tool calls, left unchanged since the snapshot, which take the page's version so progress on one tool never hides authority for another, while a part only the page holds joins the live row beside its page neighbours, parts pairing by ID or, for text and reasoning, by kind and ordinal (a row created during the fetch takes only identified parts), so a recovered part never crosses the fragments around it; a live row unchanged since the snapshot takes the page's structure, plus, while the page row is open, the live fragments the page does not hold yet. Every text and reasoning fragment of a row both sides hold then follows one rule by kind and ordinal (chooseFragment): in a row the stream changed during the fetch the live fragment stays unless it is owed (below) and the page holds it committed; otherwise a fragment the page holds committed (positive evidence only, below) takes the page, a live fragment the page's text only prefixes (a stream only appends, and an open fragment is persisted late, often empty, even when other kinds follow it) keeps its live text, and the page decides the rest. A fragment one side alone holds keeps that side. Rows created during the fetch and absent from the page ride along newest-first. Only events that remove or replace content (invalidatesFetchedPage: deletion, revert commit, inbox cancellation, compaction start/end/failure) restart the read; streamed text, reasoning, tool progress, compaction text and new rows merge, so a continuously streaming session completes its read in one fetch. Live versions are reconciled by the native full-text endings and the SDK's end-of-round refresh. A first latest-window load (loadMessages with no resident rows and no stored window) merges its 200-row page the same way and commits it while live revisions advance. Every committed latest-window page then offers the session reducer its newest 20 rows, the SDK's own page size, without another read (seedOpenCodeSessionMessages), because the reducer applies streamed events only to messages it holds: an empty reducer is seeded unless the session is known idle, and a reducer holding rows (a parked inbox row, an earlier step) is reseeded when it diverged or lacks an open assistant message of the page. Reloads and history windows keep the revision checks, so a reseeding reload saw no transcript event during its fetch. Covered by opencode-data-trailing-read.test.ts, opencode-data-read-merge.test.ts, session-api-running-open.test.ts and opencode-data-divergence.test.ts.

  • A live event that edits an assistant message, or its text, reasoning or tool part, the reducer does not hold (its start was missed: disconnect, dropped routing, a reload) or that makes the reducer throw marks the transcript diverged (stores/opencode-data-divergence.ts). A watched transcript with rows or a displayed page repairs at once: one authoritative read through the settlement path (completeSettlementRead, gated publication, shared with an in-flight read, rows streamed during the fetch kept by the read merge, a newer execution or replaced reducer fencing publication) reseeds the reducer, so later events apply. A missed part is settled only once a page holds that part (the tool by ID), not merely its message; text and reasoning fragments follow the obligation rules below, and an ambiguous partial-fragment delta is owed only to settlement. A burst of misses shares the pending read; each reducer gets three repair reads per execution, and a settlement (terminal event or non-event settlement evidence) of a still-diverged watched transcript owes one more beyond that budget and holds retirement until it lands. Unwatched sessions and reducers still awaiting their first page never read: their next latest page reseeds the reducer. Reconnect, overflow and rotation recovery already own authoritative replacement and skip the record.

  • Every live event is fitted to the reducer before it reduces (fitLiveEvent, stores/opencode-data-fragments.ts). Native ordinals count a step's text and reasoning fragments separately from 0 with one fragment of each kind open at a time, tool IDs are unique per step, and a step restarts on its message only before producing output; the SDK edits a message's latest fragment of the event's kind. Against a row holding count fragments of that kind, a start for ordinal o fits when count === o and a delta or ending when count === o + 1. More is a delivery behind an authoritative page (seed, repair or settlement read) and is dropped, as is a tool input start for a tool ID the row holds; fewer means the fragment's start was missed: the event is dropped (it would edit an earlier fragment) and records a divergence keyed by its ordinal. Each authoritative page also records the provenance of the fragments it installed exactly as fetched (the read merge kept no live version). Only positive evidence commits a fragment: its message completed, or its own ending (the native writes a text part's provider state, native, only when its ending commits, and stamps reasoning's time.completed; reasoning carries its provider state from its start, which proves nothing); text stays open while reasoning or tool parts follow it. A committed fragment drops later deltas as redeliveries, while an open fragment holding text cannot tell a redelivered delta from a new one, so the delta applies and its fragment owes the settlement read. A fragment's obligation (missed start or ambiguity) settles only through its own full-text ending or a page that installed it committed, never because a page holds its ordinal; since the read merge gives an owed fragment's committed page content precedence even in a live-changed row, the settlement read, taken after completion, wins for it. Events without an ordinal keep the SDK's behavior.

  • Shared speech byte/MediaSource transport lives in lib/audio-utils.ts; playback ownership and cancellation stay with its callers.

  • Speech keeps one active hook owner by callback identity. Identity changes and disposal cancel that owner's work and audio; delayed capabilities and synthesis responses are fenced by request version. Audio completion resets only the owner of that audio instance, including when multiple mounted views share a content identity. tests/browser/speech-lifecycle.test.ts covers recycled tool cards and playback cancellation.