diff --git a/README.md b/README.md index f6e7ad97..4d2060f4 100644 --- a/README.md +++ b/README.md @@ -765,6 +765,7 @@ The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for t | `Alt/Option+[` / `Alt/Option+]` | Previous / next session | | `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) | | `Alt/Option+B` | Collapse / expand the session sidebar (sidebar layout only) | +| `Alt/Option+Shift+C` | Switch a local or Docker Claude session between Chat and Terminal view (not on phones; see [Settings Reference](docs/wiki/Settings-Reference.md)) | | `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right | | `Ctrl/Cmd+C` | Copy selection, or interrupt when nothing is selected | | `Ctrl+Shift+C` | Copy selection (never interrupts) | diff --git a/docs/api-reference.md b/docs/api-reference.md index 98740959..30365620 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -601,6 +601,26 @@ request returns. The capture runs synchronous tmux calls on the server; the | `lines=` | With `full=1` only: read at most `` lines of tmux history above the visible frame. An integer of at least 1, clamped to the configured history limit; absent or malformed, the whole limit (100,000 lines by default), as before. When a bound below the configured limit left older lines in tmux (its `history_size` is deeper), `truncated` is true with `truncationReason: 'tail'`; a byte cap still reports `'capped'`. Without it a full capture reads all of that history before `tail` cuts it, so a client that keeps a fixed number of lines (the tile grid sends its xterm's scrollback plus its rows) should send it. | | `alt=recording` | With `full=1` only: if the pane is in the alternate screen (a nested tmux, where tmux keeps no history, or any full-screen app such as vim or less while it is open), answer with the visible frame over the byte recording instead (`source: 'mux-visible'`, `tail` applied as without `full=1`). Shells' automatic loads send it. | +## Conversation reads for the chat view + +### `GET /api/v1/sessions/:id/last-response?context=full` + +With `context=full`, the response carries the whole conversation as `messages`. Each +message read from a Claude transcript has `kind`, `label`, `role`, `text`, `turn` and, +when known, `timestamp`. A prompt the user typed while Claude was working also carries +`queued: true`. That reader also marks the turns that Codeman's prompt-cache +keep-warm sent. The nudge prompt and the reply to it both carry `keepAlive: true`, so a +client can leave them out as the chat view does. A prompt the user queued during that +turn makes the turn theirs, and its later messages carry no flag. + +A full read of a Claude transcript also starts a transcript watcher when none runs for +the session. A watcher normally starts at the session's first hook or statusline report, +so a session picked up after a server restart has none until one of those arrives. The +read starts one from the file it found, and the session's `transcript:*` events then flow +mid-turn. After a `/clear`, a read moves a watcher it started itself to the conversation's +new file. It never replaces or moves a watcher that a hook or a statusline report started, +and it starts none for a remote SSH session, whose transcript is not on this host. + ## Experimental bounded agent inspection and guarded input **Experimental:** `codeman agent inspect`, `stage` and `submit`, and their @@ -1903,6 +1923,13 @@ the stable contract — event names are not renamed without a major bump. An optional `?sessions=` filter suppresses only the high-volume terminal stream; lifecycle/metadata events are delivered to all clients regardless. +### `transcript:update` (the chat view's re-read) + +The server broadcasts `transcript:update` (`{ sessionId, timestamp }`) for a session whose +transcript watcher runs, whenever new lines arrive in its transcript. It throttles the event +to one per 750 ms per session. The first update after a quiet spell goes out at once, and a +burst after it collapses into one trailing event. + ### `sse:heartbeat` (liveness) Every 15s the server writes a `sse:heartbeat` frame to every connected client: diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 28853ae5..db3111ce 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -888,7 +888,7 @@ Two surfaces do not move with a worktree inside `workingDir`. The Git panel keep ⚠️ **Reads only on request, opt-in all the way down.** `server.ts` builds the `EditHistorySync` and hands it to the routes; its only own calls are `remove` (through `forgetEditHistory`, when the session's persisted record goes), `sweep` (startup) and `flushAll` (shutdown). No hook, no timer, no second watcher. The panel drives every read: `?sync=1` when it opens, and while it is open on that session a debounced (600 ms) re-read after a `transcript:tool_end` of an edit-capable tool (Edit, Write, MultiEdit, NotebookEdit, Bash, Agent, Task, SendUserFile), which the existing `TranscriptWatcher` already broadcasts, or the session's `session:idle` (the end of a turn, via `_onSessionIdle`; it also catches a background subagent that writes after the tool end that started it). Not `transcript:complete`: it fires on a `result` line, which claude's interactive transcript never has. A closed panel reads nothing and keeps no badge. Guarded by the "reads only on request" wiring test in `test/edit-history-sync.test.ts`. -⚠️ **Which transcript** (`resolveClaudeTranscript`). The main transcript is the path the session's `TranscriptWatcher` follows (the hook-reported `transcript_path`), so a session is read from where its claude really writes, whatever its `CLAUDE_CONFIG_DIR`. Without a watcher (server restarted, no hook since), `findClaudeTranscript()` looks for `.jsonl` under `claudeProjectsDir(session.claudeConfigDir())`: the session's own override (#255, the same dir the relaunch pin checks), else the server's. A config dir set outside Codeman (a shell profile, a wrapper) is never guessed: until the next hook such a session answers `unavailable` / `no-transcript`, and the panel says so. Subagents are `
/subagents/agent-.jsonl`. A different main file (`/clear`, resume): the previous one, next to it in the same directory, is first read to its end with its subagents (over as many syncs as that takes), then the new one from its end with fresh cursors; the stored entries stay. "Load older" reaches back within the current conversation only, and reads the stored conversation's transcript while the switch is still pending. +⚠️ **Which transcript** (`resolveClaudeTranscript`). The main transcript is the path the session's `TranscriptWatcher` follows (the `transcript_path` a hook or the statusline reported, or the file a full `last-response?context=full` read found, which the chat view and the Response Viewer's More button both make), so a session is read from where its claude really writes, whatever its `CLAUDE_CONFIG_DIR`. Without a watcher (server restarted, and no hook, statusline report or full read since), `findClaudeTranscript()` looks for `.jsonl` under `claudeProjectsDir(session.claudeConfigDir())`: the session's own override (#255, the same dir the relaunch pin checks), else the server's. A config dir set outside Codeman (a shell profile, a wrapper) is never guessed: until the next hook or statusline report such a session answers `unavailable` / `no-transcript`, and the panel says so. Subagents are `
/subagents/agent-.jsonl`. A different main file (`/clear`, resume): the previous one, next to it in the same directory, is first read to its end with its subagents (over as many syncs as that takes), then the new one from its end with fresh cursors; the stored entries stay. "Load older" reaches back within the current conversation only, and reads the stored conversation's transcript while the switch is still pending. ⚠️ **Bounded reads.** A sync is at most `MAX_FORWARD_PASSES` (3) reads, each at most `READ_BUDGET_BYTES` (8 MiB) shared by the main transcript and all subagents (main first), plus up to 8 KiB of `meta.json` per subagent seen for the first time; a first read starts that far before the end. A file whose chunk the shared budget cut short is not applied but read in a later pass (the store would take a chunk with no line end for one line longer than the budget). "Load older" reads a full-budget block of up to `MAX_OLDER_SOURCES` (3) transcripts per click; with more, they take turns. A line longer than the budget is skipped, going forward and going back, and the line after (before) it is read whole. A subagent transcript that vanished loses its cursor, not its entries. Parsing happens in the request, line by line; nothing runs on the PTY data path. One sync per session at a time, and requests during a run fold into one more run. At most `MAX_LOADED_STORES` (3) stores stay in memory: past that the least recently used one without a run in flight is written (only if it changed) and dropped, and a later request loads it again after that write. @@ -1345,7 +1345,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u ### Z-index layers -**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it). +**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the response viewer opened BEHIND the response viewer), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), chat view (20, `.chat-view`, covering the terminal inside `.terminal-wrap`) and its Chat / Terminal switch (21, `.chat-view-toggle`, above it), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it). ## Security layers diff --git a/docs/chat-view-plan.md b/docs/chat-view-plan.md new file mode 100644 index 00000000..315d9798 --- /dev/null +++ b/docs/chat-view-plan.md @@ -0,0 +1,326 @@ +# Chat view: a rendered conversation as the main session view + +## Goal + +A Claude session should be readable the way the Claude Code web and desktop apps +are: prose in a proportional font, markdown rendered, code in boxed blocks, and the +page's own light or dark colours. Codeman should keep managing the session exactly +as it does today. The agent still runs in its tmux pane, and only the way the +browser shows that pane changes. + +The Response Viewer already renders a conversation this way, and its output is the +look to keep. Its problem is placement: it is a sheet the user opens on demand, +it does not update while the agent works, and it cannot send a prompt. The chat +view moves that same rendering into the main area, keeps it live, and puts a +message box under it. + +## What the user sees + +Each Claude session gets two views of the same pane: + +- **Chat** shows the conversation rendered by the Response Viewer's markdown + pipeline, newest message at the bottom, with a message box underneath. +- **Terminal** is today's xterm.js pane, unchanged. + +A toggle switches between them, and a keyboard shortcut does the same. The choice +is remembered per session on this device. The toggle floats at the top right of the +terminal. A second per-device setting shows or hides it. It shows by default, and a +user who never uses the chat view can turn it off. The shortcut still switches views +while the toggle is hidden. A per-device setting picks the view for every session +this browser has no choice for yet, so a user who prefers chat never has to switch by +hand. The setting defaults to Terminal. Chat replaces the main view and still sends +some dialogs to the terminal in phase 1, so nobody gets it without choosing it. + +Your own prompts show in full when they are short. A prompt longer than about 12 +lines, typically a pasted log or spec, shows its first 6 lines followed by +"Show all (N lines)", so a long paste does not fill the screen between two +answers. Keep-warm nudges are hidden, as Read My Mind already drops them, because +Codeman sent them and you did not. + +While the agent works, the chat view shows a status line under the last message. +It names what the running tool works on, such as "Reading src/session.ts" or +"Running npm test". A Bash call with a description shows the description, with the +command on a second `$ …` line, as the CLI does. The status line can say this because +`transcript:tool_start` carries `detail` and `command`, which `summarizeToolCall()` and +`toolCallCommand()` in `src/tool-call-summary.ts` pick out of the call's input. Each +block of Claude's answer appears as a rendered message as soon as Claude writes it to +the transcript, so a long turn fills in while it runs. + +While Claude Code compacts the conversation, the status line says "Compacting +conversation". A compaction runs for a minute or more and writes nothing to the +transcript until it ends. Claude Code then draws `✻ Compacting conversation… (12s)` as +its working line, for `/compact` and for its own auto-compaction alike. The terminal +stays attached under the chat view, so the chat view reads that line from the +terminal's own buffer on each tick of the status line. Only Claude's newest row above +its message box counts, so an answer that quotes the line does not. + +Between turns, Claude can still run work in the background, such as a background +shell or a monitor. The server reads that off Claude's screen as the session's +`watching` value, and the status line then says so, for example "1 shell still +running". + +The chat view always shows the session's current conversation. After `/clear` it +starts empty, as Claude itself does. Claude Code runs the statusline command about a +second after a `/clear`, and its input names the new conversation and its transcript +file. The statusline exporter posts that input to the server, which moves the session +to the new conversation, so the chat view follows before the next prompt. A session +without the exporter, such as a Docker session or any session while Plan Usage Limits +is off, moves with its next prompt's hook. A session with neither moves when the chat +view next reads its conversation, as described under How the view stays live. + +## Where the conversation comes from + +Claude Code writes every session to a transcript file, one JSON object per line. +`GET /api/sessions/:id/last-response?context=full` already reads that file and +returns the whole conversation as prompt and response messages, each tagged with +its turn number. The Response Viewer's "More" button uses it today, so the chat +view needs no new reader for its first version. + +That reader keeps only text. It drops tool calls, tool results and thinking blocks, +so in phase 1 the conversation shows prompts and answers only. + +Phase 2 adds a turn's tool activity as one muted summary line, such as +"Read 9 files · edited 2 · ran 3 commands". A busy turn makes dozens of calls, and +a line per call would push the answer far down the page. Clicking the summary +expands it to one line per call ("Read src/session.ts", "Ran npm test"), and each +of those expands to show the call's input. For edits, the Edit history panel also +shows the diffs. + +The summary needs every call, so in phase 2 the parser emits a `tool` message for +each `tool_use` block. The message type already exists: the DeepSeek transcript +reader and the readers for the CLIs whose conversation Codeman reads from the pane +emit it. + +Parsing the whole file on every update would hold the server's event loop for over a +second on a long conversation. So the server keeps each transcript's parse and the +byte offset it reached, and a read parses only the bytes appended since the last one +(`src/web/claude-response-transcript.ts`). Phase 3 adds a cursor, so the browser asks +only for messages after the last one it has. + +## How the view stays live + +The server watches a Claude session's transcript. A watcher starts at the session's +first hook or statusline report, and either one reports the transcript's path. +Codeman installs those hooks in every Claude workspace unless `workspaceHooksEnabled` +is off. + +A session that sends neither a hook nor a statusline report has no watcher: + +- a session the server picked up after a restart, until either one arrives; +- a session with hooks switched off and no statusline exporter; +- a Docker case whose hooks cannot reach the server. + +For those, any full read of the conversation starts a watcher from the transcript that +read found. A full read is `GET /api/sessions/:id/last-response?context=full`, which +both the chat view and the Response Viewer's More button make. So these sessions +also update mid-turn. After a `/clear`, a read moves a watcher it started itself to +the conversation's new file, because no hook or statusline report will move it. The +read never replaces or moves a watcher that a hook or a statusline report started, +and it starts none for a remote session. + +The watcher emits `transcript:update` whenever new lines arrive. The server +broadcasts it as an SSE event, throttled to one per 750 ms per session, so the +browser learns of each new message while a turn is still running. + +The chat view also listens for these events: + +- `transcript:tool_start` drives the status line, because it carries the tool's + `detail` and, for a described Bash call, its `command`. With parallel tool calls, + the matching `transcript:tool_end` fires once, so the status line shows the most + recent tool rather than counting calls. +- `session:working` and `session:idle` mark the start and end of a turn. They come + from Codeman's idle detection, not from hooks, so they also work where no + transcript watcher runs. + +`transcript:complete` does not help here. It fires only for a `result` row, and an +interactive Claude transcript has none. + +A Docker case whose hooks do reach the server gets no mid-turn updates. Its hook reports the +transcript's path inside the container, which the host cannot open. The watcher +keeps that path, so the full read starts no second one. Such a session refetches on +`session:working` and `session:idle` alone, and so updates only at the start and end +of each turn. + +## How the user sends a prompt + +The message box is a multiline text area. On a desktop, Enter sends and +Shift+Enter adds a line. On a touch device the Send button sends, and so does +Ctrl+Enter or Cmd+Enter from a hardware keyboard. Plain Enter adds a line there, as +in the phone's Compose dialog. + +A send posts the text and its Enter as one input to `POST /api/sessions/:id/input` +with `useMux: true`. The server then pastes the text through tmux, presses Enter, +and arms its submit check. That check re-presses Enter while the prompt still sits +in Claude's composer, which Claude 2.1.277 and later cause by ignoring Enter for 30 +to 50 seconds after the composer appears. + +The browser's WebSocket input channel cannot do this. It writes raw bytes straight +into the pane and never reaches the tmux path, whatever the frame asks for. So the +chat view does not use it for prompts, even though that channel queues input +across a dropped connection. + +Each request carries a client id, made once per page load, and a sequence number. +A request that fails on the network, or that the server answers with a 5xx error, +is retried with the same pair, so the server applies it once. A request the server +refuses with a 4xx status is not retried, and the text stays in the message box. + +The submit check cannot always recognise a multi-line prompt in the composer. So a +long paste sent in the 30 to 50 seconds after Claude's composer appears can still +strand. + +Claude Code stores a pasted prompt inside a `` tag, and every +multi-line prompt sent through tmux is a paste. The chat view unwraps that tag +before rendering, or the markdown renderer would run the lines together. + +The box also gets these controls: + +- A stop button sends Esc, which interrupts the current turn. +- An attach button, drag-and-drop and pasting a screenshot or file into the message + box all reuse the existing prompt upload route. The uploaded files' paths go into + the chat message box, using the upload code's existing option to return paths + instead of typing them into the pane. A paste that carries no file the attach rules + admit stays a plain text paste. +- A slash command is sent as text, and the conversation shows it as typed + (`/dual-review`), not as the tags Claude Code records it with. A skill's body, + which Claude Code adds as a hidden row, stays out. Claude Code records `/compact` + only when its turn ends, so the sent copy stays drawn while that turn runs. A + skill's row arrives as its turn starts, followed at once by the hidden body row, + and that row takes the sent copy's place then. A command that runs no turn and is + never recorded goes from the thread after four seconds. +- Some slash commands typed with nothing after them get special handling in the chat view: + - `/quit` and `/exit` close the session at once, as the tab's close button does, + rather than waiting for the agent to exit and the server to notice. + - `/clear` empties the thread at once. Claude Code starts a new conversation file, + and the server moves to it when the statusline reports it, about a second later. + A session without the exporter moves later, as described at the end of What the + user sees. Until then the chat view leaves out every message no newer than the + newest one it drew before `/clear`. + - A built-in that opens a picker or a panel inside Claude's interface, such as a + bare `/model` or `/config`, shows the terminal, with a note that Alt+Shift+C + goes back. The session's remembered choice of view does not change. The server + marks those commands (`opensTerminal` in the `/` menu's list). + +The terminal stays mounted and attached while Chat shows. The chat view is a layer +over the terminal's area, so the terminal keeps its size and switching views never +resizes the pane. The stop button uses the terminal's connection to send Esc. Any +focus that lands on the hidden terminal moves to the message box, so keys never +reach the pane unseen. + +## What else the message box shows + +The message box also carries three things the terminal shows around Claude's +composer. + +- **A `/` menu.** Typing `/` at the start of the box opens a menu of slash commands, + fed by `GET /api/sessions/:id/slash-commands`. The list merges three sources: + Claude Code's built-in commands, the skills and prompt commands that the + transcript's `skill_listing` rows name, and the skills and commands on disk. The server reads those files from + the workspace's `.claude` folder and the user's Claude config folder, and every + read is bounded. For a Docker session it reads only the workspace's `.claude` + folder, because that session's config folder is the container's. Picking a row + puts `/ ` in the box and sends nothing. +- **The statusline.** Claude Code draws the user's statusline under its composer, + and the chat view draws the same text under the message box. Codeman's statusline + exporter wraps the user's own statusline command. Its V5 script prints that + command's output unchanged and posts a base64 copy of it as `rendered`. The server + keeps only the text, line breaks and colours, and broadcasts each change as + `session:statusLine`. A user without a statusline of their own sees Codeman's footer. + Claude Code does not run the statusline command while a session sits idle, so the + server restores the last text after a restart, and an idle session keeps its statusline. +- **The suggested next prompt.** After a turn ends, Claude Code may draw a predicted + next prompt, faint, in its empty composer. It writes that prediction nowhere else, + so `src/web/prompt-suggestion-reader.ts` reads it off the pane three times, at + about 1.5, 4 and 10 seconds after the turn ends. It reads nothing while no browser + is connected to the server. The chat view shows it as the box's placeholder, and Tab in + the empty box fills it in. A suggestion is never sent without the user. + Each read is a synchronous tmux capture that blocks the server's event loop, and + so are the reads of the submit verifier, the idle probe and keep-warm. Moving every + one of those screen reads to an async capture is a follow-up. + +## Dialogs and questions + +Claude sometimes stops to ask: a permission prompt, an AskUserQuestion with +options, a plan approval. The question appears in the transcript as a tool call, +but the dialog that answers it exists only in the pane. + +Codeman's Approvals Inbox already detects these through Claude's hooks, reads the +options from the pane, and answers them with `POST /api/approvals/:id/answer`. +Its store runs even while the inbox setting is off. In phase 2 the chat view shows a +pending item for its session as a card at the bottom of the conversation, with one +button per option. A click goes through the same answer route, which re-reads the pane +before it types anything. + +The pane can also need attention in ways the inbox cannot parse. For those, the +chat view shows a notice that says "Claude is waiting for your answer in the +terminal." and offers a button that switches to the terminal view. + +In phase 1, the `permission_prompt` and `elicitation_dialog` hooks raise that notice, +and the answer cards follow in phase 2. While the notice shows, the message box sends +nothing and keeps its text. A send then would type into the dialog, and its Enter could +pick the highlighted option. A session without working hooks gets neither the notice +nor the send block: its hooks are switched off, or it is a Docker case whose hooks +cannot reach the server. A send there can still type into a dialog. Covering those +sessions needs a read of the screen, because the Approvals Inbox behind the phase 2 +cards is fed by the same hooks. Dialogs are rare enough for this order. Codeman starts +Claude with `--dangerously-skip-permissions` by default, so a session stops only for +Claude's own questions and plan approvals. A session started in another +permission mode stops for every permission prompt and sends each one to the +terminal until phase 2. + +## Scope + +The first version covers local and Docker Claude sessions in the single main view. +Remote (SSH) and adopted sessions keep the terminal, even an adopted session that +runs on this machine, because Codeman cannot name an adopted session's transcript. +Tiles in the tile grid and the second pane of a split stay terminals. Phones keep +the terminal until phase 3. The chat view is not offered on a handheld device, whatever +its orientation, so a phone turned to landscape keeps the terminal too. + +Docker Claude sessions read their transcripts through the same route, because +the container bind-mounts the host's `~/.claude/projects`. That works only when the +folder existed when the container was created. It also works only while the server +runs without `CLAUDE_CONFIG_DIR`. With that variable set, the route reads +`$CLAUDE_CONFIG_DIR/projects`, which the container does not mount. A Docker session +whose hooks cannot reach the server updates mid-turn once a full read has started its +watcher. That read comes from the chat view or the Response Viewer's More button, as +described under "How the view stays live". + +Remote SSH sessions are not covered. The route reads the local projects folder, +and a remote session's transcript lives on the remote host. The Edit history panel +already reads remote transcripts over its bounded ssh path, and phase 3 can reuse +it. + +Codex and DeepSeek Harness also write structured transcripts, which Codeman +already reads, so they can follow in phase 3. OMP writes a structured transcript as +well, and Codeman reads it for the session history list. The conversation route has +no OMP reader yet, so OMP can follow once that route reads its transcript. Every +other CLI keeps the terminal view for now, and its toggle is hidden. For the CLIs without a structured transcript, Codeman reads the conversation +off the screen, which is too coarse for a main view, or cannot read it at all. + +The agent keeps running in its tmux pane, and respawn, Ralph, auto-compact and the +other server features work as they do now. The chat view adds no hook to the +workspaces Codeman installs hooks in, and changes nothing in a session whose chat view +is off. + +## Phases + +1. **Live chat view**, in five steps that each work on their own: + 1. **Read.** Add the Chat/Terminal toggle, the setting that hides it and the + default-view setting. Broadcast transcript updates as a throttled SSE event, + render the full conversation with the Response Viewer's pipeline, and refetch it + on transcript and session events. Show a working status line, the "waiting for + your answer in the terminal" notice with its switch button, and follow `/clear` + through the statusline. Typing still happens in the terminal. + 2. **Write.** Add the message box with send, stop and attach. + 3. **Slash commands.** Add the `/` menu, draw a typed slash command as typed, and + handle `/clear`, `/quit`, `/exit` and the picker commands. + 4. **What Claude is doing.** Name the running tool in the status line, say when + Claude compacts or still runs background work, and show the suggested next + prompt as the message box's placeholder. + 5. **The statusline** under the message box. +2. **Dialogs and tool activity.** Show approval cards inline. Extend the transcript + parser with tool messages and render each turn's calls as one expandable + summary line. +3. **Scale and reach.** Add incremental fetching with a cursor. Extend the view to + remote SSH sessions, Codex and DeepSeek Harness, and lay it out for phones, + where the chat view could replace the terminal and accessory bar entirely. diff --git a/docs/wiki/Keyboard-Shortcuts.md b/docs/wiki/Keyboard-Shortcuts.md index 8426daec..3e854749 100644 --- a/docs/wiki/Keyboard-Shortcuts.md +++ b/docs/wiki/Keyboard-Shortcuts.md @@ -14,6 +14,7 @@ Press `Ctrl+?` in the app for the same list in a floating overlay. | `Alt+1` to `Alt+9` | Switch to tab N. Physical keys, so macOS Option layouts work. | | `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move the active tab left / right. | | `Alt+B` | Collapse / expand the session sidebar, when that layout is on. | +| `Alt+Shift+C` | Switch a Claude session between Chat and Terminal view, when [the chat view](Settings-Reference#header--panels) applies to it. | `Ctrl+W` is not a Codeman shortcut: it goes to the terminal, where shells and agent CLIs use it to delete the previous word. **Close Session** has no key by default; close a session @@ -89,9 +90,20 @@ The terminal sees keystrokes before the app does. Any chord the app claims has t swallowed at the terminal layer, or xterm writes the control byte into the session as well as triggering the action. A chord **you** rebind an action to is kept out of the terminal too, so rebinding Previous Session to `Alt+J` switches the session and sends nothing to the -CLI. The built-in defaults are deliberately not held back this way: `Ctrl+L` clears the -screen and also reaches the CLI, which redraws on it. Binding an action back onto its own -default behaves like the default. +CLI. Several built-in defaults are held back too, each by a check of its own: + +- the tab switches (`Alt+1` to `Alt+9`, `Alt+[` and `Alt+]`) and the session finder + (`Ctrl+K`, `Alt+K`); +- `Alt+B`, while the sidebar layout is on; +- `Alt+Shift+C`, while the active session can show the chat view; +- Copy Selection, whose `Ctrl+Shift+C` never reaches the CLI and whose `Ctrl+C` does not + while text is selected; +- the tile grid chords. + +None of those chords types anything into the CLI when it acts as its shortcut; `Ctrl+C` +with nothing selected is the interrupt and reaches the CLI. The other defaults still +reach it: `Ctrl+L` clears the screen and also reaches the CLI, which redraws on it. +Binding an action back onto its own default behaves like the default. `Alt+1` through `Alt+9` are matched on **physical key position** rather than the character produced, so macOS Option layouts that produce `¡™£` still switch tabs. diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 5bfd53a2..18f9afd5 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -113,7 +113,21 @@ images it produced. Claude sessions, local and remote (SSH). Nothing is read unt stores those diffs (secrets included) under `~/.codeman/edit-history/`; see [Working With Files](Working-With-Files#edit-history). -Most default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear. +Under **Panels**, **Open Claude sessions in Chat view** (per device, off by default, never on +phones) picks the view a Claude session opens in. The chat view draws the session's conversation +as text, over the terminal. To type, switch to the Terminal view. The terminal keeps running underneath, so switching +views never resizes it. The chat view applies to local and Docker Claude sessions in the main +view. Remote (SSH) and adopted sessions keep the terminal, and so do the tiles of the tile grid +and the second pane of a split. Each session remembers its own choice in this browser: press +`Alt+Shift+C`, or use the Chat / Terminal switch at the terminal's top right, to change it. +Another browser or device opens the same session in its own default until you choose there too. +This setting decides only where a session with no choice of its own starts. + +**Show the Chat / Terminal switch** (per device, on by default, never on phones) shows that switch +at the top right of a Claude session. Turn it off to keep the switch from covering the +terminal's corner. Each session keeps the view it had, and `Alt+Shift+C` still switches views. + +Most header chips default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear. **Header Stats Style** picks how the system stats and plan usage are drawn: *Compact* (default; two pills with a ring beside every value), *Tiles* (label over value with a bar underneath) or *As before* (the bars and the `5H · 7D` chip). Desktop only, per device. New header controls never appear on phones. Split is desktop-only regardless of this diff --git a/src/utils/index.ts b/src/utils/index.ts index 245b6be1..2cc93f3c 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -9,6 +9,7 @@ export { BufferAccumulator } from './buffer-accumulator.js'; export { CleanupManager } from './cleanup-manager.js'; export { Debouncer, KeyedDebouncer } from './debouncer.js'; +export { KeyedThrottle } from './keyed-throttle.js'; export { startEventLoopMonitor } from './event-loop-monitor.js'; export type { EventLoopMonitorHandle } from './event-loop-monitor.js'; export { StaleExpirationMap } from './stale-expiration-map.js'; diff --git a/src/utils/keyed-throttle.ts b/src/utils/keyed-throttle.ts new file mode 100644 index 00000000..74dca34c --- /dev/null +++ b/src/utils/keyed-throttle.ts @@ -0,0 +1,65 @@ +/** + * @fileoverview Per-key throttle: at most one send per key per interval, and the last call in a + * burst is never lost. + * + * The first call for a key in a quiet period sends at once. A call inside the interval after a + * send schedules one trailing send at the interval's end, and later calls collapse into it while + * it is pending. The trailing send runs the newest `send` it was given. Timers are unref'd, so a + * pending send never holds the process open. Its method names match KeyedDebouncer's + * (debouncer.ts): `cancelKey()` forgets one key, and `dispose()` forgets them all, which is how + * it integrates with CleanupManager. + * + * @module utils/keyed-throttle + */ + +interface ThrottleState { + lastAt: number; + timer: NodeJS.Timeout | null; + send: () => void; +} + +export class KeyedThrottle { + private readonly state = new Map(); + + constructor(private readonly intervalMs: number) {} + + /** Send for `key` now if its interval has passed, else once at the interval's end. */ + fire(key: K, send: () => void): void { + let entry = this.state.get(key); + if (!entry) { + entry = { lastAt: 0, timer: null, send }; + this.state.set(key, entry); + } + entry.send = send; + // A trailing send is already scheduled, and it covers this call. + if (entry.timer) return; + const wait = entry.lastAt + this.intervalMs - Date.now(); + if (wait <= 0) { + entry.lastAt = Date.now(); + send(); + return; + } + const scheduled = entry; + scheduled.timer = setTimeout(() => { + scheduled.timer = null; + scheduled.lastAt = Date.now(); + scheduled.send(); + }, wait); + scheduled.timer.unref?.(); + } + + /** Forget `key`, dropping its pending trailing send. */ + cancelKey(key: K): void { + const entry = this.state.get(key); + if (entry?.timer) clearTimeout(entry.timer); + this.state.delete(key); + } + + /** Forget every key, dropping every pending send. The CleanupManager integration point. */ + dispose(): void { + for (const entry of this.state.values()) { + if (entry.timer) clearTimeout(entry.timer); + } + this.state.clear(); + } +} diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 5260666a..83088fd3 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -14,6 +14,8 @@ **Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default ON on desktop and OFF on handhelds and touch-primary tablets (primary pointer coarse, `getDefaultSettings()`; a touchscreen laptop keeps ON), desktop-only at 1180px, per-device; tile-grid.js, design `docs/tile-grid-plan.md`): 1 to 6 live sessions side by side (the cap is ONE constant, `TILE_GRID_MAX` in constants.js, owner decision; the layout table still covers 7 to 9, unreachable), each a `TerminalTile` with a header (state dot, harness logo, name, model, menu, zoom, ×; no +, owner decision), laid out by count (`CodemanTileGrid`, constants.js) with draggable column/row dividers, zoom (tmux-style), an Attach overlay, and per-browser persistence (`codeman:tile-grid`, localStorage only: cells with `null` holes, `count`, focus, user zoom, divider fractions, never content; written on every change, kept by EVERY close, restored INSIDE `handleInit` in place of the single-view select, so the main terminal never loads on that page load). While the grid is open the main terminal is PARKED: `activeSessionId` is the focused tile's session, and every main-terminal path that would write, fetch, resize or reconnect stands aside through `_tilesOwnTerminal()` (the WebGL long-task observer included). ⚠️ Every capture a tile fetches (initial, reconnect refresh, `{t:'r'}`, history pull) goes through ONE `TileLoadQueue` (concurrency 1, a deadline covering the body), because each is a synchronous tmux call on the server. ⚠️ Only a USER-initiated pick of a non-tiled session (or `leaveTiles`, a followed link) leaves the grid; an `auto` selection never collapses it, and every app-driven fallback (close, delete, restore) picks a tile. A caller of `closeTileGrid({ reselect: false })` must null `activeSessionId` before any `_cleanupPreviousSession`, or the parked terminal's stale content is saved as a snapshot. ⚠️ The grid and the split are never open together. ⚠️ Tile chords go through `tileShortcutFor` and are swallowed in every xterm key handler BEFORE the Shift+Enter gate; the toggle follows `showTileGridButton` (owner decision: OFF makes the chord inert, it passes through like any unbound key). ⚠️ The Tiles button's click and Ctrl+Shift+G are ONE function, `toggleTileGrid` (owner decision): they open the grid AT ONCE on `tileGridOpenSet` (constants.js): the stored grid EXACTLY as the user left it (owner decision 11: `restoreTileGridCells`, never filled to the count nor trimmed to the window; a cell whose session is gone since is filled from the ranking, a hole the user made stays), else an open split's two, else the open sessions as `rankTileSessions` orders them (working first, keyed off `lastSubmitAt` ONLY, then needing input, then most recent; `_mobileOverviewState`'s states), the active one focused, filled to the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) by `tileGridSetForCount`, never a menu. ⚠️ `removeTile(..., { gone: true })` (a session deleted, popped out or refused) keeps the stored `count` so the next open refills that cell; a removal by hand lowers it. Right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. Such a tile connects before its pane exists, the server drops that resize and spawns at 120x40, and Run's own resize measures the parked terminal (nothing), so the chrome refresh calls `tile.paneStarted()` when the session's pid appears or changes. ⚠️ An agent that exited in a live pane (`paneExit`) cannot be re-attached in place (both attach routes refuse while the pane's tmux client runs, and say so in a 200 envelope): its tile shows the exit and points at Close session. ⚠️ Each header (a tile's, both split panes': Pane A gets one only while the split is open, fitted through `sendResize`/`syncTerminalGeometry`) names the harness with PR #532's `run-mode-dot ` logo (the id is data, never a branch) and `SessionState.displayModel` (src/session-display-model.ts: custom endpoint, else the newest report from the CLI itself, i.e. claude's statusline or a footer read with `capabilities.modelDetect`, else what its config pins via the named `modelDetect.configResolver` (dsh-TUI's route, `src/deepseek-route-config.ts`: read-only, bounded, nothing on doubt), else the launch model, else nothing), painted by ONE diffing `_paintSessionHarness`; the model is untrusted text (`textContent`, `data-i18n-skip`). ⚠️ zh-CN: every string the grid shows has its own `ZH_CN` entry or `translateDynamic` pattern in i18n.js (`test/tile-grid-i18n.test.ts` harvests them from the real code; add the entry with any new string), and a refresh compares with the last ENGLISH value it set, never the DOM, which holds the translation. ⚠️ **Detach Tiles** (`tileDetachEnabled`, per-device, default OFF): a header let go outside the window pops the tile out (`detachSession` with a placement), dropped on ANOTHER Codeman window's tiles it moves there, and a pop-out's title drags back onto any grid. A foreign tile docks ONLY through `_dockForeignTile` (the target's own drop, then `tile-adopted` on the window channel), and only the window it was dragged FROM lets go of its copy (never a last-tile fallback onto that session: two windows sizing one PTY garble it). The gesture overlay moves tiles only through tile-grid.js's helpers (`tileDropTargetAt`/`dropOnTileTarget`/`detachTileAtPoint`). → [architecture-invariants#tile-grid](../../docs/architecture-invariants.md#tile-grid) +**Chat view** (`chat-view.js`, per-device `chatViewDefault`, default OFF, never on phones; design in [`docs/chat-view-plan.md`](../../docs/chat-view-plan.md)): a local or Docker Claude session in the main view can show its conversation, read from the transcript, as text; to type, the user switches to the Terminal view. `chatViewEligible()` takes the modes whose CLI declares `transcript: 'claude-jsonl'` (`window.__codemanChatViewModes`, never a mode id) and refuses a remote or an adopted session and a phone. The per-device `showChatViewSwitch` (an ABSENT key means ON, read as `!== false`) hides only the Chat / Terminal switch; the view and Alt+Shift+C keep working. ⚠️ The terminal stays mounted, attached and sized under the chat layer, so switching views never resizes the PTY. Focus that lands on the hidden terminal moves to the conversation, and `body.chat-view-showing` hides the keyboard accessory bar and, on touch devices, the CJK input field while Chat shows, because both write into the pane. While the tile grid owns the terminal, the chat view is hidden whatever the session's choice (`_tilesOwnTerminal()`, synced from tile-grid.js). A pending `permission_prompt` or `elicitation_dialog` hook shows a notice whose button switches to the terminal. Codeman's keep-alive turn shows no status line. i18n.js skips the `data-i18n-skip` conversation, so the strings drawn there go through `_chatViewT()`. Tests: `test/chat-view.test.ts`, `test/chat-view-i18n.test.ts`. + **Terminal touch gestures: link taps and text selection**: on touch devices xterm's linkifier and SelectionService never see the gesture, so both are driven explicitly (terminal-ui.js). ⚠️ A tap activates the link under it through the SAME provider as the hover linkifier (`_terminalLinkAtPoint`), synchronously inside `touchend` (keeps the user gesture `window.open` needs) and BEFORE any mouse report; the caret's logical line (`_tapIsOnCaretLine`) and TUI-owned rows (`_isActionableMobileTerminalTap`) keep their meaning. ⚠️ Gate on the caret line, never on tap intent (a shell calls every tap `'input'`). ⚠️ Long-press selects via xterm's public `select()`; keep the three guards: suppress the compat mouse pair after `touchend`, the bounded focus guard + `contextmenu` suppression for the platform long-press, and no closing `terminal.focus()` on phones. ⚠️ A sideways drag belongs to the session swipe (`SwipeHandler`, mobile-handlers.js): the touch handler locks the dominant axis on the first travel past the tap slop (`panAxis`: `y` scrolls, `x` pans a terminal wider than its box, `swipe` otherwise) and publishes it as `app._terminalGestureAxis`; a `swipe` drag neither scrolls nor ends as a tap on the session being left until it passes the swipe's own vertical drift limit (`SwipeHandler.maxVerticalDrift`), where it is handed back to the scroll as `y` (a scroll that opens on a thumb arc), and the swipe stands aside for `x`/`y`, a touch selection, a second finger and surfaces with controls of their own (`IGNORE_SELECTOR`; the phone overview and welcome screen are deliberately not listed). A swipe is 80 px within 500 ms with at most 50 px of vertical drift at any point; a touch starting outside the terminal (the home screen) resets the published axis, and a lift the terminal consumed (`defaultPrevented`, its selection gesture) is never a swipe (`test/session-swipe-gesture.test.ts`). Tests: `test/terminal-touch-tap.test.ts`. → [architecture-invariants#terminal-touch-gestures-link-taps-and-text-selection](../../docs/architecture-invariants.md#terminal-touch-gestures-link-taps-and-text-selection) **Auto Copy (copy-on-select)** (`autoCopySelection`, per-device, default OFF): a finished terminal selection lands on the clipboard with no keystroke. ⚠️ Copy at the END of a gesture, never in `onSelectionChange` (per-cell); it only arms `_autoCopyPending` and a document-level `mouseup` flushes. ⚠️ The flush must be SYNCHRONOUS in the handler (both clipboard paths need user activation); never defer it to a timer. ⚠️ Touch needs its own calls from `_endTouchSelectionGesture()`/`_selectTouchSelectionLine()` (no mouseup arrives). ⚠️ Unlike `copyTerminalSelection()`, never clear the selection or focus the terminal; restore prior focus. Guards are pure in `decideAutoCopy()` (constants.js, 1M-char cap, refused not truncated). Tests: `test/terminal-auto-copy.test.ts`. → [architecture-invariants#auto-copy-copy-on-select](../../docs/architecture-invariants.md#auto-copy-copy-on-select) @@ -56,7 +58,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L **Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry) -**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema. +**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare**, among others, `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, `extendedKeyboardBar`, `chatViewDefault`, or `showChatViewSwitch`, so sending one of those is a validation error. Others (`showResponseViewer`, `showPlanUsageLimits`, `language`, and many `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema. **Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `
` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden ``, + { runScripts: 'outside-only', pretendToBeVisual: true, url: 'http://localhost/' } + ); + const win = dom.window as unknown as Window & { eval: (s: string) => unknown; [k: string]: unknown }; + win.__codemanChatViewModes = ['claude']; + // The window has a Date of its own. Tie it to the test's clock, so vi.setSystemTime reaches + // the module's elapsed times. + (win.Date as DateConstructor).now = () => Date.now(); + win.eval('class CodemanApp {}; window.CodemanApp = CodemanApp;'); + win.eval(read('constants.js')); + win.eval(read('chat-view.js')); + const proto = (win.CodemanApp as { prototype: object }).prototype; + + const pages = [...(opts.messages ?? [[]])]; + const app = Object.assign(Object.create(proto), { + activeSessionId: 's1', + sessions: new Map>([ + ['s1', { id: 's1', mode: 'claude', status: 'idle' }], + ['s2', { id: 's2', mode: 'claude', status: 'idle', remote: { hostId: 'h' } }], + ['s3', { id: 's3', mode: 'claude', status: 'idle', adopt: { target: 'x' } }], + ['s4', { id: 's4', mode: 'codex', status: 'idle' }], + ['s5', { id: 's5', mode: 'claude', status: 'idle', docker: { caseName: 'box' } }], + ]), + pendingHooks: new Map>(), + loadAppSettingsFromStorage: () => ({}), + _getResponseViewerAgentLabel: () => 'Claude', + _buildResponseViewerMessage: (text: string, role: string, _label: string, meta?: { continuation?: boolean }) => { + const div = win.document.createElement('div'); + div.className = `rv-message rv-msg-${role}`; + if (meta?.continuation) div.classList.add('rv-msg-cont'); + const body = win.document.createElement('div'); + body.className = 'rv-text'; + body.textContent = text; + div.appendChild(body); + return div; + }, + _bindResponseViewerInteractions: () => {}, + _api: vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ success: true }) })), + _apiJson: vi.fn(async () => ({ messages: pages.length > 1 ? pages.shift() : pages[0] })), + showToast: vi.fn(), + _sendInputAsync: vi.fn(), + terminal: { focus: vi.fn() }, + }) as ChatApp; + return { dom, win, app }; +} + +const settle = () => new Promise((r) => setTimeout(r, 0)); + +describe('chat view module', () => { + it('is offered only for sessions whose run mode has a Claude transcript, local or Docker', () => { + const { app } = loadModule(); + expect(app.chatViewEligible('s1')).toBe(true); + expect(app.chatViewEligible('s5')).toBe(true); // Docker + expect(app.chatViewEligible('s2')).toBe(false); // remote + expect(app.chatViewEligible('s3')).toBe(false); // adopted + expect(app.chatViewEligible('s4')).toBe(false); // not in __codemanChatViewModes + expect(app.chatViewEligible('missing')).toBe(false); + }); + + it('is not offered on a phone, even one turned to landscape', () => { + const { win, app } = loadModule(); + // A phone in landscape is wider than the phone breakpoint, so its width says "desktop". + win.MobileDetection = { isHandheldDevice: () => true, getDeviceType: () => 'desktop' }; + expect(app.chatViewEligible('s1')).toBe(false); + win.MobileDetection = { isHandheldDevice: () => false, getDeviceType: () => 'desktop' }; + expect(app.chatViewEligible('s1')).toBe(true); + }); + + it('opens in Chat when the device setting says so, unless the session remembers Terminal', () => { + const { win, app } = loadModule(); + app.loadAppSettingsFromStorage = () => ({ chatViewDefault: true }); + expect(app.chatViewModeFor('s1')).toBe('chat'); + win.localStorage.setItem('codeman:chatViewModes', JSON.stringify({ s1: 'terminal' })); + expect(app.chatViewModeFor('s1')).toBe('terminal'); + }); + + it('marks the body while Chat shows, so the keyboard accessory bar stays hidden', () => { + const { win, app } = loadModule(); + app.onChatViewActiveSession('s1'); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(false); + app.setChatViewMode('s1', 'chat'); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(true); + app.setChatViewMode('s1', 'terminal'); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(false); + }); + + it('moves a focus that lands in the hidden terminal to the conversation', () => { + const { win, app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + const inner = win.document.createElement('textarea'); + win.document.getElementById('terminalContainer')!.appendChild(inner); + inner.focus(); + expect(win.document.activeElement).toBe(app._chatView.scroller); + }); + + it('moves a focus that lands on the CJK input field to the conversation', () => { + // With CJK input on, terminal.focus() lands on #cjkInput, outside #terminalContainer. + const { win, app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + (win.document.getElementById('cjkInput') as HTMLTextAreaElement).focus(); + expect(win.document.activeElement).toBe(app._chatView.scroller); + }); + + it('keeps a dropped file from opening in the browser while Chat shows', () => { + const { win, app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + // The Chat / Terminal switch is a sibling of the chat view root, so it needs the guard too. + for (const target of [app._chatView.root, app._chatView.toggle]) { + for (const type of ['dragover', 'drop']) { + const ev = new win.Event(type, { bubbles: true, cancelable: true }); + target.dispatchEvent(ev); + expect(ev.defaultPrevented).toBe(true); + } + } + }); + + it('hides the chat view, its switch and the body mark when the home screen shows', () => { + const { win, app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + expect(app._chatView.root.hidden).toBe(false); + app._chatViewHide(); + expect(app._chatView.root.hidden).toBe(true); + expect(app._chatView.toggle.hidden).toBe(true); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(false); + }); + + it('starts in Terminal, covers the terminal once Chat is picked, and remembers the choice', async () => { + const { win, app } = loadModule({ messages: [[{ role: 'user', text: 'Hi', turn: 1 }]] }); + app.onChatViewActiveSession('s1'); + expect(app.chatViewModeFor('s1')).toBe('terminal'); + expect(app._chatView.toggle.hidden).toBe(false); + expect(app._chatView.root.hidden).toBe(true); + + app.setChatViewMode('s1', 'chat'); + await settle(); + expect(app._chatView.root.hidden).toBe(false); + // The terminal stays in the DOM underneath: nothing is removed or resized. + expect(win.document.getElementById('terminalContainer')).not.toBeNull(); + expect(win.document.querySelector('.terminal-wrap')!.classList.contains('chat-view-active')).toBe(true); + expect(app._apiJson).toHaveBeenCalledWith('/api/sessions/s1/last-response?context=full'); + expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' }); + + // The per-session turn state goes with the session too. + const state = app as unknown as Record | Set>; + state._chatViewTurnStarts = new Map([['s1', 1]]); + state._chatViewIdleSeen = new Set(['s1']); + state._chatViewKeepAliveTurns = new Set(['s1']); + + // A detach sends the same event as a delete, so the view choice outlives it. + app._chatViewForget('s1'); + expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' }); + for (const key of ['_chatViewTurnStarts', '_chatViewIdleSeen', '_chatViewKeepAliveTurns']) { + expect(state[key].has('s1')).toBe(false); + } + }); + + it("drops the view choices of sessions that are not in the init's session list", () => { + const { app, win } = loadModule(); + win.localStorage.setItem('codeman:chatViewModes', JSON.stringify({ s1: 'chat', gone: 'terminal' })); + app.setChatViewMode('s1', 'chat'); + app.setChatViewMode('gone', 'terminal'); + app._chatViewPruneModes(new Set(['s1', 's2'])); + expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' }); + win.localStorage.clear(); + expect(app.chatViewModeFor('gone')).toBe('terminal'); + expect(app.chatViewModeFor('s1')).toBe('chat'); + }); + + it('prunes the view choices from handleInit in app.js', () => { + const appJs = read('app.js'); + const start = appJs.indexOf(' handleInit(data) {'); + const init = appJs.slice(start, appJs.indexOf('\n }\n', start)); + expect(init).toContain('this._chatViewPruneModes?.(new Set(data.sessions.map((s) => s.id)));'); + }); + + it('shows the Chat / Terminal switch when the device has no showChatViewSwitch setting', () => { + const { app } = loadModule(); + app.loadAppSettingsFromStorage = () => ({}); + app.onChatViewActiveSession('s1'); + expect(app._chatView.toggle.hidden).toBe(false); + app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: true }); + app._chatViewSync(); + expect(app._chatView.toggle.hidden).toBe(false); + }); + + it('hides the switch when the setting is off, while Alt+Shift+C still switches views', async () => { + const { win, app } = loadModule({ messages: [[{ role: 'user', text: 'Hi', turn: 1 }]] }); + app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: false }); + app.onChatViewActiveSession('s1'); + expect(app._chatView.toggle.hidden).toBe(true); + + app.toggleChatView(); + await settle(); + expect(app.chatViewModeFor('s1')).toBe('chat'); + expect(app._chatView.root.hidden).toBe(false); + expect(app._chatView.toggle.hidden).toBe(true); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(true); + + app.toggleChatView(); + expect(app.chatViewModeFor('s1')).toBe('terminal'); + expect(app._chatView.root.hidden).toBe(true); + + // A settings save re-syncs: turning the setting back on shows the switch again. + app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: true }); + app._chatViewSync(); + expect(app._chatView.toggle.hidden).toBe(false); + }); + + it('hides the toggle for a session that cannot show the chat view', () => { + const { app } = loadModule(); + app.onChatViewActiveSession('s1'); + app.activeSessionId = 's4'; + app.onChatViewActiveSession('s4'); + expect(app._chatView.toggle.hidden).toBe(true); + expect(app._chatView.root.hidden).toBe(true); + }); + + it('draws the conversation without keep-warm turns, folds long prompts and appends new messages', async () => { + const long = Array.from({ length: 20 }, (_, i) => `log ${i}`).join('\n'); + const first: Msg[] = [ + { role: 'user', text: long, turn: 1 }, + { role: 'assistant', text: 'Looked at it.', turn: 1 }, + { role: 'assistant', text: 'Checked the tests too.', turn: 1 }, + { role: 'user', text: 'keep-warm nudge', turn: 2, keepAlive: true }, + { role: 'assistant', text: 'keep-warm reply', turn: 2, keepAlive: true }, + ]; + const second: Msg[] = [...first, { role: 'user', text: 'Next', turn: 3 }]; + const { app } = loadModule({ messages: [first, second] }); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + await settle(); + + const nodes = Array.from(app._chatView.thread.children) as HTMLElement[]; + expect(nodes).toHaveLength(3); + expect(nodes[0].querySelector('.chat-view-show-all')!.textContent).toBe('Show all (20 lines)'); + expect(nodes[0].textContent).not.toContain('log 10'); + expect(app._chatView.thread.textContent).not.toContain('keep-warm'); + // One badge per speaker per turn: Claude's second message in the turn continues the first. + expect(nodes[1].classList.contains('rv-msg-cont')).toBe(false); + expect(nodes[2].classList.contains('rv-msg-cont')).toBe(true); + + await app._chatViewFetch(); + const after = Array.from(app._chatView.thread.children); + expect(after).toHaveLength(4); + expect(after[0]).toBe(nodes[0]); // appended, not redrawn + + (nodes[0].querySelector('.chat-view-show-all') as HTMLButtonElement).click(); + expect(app._chatView.thread.children[0].textContent).toContain('log 19'); + }); + + it('puts the Working line right under the last message, inside the scrolling list', () => { + const { app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + const view = app._chatView as unknown as { status: HTMLElement; thread: HTMLElement; scroller: HTMLElement }; + expect(view.status.parentElement).toBe(view.scroller); + expect(view.thread.nextElementSibling).toBe(view.status); + }); + + it('counts a turn already running when the page loaded from the last Enter, not from the page load', () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-11-24T12:00:00Z')); + const { app } = loadModule(); + app.sessions.set('s1', { + id: 's1', + mode: 'claude', + status: 'busy', + workingDir: '/work', + lastSubmitAt: Date.now() - 73_000, + }); + app.setChatViewMode('s1', 'chat'); + const a = app as unknown as { + onChatViewTurnEvent: (id: string, idle: boolean) => void; + _chatView: { statusText: HTMLElement }; + }; + // A working event for a session this page never saw idle says nothing about the turn's start. + a.onChatViewTurnEvent('s1', false); + app.onChatViewActiveSession('s1'); + expect(a._chatView.statusText.textContent).toBe('Working · 1m 13s'); + // Stop the status line's ticking before the real clock comes back. + app.setChatViewMode('s1', 'terminal'); + vi.useRealTimers(); + }); + + it('counts a turn this page saw start from its session:working event', () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-11-24T12:00:00Z')); + try { + const { app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + app.onChatViewTurnEvent('s1', true); + vi.setSystemTime(Date.now() + 30_000); + const session = app.sessions.get('s1')!; + session.status = 'busy'; + // An older Enter, which must not be the start of the turn the page saw begin. + session.lastSubmitAt = Date.now() - 60_000; + app.onChatViewTurnEvent('s1', false); + vi.setSystemTime(Date.now() + 5_000); + app._chatViewRenderStatus(); + expect(app._chatView.statusText.textContent).toBe('Working · 5s'); + app.setChatViewMode('s1', 'terminal'); + } finally { + vi.useRealTimers(); + } + }); + + it("shows no status line during Codeman's keep-alive turn", () => { + const { app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + const session = app.sessions.get('s1')!; + session.status = 'busy'; + app.onChatViewTurnEvent('s1', false, true); + expect(app._chatView.status.hidden).toBe(true); + + session.status = 'idle'; + app.onChatViewTurnEvent('s1', true, true); + // A real turn shows it again. + session.status = 'busy'; + app.onChatViewTurnEvent('s1', false); + expect(app._chatView.status.hidden).toBe(false); + session.status = 'idle'; + app.onChatViewTurnEvent('s1', true); + }); + + /** A Chat session that is busy, on a device that is touch or not, with app.js's focus rule. */ + function loadForFocus(touch: boolean) { + const loaded = loadModule(); + const { win, app } = loaded; + // The rule the app applies to a tab switch (app.js), run as written. + const appJs = read('app.js'); + const method = appJs.match(/\n {2}_shouldFocusTerminalForTabSwitch\(\) \{[\s\S]*?\n {2}\}\n/)![0]; + Object.assign(app, win.eval(`({${method}})`) as object); + win.MobileDetection = { + isHandheldDevice: () => false, + getDeviceType: () => (touch ? 'tablet' : 'desktop'), + isTouchDevice: () => touch, + }; + win.KeyboardHandler = { keyboardVisible: false }; + app.sessions.get('s1')!.status = 'busy'; + app.setChatViewMode('s1', 'terminal'); + return loaded; + } + const nextFrame = (win: Window) => new Promise((r) => win.requestAnimationFrame(() => r())); + + it('follows the tab-switch focus rule on a touch device: no focus on a switch to Chat', async () => { + const { win, app } = loadForFocus(true); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + await nextFrame(win); + expect(win.document.activeElement).not.toBe(app._chatView.scroller); + }); + + it('moves a focus left in the terminal to the conversation on a switch to Chat, on a touch device', async () => { + const { win, app } = loadForFocus(true); + const inner = win.document.createElement('textarea'); + win.document.getElementById('terminalContainer')!.appendChild(inner); + inner.focus(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + await nextFrame(win); + expect(win.document.activeElement).toBe(app._chatView.scroller); + }); + + it('moves a focus left on the CJK input field to the conversation on a switch to Chat, on a touch device', async () => { + const { win, app } = loadForFocus(true); + (win.document.getElementById('cjkInput') as HTMLTextAreaElement).focus(); + expect(win.document.activeElement?.id).toBe('cjkInput'); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + await nextFrame(win); + expect(win.document.activeElement).toBe(app._chatView.scroller); + }); + + it('focuses the conversation on a desktop, on a switch to Chat', async () => { + const { win, app } = loadForFocus(false); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + await nextFrame(win); + expect(win.document.activeElement).toBe(app._chatView.scroller); + }); + + it('unfolds a long prompt in place, with the badge it was drawn with', () => { + const { win, app } = loadModule(); + const a = app as unknown as { + _buildResponseViewerMessage: (t: string, r: string, l: string, m?: { continuation?: boolean }) => HTMLElement; + _chatViewBuildMessage: (m: Msg, label: string, continuation: boolean) => HTMLElement; + }; + // As the real builder does: a prompt that is not a continuation carries its "You" badge. + const build = a._buildResponseViewerMessage; + a._buildResponseViewerMessage = (text, role, label, meta) => { + const el = build(text, role, label, meta); + if (!meta?.continuation) { + const badge = win.document.createElement('div'); + badge.className = 'rv-role rv-role-user'; + el.prepend(badge); + } + return el; + }; + const long = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n'); + const el = a._chatViewBuildMessage({ role: 'user', text: long, turn: 1 }, 'Claude', true); + expect(el.classList.contains('rv-msg-cont')).toBe(true); + (el.querySelector('.chat-view-show-all') as HTMLButtonElement).click(); + expect(el.querySelector(':scope > .rv-role')).toBeNull(); + expect(el.classList.contains('rv-msg-cont')).toBe(true); + expect(el.querySelector('.chat-view-show-all')).toBeNull(); + expect(el.textContent).toContain('line 29'); + }); + + it('shows the waiting notice while a permission prompt or question is pending', () => { + const { app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + expect(app._chatView.dialog.hidden).toBe(true); + app.pendingHooks.set('s1', new Set(['elicitation_dialog'])); + app.onChatViewHooksChanged('s1'); + expect(app._chatView.dialog.hidden).toBe(false); + app.pendingHooks.set('s1', new Set(['idle_prompt'])); + app.onChatViewHooksChanged('s1'); + expect(app._chatView.dialog.hidden).toBe(true); + // Claude's AskUserQuestion, plan approval and permission dialogs arrive as permission_prompt. + app.pendingHooks.set('s1', new Set(['permission_prompt'])); + app.onChatViewHooksChanged('s1'); + expect(app._chatView.dialog.hidden).toBe(false); + }); + + it('re-reads on transcript:update only for its own session and only while showing', () => { + const { app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + const reload = vi.spyOn(app, '_chatViewReload').mockImplementation(() => {}); + app._onChatViewTranscriptUpdate({ sessionId: 's1' }); + expect(reload).toHaveBeenCalledTimes(1); + app._onChatViewTranscriptUpdate({ sessionId: 's2' }); + expect(reload).toHaveBeenCalledTimes(1); + app.setChatViewMode('s1', 'terminal'); + app._onChatViewTranscriptUpdate({ sessionId: 's1' }); + expect(reload).toHaveBeenCalledTimes(1); + }); + + it('reads nothing once hidden, even for a re-read armed while Chat showed', async () => { + vi.useFakeTimers(); + try { + const { app } = loadModule(); + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + await vi.advanceTimersByTimeAsync(0); + const reads = app._apiJson.mock.calls.length; + app._onChatViewTranscriptUpdate({ sessionId: 's1' }); + app.setChatViewMode('s1', 'terminal'); + await vi.advanceTimersByTimeAsync(300); + expect(app._apiJson.mock.calls.length).toBe(reads); + } finally { + vi.useRealTimers(); + } + }); + + /** A read of the conversation that stays pending until the test resolves it. */ + function deferredRead() { + let resolve!: (v: { messages: Msg[] }) => void; + const promise = new Promise<{ messages: Msg[] }>((r) => (resolve = r)); + return { promise, resolve }; + } + + it('reads once more when an update arrived while a read was in flight', async () => { + vi.useFakeTimers(); + try { + const { app } = loadModule(); + const first = deferredRead(); + app._apiJson.mockImplementationOnce(() => first.promise); + app.setChatViewMode('s1', 'chat'); + expect(app._apiJson).toHaveBeenCalledTimes(1); + + // The update's debounced read finds the first one still in flight. + app._onChatViewTranscriptUpdate({ sessionId: 's1' }); + await vi.advanceTimersByTimeAsync(300); + expect(app._apiJson).toHaveBeenCalledTimes(1); + + first.resolve({ messages: [{ role: 'user', text: 'Hi', turn: 1 }] }); + await vi.advanceTimersByTimeAsync(300); + expect(app._apiJson).toHaveBeenCalledTimes(2); + app.setChatViewMode('s1', 'terminal'); + } finally { + vi.useRealTimers(); + } + }); + + it('drops a read that finishes after the user switched to another session', async () => { + vi.useFakeTimers(); + try { + const { app } = loadModule(); + const s1Read = deferredRead(); + app._apiJson.mockImplementationOnce(() => s1Read.promise); + app.setChatViewMode('s1', 'chat'); + app.setChatViewMode('s5', 'chat'); + app.activeSessionId = 's5'; + app.onChatViewActiveSession('s5'); + + s1Read.resolve({ messages: [{ role: 'assistant', text: 'Answer for s1 only', turn: 1 }] }); + // Checked before the debounced read for s5 runs, which would redraw the thread anyway. + await vi.advanceTimersByTimeAsync(0); + expect(app._chatView.thread.textContent).not.toContain('Answer for s1 only'); + await vi.advanceTimersByTimeAsync(300); + expect(app._chatView.thread.textContent).not.toContain('Answer for s1 only'); + app.setChatViewMode('s5', 'terminal'); + } finally { + vi.useRealTimers(); + } + }); + + describe('the Alt+Shift+C chord', () => { + const chord = { altKey: true, shiftKey: true, key: 'C', code: 'KeyC' }; + + /** The module with app.js's shortcut matcher, run as written, and a registry holding the chord. */ + function loadForChord(disabled = false) { + const loaded = loadModule(); + const { win, app } = loaded; + const method = read('app.js').match(/\n {2}matchesShortcutEvent\(e, shortcut\) \{[\s\S]*?\n {2}\}\n/)![0]; + Object.assign(app, win.eval(`({${method}})`) as object, { + getShortcutRegistry: () => [ + { id: 'toggle-chat-view', bindings: [{ modifiers: ['alt', 'shift'], key: 'C', code: 'KeyC' }], disabled }, + ], + }); + return loaded; + } + + it('applies to an active session that can show the chat view', () => { + const { app } = loadForChord(); + expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(true); + }); + + it('reaches the terminal in a session that cannot show the chat view', () => { + const { app } = loadForChord(); + app.sessions.set('s6', { id: 's6', mode: 'shell', status: 'idle' }); + app.activeSessionId = 's6'; + expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false); + }); + + it('reaches the tiles while the tile grid owns the terminal', () => { + const { app } = loadForChord(); + (app as unknown as { _tilesOwnTerminal: () => boolean })._tilesOwnTerminal = () => true; + expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false); + }); + + it('needs a modifier', () => { + const { app } = loadForChord(); + expect(app.shouldToggleChatViewFromShortcut({ key: 'C', code: 'KeyC' })).toBe(false); + }); + + it('does nothing when the user disabled the shortcut', () => { + const { app } = loadForChord(true); + expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false); + }); + }); + + it('stays hidden while the tile grid owns the terminal, so the keyboard bar shows for the tiles', () => { + const { win, app } = loadModule(); + const a = app as unknown as { + _tileGrid?: { open: boolean }; + _tilesOwnTerminal: () => boolean; + _chatViewSync: () => void; + }; + a._tilesOwnTerminal = () => !!a._tileGrid?.open; + app.setChatViewMode('s1', 'chat'); + app.onChatViewActiveSession('s1'); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(true); + + a._tileGrid = { open: true }; + a._chatViewSync(); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(false); + expect(app._chatView.root.hidden).toBe(true); + + a._tileGrid = { open: false }; + a._chatViewSync(); + expect(win.document.body.classList.contains('chat-view-showing')).toBe(true); + expect(app._chatView.root.hidden).toBe(false); + }); +}); + +describe('chat view wiring', () => { + it("swallows the toggle chord in the xterm key handler and in Pane B's", () => { + const terminalUi = read('terminal-ui.js'); + expect(terminalUi).toMatch(/shouldToggleChatViewFromShortcut\?\.\(ev\)\)\s*\{\s*return false;/); + const tile = read('terminal-tile.js'); + expect(tile).toContain( + "if (ev.type === 'keydown' && global.app?.shouldToggleChatViewFromShortcut?.(ev)) return false;" + ); + }); + + it('re-reads the conversation after an SSE reconnect onto the session on screen', () => { + const app = read('app.js'); + expect(app).toMatch( + /void this\._onSessionNeedsRefresh\(\{ id: restoreId \}\);[\s\S]{0,300}?this\._chatViewReload\?\.\(\{ immediate: true \}\);/ + ); + }); + + it('hides the chat view when the home screen shows', () => { + const terminalUi = read('terminal-ui.js'); + expect(terminalUi).toMatch(/\n {2}showWelcome\(\) \{\n {4}this\._chatViewHide\?\.\(\);/); + }); + + it('keeps the chat view layers under the narrow-width sidebar drawer', () => { + // The drawer (z-index 12, mobile.css) is a sibling of .terminal-wrap: the chat view's 20 and 21 + // must stay inside the terminal area's own stacking context. + const css = read('styles.css'); + expect(css).toMatch(/\n\.terminal-wrap \{[^}]*isolation: isolate;[^}]*\}/); + }); + + it('binds Alt+Shift+C to the toggle in the shortcut registry', () => { + const app = read('app.js'); + expect(app).toMatch( + /id: 'toggle-chat-view',[\s\S]*?modifiers: \['alt', 'shift'\], key: 'C', code: 'KeyC'[\s\S]*?action: 'toggleChatView'/ + ); + expect(app).toContain('toggleChatView: () => this.toggleChatView?.()'); + }); + + it('keeps chatViewDefault per device and out of the server PUT', () => { + const settings = read('settings-ui.js'); + expect(settings).toMatch(/'showEditHistory', 'chatViewDefault',/); + expect(settings).toContain('chatViewDefault: _cvd,'); + const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8'); + expect(schemas).not.toContain('chatViewDefault'); + }); + + it('keeps showChatViewSwitch per device, out of the server PUT, and on when absent', () => { + const settings = read('settings-ui.js'); + expect(settings).toMatch(/'showEditHistory', 'chatViewDefault', 'showChatViewSwitch',/); + expect(settings).toContain('showChatViewSwitch: _scvs,'); + expect(settings).toContain( + "document.getElementById('appSettingsShowChatViewSwitch').checked = settings.showChatViewSwitch !== false;" + ); + const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8'); + expect(schemas).not.toContain('showChatViewSwitch'); + // A settings save re-syncs the chat view, so the switch follows the new value at once. + expect(settings).toMatch(/this\._chatViewSync\?\.\(\);/); + const html = read('index.html'); + expect(html).toContain('id="appSettingsShowChatViewSwitch"'); + }); + + it('passes the keep-alive flag of session:working and session:idle to the chat view', () => { + const app = read('app.js'); + expect(app).toContain('this.onChatViewTurnEvent?.(data.id, true, data.keepAlive);'); + expect(app).toContain('this.onChatViewTurnEvent?.(data.id, false, data.keepAlive);'); + }); + + it('hides the CJK input field on a touch device while Chat shows', () => { + // The field is fixed over the bottom of the chat view there, and its text goes into the pane. + const css = read('styles.css'); + expect(css).toMatch( + /\nbody\.chat-view-showing\.touch-device #cjkInput\.cjk-input-visible \{\s*display: none !important;\s*\}/ + ); + }); + + it("starts the chat layer and its switch below Pane A's split header", () => { + const css = read('styles.css'); + expect(css).toMatch(/\.terminal-pane-a-header ~ \.chat-view \{\s*top: 28px;\s*\}/); + expect(css).toMatch(/\.terminal-pane-a-header ~ \.chat-view-toggle \{\s*top: 36px;\s*\}/); + }); + + it('centres the empty notice over the Response Viewer paragraph margin', () => { + // The notice is a

directly inside .response-viewer-body, whose `> p` margin rule + // outranks `.chat-view-empty` alone and left it against the window's left edge. + const css = read('styles.css'); + expect(css).toMatch(/\.chat-view-scroll > \.chat-view-empty \{\s*margin-left: auto;\s*margin-right: auto;\s*\}/); + }); + + it('loads chat-view.js after local-model-ui.js', () => { + const html = read('index.html'); + expect(html.indexOf('src="chat-view.js"')).toBeGreaterThan(html.indexOf('src="local-model-ui.js"')); + }); +}); diff --git a/test/claude-conversation-report-docker.test.ts b/test/claude-conversation-report-docker.test.ts new file mode 100644 index 00000000..0221f60c --- /dev/null +++ b/test/claude-conversation-report-docker.test.ts @@ -0,0 +1,51 @@ +/** + * @fileoverview A Docker session's reported transcript path is watched on the host + * (src/web/claude-conversation-report.ts). + * + * Claude in a Docker case runs with `HOME=/home/agent`, so a hook or the statusline reports a + * transcript under `/home/agent/.claude/projects`, which does not exist on the host. The case + * mounts the host's `~/.claude/projects` there, so the watcher must follow the host's copy. + */ + +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; +import { hostTranscriptPath, noteClaudeConversationReport } from '../src/web/claude-conversation-report.js'; +import { CONTAINER_CLAUDE_DIR } from '../src/docker-hosts.js'; +import type { Session } from '../src/session.js'; + +const docker = { docker: { containerName: 'codeman-case' } } as unknown as Pick; +const reported = `${CONTAINER_CLAUDE_DIR}/projects/-workspace-app/abc.jsonl`; + +describe('hostTranscriptPath', () => { + it("maps a Docker session's container path into the host's projects folder", () => { + expect(hostTranscriptPath(docker, reported)).toBe( + join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl') + ); + }); + + it('leaves a local session, a path outside the projects folder and a path with `..` as reported', () => { + expect(hostTranscriptPath({ docker: undefined }, reported)).toBe(reported); + expect(hostTranscriptPath(undefined, reported)).toBe(reported); + expect(hostTranscriptPath(docker, '/home/agent/elsewhere/abc.jsonl')).toBe('/home/agent/elsewhere/abc.jsonl'); + const escape = `${CONTAINER_CLAUDE_DIR}/projects/../../.ssh/id_rsa`; + expect(hostTranscriptPath(docker, escape)).toBe(escape); + }); +}); + +describe('noteClaudeConversationReport', () => { + it("starts a Docker session's watcher on the host path", () => { + const startTranscriptWatcher = vi.fn(); + const session = { ...docker, claudeSessionChain: [], adoptClaudeSessionId: vi.fn() }; + const ctx = { + sessions: new Map([['s1', session]]), + startTranscriptWatcher, + persistSessionState: vi.fn(), + } as unknown as Parameters[0]; + noteClaudeConversationReport(ctx, 's1', { transcript_path: reported }); + expect(startTranscriptWatcher).toHaveBeenCalledWith( + 's1', + join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl') + ); + }); +}); diff --git a/test/claude-response-transcript.test.ts b/test/claude-response-transcript.test.ts new file mode 100644 index 00000000..d9ede3f7 --- /dev/null +++ b/test/claude-response-transcript.test.ts @@ -0,0 +1,216 @@ +/** + * @fileoverview The incremental Claude transcript reader behind `last-response` + * (src/web/claude-response-transcript.ts). + * + * Every read must answer what a parse of the whole file answers, whatever the file did between + * reads: grew, grew by half a line, shrank, was replaced, or was rewritten in place. A read must + * also parse only the bytes appended since the last one, and overlapping reads of one file must + * share their passes. + */ + +import { appendFileSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import fs from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + ClaudeResponseParser, + ClaudeTranscriptReader, + parseClaudeResponseTranscript, +} from '../src/web/claude-response-transcript.js'; +import { KEEP_WARM_NUDGE } from '../src/prompt-cache-keepwarm.js'; + +const user = (text: string, extra: Record = {}) => + JSON.stringify({ type: 'user', timestamp: '2026-11-27T10:00:00Z', message: { content: text }, ...extra }); +const assistant = (text: string, ts = '2026-11-27T10:00:01Z') => + JSON.stringify({ type: 'assistant', timestamp: ts, message: { content: [{ type: 'text', text }] } }); +const toolUse = () => + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', id: 't', name: 'Bash', input: {} }] } }); +const toolResult = () => + JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', content: 'ok' }] } }); +const queued = (prompt: string) => + JSON.stringify({ + type: 'attachment', + attachment: { type: 'queued_command', prompt, commandMode: 'prompt', origin: { kind: 'human' } }, + }); + +/** A conversation that exercises turns, queued prompts, replays, keep-warm turns and tool rows. */ +const LINES = [ + user('first prompt'), + user('first prompt'), // a replayed row, collapsed + toolUse(), + toolResult(), + assistant('first answer'), + assistant('first answer'), // a replayed snapshot, collapsed + user('second prompt'), + queued('queued while working'), + assistant('second answer — with ünïcödé and 漢字 to cut mid-character'), + JSON.stringify({ type: 'user', isSidechain: true, message: { content: 'sidechain' } }), + user(KEEP_WARM_NUDGE), + assistant('ok'), + '{ not json', + user('synthetic'), + user('third prompt'), + assistant('third answer'), +]; + +describe('ClaudeResponseParser', () => { + it('answers the same whether fed at once or line by line, and its answers never change later', () => { + const whole = parseClaudeResponseTranscript(LINES.join('\n') + '\n'); + const parser = new ClaudeResponseParser(); + const early = (() => { + for (const line of LINES.slice(0, 5)) parser.feedLine(line); + return parser.result(); + })(); + for (const line of LINES.slice(5)) parser.feedLine(line); + expect(parser.result()).toEqual(whole); + expect(early.messages).toHaveLength(2); + expect(whole.text).toBe('third answer'); + expect(whole.messages.map((m) => m.text)).toEqual([ + 'first prompt', + 'first answer', + 'second prompt', + 'queued while working', + 'second answer — with ünïcödé and 漢字 to cut mid-character', + KEEP_WARM_NUDGE, + 'ok', + 'third prompt', + 'third answer', + ]); + expect(whole.messages.filter((m) => m.keepAlive).map((m) => m.text)).toEqual([KEEP_WARM_NUDGE, 'ok']); + }); + + it('leaves the original untouched when a clone parses more', () => { + const parser = new ClaudeResponseParser(); + parser.feedLine(user('p')); + const copy = parser.clone(); + copy.feedLine(assistant('a')); + expect(parser.result().messages).toHaveLength(1); + expect(copy.result().messages).toHaveLength(2); + }); +}); + +describe('ClaudeTranscriptReader', () => { + let dir: string; + let file: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'claude-transcript-reader-')); + file = join(dir, 'conversation.jsonl'); + }); + afterEach(() => { + vi.restoreAllMocks(); + rmSync(dir, { recursive: true, force: true }); + }); + + const whole = () => parseClaudeResponseTranscript(LINES.join('\n') + '\n'); + + it('answers a parse of the whole file after each append, at any byte boundary', async () => { + const bytes = Buffer.from(LINES.join('\n') + '\n', 'utf8'); + // A tiny chunk size makes reads cut lines and multi-byte characters. + const reader = new ClaudeTranscriptReader({ chunkBytes: 7 }); + writeFileSync(file, ''); + for (let cut = 0; cut < bytes.length; ) { + const next = Math.min(bytes.length, cut + 1 + ((cut * 37) % 53)); + appendFileSync(file, bytes.subarray(cut, next)); + cut = next; + const expected = parseClaudeResponseTranscript(bytes.subarray(0, cut).toString('utf8')); + // A cut inside a multi-byte character leaves a line that is not JSON either way. + expect(await reader.read(file)).toEqual(expected); + } + expect(await reader.read(file)).toEqual(whole()); + }); + + it('parses only the bytes appended since the last read', async () => { + writeFileSync(file, LINES.slice(0, 8).join('\n') + '\n'); + const reader = new ClaudeTranscriptReader(); + await reader.read(file); + const expected = whole(); + const feed = vi.spyOn(ClaudeResponseParser.prototype, 'feedLine'); + appendFileSync(file, LINES.slice(8).join('\n') + '\n'); + expect(await reader.read(file)).toEqual(expected); + // Only the appended lines; the empty string after the last newline is never fed. + expect(feed.mock.calls.map(([line]) => line)).toEqual(LINES.slice(8)); + feed.mockClear(); + expect(await reader.read(file)).toEqual(expected); + expect(feed).not.toHaveBeenCalled(); + }); + + it('answers a last line that has no newline yet, and parses it once its newline arrives', async () => { + writeFileSync(file, `${user('p')}\n${assistant('a')}`); + const reader = new ClaudeTranscriptReader(); + expect((await reader.read(file)).text).toBe('a'); + appendFileSync(file, `\n${assistant('b')}\n`); + expect(await reader.read(file)).toEqual( + parseClaudeResponseTranscript(`${user('p')}\n${assistant('a')}\n${assistant('b')}\n`) + ); + }); + + it('starts again from byte 0 when the file shrank', async () => { + writeFileSync(file, LINES.join('\n') + '\n'); + const reader = new ClaudeTranscriptReader(); + await reader.read(file); + writeFileSync(file, `${user('new')}\n${assistant('fresh')}\n`); + expect(await reader.read(file)).toEqual(parseClaudeResponseTranscript(`${user('new')}\n${assistant('fresh')}\n`)); + }); + + it('starts again from byte 0 when another file replaced it', async () => { + writeFileSync(file, `${user('p')}\n${assistant('a')}\n`); + const reader = new ClaudeTranscriptReader(); + await reader.read(file); + const replacement = join(dir, 'replacement.jsonl'); + writeFileSync(replacement, LINES.join('\n') + '\n'); + renameSync(replacement, file); + expect(await reader.read(file)).toEqual(whole()); + }); + + it('starts again from byte 0 when the file was rewritten in place to a larger size', async () => { + writeFileSync(file, `${user('p')}\n${assistant('a')}\n`); + const reader = new ClaudeTranscriptReader(); + await reader.read(file); + const handle = await fs.open(file, 'r+'); + await handle.truncate(0); + await handle.write(LINES.join('\n') + '\n', 0); + await handle.close(); + expect(await reader.read(file)).toEqual(whole()); + }); + + it('shares one pass between reads asked for while a read runs', async () => { + writeFileSync(file, LINES.join('\n') + '\n'); + const reader = new ClaudeTranscriptReader(); + const open = vi.spyOn(fs, 'open'); + const results = await Promise.all([reader.read(file), reader.read(file), reader.read(file), reader.read(file)]); + for (const result of results) expect(result).toEqual(whole()); + // The first read, then one pass for every read that waited on it. + expect(open).toHaveBeenCalledTimes(2); + }); + + it('sees bytes appended while an earlier read ran', async () => { + writeFileSync(file, `${user('p')}\n`); + const reader = new ClaudeTranscriptReader(); + const first = reader.read(file); + appendFileSync(file, `${assistant('late')}\n`); + const second = reader.read(file); + await first; + expect((await second).text).toBe('late'); + }); + + it('rejects for a missing file, and reads it once it exists', async () => { + const reader = new ClaudeTranscriptReader(); + await expect(reader.read(file)).rejects.toThrow(); + writeFileSync(file, `${assistant('there')}\n`); + expect((await reader.read(file)).text).toBe('there'); + }); + + it('awaits between chunks, so a large first read does not hold the event loop in one step', async () => { + const big = Array.from({ length: 4000 }, (_, i) => `${user(`p${i}`)}\n${assistant(`a${i}`)}`).join('\n') + '\n'; + writeFileSync(file, big); + const reader = new ClaudeTranscriptReader({ chunkBytes: 16 * 1024 }); + let ticks = 0; + const timer = setInterval(() => ticks++, 0); + const result = await reader.read(file); + clearInterval(timer); + expect(result).toEqual(parseClaudeResponseTranscript(big)); + expect(ticks).toBeGreaterThan(0); + }); +}); diff --git a/test/frontend-cli-no-id-branching.test.ts b/test/frontend-cli-no-id-branching.test.ts index 9eee6e28..96051ff8 100644 --- a/test/frontend-cli-no-id-branching.test.ts +++ b/test/frontend-cli-no-id-branching.test.ts @@ -41,6 +41,9 @@ const SCANNED_FILES = [ // The harness a local model is paired with arrives as a label in the payload // (`Candidate.cliLabel`); the card names no CLI and compares no id. 'local-model-ui.js', + // Which sessions can show the chat view comes from the injected transcript capability + // (window.__codemanChatViewModes), never from an id here. + 'chat-view.js', ]; /** diff --git a/test/keyed-throttle.test.ts b/test/keyed-throttle.test.ts new file mode 100644 index 00000000..46c9d7fd --- /dev/null +++ b/test/keyed-throttle.test.ts @@ -0,0 +1,94 @@ +/** + * @fileoverview KeyedThrottle (src/utils/keyed-throttle.ts), the per-key throttle behind the + * server's `transcript:update` broadcast. + * + * Pinned: the first call sends at once, a burst inside the interval collapses into one trailing + * send at the interval's end, the trailing send runs the newest send it was given, a call after + * the interval sends at once, keys are independent, and cancelKey()/dispose() drop a pending + * trailing send. + * + * Port: N/A + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { KeyedThrottle } from '../src/utils/index.js'; + +describe('KeyedThrottle', () => { + let throttle: KeyedThrottle; + let sends: Array<{ key: string; at: number }>; + const fire = (key: string) => throttle.fire(key, () => sends.push({ key, at: Date.now() })); + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(10_000); + throttle = new KeyedThrottle(750); + sends = []; + }); + + afterEach(() => { + throttle.dispose(); + vi.useRealTimers(); + }); + + it('sends the first call at once', () => { + fire('a'); + expect(sends).toEqual([{ key: 'a', at: 10_000 }]); + }); + + it('collapses a burst into one trailing send at the end of the interval', () => { + fire('a'); + vi.advanceTimersByTime(100); + fire('a'); + fire('a'); + vi.advanceTimersByTime(300); + fire('a'); + expect(sends).toHaveLength(1); + vi.advanceTimersByTime(349); + expect(sends).toHaveLength(1); + vi.advanceTimersByTime(1); + expect(sends).toEqual([ + { key: 'a', at: 10_000 }, + { key: 'a', at: 10_750 }, + ]); + vi.advanceTimersByTime(5000); + expect(sends).toHaveLength(2); + }); + + it('runs the newest send it was given when the trailing send fires', () => { + const labels: string[] = []; + throttle.fire('a', () => labels.push('first')); + throttle.fire('a', () => labels.push('second')); + throttle.fire('a', () => labels.push('third')); + vi.advanceTimersByTime(750); + expect(labels).toEqual(['first', 'third']); + }); + + it('sends at once again once the interval has passed', () => { + fire('a'); + vi.advanceTimersByTime(800); + fire('a'); + expect(sends.map((s) => s.at)).toEqual([10_000, 10_800]); + }); + + it('throttles each key on its own', () => { + fire('a'); + fire('b'); + expect(sends.map((s) => s.key)).toEqual(['a', 'b']); + }); + + it('drops a pending trailing send on cancelKey() and dispose()', () => { + fire('a'); + fire('a'); + fire('b'); + fire('b'); + throttle.cancelKey('a'); + vi.advanceTimersByTime(1000); + expect(sends.map((s) => s.key)).toEqual(['a', 'b', 'b']); + + fire('c'); + fire('c'); + throttle.dispose(); + vi.advanceTimersByTime(1000); + expect(sends.map((s) => s.key)).toEqual(['a', 'b', 'b', 'c']); + }); +}); diff --git a/test/render-index-html.test.ts b/test/render-index-html.test.ts index 27e9a8d3..91a1b85f 100644 --- a/test/render-index-html.test.ts +++ b/test/render-index-html.test.ts @@ -263,6 +263,16 @@ describe('WebServer.renderIndexHtml', () => { } }); + it('injects the chat view modes from the transcript capability, in solo windows too', async () => { + for (const solo of [undefined, 'sess-123']) { + const { server } = makeServer(); + const html = await render(server, solo); + const match = html.match(/window\.__codemanChatViewModes=(\[[^<]*\]);/); + expect(match).not.toBeNull(); + expect(JSON.parse(match![1])).toEqual(['claude']); + } + }); + it('escapes the solo id so it cannot break out of the inline '); diff --git a/test/routes/session-routes-claude-last-response.test.ts b/test/routes/session-routes-claude-last-response.test.ts index fcf52253..928453aa 100644 --- a/test/routes/session-routes-claude-last-response.test.ts +++ b/test/routes/session-routes-claude-last-response.test.ts @@ -8,13 +8,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import Fastify, { type FastifyInstance } from 'fastify'; import fastifyCookie from '@fastify/cookie'; -import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; +import fsPromises from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { installRouteErrorHandler } from '../../src/web/route-error-handler.js'; import { registerSessionRoutes } from '../../src/web/routes/session-routes.js'; import { ApiErrorCode, httpStatusForErrorCode } from '../../src/types.js'; import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js'; +import { KEEP_WARM_NUDGE } from '../../src/prompt-cache-keepwarm.js'; interface LocalHarness { app: FastifyInstance; @@ -239,6 +241,261 @@ describe('GET /api/sessions/:id/last-response (claude)', () => { ]); }); + it('starts a transcript watcher for the chat view when the session has none, and only then', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]); + const start = harness.ctx.startTranscriptWatcher as ReturnType; + const current = harness.ctx.getTranscriptPath as ReturnType; + + // The brief view and agent pollers read without starting anything. + await getLastResponse(sessionId, false); + expect(start).not.toHaveBeenCalled(); + + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + expect(start.mock.calls[0][0]).toBe(sessionId); + expect(String(start.mock.calls[0][1])).toMatch(new RegExp(`${sessionId}\\.jsonl$`)); + + // A watcher already running (a hook reported its path) is left alone. + current.mockReturnValue('/some/path.jsonl'); + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + }); + + it('moves a watcher it started itself to the new file after /clear', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]); + const start = harness.ctx.startTranscriptWatcher as ReturnType; + const current = harness.ctx.getTranscriptPath as ReturnType; + + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + const fileA = String(start.mock.calls[0][1]); + current.mockReturnValue(fileA); + + // The same file again: nothing to move. + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + + // A /clear starts a new conversation file, and no hook moves the watcher onto it. + const clearedId = 'b0c1d2e3-0000-4000-8000-000000000001'; + session.claudeSessionId = clearedId; + writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]); + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(2); + expect(start.mock.calls[1][0]).toBe(sessionId); + expect(String(start.mock.calls[1][1])).toMatch(new RegExp(`${clearedId}\\.jsonl$`)); + }); + + it('never moves a watcher whose path a hook set', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]); + const start = harness.ctx.startTranscriptWatcher as ReturnType; + const current = harness.ctx.getTranscriptPath as ReturnType; + + // A hook started the watcher on a path this read never recorded. + current.mockReturnValue('/hook/reported.jsonl'); + await getLastResponse(sessionId, true); + const clearedId = 'b0c1d2e3-0000-4000-8000-000000000002'; + session.claudeSessionId = clearedId; + writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]); + await getLastResponse(sessionId, true); + expect(start).not.toHaveBeenCalled(); + }); + + it('leaves a watcher it started alone once a hook moved it', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]); + const start = harness.ctx.startTranscriptWatcher as ReturnType; + const current = harness.ctx.getTranscriptPath as ReturnType; + + // The read starts the watcher on transcript A. + current.mockReturnValue(null); + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + + // A hook then moves it to B, and a /clear leaves the conversation in C. + current.mockReturnValue('/hook/moved.jsonl'); + const clearedId = 'b0c1d2e3-0000-4000-8000-000000000003'; + session.claudeSessionId = clearedId; + writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]); + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + + // The read forgot its record, so a later read leaves the hook's watcher alone too. + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + + // Even once the watcher is back on the path the read first recorded, and the conversation + // moved on to a new file: a read that still held its record would move the watcher there. + current.mockReturnValue(String(start.mock.calls[0][1])); + const laterId = 'b0c1d2e3-0000-4000-8000-000000000004'; + session.claudeSessionId = laterId; + writeTranscript(laterId, [userEntry('Later'), assistantEntry('Later still.', '2026-07-21T00:00:03Z')]); + await getLastResponse(sessionId, true); + expect(start).toHaveBeenCalledTimes(1); + }); + + it('starts no transcript watcher for a session removed while the read was in flight', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]); + const start = harness.ctx.startTranscriptWatcher as ReturnType; + + // A delete or detach between the route's lookup and the transcript scan leaves the + // session out of the server's map; nothing would ever stop a watcher started for it. + harness.ctx.sessions.delete(sessionId); + const result = await harness.ctx.lastResponseFor!(session as never, 'full'); + expect(start).not.toHaveBeenCalled(); + expect((result as { messages?: unknown[] }).messages?.length).toBeGreaterThan(0); + }); + + it('remembers where a transcript was found, and scans again once the file moved', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]); + const projectsDir = join(testHome, '.claude', 'projects'); + const readdir = vi.spyOn(fsPromises, 'readdir'); + const projectScans = () => readdir.mock.calls.filter((call) => String(call[0]) === projectsDir).length; + try { + await getLastResponse(sessionId, true); + expect(projectScans()).toBe(1); + + const second = await getLastResponse(sessionId, true); + expect(projectScans()).toBe(1); + expect(second.body.data.text).toBe('Hello.'); + + // The file moves to another project folder: the remembered path fails, the scan finds it. + const movedDir = join(projectsDir, '-elsewhere'); + mkdirSync(movedDir, { recursive: true }); + renameSync(join(projectsDir, '-workspace', `${sessionId}.jsonl`), join(movedDir, `${sessionId}.jsonl`)); + const third = await getLastResponse(sessionId, true); + expect(projectScans()).toBe(2); + expect(third.body.data.text).toBe('Hello.'); + } finally { + readdir.mockRestore(); + } + }); + + it("marks Codeman's keep-warm turns so the chat view can leave them out", async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [ + userEntry('Fix the bug'), + assistantEntry('Fixed.', '2026-07-21T00:00:01Z'), + userEntry(KEEP_WARM_NUDGE), + assistantEntry('ok', '2026-07-21T00:00:02Z'), + userEntry('Thanks'), + assistantEntry('You are welcome.', '2026-07-21T00:00:03Z'), + ]); + + const { body } = await getLastResponse(sessionId, true); + expect( + body.data.messages.map((message: { role: string; text: string; keepAlive?: boolean }) => [ + message.role, + message.text, + message.keepAlive === true, + ]) + ).toEqual([ + ['user', 'Fix the bug', false], + ['assistant', 'Fixed.', false], + ['user', KEEP_WARM_NUDGE, true], + ['assistant', 'ok', true], + ['user', 'Thanks', false], + ['assistant', 'You are welcome.', false], + ]); + }); + + it('keeps a prompt the user queued during a keep-warm turn, and the answer to it', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [ + userEntry(KEEP_WARM_NUDGE), + queuedEntry('Also run the tests', '2026-07-21T00:00:01Z'), + assistantEntry('ok. Tests pass.', '2026-07-21T00:00:02Z'), + ]); + + const { body } = await getLastResponse(sessionId, true); + expect( + body.data.messages.map((message: { text: string; keepAlive?: boolean }) => [ + message.text, + message.keepAlive === true, + ]) + ).toEqual([ + [KEEP_WARM_NUDGE, true], + ['Also run the tests', false], + ['ok. Tests pass.', false], + ]); + }); + + it('opens a keep-warm turn of its own after a turn that ended without assistant text', async () => { + const sessionId = harness.ctx._session.id; + const session = harness.ctx._session as typeof harness.ctx._session & { + claudeSessionId: string; + adoptClaudeSessionId: ReturnType; + }; + session.claudeSessionId = sessionId; + session.adoptClaudeSessionId = vi.fn(); + writeTranscript(sessionId, [ + userEntry('Fix the bug'), + { type: 'assistant', message: { content: [{ type: 'tool_use', id: 'tool-1' }] } }, + userEntry(KEEP_WARM_NUDGE), + assistantEntry('ok', '2026-07-21T00:00:02Z'), + ]); + + const { body } = await getLastResponse(sessionId, true); + const messages = body.data.messages as Array<{ role: string; text: string; turn: number; keepAlive?: boolean }>; + const prompt = messages.find((message) => message.text === 'Fix the bug'); + const reply = messages.find((message) => message.text === 'ok'); + expect(prompt?.keepAlive).toBeUndefined(); + expect(reply?.keepAlive).toBe(true); + expect(reply?.turn).not.toBe(prompt?.turn); + }); + /** * A prompt typed while Claude is working is absorbed mid-turn and recorded * ONLY as an attachment row — 160 of the 347 user cards across a real @@ -727,7 +984,7 @@ describe('GET /api/sessions/:id/last-response (relocated Claude config folder, # expect(pane.adoptClaudeSessionId).toHaveBeenCalledWith('after-clear'); }); - it("keeps a Docker session off its override, which names a folder inside the container", async () => { + it('keeps a Docker session off its override, which names a folder inside the container', async () => { const home = join(testHome, '.claude'); writeTranscript(home, 'conversation-a', 'what the host folder holds'); writeTranscript(relocated, 'conversation-a', 'a host folder that only shares the path'); diff --git a/test/routes/status-telemetry-routes.test.ts b/test/routes/status-telemetry-routes.test.ts index f9046a1d..fc2c9eec 100644 --- a/test/routes/status-telemetry-routes.test.ts +++ b/test/routes/status-telemetry-routes.test.ts @@ -13,6 +13,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js'; import { registerStatusTelemetryRoutes } from '../../src/web/routes/status-telemetry-routes.js'; +import { registerHookEventRoutes } from '../../src/web/routes/hook-event-routes.js'; import { SessionPromptCache, SessionStatusTelemetry } from '../../src/web/sse-events.js'; import { Session } from '../../src/session.js'; @@ -81,6 +82,131 @@ describe('POST /api/status-telemetry', () => { }); }); + describe('the conversation the pane runs', () => { + // As measured on Claude Code 2.1.332: the statusline runs about a second after a `/clear`, + // with the new conversation's id and transcript path, before any hook reports them. + const cleared = { + session_id: 'conv-2', + transcript_path: '/home/u/.claude/projects/-w/conv-2.jsonl', + }; + + it('follows the new conversation the statusline reports after /clear', async () => { + const res = await post({ sessionId: SID, data: cleared }); + expect(res.statusCode).toBe(200); + expect(h.ctx._session.claudeSessionId).toBe('conv-2'); + expect(h.ctx._session.claudeSessionIdIsFirstHand).toBe(true); + expect(h.ctx.startTranscriptWatcher).toHaveBeenCalledWith(SID, cleared.transcript_path); + expect(h.ctx.persistSessionState).toHaveBeenCalledTimes(1); + // The next render reports the same conversation: nothing is persisted again. + await post({ sessionId: SID, data: cleared }); + expect(h.ctx.persistSessionState).toHaveBeenCalledTimes(1); + }); + + /** + * The exporter backgrounds its POST when it wraps the user's own statusline, so a report sent + * before the `/clear` can land after the one sent after it. That old report must not move the + * session back to the conversation the `/clear` ended. + */ + it('ignores a delayed report that names an earlier conversation', async () => { + const report = (id: string) => ({ + sessionId: SID, + data: { session_id: id, transcript_path: `/home/u/.claude/projects/-w/${id}.jsonl` }, + }); + await post(report('conv-1')); + await post(report('conv-2')); + await post(report('conv-1')); // the delayed old POST + const session = h.ctx._session; + expect(session.claudeSessionId).toBe('conv-2'); + expect(session.claudeSessionChain[session.claudeSessionChain.length - 1]).toBe('conv-2'); + expect(h.ctx.startTranscriptWatcher).toHaveBeenLastCalledWith(SID, report('conv-2').data.transcript_path); + }); + + /** + * With workspace hooks off no hook ever follows a `/resume`, so a statusline report that names + * an earlier conversation must move the session back once the last move is old enough that no + * delayed POST from before it can still arrive. + */ + it('follows a /resume back to an earlier conversation once the last move is more than 10 s old', async () => { + const report = (id: string) => ({ + sessionId: SID, + data: { session_id: id, transcript_path: `/home/u/.claude/projects/-w/${id}.jsonl` }, + }); + // Only the clock is faked: Fastify's inject still needs real timers. + vi.useFakeTimers({ toFake: ['Date'] }); + try { + vi.setSystemTime(new Date('2026-11-26T10:00:00Z')); + await post(report('conv-1')); + await post(report('conv-2')); + vi.setSystemTime(new Date('2026-11-26T10:00:11Z')); + await post(report('conv-1')); // the /resume back + } finally { + vi.useRealTimers(); + } + const session = h.ctx._session; + expect(session.claudeSessionId).toBe('conv-1'); + expect(session.claudeSessionChain[session.claudeSessionChain.length - 1]).toBe('conv-1'); + expect(h.ctx.startTranscriptWatcher).toHaveBeenLastCalledWith(SID, report('conv-1').data.transcript_path); + }); + + /** + * A report naming the session's current conversation is never refused, so after a server + * restart the statusline still starts the transcript watcher for it. + */ + it('starts the transcript watcher for a report that names the current conversation', async () => { + await post({ sessionId: SID, data: cleared }); + h.ctx.startTranscriptWatcher.mockClear(); + await post({ sessionId: SID, data: cleared }); + expect(h.ctx.startTranscriptWatcher).toHaveBeenCalledWith(SID, cleared.transcript_path); + }); + + /** + * The run summary records a `prompt_submitted` only for a `/clear` successor's first prompt. + * The statusline adopts the successor before that prompt's hook, so the hook must still learn + * that the conversation moved. + */ + it("records the /clear successor's first prompt in the run summary after the statusline moved it", async () => { + const both = await createRouteTestHarness( + (app, ctx) => { + registerStatusTelemetryRoutes(app, ctx); + registerHookEventRoutes(app, ctx); + }, + { sessionId: SID } + ); + const tracker = { recordHookEvent: vi.fn() }; + both.ctx.runSummaryTrackers.set(SID, tracker as never); + const prompt = () => + both.app.inject({ + method: 'POST', + url: '/api/hook-event', + payload: { event: 'prompt_submitted', sessionId: SID, data: { session_id: 'conv-2' } }, + }); + + await both.app.inject({ + method: 'POST', + url: '/api/status-telemetry', + payload: { sessionId: SID, data: cleared }, + }); + await prompt(); + expect(tracker.recordHookEvent).toHaveBeenCalledTimes(1); + expect(tracker.recordHookEvent).toHaveBeenCalledWith('prompt_submitted', expect.any(Object)); + + await prompt(); // the next prompt in the same conversation + expect(tracker.recordHookEvent).toHaveBeenCalledTimes(1); + }); + + it('refuses a transcript path with shell syntax in it', async () => { + await post({ sessionId: SID, data: { ...cleared, transcript_path: '/tmp/$(id).jsonl' } }); + expect(h.ctx.startTranscriptWatcher).not.toHaveBeenCalled(); + }); + + it('takes no report from a CLI without a statusline exporter', async () => { + h.ctx._session.mode = 'shell'; + await post({ sessionId: SID, data: cleared }); + expect(h.ctx._session.claudeSessionId).not.toBe('conv-2'); + expect(h.ctx.startTranscriptWatcher).not.toHaveBeenCalled(); + }); + }); + it('does not broadcast for an unknown session; returns an EMPTY footer, never a brand word', async () => { const res = await post({ sessionId: 'does-not-exist', data: REAL }); expect(res.statusCode).toBe(200); diff --git a/test/server-index-title.test.ts b/test/server-index-title.test.ts index ed3a5ae8..4b331b0a 100644 --- a/test/server-index-title.test.ts +++ b/test/server-index-title.test.ts @@ -118,6 +118,8 @@ describe('WebServer index.html templating (#82)', () => { .replace(/<script>window\.__codemanTranscriptPageKeys=\[.*?\];<\/script>\n/, '') // And the keyboard-hold mode list, built the same way. .replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '') + // And the chat view mode list, built the same way. + .replace(/<script>window\.__codemanChatViewModes=\[.*?\];<\/script>\n/, '') // And the wheel-forwarding rules: an object keyed by run mode, always injected. .replace(/<script>window\.__codemanWheelForward=\{.*?\};<\/script>\n/, ''); const beforeTitle = rawTemplate.split('<title>Codeman')[0]; diff --git a/test/tile-grid-park-guards.test.ts b/test/tile-grid-park-guards.test.ts index 82484793..3c72b8b1 100644 --- a/test/tile-grid-park-guards.test.ts +++ b/test/tile-grid-park-guards.test.ts @@ -199,6 +199,20 @@ describe('parking the main terminal', () => { app.closeTileGrid({ reselect: false }); expect(app.selectSession).not.toHaveBeenCalled(); }); + + it('opening and closing re-sync the chat view, so it hides for the tiles and comes back after', () => { + const app = makeApp(); + // What the grid reported when the chat view was told, one entry per call. + const owned: boolean[] = []; + app._chatViewSync = vi.fn(() => owned.push(app._tilesOwnTerminal())); + + app.openTileGrid(IDS); + expect(owned).toContain(true); + + owned.length = 0; + app.closeTileGrid({ reselect: false }); + expect(owned).toContain(false); + }); }); /** An app with the grid open on IDS (focus s-a), or closed, for the paired guard checks. */ diff --git a/test/transcript-update-broadcast.test.ts b/test/transcript-update-broadcast.test.ts new file mode 100644 index 00000000..b14cad20 --- /dev/null +++ b/test/transcript-update-broadcast.test.ts @@ -0,0 +1,88 @@ +/** + * @fileoverview The server path from a transcript watcher's `transcript:update` event to the + * throttled `transcript:update` SSE broadcast, which the chat view's live updates depend on. + * + * Pinned: the first update broadcasts at once and a second one inside the interval broadcasts + * once at its end (750 ms), stopTranscriptWatcher drops a pending trailing broadcast, and no + * watcher starts for a session that cleanup is removing. + * + * Strategy: construct WebServer on port 0 in test mode (nothing listens until start()) and call + * its private watcher methods directly. + * + * Port: N/A (no server start) + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import type { EventEmitter } from 'node:events'; +import { WebServer } from '../src/web/server.js'; +import { SseEvent } from '../src/web/sse-events.js'; + +interface ServerInternals { + broadcast: (event: string, data: unknown) => void; + startTranscriptWatcher: (sessionId: string, transcriptPath: string) => void; + stopTranscriptWatcher: (sessionId: string) => void; + transcriptWatchers: Map; + cleaningUp: Set; +} + +describe('transcript:update broadcast', () => { + const SID = 'transcript-update-session'; + let server: ServerInternals; + let broadcast: ReturnType; + let transcriptPath: string; + + const updates = () => broadcast.mock.calls.filter(([event]) => event === SseEvent.TranscriptUpdate); + + beforeEach(() => { + server = new WebServer(0, false, true) as unknown as ServerInternals; + broadcast = vi.spyOn(server, 'broadcast').mockImplementation(() => {}); + transcriptPath = join(mkdtempSync(join(tmpdir(), 'codeman-transcript-update-')), 'conv.jsonl'); + writeFileSync(transcriptPath, ''); + }); + + afterEach(() => { + server.stopTranscriptWatcher(SID); + vi.useRealTimers(); + }); + + it('broadcasts the first update at once and a second one at the end of the interval', () => { + server.startTranscriptWatcher(SID, transcriptPath); + const watcher = server.transcriptWatchers.get(SID); + expect(watcher).toBeDefined(); + vi.useFakeTimers(); + + watcher!.emit('transcript:update'); + watcher!.emit('transcript:update'); + expect(updates()).toHaveLength(1); + expect(updates()[0][1]).toMatchObject({ sessionId: SID }); + + vi.advanceTimersByTime(749); + expect(updates()).toHaveLength(1); + vi.advanceTimersByTime(1); + expect(updates()).toHaveLength(2); + expect(updates()[1][1]).toMatchObject({ sessionId: SID }); + }); + + it('drops a pending trailing broadcast when the watcher stops', () => { + server.startTranscriptWatcher(SID, transcriptPath); + const watcher = server.transcriptWatchers.get(SID)!; + vi.useFakeTimers(); + + watcher.emit('transcript:update'); + watcher.emit('transcript:update'); + server.stopTranscriptWatcher(SID); + vi.advanceTimersByTime(1000); + expect(updates()).toHaveLength(1); + expect(server.transcriptWatchers.has(SID)).toBe(false); + }); + + it('starts no watcher for a session that cleanup is removing', () => { + server.cleaningUp.add(SID); + server.startTranscriptWatcher(SID, transcriptPath); + expect(server.transcriptWatchers.has(SID)).toBe(false); + server.cleaningUp.delete(SID); + }); +});