Walnut Web Frontend
Understand the React session chat interface architecture and rendering patterns.
Installation
- Make sure Claude is on your device and in your terminal.
Skills load from
~/.claude/skills/when Claude Code starts up — so you need it on your machine first. If you don't have it yet, install it once with the command below, then runclaudein any terminal to verify.One-time setupnpm i -g @anthropic-ai/claude-codeAlready have it? Skip ahead.
- Paste into Claude Code or into your terminal.
This copies the whole skill folder into
~/.claude/skills/walnut-web-frontend-evanzhang008/— the SKILL.md plus any scripts, reference docs, or templates the skill ships with. Works for every skill.What this command does
- Makes a new, empty temporary folder.
- Downloads the skill's folder,
.claude/skills/walnut-web-frontend, fromgithub.com/EvanZhang008/open-walnut(branchmain), the GitHub repository it's listed from. You get the version that is there now, not a copy we keep. - Copies that folder to
~/.claude/skills/walnut-web-frontend-evanzhang008/. - Deletes the temporary folder.
Installing runs none of the skill's files; it only downloads and copies them. When you later use the skill, Claude follows its SKILL.md and may run scripts that come with it. Read them first.
Faster alternative (instruction-only skills)
Skips the clone and grabs only the SKILL.md file. Don't use this if the skill ships Python scripts, reference markdowns, or asset templates — they won't be downloaded and the skill will fail when it tries to load them.
Quick install (SKILL.md only)Sign up to copy - Restart Claude Code.
Quit and reopen Claude Code (or any other agent that loads from
~/.claude/skills/). New skills are picked up on startup. - Just ask Claude.
Skills auto-activate when your request matches the skill's description — no slash command needed. Trigger phrases live in the skill's own frontmatter; you can read them in the “What this skill does” section above.
Prefer to read the source first? Open on GitHub.
When Claude uses it
Implementation details for web/src/ (React SPA) — session chat single-timeline model (streaming blocks, render-filter absorption, optimistic dedup, turn watermark), UX patterns (task refs, images, plan cards, slash commands), frontend file structure. MUST read before touching session chat, turn boundaries, or streaming block rendering.
What this skill does
Web GUI — Implementation Details
For architecture overview and routes, see project CLAUDE.md.
Rendering model text (markdown, rich HTML, marked extensions, sanitize policy) lives in its own skill: walnut-markdown-rendering. Load that one before changing web/src/utils/markdown.ts or rich-blocks.ts; it holds the hard rules (never patch marked, register a retune on BOTH Marked instances, collapse blank lines at render time only).
UX Implementation Details
-
Design options go out as ONE HTML page: when the user has to pick between designs or mockups, send one self-contained HTML page with every option's picture inline, your pick and why first, then the backup, then the rest. Never a folder of separate images.
-
Source-aware message isolation: Streaming agent responses from different sources (heartbeat, cron, triage, user-chat) render as separate message blocks.
useChattrackscurrentSourceRefduring streaming and passes it toupsertLastAssistantwhich only merges into the last assistant message if the source matches. The turn-merger inchatEntriesToMessageschecksentry.sourceboundaries to prevent cross-source merging on history reload. -
Rich task references: Session result/error messages use
[taskId|Project / Title]format rendered as clickable pills via a custommarkedinline extension (ChatMessage.tsx). Backend enriches events with task metadata (resolveTaskRef()inserver.ts); frontend builds the format viabuildTaskRef()inuseChat.ts. Entity refs (<task-ref>,<session-ref>) also render as clickable pills. On MainPage, clicking a task ref focuses it in TodoPanel (auto-switches tab, expands groups, scrolls into view) and clicking a session ref opens the inline SessionPanel + focuses the linked task — no page navigation. -
Inline image rendering: Image paths in markdown text are rendered as
<img>tags via three mechanisms inChatMessage.tsx: (1)imagePathinline extension for bare paths in text, (2)linkrenderer override for[text](/api/images/...)markdown links, (3)codespanrenderer for backtick-wrapped paths. Thelinkrenderer only matches local paths (href.startsWith('/')) to avoid hijacking external URLs./api/images/URLs render directly; absolute file paths proxy throughGET /api/local-image?path=...(src/web/routes/local-image.ts) with extension whitelist, traversal protection, and 50MB size limit. Clicking any image opens a lightbox modal (Lightbox.tsx). Works in chat, session history, and session streaming views via themarkedsingleton. -
Tool result image rendering:
GenericToolCallinSessionMessage.tsxauto-detects images in tool results via three mechanisms: (1) Anthropic content-block JSON withtype:"image"+ base64 data → renders as<img src="data:...">, (2) file paths ending in.png/.jpg/.gif/.webpin result text → renders via/api/local-imageproxy, (3) inputfile_path/path/filenamepointing to image files → shows preview when result has no images. Relative paths (e.g.,screenshot.pngfrom Playwright) are resolved using the session'scwdviaresolveImagePath()— thesessionCwdprop threads throughSessionChatHistory→SessionMessage→GenericToolCall. Detection utilities inweb/src/utils/markdown.ts(extractContentBlockImages,findImagePaths,isImageFilePath,resolveImagePath). Result prop merges streaming (resultprop) and persisted history (tool.resultfield) paths. Images constrained to panel width viamax-width: 100%; lightbox click-to-zoom via existingdata-lightbox-srcdelegation. -
Session streaming (single-timeline model): Backend-buffered per-session streaming.
SessionStreamBuffer(src/web/session-stream-buffer.ts) accumulates blocks in memory;session:stream-subscribeRPC returns a snapshot. All stream events broadcast to all WebSocket clients — frontend filters bysessionId(supports multi-panel streaming).useSessionStreamhook handles subscribe-on-switch with catch-up. Frontend accumulation semantics live in ONE place:web/src/stream/stream-reducer.ts(pure functions: lane isolation byparentToolUseId, msgId-boundary = new block, tool-result backfill newest-calling-first) — shared byuseSessionStreamANDsession-cache. The server buffer is the only remaining twin (language boundary — keep it semantically aligned when touching either). Streaming tool calls reuseGenericToolCallfromSessionMessage.tsx(same expand/collapse as history) —statusprop drives icon/class (calling→done→error),resultprop renders when available. -
Session message queue: Persistent disk-backed queue (
src/core/session-message-queue.ts) for session chat. Messages enqueued aspending, drained and combined bySessionRunner.processNext(), cleared aftersession:result. Supports edit/delete of pending messages. Survives server restart (at-least-once delivery). -
Session image support: Session chat inputs reuse the main
ChatInputcomponent (withshowCommands={false}and customplaceholder). Images are pasted/dropped/attached client-side, sent as base64 via WS RPC, saved to~/.open-walnut/images/server-side, and their file paths are embedded in the message text. -
Session columns on home page: Up to 3 session panels displayed side by side between chat and ToDo (
MainPage.tsx).sessionColumns: string[]queue with FIFO eviction. Triage takes the first column slot, reducing session max to 2 when open. Panel area width graduates by column count (35%→45%→55%) viauseResizablePanel.setPct(). Chat panel toggleable via Focus Dock button. Session pills gainisActiveprop to highlight open columns. Legacy single-sessionsessionStoragekey auto-migrates to array format. EachSessionPanelinstance streams independently (WS broadcasts all events, frontend filters by sessionId). Session pills use a three-layer badge format:Session · Plan/Bypass · WorkStatus / ProcessStatus— the outer label is always "Session" (unified naming), inner mode shows Plan or Bypass. Clicking the pill directly opens the session panel (one-click viastopPropagation). The initial prompt (first user message) renders at the top of the session chat timeline. Mode indicators use muted labels (📋 Plan/⚡ Bypass) instead of blue accent badges. -
Focus Dock pin state: Shared via
FocusBarContext(web/src/contexts/FocusBarContext.tsx), provided inAppShellinsideTasksProvider. BothAppShell(rendersFocusDock) andMainPage(provides pin/unpin toTodoPanel) consume the same context — ensures optimistic pin/unpin updates are instant (~6ms) rather than waiting for API round-trips. TheuseFocusBarhook only re-fetches onconfig:changedevents withkey === 'focus_bar'to avoid stale-config races from other config writers. No pin count limit — users can pin any number of tasks; Focus Dock renders only the first 3 (FOCUS_DOCK_MAX_VISIBLEinFocusDock.tsx), while TodoPanel's pinned section shows all. -
Search child task expansion: Search results include
parentTaskIdandisAutoExpandedfrom the backend (src/core/search.ts). When a parent task matches, its children are auto-inserted after it withisAutoExpanded: true. FrontendSearchResults.tsxrenders children with↳ Childbadge, left-indent (search-result-childCSS), and anautobadge for auto-expanded items. -
Segmented filter bars: TodoPanel uses joined segmented controls (not dropdowns) for Priority, Phase, Session, and Source filters. Icons use a unified minimalist set (○ ◐ ✓ [person-svg] ⋈ ▷ ✓✓) consistent across
PHASE_ICON,StatusBadge, and filter chips. AWAIT_HUMAN_ACTION uses an SVGPersonIconcomponent (PersonIcon.tsx) instead of a Unicode character. Icon maps areRecord<string, ReactNode>to support mixed string/JSX icons. -
Slash commands: Dual-layer system — hardcoded frontend commands (
/compact,/plan,/tasks) + markdown-based commands (built-in.mdinsrc/data/slash-commands/+ user-created in~/.open-walnut/commands/). User commands override built-in by name. Backend:src/core/command-store.ts,src/web/routes/commands.ts. Frontend:web/src/commands/(registry + markdown-bridge),/commandspage. -
Session slash command autocomplete: Session inputs (
SessionPanel) show a command palette when typing/. Aggregates 4 sources: skills, Walnut commands,~/.claude/commands/(root),{cwd}/.claude/commands/(project). Backend:GET /api/slash-commands?cwd=...(src/web/routes/slash-commands.ts). Frontend:useSlashCommandshook with cwd-based caching and ranked search (name prefix > name contains > description contains).ChatInputsupportssessionCommandsprop — selecting inserts text instead of executing. Source badges show origin (Skill, Walnut, Claude, Project). -
Plan content rendering: In session chat,
ExitPlanModerenders as aPlanCard— an accent-bordered, collapsible card with formatted plan markdown. Plan content resolved fromExitPlanMode.input.plan(primary) or from a precedingWriteto~/.claude/plans/(fallback). Components:PlanCardandCollapsedPlanWriteinSessionMessage.tsx. Live updates:PlanCardconsumesPlanContentContext(provided bySessionPanel) to show live plan content fromuseSessionPlanpolling — this bypassesmemo()onSessionMessageso both the topPlanPreviewSectionand bottom chatPlanCardauto-refresh when the plan file changes. Context:web/src/contexts/PlanContentContext.ts. Expand features:PlanCardheader has a hover-reveal expand button that opensPlanPopup(60vw centered popup via portal).SessionPanelheader has an expand button that promotes the panel to 95vw×95vh fullscreen viauseFullscreen(CSS class toggle — no new component instance).PlanPopupsharesuseModalOverlayfor ref-counted scroll lock + Escape support;useFullscreenparticipates in the same scroll-lock ref count via the exportedlockScroll/unlockScrollfromuseModalOverlay.ts. z-index: session=9000, plan=9100, lightbox=9999. Fullscreen exits live in the hook, never per consumer: on a pathname change, and on thefullscreen:yieldwindow event that MainPage's two column-opening entry points (openSessionOrToast,openDraftColumn) fire viayieldFullscreen(reason); without it a toast's "Open session ↗" or the panel's own Fork chip opened the new column BEHIND the sheet.openSessionOnHomedispatchesmain:open-session(the yield) BEFOREarmSessionInboxLink(re-enters fullscreen on the Inbox tab) so an already-fullscreen panel lands on the letter. Ratchet:tests/e2e/browser/fullscreen-yields-to-column-open.spec.ts. -
Session header actions: Only four chips stay visible outside the ⋮ kebab — Fork / Changed / Files / Terminal. Everything else (copy CWD/ID/Resume, Restart, Investigate, Notes, Msgs, Plan & Execute) lives in the kebab's
Sessionsection. The kebab is the sharedTaskQuickActions(slot="kebab"); it takes anextraSection={(close) => …}render-prop so one dropdown holds Task actions (top) + Session actions (bottom,SessionKebabSection.tsx). The kebab now renders even for a task-less session (whenextraSectionis supplied).SessionForkButton.tsxis the standalone Fork action (callsPOST /api/sessions/:id/forkwithcreate_child_task: true; backend auto-creates a child task then forks; navigates to/tasks/{newChildId}). Wired intoSessionPanel. Exit-fullscreen uses the sharedICON_COLLAPSE(lucide minimize-2, arrows inward). -
Service links open in the Web view: a click on an http(s) link in a session's chat column whose host is loopback (
localhost,127.x,0.0.0.0,::1), the session's host, or any configured host (with a port) opensSessionWebViewin the split instead of a browser tab. The decision is made at CLICK time inSessionPanel(handleServiceLinkClickon.session-panel-chat-col, classifierweb/src/utils/service-link.ts), so rendered HTML stays a plain<a target=_blank>everywhere; ⌘/Ctrl/Shift/middle clicks, anchors markeddata-native-link, and a console not served from loopback keep native behavior. The server (POST /api/sessions/:id/service-preview,src/core/session-service-preview.ts) picks the serving host, opens an SSH forward throughDaemonConnection.ensurePortForward(port, target)for a remote one, probes the page (refused vs slow, X-Frame-Options / frame-ancestors), and answers the 127.0.0.1 URL the iframe loads. Loopback/host matching rules live in ONE zero-import module shared by both sides:src/core/service-url.ts(@open-walnut/service-url). The kebab's "Web preview" opens the view empty for a typed address (8080,:8080/x,host:port). Ratchets:tests/web/routes/sessions-service-preview.test.ts,tests/e2e/browser/session-service-preview.spec.ts. -
Quick Add behavior: The "Quick add task..." form in
TodoPanel.tsxalways creates tasks underInbox / Quick Start(hardcodedcategory+project). After creation: if on the All tab, stays (task visible); any other tab (Star, category tabs) auto-switches to the Inbox tab. The new task is auto-focused and scrolled into view viaonFocusTask. AfocusHandledRefprevents race conditions when the task arrives via WebSocket afterfocusedTaskIdwas set. -
Multi-level child task nesting:
TodoPanel.tsxcomputesdepthMap(task ID → nesting depth) via recursive parent-chain walk in the child-taskuseMemo.isChildHiddenwalks the full ancestor chain — collapsing any ancestor hides all descendants. Depth-basedpaddingLeft(20px per level, max depth 10) replaces the old fixed.todo-panel-item-childCSS class for unlimited nesting support. -
Memory Browser (
/memory): Split-view page for browsing and editing all memory files. Left panel (MemoryTreePanel) shows collapsible sections (Global, Daily Logs, Projects, Sessions, Knowledge) with filter input. Right panel (MemoryContentPanel) renders selected file as markdown with an Edit toggle — clicking Edit switches to a monospace textarea for raw markdown editing with Save/Cancel buttons and keyboard shortcuts (Cmd+S, Escape). Edit state resets on file switch. Backend:GET/PUT /api/memory/browse|global+GET/PUT /api/memory/*(path-based with traversal protection). URL state via?path=query param. Resizable left panel with localStorage persistence. -
Browser console log persistence:
web/src/utils/browser-logger.tsmonkey-patchesconsole.log/info/warn/errorto persist browser logs to disk. Initialized inmain.tsxbefore React mount. Logs sent via WS RPCbrowser:logs(batched every 2s or 50 entries) withsendBeaconfallback on page unload. Backend writes to the same log file (subsystem: 'browser'). View withopen-walnut logs -s browser. Seesrc/logging/AGENTS.mdfor full details on investigating frontend issues.
Session Chat — Single-Timeline Model (streaming blocks + persisted history + optimistic bubbles)
Session chat renders three data sources: persisted JSONL history (server-parsed from Claude Code output files), streaming blocks (WS deltas accumulated in useSessionStream), and optimistic messages (client-side state in useSessionSend). The core challenge is showing content immediately and gracefully converging to persisted data, without duplicates or disappearances.
The single-timeline invariant (2026-07 refactor — read before touching turn boundaries)
The old model DELETED streaming blocks at turn boundaries via evidence reconciliation (clearCompleted, completedLen, awaitingRefresh, deferred clears, 5s fallback timers). Every new CLI stream format broke one of the heuristics → 7 same-shape "message vanished / pinned at bottom / looks unfinished" incidents in 2026-06~07. The refactor inverts the failure mode:
- Streaming blocks are APPEND-ONLY. No event handler deletes blocks.
session:resultonly stampscompletedLen(a MERGE boundary for the text accumulator, nothing else). - Absorption is a render-time filter, not a mutation:
web/src/stream/render-filter.ts(computeRenderFilter) hides a block iff current history PROVES it was absorbed — msgId twin (watermark-immune), toolUseId twin (incl.childMessagesrecursion), content twin within the turn window, or parent-AgentbgTaskFinishedfor subagent-lane blocks. Matching rules live inweb/src/cache/promote-blocks.ts(computeAbsorbedIndices) — the exact semantics that survived the incident chain. - Failure inverts: a missed match means a block briefly renders TWICE (next to its history twin) and collapses when evidence lands; it can never vanish. Unmatched finished blocks log a
render-filter: … no delta twinwarning — a persistent one means archive & stream genuinely disagree (real bug, surface it). - Turn watermark (
SessionChatHistory): history length when the current turn started streaming (isStreamingfalse→true edge; seeded at first history load). Content matching for id-less blocks only trustsmessages[watermark..]; id matching is scope-safe at any range. On /compact shrink the slice clamps empty → content matching pauses, ids unaffected. - Live-tail guard: while streaming, the last MAIN-lane block (
lastMainLaneIndex) is never matched: its partial content / early-known msgId must not hide it mid-accumulation. Exception: an Agent/Task tool_call tail IS matched (exact toolUseId; its persisted row is the anchor we want, see the subagent bullet below). - Subagents follow the Claude Code model: the lane never renders in the main conversation (
web/src/stream/group-blocks.ts, 2026-09-08). One compact Agent card sits at the spawn position (streamingStreamingTaskGroupwhile the tool_call is in the buffer, collapsed by default; the persistedTaskGroupthe moment history absorbs it), the Background ledger (WorkflowProgress, pinned above the scroll area, fed bysession:background-tasks) carries the run with per-agent elapsed/tokens/tool-uses/activity and "View transcript", and every lane block (anyparentToolUseId) is CONSUMED: inside the card when opened, nowhere when its anchor is hidden or gone. There is no "orphan group" any more, and a groupable parent absorbs on its bare toolUseId twin like any tool_call (promote-blocks.ts). Two designs preceded this and both put the same agent on screen twice: an anonymous "Subagent (continued)" box at the tail (inc-1785965937858), then a labeled live duplicate kept "as the safe direction" while the ✓ history card already rendered (the user could not tell which was current). Lane blocks of a running agent stay HELD silently (the ledger reads them;allBlocksAbsorbedwaits forbgTaskFinished), just not rendered. Pinned bytests/web/chat-lab/scenarios.test.ts,tests/web/stream/group-blocks-nested-lane.test.ts,tests/e2e/browser/subagent-interleave.spec.ts. - A reply looks the same streamed and persisted (2026-11-01, the user: "no flash, no change of format, font whatever"). The persisted row TAKES OVER the streamed reply's own DOM: a top-level reply text block (msgId, no
parentToolUseId, not yet in history) renders as a historySessionMessagerow (useStreamReplyRows, markeddata-stream-reply) in the same children array as the persisted rows (bodyRowsinSessionChatHistory), with each of the turn's other items a direct row there too (.session-live-row,display: contents, keyed by the item, so a person's message saved mid-turn never re-parents a live row), so when history gains the twin React keeps the same element and anhtml-appisland iframe never reloads (WebKit reloads an iframe on any re-parenting and has nomoveBefore, so the node must never move). Tests find the persisted row with[data-msg-ts]:not([data-stream-reply]). Everything else a row's look depends on must still be the same on both sides: every streaming text block wearssession-msg session-msg-assistant+session-msg-content(message styles hang off those classes: the dark code block is.session-msg-assistant .markdown-body pre), the streaming reply carries the persisted row'sMessageMetaRowstrip (StreamingReplyMeta, the last one sticky once the turn ended) and its image strip (ReplyImageStrip), a turn whose answer this view watched stream keeps theopenshape until a later turn begins (watchedReplies, so its steps do not fold at the handover), and a re-created chat image is eager and held at its drawn box (utils/image-size-hold.ts). The phone does the same in UIKit: before the timeline reloads, the visible rich cells offer their web views (TimelineRichHTMLCell.offerDocuments), and a cell bound to the same document takes one over instead of loading. A disclosure keeps its state by what it shows, not by its element (components/sessions/row-disclosure.ts): a tool run (run-<first toolUseId or msgId>, the same id asrunRowKey), a tool card, the reasoning, a diff, a plan, a details block keep their open state per session (RowDisclosureScope, given bySessionChatHistoryandTranscriptBody), so an opened run stays open when its saved row (another component) replaces it;tests/web/row-disclosure-ratchet.test.tswalks every component a row draws and fails on an open state inuseStateor an uncontrolled<details>. Live and saved rows share ONE merge rule (stream/tool-merge.ts: agent spawns, the plan exit and plan writes, and messages to other sessions stand alone;tests/web/stream/tool-merge-parity.test.ts) and ONE card dispatcher (SessionToolCall, so a live Edit is already the diff). A subagent's reader follows the same model: the running lane is synthesized into the transcript's own message shape (laneMessagesFromStream) and drawn by the sameLaneHistoryTimelinein the same place, so the saved transcript takes over its rows when the agent finishes, with no fetch while it runs and no loading line after (subagent-interleave.spec.ts,stream-disclosure-handover.spec.ts). Guards:tests/e2e/browser/stream-final-render-parity{,-real}.spec.ts(every element's computed style and box streamed vs finished, every frame and DOM commit across the handover, no reply node replaced, the island loaded once),ios-native/WalnutTests/RichHTMLHandoverTests.swift,IslandStreamUITests.testTwoIslandsKeepTheirRunningPagesWhenTheTurnEnds. - Memory reclamation is all-or-nothing:
resetIfAbsorbedinuseSessionStreamdrops the whole array only when every block is hidden and no turn is live (allBlocksAbsorbed). Because reset is atomic and blocks are append-only, array indices are stable render identities — no blockSeq needed;blockIndexMapbubble anchors are set-once and clamp to 0 on full reset. session-cache's streaming state is a background accumulator;gcAbsorbedBlocksis memory-bound GC only (correctness lives in the render filter, never in the cache).- Fault-injection e2e pins the invariants:
tests/e2e/browser/single-timeline-fault-injection.spec.ts(batch-before-result race, held refetch, /compact shrink). - History refetch triggers (
historyVersionbumps inSessionChatHistory):session:batch-completed,session:error(notdelivery_failed),_ws:reconnected,isStreamingtrue→false, and the turn-START edge (turn-prompt-refetch.ts): the live turn's first MODEL-output block (text/thinking/tool_call/permission) while no user row ≥ watermark and no optimistic bubble exists. That edge exists because the CLI writes the launch prompt to the transcript only after it boots (3-7 s after spawn), AFTER the panel's opening fetches — without it the first message stayed hidden until turn end (2026-09-03). System blocks never qualify: hook/init notifications land ~20 ms BEFORE the user line. - Launch-prompt bubble (2026-09-28, the edge above still left 13 s of "working…" over an empty timeline): the server keeps each native launch's prompt in memory until the first turn ends (
src/core/sessions/launch-prompts.ts, fed bysession:start, skipping forks, side-thread lanes and ACP engines) andsession:get-queuereturns it aslaunchPromptBESIDE the queue.useSessionSendprepends it as adeliveredbubble flaggedlaunch(seeded synchronously fromlaunch-prompt-seed.tsin the tab that pressed Start, so the pending column's echo never blinks out at promotion);SessionChatHistoryrenders it at the HEAD of the conversation, above persisted rows and outside the live timeline, so a transcript that never yields its row can't leave it pinned under the answer;optimistic-dedup.tsabsorbs it by POSITION (the first typed user row,launchRowIndex), never by text or watermark, because the row can carry Walnut's wrappers and the bubble can arrive after the watermark passed it (a tail-windowed history,historyFromStart: false, counts it absorbed: its row is above the window). Pinned bytests/web/optimistic-dedup-launch.test.ts,tests/core/launch-prompts.test.ts,tests/e2e/browser/launch-prompt-first-message.spec.ts.
How Claude Code JSONL records user messages
Claude Code CLI writes JSONL output (one JSON object per line). User messages appear via 3 patterns:
| Pattern | When | JSONL entries | Reliable? |
|---|---|---|---|
| A (FIFO mid-stream) | User sends while CLI is running a turn | queue-operation:enqueue → queue-operation:dequeue → normal human_turn_start | Usually, but CLI may finish before reading FIFO |
| B (FIFO unprocessed) | FIFO msg not consumed before turn ends | queue-operation:enqueue only (no dequeue) — parser synthesizes user msg | Yes (enqueue always logged) |
| C (--resume) | No running process → server spawns claude --resume -p "msg" | Normal human_turn_start | Always |
Server-side parser (src/core/session-history.ts): matches enqueue→dequeue pairs (Pattern A skips enqueue, uses the user message that follows). Unmatched enqueues (Pattern B) are synthesized as user messages at their chronological position.
remove has two meanings (CLI 2.1.280). A send that arrives while a tool runs is handed to the model at the next tool boundary as an attachment line of type queued_command (its prompt is the text, or a content array for an image send), then the CLI logs queue-operation:remove. A Stop with cancel_queued also logs remove, with no attachment. Only the second hides the enqueue; the first stays a Pattern B row at its enqueue. Treating every remove as a drop hid nearly every mid-turn send and left its "Delivered" bubble below the later turns (inc-1790637095180, tests/core/session-history-queued-command.test.ts).
Optimistic message lifecycle
pending → received → delivered → committed → (deduped by persisted history)
| Status | Trigger | Meaning | Visual |
|---|---|---|---|
pending | send() | Exists only in React state | Grey |
received | WS RPC response | Server acknowledged, queueId = real messageId | "Queued" badge |
delivered | session:messages-delivered event | Written to FIFO or --resume spawned | "Delivered ✓" badge |
committed | session:batch-completed → handleBatchCompleted | CLI consumed the message | Normal text |
| (hidden) | Render dedup (consumedQueueIds sticky set) | Persisted history now contains this message | — |
| (removed) | GC notification effect → onBatchCompleted(0, ids) | Post-render cleanup of hidden bubbles | — |
Dedup logic (critical — was source of a disappearing-message bug)
Problem: Text-based dedup against ALL persisted history caused false matches. If the user previously sent "hi" in turn N, and sent "hi" again mid-stream in turn N+1, the new optimistic "hi" was matched against the OLD persisted "hi" and removed.
Solution (two-tier dedup, optimistic-dedup.ts):
- Non-committed (pending/received/delivered): Only dedup against messages that appeared since the turn watermark (
messages[watermark..length]). Old persisted messages cannot absorb new optimistic messages. (The watermark replaced the oldprevMsgLenfreeze dance — it advances only on theisStreamingfalse→true edge, so no per-render bookkeeping.) - Committed: Dedup against ALL persisted messages. Safe because committed = CLI consumed it, so the persisted copy exists somewhere.
Both tiers use multiset (count-based) matching for correctness with duplicate texts, with a walnutMessageId id-first pass (echo-claim) before any text matching. Deduped bubbles enter the sticky consumedQueueIds set (render tombstone); a post-render effect notifies useSessionSend (onBatchCompleted(0, ids) — count 0 so the count-fallback path can't misfire) to physically remove them.
The index window alone is not enough (inc-1790922678361, 2026-10-02). A bubble carries its enqueue time (timestamp: the server's enqueuedAt, returned by session:send and carried on session:message-queued; the client clock only until the RPC answers), and every row carries the CLI's timestamp. Two more ways a row proves a bubble, both in optimistic-dedup.ts: (a) a user row BELOW the watermark still counts when it is not older than the bubble's enqueue minus BUBBLE_CLOCK_SLACK_MS (10 s; NTP drift is sub-second and every second of slack lets an identical earlier send absorb the new bubble early), so a row that landed under a watermark that moved on, or under a re-seeded one, is still found; (b) when the history is a tail window (historyFromStart: false), a delivered bubble enqueued before the window's first row by more than the slack is absorbed by position, like the launch bubble, because its row sits above what is loaded. The incident: a redeploy mid-turn left the server's history cache cold, the panel's refetch came back as a byte-bounded tail window starting at the compaction, and six mid-turn sends whose rows sat above it stayed "Delivered ✓" under every later turn until a reload (deltas only append; session:batch-completed is not a removal signal and its ids under-report). Only delivered qualifies for (b): pending/received never reached the CLI, and inside the window a missing row is a real mismatch that must stay visible. Pinned by tests/web/optimistic-dedup-window.test.ts and tests/e2e/browser/bubble-window-swap.spec.ts.
Key files
| File | Role |
|---|---|
web/src/stream/stream-reducer.ts | THE single copy of frontend accumulation semantics (lane isolation, msgId boundary, tool-result backfill). Pure functions. |
web/src/stream/render-filter.ts | Non-destructive absorption: computeRenderFilter (hidden set + unmatched diagnostics), allBlocksAbsorbed reset gate. |
web/src/cache/promote-blocks.ts | computeAbsorbedIndices = the evidence-matching core (id-first, content multiset, join-run, childMessages, bgTaskFinished). promoteCompletedBlocks = destructive wrapper used only for cache GC. |
web/src/components/sessions/SessionChatHistory.tsx | Renders persisted + streaming (filtered) + optimistic. Turn watermark. Bubble dedup + GC notification. Timeline interleaving. |
web/src/components/sessions/optimistic-dedup.ts | Bubble dedup (id pass + watermark-windowed multiset). |
web/src/hooks/useSessionSend.ts | Optimistic state machine (pending→committed). |
web/src/hooks/useSessionStream.ts | Streaming blocks from WS (append-only; resetIfAbsorbed for memory reclamation). |
web/src/cache/session-cache.ts | Background accumulator for offscreen sessions + history LRU. gcAbsorbedBlocks = memory GC only. |
web/src/hooks/useSessionHistory.ts | Fetches persisted history via REST (cursor/delta transport, stale self-heal). Re-fetches on historyVersion change. |
src/web/session-stream-buffer.ts | Server-side accumulator twin (language boundary — keep semantics aligned with stream-reducer). |
src/core/session-history.ts | Server-side JSONL parser. Pattern A/B/C handling. |
src/providers/claude-code-session.ts | FIFO write (writeMessage), processNext (FIFO→--resume fallback). |
src/core/session-message-queue.ts | Disk-backed message queue. Survives server restart. |
Frontend File Structure
web/src/
├── App.tsx # Routes (see CLAUDE.md routes table)
├── pages/ # MainPage, DashboardPage, SearchPage, SettingsPage,
│ # TaskDetailPage, ChatPage, CronPage, UsagePage
├── components/
│ ├── chat/ # ChatPanel, ChatInput, ChatMessage
│ ├── tasks/ # TodoPanel, TaskList, TaskCard, TaskForm, SubtaskList
│ ├── context/ # ContextInspectorPanel, ContextSection, ToolCard, ApiMessageBlock
│ ├── sessions/ # SessionPanel (the ONLY session surface), PlanPopup, SessionChatHistory
│ ├── settings/ # SettingsNav, inputs/ (SectionCard, SecretInput, ToggleSwitch, NumberInput,
│ │ # ListEditor, KeyValueEditor, StatusIndicator), sections/ (9 section components)
│ ├── memory/ # MemoryTreePanel, MemoryContentPanel
│ ├── usage/ # UsageSummaryCards, UsageDailyChart, UsageBreakdownTable, UsageRecentTable
│ ├── cron/ # Cron job management components
│ ├── layout/ # Sidebar, AppShell
│ ├── search/ # SearchBar, SearchResults (child task display with indentation)
│ └── common/ # EmptyState, LoadingSpinner, StatusBadge, PriorityBadge
├── hooks/ # useTasks, useChat, useWebSocket, useSessionStream, useResizablePanel,
│ # useSessionHistory, useContextInspector, useCronJobs, useFavorites, useOrdering,
│ # useUsage, useSettingsConfig, useModalOverlay
├── api/ # REST client: tasks, sessions, search, config, ws
├── utils/ # Shared utilities (markdown rendering, session-status, time)
└── styles/globals.css # Theme
Related skills
Logo Creator
SamurAIGPT
Generate minimalist, scalable vector logos using geometric shapes and negative space.
Design Audit
thedotmack
Score a design against Dieter Rams' principles and create a plan to improve it.
De-Vibe
ucsandman
Remove AI-generated patterns and add handcrafted polish before shipping.
Design Critique
plugin87
Review and argue against current design work to catch flaws and weaknesses.