mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-05 01:29:32 +01:00
feat(web): a chat view shows a Claude session's conversation, rendered and live
A local or Docker Claude session can show its conversation as rendered text, the way the Response Viewer draws it, in place of the terminal. The terminal stays attached and sized underneath, so switching views never resizes the pane, and the user still types in the terminal. Discussion #858 has the background. - A Chat / Terminal switch and Alt+Shift+C change the view, and each session remembers its choice on this device until the session is gone. Two per-device settings pick the default view and hide the switch. Phones, remote and adopted sessions keep the terminal. - The server broadcasts `transcript:update`, at most one per 750 ms per session, and the view re-reads the conversation on it, so an answer fills in mid-turn. - The server keeps each transcript's parse and the byte offset it reached, so a read parses only the bytes appended since the last one, in chunks with an await between them. Overlapping reads of one file share one pass. The Response Viewer and the Discord bridge read through it too. - A full conversation read starts a transcript watcher for a session that has none, such as one picked up after a server restart. - A Docker session's hook reports the container's transcript path, and the server watches the host's copy of that file. - After `/clear`, Claude Code runs the statusline command with the new conversation's id and transcript path. The statusline exporter posts them, and the server follows the new conversation the way it follows a hook's report. - Keep-warm turns are hidden, long prompts fold, a "Working" line shows the turn's running time, and a pending dialog shows a notice that opens the terminal. The design note, docs/chat-view-plan.md, covers this and the four steps that follow it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
babb55e4d9
commit
c6fff5e6a8
39 files changed
+3844
-244
No files matched your search
@@ -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) |
|
||||
|
||||
@@ -601,6 +601,26 @@ request returns. The capture runs synchronous tmux calls on the server; the
|
||||
| `lines=<n>` | With `full=1` only: read at most `<n>` 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=<id,...>` 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:
|
||||
|
||||
@@ -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 `<claudeSessionId|id>.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 `<main path without .jsonl>/subagents/agent-<id>.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 `<claudeSessionId|id>.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 `<main path without .jsonl>/subagents/agent-<id>.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
|
||||
|
||||
|
||||
@@ -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 `<pasted_content>` 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 `/<name> ` 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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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<K = string> {
|
||||
private readonly state = new Map<K, ThrottleState>();
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -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. SuchLine truncated
|
||||
|
||||
**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 `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
|
||||
|
||||
@@ -94,6 +96,6 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` can stop delivering without erroring, so the client forces a reconnect when nothing arrives. ⚠️ The server keepalive must stay the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), never an SSE comment, which `EventSource` cannot observe; its no-op client listener must stay registered. ⚠️ Judge staleness only while `connected` and online (the loop breaker). ⚠️ The liveness stamp lives inside `addListener`. ⚠️ Clear the interval only at the top of `connectSSE()`, or intervals stack. ⚠️ The watchdog cannot see an attempt that never OPENS (no response headers: no `open`, no `error`, never `connected`), so each attempt is bounded by `SSE_CONNECT_TIMEOUT_MS` (15s, `CodemanSseStale.CONNECT_TIMEOUT_MS`) and then retried through `_handleSseConnectionFailure()`, the same backoff `onerror` uses. Its timer is cleared at the top of `connectSSE()` BEFORE the offline early return, on `open`, and in `_handleSseConnectionFailure()`; the timer and the handler both ignore an `EventSource` that has been replaced. The window `offline` handler leaves it running on purpose (`navigator.onLine` can report offline on a working network). Tests: `test/sse-connect-timeout.test.ts`. → [architecture-invariants#sse-staleness-watchdog](../../docs/architecture-invariants.md#sse-staleness-watchdog)
|
||||
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), chat view (20, covering the terminal inside `.terminal-wrap`) and its Chat / Terminal switch (21, above it), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`).
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* @fileoverview A Claude pane's report of its live conversation: the conversation id and the
|
||||
* transcript path that Claude Code hands to every hook and to the statusline command.
|
||||
*
|
||||
* Two routes receive the report. `POST /api/hook-event` gets it from every hook Codeman
|
||||
* installs. `POST /api/status-telemetry` gets it from the statusline exporter, and Claude Code
|
||||
* runs the statusline command again about a second after a `/clear` (measured on 2.1.332), so
|
||||
* the server learns of the new conversation before the next prompt without a hook of its own.
|
||||
*
|
||||
* Both reports are first-hand: they come from the CLI process in the pane, addressed by the
|
||||
* pane's own `$CODEMAN_SESSION_ID`, so no cwd or timestamp guess is involved.
|
||||
*
|
||||
* @dependency web/schemas.ts (isValidWorkingDir), docker-hosts.ts (the Docker resume seed and the
|
||||
* container's Claude folder)
|
||||
*/
|
||||
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { CONTAINER_CLAUDE_DIR, persistDockerCaseClaudeSessionId } from '../docker-hosts.js';
|
||||
import { getDataDir } from '../config/instance.js';
|
||||
import { isValidWorkingDir } from './schemas.js';
|
||||
import type { Session } from '../session.js';
|
||||
import type { ConfigPort, SessionPort } from './ports/index.js';
|
||||
|
||||
/**
|
||||
* The host path of a transcript a pane reported. Claude in a Docker case runs with
|
||||
* `HOME=/home/agent`, so it reports `/home/agent/.claude/projects/...`, a path that does not exist
|
||||
* on the host. The case mounts the host's `~/.claude/projects` at that folder
|
||||
* (resolveDockerClaudeArtifacts in docker-hosts.ts), so the same file is under the host's folder.
|
||||
* Every other path is returned as reported.
|
||||
*/
|
||||
export function hostTranscriptPath(session: Pick<Session, 'docker'> | undefined, reported: string): string {
|
||||
if (!session?.docker) return reported;
|
||||
const containerProjects = `${CONTAINER_CLAUDE_DIR}/projects/`;
|
||||
if (!reported.startsWith(containerProjects)) return reported;
|
||||
const rest = reported.slice(containerProjects.length);
|
||||
// A `..` segment would leave the projects folder; such a path is left as reported.
|
||||
if (rest.split('/').some((part) => part === '..' || part === '')) return reported;
|
||||
return join(homedir(), '.claude', 'projects', rest);
|
||||
}
|
||||
|
||||
/** The two fields of a hook or statusline payload that name the conversation. */
|
||||
export interface ClaudeConversationReport {
|
||||
session_id?: unknown;
|
||||
transcript_path?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long after a session's last accepted move a statusline report may not move it back to an
|
||||
* earlier conversation. The exporter's POST is bounded by `curl --max-time 5` (hooks-config.ts),
|
||||
* so a report sent before the newest move lands within this window.
|
||||
*/
|
||||
const STATUSLINE_REORDER_WINDOW_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Sessions whose conversation moved since their last `prompt_submitted` hook. The statusline can
|
||||
* adopt a `/clear` successor before the next prompt's hook arrives, so that hook would see no
|
||||
* change in its own report; it asks {@link takeConversationMove} instead.
|
||||
*/
|
||||
const conversationMoves = new WeakSet<Session>();
|
||||
|
||||
/** When each session last moved to another conversation, for {@link STATUSLINE_REORDER_WINDOW_MS}. */
|
||||
const lastConversationMoveAt = new WeakMap<Session, number>();
|
||||
|
||||
/**
|
||||
* Report whether the session's conversation moved since the last call for it, and forget the move.
|
||||
* The hook route calls it for each `prompt_submitted`, to record a `/clear` successor's first prompt.
|
||||
*/
|
||||
export function takeConversationMove(session: Session | undefined): boolean {
|
||||
return !!session && conversationMoves.delete(session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the conversation a Claude pane reports: point the session's transcript watcher at the
|
||||
* reported file, adopt the reported conversation id, and persist the session when the id moved.
|
||||
* Returns true when the conversation changed.
|
||||
*
|
||||
* `forwardOnly` refuses a report that names an earlier conversation of the session's chain while
|
||||
* the session's last move is less than {@link STATUSLINE_REORDER_WINDOW_MS} old.
|
||||
*/
|
||||
export function noteClaudeConversationReport(
|
||||
ctx: SessionPort & Pick<ConfigPort, 'startTranscriptWatcher'>,
|
||||
sessionId: string,
|
||||
report: ClaudeConversationReport | null | undefined,
|
||||
options: { forwardOnly?: boolean } = {}
|
||||
): boolean {
|
||||
if (!report) return false;
|
||||
|
||||
// The statusline exporter can post out of order, because it backgrounds the POST when it wraps
|
||||
// the user's own statusline. So a statusline report moves the session back to an earlier
|
||||
// conversation, as a `/resume` makes, only when the last move is more than the window old.
|
||||
// Inside the window the move waits for the next hook or the next statusline report after it.
|
||||
if (options.forwardOnly && typeof report.session_id === 'string' && report.session_id) {
|
||||
const reported = ctx.sessions.get(sessionId);
|
||||
const chain = reported?.claudeSessionChain;
|
||||
if (
|
||||
reported &&
|
||||
chain &&
|
||||
chain.includes(report.session_id) &&
|
||||
chain[chain.length - 1] !== report.session_id &&
|
||||
Date.now() - (lastConversationMoveAt.get(reported) ?? 0) < STATUSLINE_REORDER_WINDOW_MS
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Watch the reported transcript when its path is safe. The watcher ignores a path it already watches.
|
||||
if (typeof report.transcript_path === 'string') {
|
||||
const transcriptPath = hostTranscriptPath(ctx.sessions.get(sessionId), report.transcript_path);
|
||||
if (isValidWorkingDir(transcriptPath)) ctx.startTranscriptWatcher(sessionId, transcriptPath);
|
||||
}
|
||||
|
||||
// Sync Claude's current conversation id. Interactive PTY mode never emits `session_id` on
|
||||
// stdout, so these reports are the only reliable way to learn that the user ran `/clear`,
|
||||
// which starts a new conversation file.
|
||||
if (typeof report.session_id !== 'string' || !report.session_id) return false;
|
||||
const session = ctx.sessions.get(sessionId);
|
||||
if (!session) return false;
|
||||
const prevClaudeSessionId = session.claudeSessionId;
|
||||
const prevChainLength = session.claudeSessionChain.length;
|
||||
// FIRST-HAND, so the response viewer can stop guessing (see resolveActiveClaudeSessionIdFromHistory).
|
||||
session.adoptClaudeSessionId(report.session_id, { firstHand: true });
|
||||
if (session.claudeSessionId === prevClaudeSessionId && session.claudeSessionChain.length === prevChainLength) {
|
||||
return false;
|
||||
}
|
||||
// Persist when the conversation actually moved: `/clear` emits no completion event, so without
|
||||
// this the successor id is lost on restart and recovery falls back to the launch conversation.
|
||||
ctx.persistSessionState(session);
|
||||
conversationMoves.add(session);
|
||||
lastConversationMoveAt.set(session, Date.now());
|
||||
// Docker sessions: keep the case's resume seed following the LIVE conversation, so a container
|
||||
// stop or reboot relaunch resumes the right transcript.
|
||||
if (session.docker && session.claudeSessionId && session.claudeSessionId !== prevClaudeSessionId) {
|
||||
void persistDockerCaseClaudeSessionId(getDataDir(), session.docker.containerName, session.claudeSessionId).catch(
|
||||
() => {}
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* @fileoverview A Claude transcript read into the Response Viewer's messages, incrementally.
|
||||
*
|
||||
* `GET /api/sessions/:id/last-response` answers the Response Viewer, the Discord bridge and the
|
||||
* chat view from a Claude session's transcript, an append-only JSONL file that grows past 200 MB
|
||||
* on long sessions. The chat view asks again on every `transcript:update`, up to once per 750 ms
|
||||
* per session while a turn runs. A read that parsed the whole file each time held the event loop
|
||||
* for 375 ms on a 66 MB transcript and 1.5 s on a 219 MB one, which froze every terminal and SSE
|
||||
* stream on the server.
|
||||
*
|
||||
* {@link ClaudeTranscriptReader} keeps the parser's state and the byte offset it reached for each
|
||||
* transcript path, in a small LRU. A read parses only the bytes appended since the last one, in
|
||||
* chunks with an await between them, so even the first read of a large file never holds the event
|
||||
* loop for long. It starts again from byte 0 when the file shrank, was replaced by another file,
|
||||
* or no longer holds the bytes it ended on. Reads of one path that overlap share one pass.
|
||||
*
|
||||
* The parser consumes whole lines only. A last line without its newline is parsed on a copy of
|
||||
* the state for that one answer, and parsed for good once its newline arrives, so the answer
|
||||
* always equals a parse of the whole file.
|
||||
*
|
||||
* @dependency prompt-cache-keepwarm.ts (KEEP_WARM_NUDGE), utils/lru-map.ts
|
||||
*/
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import { KEEP_WARM_NUDGE } from '../prompt-cache-keepwarm.js';
|
||||
import { LRUMap } from '../utils/lru-map.js';
|
||||
|
||||
export interface ClaudeResponseMessage {
|
||||
kind: 'prompt' | 'response';
|
||||
label: 'Prompt' | 'Response';
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
timestamp?: string;
|
||||
turn: number;
|
||||
queued?: boolean;
|
||||
/**
|
||||
* Part of a keep-warm turn (prompt-cache-keepwarm.ts): Codeman sent the prompt, not the user,
|
||||
* and the reply is its "ok". The chat view leaves such turns out, as Read My Mind does.
|
||||
*/
|
||||
keepAlive?: boolean;
|
||||
}
|
||||
|
||||
/** The last assistant text of a transcript and every message, as the route answers them. */
|
||||
export interface ClaudeResponseTranscript {
|
||||
text: string;
|
||||
timestamp: string;
|
||||
messages: ClaudeResponseMessage[];
|
||||
}
|
||||
|
||||
interface ClaudeTranscriptEntry {
|
||||
type?: string;
|
||||
timestamp?: string;
|
||||
isMeta?: boolean;
|
||||
isSidechain?: boolean;
|
||||
isCompactSummary?: boolean;
|
||||
message?: { content?: unknown };
|
||||
// A prompt typed while Claude is working is absorbed mid-turn and recorded
|
||||
// ONLY here — the CLI never re-emits it as a `user` row. Every field stays
|
||||
// optional and unvalidated: `queued_command` is not a documented CLI
|
||||
// contract, so a missing/renamed field must mean "skip", which is also what
|
||||
// the CLI's own non-human queue entries (commandMode 'task-notification',
|
||||
// no `origin` key) require. Shape observed on Claude Code 2.1.220-2.1.251.
|
||||
attachment?: {
|
||||
type?: string;
|
||||
prompt?: string;
|
||||
commandMode?: string;
|
||||
timestamp?: string;
|
||||
origin?: { kind?: string };
|
||||
};
|
||||
}
|
||||
|
||||
function extractClaudeText(content: unknown, separator: string): string {
|
||||
if (typeof content === 'string') return content;
|
||||
if (!Array.isArray(content)) return '';
|
||||
return content
|
||||
.filter(
|
||||
(block): block is { type: string; text: string } =>
|
||||
!!block &&
|
||||
typeof block === 'object' &&
|
||||
(block as { type?: string }).type === 'text' &&
|
||||
typeof (block as { text?: string }).text === 'string'
|
||||
)
|
||||
.map((block) => block.text)
|
||||
.join(separator);
|
||||
}
|
||||
|
||||
function isClaudeSyntheticUserMessage(entry: ClaudeTranscriptEntry, text: string): boolean {
|
||||
if (entry.isMeta || entry.isCompactSummary) return true;
|
||||
return /^(?:<local-command|<command-name>|<task-notification>|<system-reminder>|<teammate-message\b|Another Claude session sent a message:|Base directory for this skill:)/i.test(
|
||||
text
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude writes an append-only event log: tool results arrive as user rows,
|
||||
* thinking/tool_use rows carry no text, and a prompt typed while the agent is
|
||||
* working is only ever recorded as an `attachment/queued_command` row. But one
|
||||
* assistant row IS one whole model message: measured across ~/.claude/projects
|
||||
* (CLI 2.1.220-2.1.251) no assistant row carries more than one content block
|
||||
* and no message id carries more than one text block, so there is nothing to
|
||||
* reassemble. Emit one card per row and group them with `turn` instead of
|
||||
* concatenating a human turn's replies into a single card (#169), which fused
|
||||
* up to 74 distinct model messages into one card. Splitting is safe for
|
||||
* markdown: no adjacent pair of assistant text rows in the corpus continues a
|
||||
* table, a list, or an open code fence.
|
||||
*
|
||||
* The state is the parse so far, fed one line at a time, so a reader can stop at the end of the
|
||||
* file and go on from there when it grows.
|
||||
*/
|
||||
export class ClaudeResponseParser {
|
||||
private lastText = '';
|
||||
private lastTimestamp = '';
|
||||
private messages: ClaudeResponseMessage[] = [];
|
||||
// #169's replay guards, kept: they now SKIP a duplicated row instead of
|
||||
// concatenating it into the previous card.
|
||||
private currentUserFragments = new Set<string>();
|
||||
private currentAssistantFragments = new Set<string>();
|
||||
// Turn 0 is reserved for anything emitted before the first human prompt.
|
||||
private turn = 0;
|
||||
// Whether the current turn opened with Codeman's keep-warm nudge.
|
||||
private keepAliveTurn = false;
|
||||
|
||||
/** A parser in the same state, for parsing a line that may not be finished yet. */
|
||||
clone(): ClaudeResponseParser {
|
||||
const copy = new ClaudeResponseParser();
|
||||
copy.lastText = this.lastText;
|
||||
copy.lastTimestamp = this.lastTimestamp;
|
||||
copy.messages = this.messages.slice();
|
||||
copy.currentUserFragments = new Set(this.currentUserFragments);
|
||||
copy.currentAssistantFragments = new Set(this.currentAssistantFragments);
|
||||
copy.turn = this.turn;
|
||||
copy.keepAliveTurn = this.keepAliveTurn;
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** The parse so far. The messages array is a copy, so a later line never changes an answer. */
|
||||
result(): ClaudeResponseTranscript {
|
||||
return { text: this.lastText, timestamp: this.lastTimestamp, messages: this.messages.slice() };
|
||||
}
|
||||
|
||||
/** Feed text holding whole lines separated by `\n`. */
|
||||
feedLines(text: string): void {
|
||||
for (const line of text.split('\n')) this.feedLine(line);
|
||||
}
|
||||
|
||||
private pushUserMessage(text: string, timestamp: string | undefined, queued: boolean): void {
|
||||
// A run of consecutive human inputs (a mid-turn queued burst) is ONE turn,
|
||||
// so the viewer renders it under one badge instead of one badge per line.
|
||||
// The keep-warm nudge never joins an earlier user run: the turn before it
|
||||
// may have ended without assistant text (an interrupt before Claude wrote
|
||||
// anything, or a turn of tool calls only), and its reply belongs to the
|
||||
// keep-alive turn, not to the user's prompt.
|
||||
const isNudge = text === KEEP_WARM_NUDGE;
|
||||
if (isNudge || this.messages.at(-1)?.role !== 'user') {
|
||||
this.turn += 1;
|
||||
this.keepAliveTurn = isNudge;
|
||||
} else if (!isNudge) {
|
||||
// A prompt the user queued during the keep-warm turn makes the turn theirs.
|
||||
this.keepAliveTurn = false;
|
||||
}
|
||||
const message: ClaudeResponseMessage = {
|
||||
kind: 'prompt',
|
||||
label: 'Prompt',
|
||||
role: 'user',
|
||||
text,
|
||||
timestamp,
|
||||
turn: this.turn,
|
||||
};
|
||||
if (queued) message.queued = true;
|
||||
if (isNudge) message.keepAlive = true;
|
||||
this.messages.push(message);
|
||||
this.currentUserFragments.add(text);
|
||||
this.currentAssistantFragments.clear();
|
||||
}
|
||||
|
||||
feedLine(line: string): void {
|
||||
if (!line) return;
|
||||
let entry: ClaudeTranscriptEntry;
|
||||
try {
|
||||
entry = JSON.parse(line) as ClaudeTranscriptEntry;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// Sidechains belong to agents/forks, not the main conversation. Meta user
|
||||
// rows include repeated image dimensions and other UI-generated context.
|
||||
if (entry.isSidechain) return;
|
||||
|
||||
// A prompt typed while Claude is working is absorbed mid-turn and lives
|
||||
// ONLY in an attachment row, so it was lost outright. `origin.kind` and
|
||||
// `commandMode` separate the human's queue entries from the CLI's own:
|
||||
// measured over 57 real transcripts on 2026-09-01, 322 queued_command rows
|
||||
// split 163 `prompt`/`human` and 159 `task-notification`, and not one of
|
||||
// those 159 carries an `origin` key. The 163 human rows become 162 user
|
||||
// cards here — one is a verbatim repeat inside a still-unanswered user run
|
||||
// and is collapsed by the dedup guard below — out of 353 user cards total.
|
||||
if (entry.type === 'attachment') {
|
||||
const queued = entry.attachment;
|
||||
if (!queued || queued.type !== 'queued_command') return;
|
||||
if (queued.origin?.kind !== 'human' || queued.commandMode !== 'prompt') return;
|
||||
const text = typeof queued.prompt === 'string' ? queued.prompt.trim() : '';
|
||||
if (!text || isClaudeSyntheticUserMessage(entry, text)) return;
|
||||
if (this.currentUserFragments.has(text)) return;
|
||||
this.pushUserMessage(text, queued.timestamp || entry.timestamp, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (entry.type === 'user') {
|
||||
const text = extractClaudeText(entry.message?.content, '\n').trim();
|
||||
// A tool_result block has no text block and naturally drops out here.
|
||||
if (!text || isClaudeSyntheticUserMessage(entry, text)) return;
|
||||
// Claude replays the initial user row while restoring a transcript, and
|
||||
// a CLI that also wrote an absorbed prompt as a user row would double it.
|
||||
// Both collapse here. The same prompt sent again AFTER a reply is a
|
||||
// legitimate second turn, because that reply cleared the set.
|
||||
if (this.currentUserFragments.has(text)) return;
|
||||
this.pushUserMessage(text, entry.timestamp, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (entry.type !== 'assistant') return;
|
||||
const text = extractClaudeText(entry.message?.content, '\n\n').trim();
|
||||
if (!text) return;
|
||||
this.lastText = text;
|
||||
this.lastTimestamp = entry.timestamp || '';
|
||||
|
||||
// Replayed snapshots repeat an identical text block inside one turn.
|
||||
if (this.currentAssistantFragments.has(text)) return;
|
||||
const response: ClaudeResponseMessage = {
|
||||
kind: 'response',
|
||||
label: 'Response',
|
||||
role: 'assistant',
|
||||
text,
|
||||
timestamp: entry.timestamp,
|
||||
turn: this.turn,
|
||||
};
|
||||
if (this.keepAliveTurn) response.keepAlive = true;
|
||||
this.messages.push(response);
|
||||
this.currentAssistantFragments.add(text);
|
||||
this.currentUserFragments.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse a whole transcript at once. */
|
||||
export function parseClaudeResponseTranscript(content: string): ClaudeResponseTranscript {
|
||||
const parser = new ClaudeResponseParser();
|
||||
parser.feedLines(content);
|
||||
return parser.result();
|
||||
}
|
||||
|
||||
/** How many bytes before the offset a reader compares, to notice a file rewritten in place. */
|
||||
const CHECK_BYTES = 64;
|
||||
|
||||
interface CachedTranscript {
|
||||
parser: ClaudeResponseParser | null;
|
||||
dev: number;
|
||||
ino: number;
|
||||
/** The byte just after the last newline the parser consumed. */
|
||||
offset: number;
|
||||
/** The bytes that ended at `offset` when the parser reached it. */
|
||||
check: Buffer;
|
||||
running: Promise<ClaudeResponseTranscript> | null;
|
||||
queued: Promise<ClaudeResponseTranscript> | null;
|
||||
}
|
||||
|
||||
export interface ClaudeTranscriptReaderOptions {
|
||||
/** How many transcripts keep their parse. */
|
||||
maxEntries?: number;
|
||||
/** How many bytes one read call takes, and so how much one synchronous parse step covers. */
|
||||
chunkBytes?: number;
|
||||
}
|
||||
|
||||
/** Reads Claude transcripts, parsing each file's new bytes only. See the file overview. */
|
||||
export class ClaudeTranscriptReader {
|
||||
private readonly cache: LRUMap<string, CachedTranscript>;
|
||||
private readonly chunkBytes: number;
|
||||
|
||||
constructor(options: ClaudeTranscriptReaderOptions = {}) {
|
||||
this.cache = new LRUMap({ maxSize: options.maxEntries ?? 16 });
|
||||
this.chunkBytes = options.chunkBytes ?? 1024 * 1024;
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript at `path`, parsed to its current end. Rejects when the file cannot be read.
|
||||
*
|
||||
* A read asked for while another runs waits for it and then parses what was appended meanwhile,
|
||||
* so it never answers from before its own request. Every read asked for during that wait
|
||||
* shares the one pass that follows.
|
||||
*/
|
||||
read(path: string): Promise<ClaudeResponseTranscript> {
|
||||
let entry = this.cache.get(path);
|
||||
if (!entry) {
|
||||
entry = { parser: null, dev: 0, ino: 0, offset: 0, check: Buffer.alloc(0), running: null, queued: null };
|
||||
this.cache.set(path, entry);
|
||||
}
|
||||
const cached = entry;
|
||||
if (cached.queued) return cached.queued;
|
||||
if (cached.running) {
|
||||
cached.queued = cached.running
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
cached.queued = null;
|
||||
return this.start(path, cached);
|
||||
});
|
||||
return cached.queued;
|
||||
}
|
||||
return this.start(path, cached);
|
||||
}
|
||||
|
||||
private start(path: string, entry: CachedTranscript): Promise<ClaudeResponseTranscript> {
|
||||
entry.running = this.update(path, entry).finally(() => {
|
||||
entry.running = null;
|
||||
});
|
||||
return entry.running;
|
||||
}
|
||||
|
||||
private async update(path: string, entry: CachedTranscript): Promise<ClaudeResponseTranscript> {
|
||||
const handle = await fs.open(path, 'r');
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile()) throw new Error(`not a file: ${path}`);
|
||||
|
||||
let reset = !entry.parser || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size < entry.offset;
|
||||
if (!reset && entry.check.length > 0) {
|
||||
const now = Buffer.alloc(entry.check.length);
|
||||
const { bytesRead } = await handle.read(now, 0, now.length, entry.offset - now.length);
|
||||
reset = bytesRead !== now.length || !now.equals(entry.check);
|
||||
}
|
||||
if (reset || !entry.parser) {
|
||||
entry.parser = new ClaudeResponseParser();
|
||||
entry.dev = stat.dev;
|
||||
entry.ino = stat.ino;
|
||||
entry.offset = 0;
|
||||
entry.check = Buffer.alloc(0);
|
||||
}
|
||||
const parser = entry.parser;
|
||||
|
||||
// Read to the size the stat saw; bytes written after it wait for the next read.
|
||||
let position = entry.offset;
|
||||
let carry = Buffer.alloc(0);
|
||||
while (position < stat.size) {
|
||||
const chunk = Buffer.allocUnsafe(Math.min(this.chunkBytes, stat.size - position));
|
||||
const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
|
||||
if (bytesRead === 0) break;
|
||||
position += bytesRead;
|
||||
const data =
|
||||
carry.length > 0 ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
|
||||
// A newline byte never occurs inside a multi-byte UTF-8 character, so cutting there is safe.
|
||||
const newline = data.lastIndexOf(0x0a);
|
||||
if (newline === -1) {
|
||||
carry = data;
|
||||
continue;
|
||||
}
|
||||
parser.feedLines(data.toString('utf8', 0, newline));
|
||||
entry.offset = position - (data.length - newline - 1);
|
||||
entry.check = Buffer.from(data.subarray(Math.max(0, newline + 1 - CHECK_BYTES), newline + 1));
|
||||
carry = Buffer.from(data.subarray(newline + 1));
|
||||
}
|
||||
|
||||
if (carry.length === 0) return parser.result();
|
||||
const unfinished = parser.clone();
|
||||
unfinished.feedLine(carry.toString('utf8'));
|
||||
return unfinished.result();
|
||||
} catch (err) {
|
||||
// A parse left part-way is not trusted: the next read starts from byte 0.
|
||||
entry.parser = null;
|
||||
throw err;
|
||||
} finally {
|
||||
await handle.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,6 +289,10 @@ const _SSE_HANDLER_MAP = [
|
||||
// (and its turn ends, from _onSessionIdle: one handler per event in this map)
|
||||
[SSE_EVENTS.TRANSCRIPT_TOOL_END, '_onEditHistoryTranscriptEvent'],
|
||||
|
||||
// Chat view (chat-view.js): re-read the conversation as the transcript grows. Turn starts and
|
||||
// ends reach it from _onSessionWorking / _onSessionIdle.
|
||||
[SSE_EVENTS.TRANSCRIPT_UPDATE, '_onChatViewTranscriptUpdate'],
|
||||
|
||||
// Tunnel
|
||||
[SSE_EVENTS.TUNNEL_STARTED, '_onTunnelStarted'],
|
||||
[SSE_EVENTS.TUNNEL_STOPPED, '_onTunnelStopped'],
|
||||
@@ -535,6 +539,16 @@ const DEFAULT_SHORTCUTS = [
|
||||
bindings: [{ modifiers: ['alt'], key: 'b', code: 'KeyB' }],
|
||||
action: 'toggleSessionSidebar',
|
||||
},
|
||||
{
|
||||
id: 'toggle-chat-view',
|
||||
group: 'Session',
|
||||
label: 'Toggle Chat / Terminal View',
|
||||
// Alt+Shift+C: no browser binds it, and the xterm key handler swallows it only while the
|
||||
// active session can show the chat view (shouldToggleChatViewFromShortcut), so elsewhere
|
||||
// the chord still reaches the terminal.
|
||||
bindings: [{ modifiers: ['alt', 'shift'], key: 'C', code: 'KeyC' }],
|
||||
action: 'toggleChatView',
|
||||
},
|
||||
// Tile grid (tile-grid.js). Dispatched by tileShortcutFor()/runTileShortcut()
|
||||
// and deliberately absent from SHORTCUT_ACTIONS: each applies only in some
|
||||
// states (the focus chords only while the grid is open), and outside them the
|
||||
@@ -1159,6 +1173,8 @@ class CodemanApp {
|
||||
this.tabAlerts.set(sessionId, 'idle');
|
||||
}
|
||||
this.renderSessionTabs();
|
||||
// An open chat view shows a dialog the pane is waiting on (chat-view.js).
|
||||
this.onChatViewHooksChanged?.(sessionId);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -2435,6 +2451,8 @@ class CodemanApp {
|
||||
if (session.id === this.activeSessionId) this._reconcileKeyboardHold?.();
|
||||
// The agent moved into or out of a git worktree while the Files panel is open (#765).
|
||||
if (session.id === this.activeSessionId) this._followFileBrowserWorktree?.(session);
|
||||
// A started or switched agent can change whether the chat view applies (chat-view.js).
|
||||
if (session.id === this.activeSessionId) this._chatViewSync?.();
|
||||
// Update parentSessionName for any subagents belonging to this session
|
||||
// (fixes stale name display after session rename)
|
||||
this.updateSubagentParentNames(session.id);
|
||||
@@ -2462,6 +2480,7 @@ class CodemanApp {
|
||||
// Dashboard: a detached session ended → clear its detached state/timers.
|
||||
if (this.detachedSessions.has(data.id)) this._redock(data.id);
|
||||
this._cleanupSessionData(data.id);
|
||||
this._chatViewForget?.(data.id);
|
||||
// ⚠️ Skip the whole active-session handoff while THIS tab is closing that
|
||||
// session: closeSession() owns the follow-up selection and moves you to the
|
||||
// next tab, so acting here would race it and flash the welcome screen (or
|
||||
@@ -3656,6 +3675,7 @@ class CodemanApp {
|
||||
// An open Edit history panel re-reads at the end of its session's turn (edit-history-ui.js),
|
||||
// not after Codeman's own keep-alive turn, which edits nothing.
|
||||
if (!data.keepAlive) this.onEditHistorySessionIdle?.(data.id);
|
||||
this.onChatViewTurnEvent?.(data.id, true, data.keepAlive);
|
||||
// Start stuck detection timer (only if no respawn running). Not at the end of Codeman's
|
||||
// own keep-alive turn (`keepAlive`): the session has been waiting since the last real
|
||||
// turn, whose timer is still running or has already fired.
|
||||
@@ -3681,6 +3701,7 @@ class CodemanApp {
|
||||
this.sendPendingCtrlL(data.id);
|
||||
if (data.id === this.activeSessionId) this._updateLocalEchoState();
|
||||
}
|
||||
this.onChatViewTurnEvent?.(data.id, false, data.keepAlive);
|
||||
// Clear stuck detection timer, unless this is Codeman's own keep-alive turn, which is
|
||||
// no sign of life from the agent's side.
|
||||
const timer = data.keepAlive ? null : this.idleTimers.get(data.id);
|
||||
@@ -5116,6 +5137,8 @@ class CodemanApp {
|
||||
});
|
||||
}
|
||||
});
|
||||
// The chat view's per-device choices of sessions that are gone (chat-view.js).
|
||||
this._chatViewPruneModes?.(new Set(data.sessions.map((s) => s.id)));
|
||||
|
||||
// Server is source of truth for open sessions — don't resurrect stale tabs
|
||||
// from localStorage (would show phantom "ended" tabs when a session was closed
|
||||
@@ -5275,6 +5298,9 @@ class CodemanApp {
|
||||
// The fresh session record may no longer qualify for a keyboard row hold.
|
||||
this._reconcileKeyboardHold?.();
|
||||
void this._onSessionNeedsRefresh({ id: restoreId });
|
||||
// The transcript events sent during the outage are lost, so the chat view re-reads the
|
||||
// conversation now (a no-op while Chat is not showing).
|
||||
this._chatViewReload?.({ immediate: true });
|
||||
// The split pane's second terminal reconnects on its own backoff (up to
|
||||
// 10 s between tries); the server is back now, so skip the wait. A no-op
|
||||
// while its socket is open, stopped for good, or destroyed.
|
||||
@@ -10095,6 +10121,8 @@ class CodemanApp {
|
||||
this.refreshHostWakeBanner?.(sessionId);
|
||||
// An open Edit history panel follows the active session (edit-history-ui.js; no poll).
|
||||
this.onEditHistoryActiveSession?.(sessionId);
|
||||
// The chat view follows the active session too, showing it or the terminal (chat-view.js).
|
||||
this.onChatViewActiveSession?.(sessionId);
|
||||
|
||||
// Restore flushed offset AND text IMMEDIATELY so backspace/typing work during
|
||||
// the async buffer load. Without this, the offset is 0 during the
|
||||
@@ -11312,6 +11340,7 @@ class CodemanApp {
|
||||
moveActiveTabLeft: () => this.moveActiveTabLeft(),
|
||||
moveActiveTabRight: () => this.moveActiveTabRight(),
|
||||
toggleSessionSidebar: () => this.toggleSessionSidebar(),
|
||||
toggleChatView: () => this.toggleChatView?.(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
/**
|
||||
* @fileoverview Chat view: a session's conversation, rendered like the Response Viewer, as the
|
||||
* session's main view (docs/chat-view-plan.md, phase 1).
|
||||
*
|
||||
* The agent keeps running in its tmux pane. The chat view is a second way to look at that pane:
|
||||
* it covers the terminal (which stays mounted, attached and sized, so the PTY is never resized
|
||||
* by a view switch) and draws the conversation from the session's transcript.
|
||||
*
|
||||
* - Which sessions can have it: those whose run mode Codeman reads from a Claude-format
|
||||
* transcript (`window.__codemanChatViewModes`, published from the `transcript` capability,
|
||||
* never an id list here), local or Docker, not remote and not adopted, and not on a phone.
|
||||
* - Which view a session shows: the per-device choice remembered for that session
|
||||
* (`codeman:chatViewModes` in localStorage), else the per-device setting `chatViewDefault`
|
||||
* (default off, so a session opens in Terminal until the user picks Chat).
|
||||
* - The Chat / Terminal switch: shown on an eligible session unless the per-device setting
|
||||
* `showChatViewSwitch` is false (an absent key means shown). Hiding it changes nothing else:
|
||||
* the session keeps its view, and Alt+Shift+C still switches.
|
||||
* - Live updates: the conversation is re-read (debounced) on the session's `transcript:update`,
|
||||
* `session:working` and `session:idle`. Nothing is read while the chat view is hidden.
|
||||
* - Typing: the chat view has no message box yet, so the user types in the terminal. A focus
|
||||
* that lands on the hidden terminal moves to the conversation, so keys never reach the pane
|
||||
* unseen.
|
||||
* - A dialog in the pane (permission, question, plan approval) shows as a notice with a button
|
||||
* that switches to the terminal, where it is answered.
|
||||
*
|
||||
* Messages are model and user text: they go through the Response Viewer's sanitising markdown
|
||||
* pipeline (`_buildResponseViewerMessage`), and everything else is set with `textContent`.
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency app.js (this.activeSessionId, this.sessions, this.pendingHooks, _buildResponseViewerMessage,
|
||||
* _bindResponseViewerInteractions, _getResponseViewerAgentLabel)
|
||||
* @dependency constants.js (CodemanChatView)
|
||||
* @dependency api-client.js at runtime (this._apiJson)
|
||||
* @loadorder 12.595 of 16, after local-model-ui.js, before entrance-animations.js
|
||||
*/
|
||||
|
||||
const CHAT_VIEW_MODES_KEY = 'codeman:chatViewModes';
|
||||
/** Wait after an update before re-reading, so a burst of events costs one read. */
|
||||
const CHAT_VIEW_RELOAD_DEBOUNCE_MS = 250;
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
// ─── Eligibility and choice ──────────────────────────────────
|
||||
|
||||
/** Whether `sessionId` can show the chat view on this device. */
|
||||
chatViewEligible(sessionId) {
|
||||
const session = sessionId ? this.sessions?.get(sessionId) : null;
|
||||
if (!session) return false;
|
||||
const modes = Array.isArray(window.__codemanChatViewModes) ? window.__codemanChatViewModes : [];
|
||||
if (!session.mode || !modes.includes(session.mode)) return false;
|
||||
// A remote session's transcript lives on its host, and an adopted one has none Codeman can name.
|
||||
if (session.remote || session.adopt) return false;
|
||||
// Phones keep the terminal and its keyboard bars (phase 3 lays the chat view out for them),
|
||||
// whatever their orientation or fold: a phone turned to landscape is still a phone.
|
||||
if (typeof MobileDetection !== 'undefined') {
|
||||
const phone = MobileDetection.isHandheldDevice?.() ?? MobileDetection.getDeviceType?.() === 'mobile';
|
||||
if (phone) return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
/** The per-device choice for each session, `{ [sessionId]: 'chat' | 'terminal' }`. */
|
||||
_chatViewStoredModes() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(CHAT_VIEW_MODES_KEY) || '{}');
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
|
||||
_chatViewStoreModes(modes) {
|
||||
try {
|
||||
localStorage.setItem(CHAT_VIEW_MODES_KEY, JSON.stringify(modes));
|
||||
} catch {
|
||||
// Storage blocked: the choice lasts for this page load only.
|
||||
}
|
||||
},
|
||||
|
||||
/** 'chat' or 'terminal' for `sessionId`. */
|
||||
chatViewModeFor(sessionId) {
|
||||
const stored = this._chatViewStoredModes()[sessionId];
|
||||
if (stored === 'chat' || stored === 'terminal') return stored;
|
||||
if (this._chatViewMemoryModes?.has(sessionId)) return this._chatViewMemoryModes.get(sessionId);
|
||||
return this.loadAppSettingsFromStorage?.().chatViewDefault === true ? 'chat' : 'terminal';
|
||||
},
|
||||
|
||||
setChatViewMode(sessionId, mode) {
|
||||
if (!sessionId || (mode !== 'chat' && mode !== 'terminal')) return;
|
||||
if (!this._chatViewMemoryModes) this._chatViewMemoryModes = new Map();
|
||||
this._chatViewMemoryModes.set(sessionId, mode);
|
||||
const modes = this._chatViewStoredModes();
|
||||
modes[sessionId] = mode;
|
||||
this._chatViewStoreModes(modes);
|
||||
if (sessionId === this.activeSessionId) this._chatViewSync({ focus: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Called after each init (app.js) with the server's session list: drop the view choice of every
|
||||
* session not in it. A session deleted while no page was open sends this page no event.
|
||||
*/
|
||||
_chatViewPruneModes(liveIds) {
|
||||
for (const id of [...(this._chatViewMemoryModes?.keys() ?? [])]) {
|
||||
if (!liveIds.has(id)) this._chatViewMemoryModes.delete(id);
|
||||
}
|
||||
const modes = this._chatViewStoredModes();
|
||||
const kept = Object.fromEntries(Object.entries(modes).filter(([id]) => liveIds.has(id)));
|
||||
if (Object.keys(kept).length !== Object.keys(modes).length) this._chatViewStoreModes(kept);
|
||||
},
|
||||
|
||||
/** Whether this device shows the Chat / Terminal switch. An absent setting means it does. */
|
||||
_chatViewSwitchShown() {
|
||||
return this.loadAppSettingsFromStorage?.().showChatViewSwitch !== false;
|
||||
},
|
||||
|
||||
/** The Alt+Shift+C action: flip the active session between Chat and Terminal. */
|
||||
toggleChatView() {
|
||||
const id = this.activeSessionId;
|
||||
if (!this.chatViewEligible(id) || this._tilesOwnTerminal?.()) return;
|
||||
this.setChatViewMode(id, this.chatViewModeFor(id) === 'chat' ? 'terminal' : 'chat');
|
||||
},
|
||||
|
||||
/**
|
||||
* True when `e` is the chat view toggle chord and it applies here, so the xterm key handler
|
||||
* swallows it. Outside a session that can show the chat view, the chord reaches the terminal.
|
||||
*/
|
||||
shouldToggleChatViewFromShortcut(e) {
|
||||
if (!e || (!e.ctrlKey && !e.metaKey && !e.altKey)) return false;
|
||||
if (!this.chatViewEligible(this.activeSessionId) || this._tilesOwnTerminal?.()) return false;
|
||||
if (typeof this.getShortcutRegistry !== 'function' || typeof this.matchesShortcutEvent !== 'function') return false;
|
||||
const shortcut = this.getShortcutRegistry().find((s) => s.id === 'toggle-chat-view');
|
||||
if (!shortcut || shortcut.disabled) return false;
|
||||
return this.matchesShortcutEvent(e, shortcut);
|
||||
},
|
||||
|
||||
// ─── DOM ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* `text` in the page's language. i18n.js translates the DOM as it changes, but it skips every
|
||||
* <textarea> and the `data-i18n-skip` conversation, so the strings drawn there are looked up here.
|
||||
*/
|
||||
_chatViewT(text, vars) {
|
||||
return window.CodemanI18n?.t?.(text, vars) ?? text;
|
||||
},
|
||||
|
||||
_chatViewEnsureDom() {
|
||||
if (this._chatView) return this._chatView;
|
||||
const wrap = document.querySelector('.terminal-wrap');
|
||||
if (!wrap) return null;
|
||||
|
||||
const toggle = document.createElement('div');
|
||||
toggle.className = 'chat-view-toggle';
|
||||
toggle.setAttribute('role', 'group');
|
||||
toggle.setAttribute('aria-label', 'Session view');
|
||||
toggle.hidden = true;
|
||||
const chatBtn = document.createElement('button');
|
||||
chatBtn.type = 'button';
|
||||
chatBtn.className = 'chat-view-toggle-btn';
|
||||
chatBtn.dataset.mode = 'chat';
|
||||
chatBtn.textContent = 'Chat';
|
||||
chatBtn.title = 'Show the conversation (Alt+Shift+C)';
|
||||
const termBtn = document.createElement('button');
|
||||
termBtn.type = 'button';
|
||||
termBtn.className = 'chat-view-toggle-btn';
|
||||
termBtn.dataset.mode = 'terminal';
|
||||
termBtn.textContent = 'Terminal';
|
||||
termBtn.title = 'Show the terminal (Alt+Shift+C)';
|
||||
toggle.append(chatBtn, termBtn);
|
||||
toggle.addEventListener('click', (ev) => {
|
||||
const btn = ev.target.closest('.chat-view-toggle-btn');
|
||||
if (btn && this.activeSessionId) this.setChatViewMode(this.activeSessionId, btn.dataset.mode);
|
||||
});
|
||||
|
||||
const root = document.createElement('section');
|
||||
root.className = 'chat-view';
|
||||
root.setAttribute('aria-label', 'Conversation');
|
||||
root.hidden = true;
|
||||
|
||||
// The Response Viewer's body class: the chat view renders exactly as the viewer does.
|
||||
const scroller = document.createElement('div');
|
||||
scroller.className = 'chat-view-scroll response-viewer-body';
|
||||
scroller.setAttribute('data-i18n-skip', '');
|
||||
// Focusable, so a focus taken from the hidden terminal has somewhere to go.
|
||||
scroller.tabIndex = -1;
|
||||
const thread = document.createElement('div');
|
||||
thread.className = 'chat-view-thread';
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'chat-view-empty';
|
||||
empty.hidden = true;
|
||||
scroller.append(thread, empty);
|
||||
|
||||
const dialog = document.createElement('div');
|
||||
dialog.className = 'chat-view-dialog';
|
||||
dialog.setAttribute('role', 'status');
|
||||
dialog.hidden = true;
|
||||
const dialogText = document.createElement('span');
|
||||
dialogText.className = 'chat-view-dialog-text';
|
||||
dialogText.textContent = 'Claude is waiting for your answer in the terminal.';
|
||||
const dialogBtn = document.createElement('button');
|
||||
dialogBtn.type = 'button';
|
||||
dialogBtn.className = 'chat-view-btn chat-view-btn-primary';
|
||||
dialogBtn.textContent = 'Open terminal';
|
||||
dialogBtn.addEventListener('click', () => {
|
||||
const id = this.activeSessionId;
|
||||
if (!id) return;
|
||||
this.setChatViewMode(id, 'terminal');
|
||||
this.terminal?.focus?.();
|
||||
});
|
||||
dialog.append(dialogText, dialogBtn);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'chat-view-status';
|
||||
status.setAttribute('role', 'status');
|
||||
status.setAttribute('aria-live', 'polite');
|
||||
status.hidden = true;
|
||||
const statusDot = document.createElement('span');
|
||||
statusDot.className = 'chat-view-status-dot';
|
||||
statusDot.setAttribute('aria-hidden', 'true');
|
||||
const statusBody = document.createElement('div');
|
||||
statusBody.className = 'chat-view-status-body';
|
||||
const statusText = document.createElement('div');
|
||||
statusText.className = 'chat-view-status-text';
|
||||
statusBody.append(statusText);
|
||||
status.append(statusDot, statusBody);
|
||||
|
||||
// The status line follows the last message, inside the scrolling area, so an eye watching
|
||||
// the newest output finds it there and not at the bottom of the window.
|
||||
scroller.insertBefore(status, empty);
|
||||
root.append(scroller, dialog);
|
||||
wrap.append(root, toggle);
|
||||
|
||||
// Keys must never reach the hidden terminal: a focus that lands there (a click-through, a
|
||||
// code path that refocuses the terminal after a load) moves to the conversation. That covers
|
||||
// #terminalContainer and #cjkInput, which takes terminal.focus() while CJK input is on and
|
||||
// sits outside the container, under the chat layer.
|
||||
const redirectFocus = () => {
|
||||
if (this._chatViewShowing()) this._chatView?.scroller.focus({ preventScroll: true });
|
||||
};
|
||||
document.getElementById('terminalContainer')?.addEventListener('focusin', redirectFocus);
|
||||
document.getElementById('cjkInput')?.addEventListener('focusin', redirectFocus);
|
||||
|
||||
// A file dropped on the conversation or on the Chat / Terminal switch must not make the
|
||||
// browser open it and leave Codeman. Nothing is uploaded here: an upload would type the file's
|
||||
// path into the hidden pane, and attaching belongs to the message box (docs/chat-view-plan.md,
|
||||
// phase 1 step 2). The no-drop cursor tells a user who drags a file here that Chat takes none.
|
||||
const refuseDragOver = (ev) => {
|
||||
ev.preventDefault();
|
||||
if (ev.dataTransfer) ev.dataTransfer.dropEffect = 'none';
|
||||
};
|
||||
const refuseDrop = (ev) => ev.preventDefault();
|
||||
for (const target of [root, toggle]) {
|
||||
target.addEventListener('dragover', refuseDragOver);
|
||||
target.addEventListener('drop', refuseDrop);
|
||||
}
|
||||
|
||||
this._chatView = {
|
||||
root,
|
||||
toggle,
|
||||
chatBtn,
|
||||
termBtn,
|
||||
scroller,
|
||||
thread,
|
||||
empty,
|
||||
dialog,
|
||||
status,
|
||||
statusText,
|
||||
sessionId: null,
|
||||
keys: [],
|
||||
reloadTimer: null,
|
||||
statusTimer: null,
|
||||
loading: false,
|
||||
reloadAgain: false,
|
||||
};
|
||||
return this._chatView;
|
||||
},
|
||||
|
||||
/** Whether the chat view is what the main area shows right now. */
|
||||
_chatViewShowing() {
|
||||
return !!this._chatView && !this._chatView.root.hidden;
|
||||
},
|
||||
|
||||
/** Whether keyboard focus sits in the terminal: inside #terminalContainer, or on #cjkInput. */
|
||||
_chatViewFocusInTerminal() {
|
||||
const active = document.activeElement;
|
||||
if (!active) return false;
|
||||
if (active.id === 'cjkInput') return true;
|
||||
return !!document.getElementById('terminalContainer')?.contains(active);
|
||||
},
|
||||
|
||||
// ─── Sync with the active session ────────────────────────────
|
||||
|
||||
/** app.js selectSession(): the active session changed. */
|
||||
onChatViewActiveSession() {
|
||||
this._chatViewSync({ focus: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Show or hide the toggle and the chat view for the active session, and (re)load the
|
||||
* conversation when the chat view starts showing a session.
|
||||
*/
|
||||
_chatViewSync(opts = {}) {
|
||||
const id = this.activeSessionId;
|
||||
const eligible = this.chatViewEligible(id);
|
||||
if (!eligible && !this._chatView) return;
|
||||
const view = this._chatViewEnsureDom();
|
||||
if (!view) return;
|
||||
// Focus follows the app's tab-switch rule, as the terminal's does.
|
||||
const focus = !!opts.focus && (this._shouldFocusTerminalForTabSwitch?.() ?? true);
|
||||
const mode = eligible ? this.chatViewModeFor(id) : 'terminal';
|
||||
// The tile grid owns the terminal area while it is open, and its tiles are terminals: the
|
||||
// chat view stays hidden, whatever the active session's choice (tile-grid.js syncs it).
|
||||
const showChat = eligible && mode === 'chat' && !this._tilesOwnTerminal?.();
|
||||
|
||||
// The setting hides only the switch: the session keeps its view, and Alt+Shift+C still works.
|
||||
view.toggle.hidden = !eligible || !this._chatViewSwitchShown();
|
||||
view.chatBtn.setAttribute('aria-pressed', String(showChat));
|
||||
view.termBtn.setAttribute('aria-pressed', String(!showChat));
|
||||
view.toggle.classList.toggle('chat-view-toggle--over-chat', showChat);
|
||||
|
||||
const wasShowing = !view.root.hidden;
|
||||
const previousId = view.sessionId;
|
||||
view.root.hidden = !showChat;
|
||||
document.querySelector('.terminal-wrap')?.classList.toggle('chat-view-active', showChat);
|
||||
// styles.css hides the keyboard accessory bar while this is set: its keys write into the pane.
|
||||
document.body.classList.toggle('chat-view-showing', showChat);
|
||||
if (!showChat) {
|
||||
if (view.statusTimer) {
|
||||
clearInterval(view.statusTimer);
|
||||
view.statusTimer = null;
|
||||
}
|
||||
if (wasShowing && focus && eligible) this.terminal?.focus?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousId !== id) {
|
||||
view.sessionId = id;
|
||||
view.keys = [];
|
||||
view.thread.replaceChildren();
|
||||
view.empty.hidden = true;
|
||||
}
|
||||
const agent = this._getResponseViewerAgentLabel?.() || 'Claude';
|
||||
view.root.querySelector('.chat-view-dialog-text').textContent =
|
||||
`${agent} is waiting for your answer in the terminal.`;
|
||||
this._chatViewSyncDialog(id);
|
||||
this._chatViewRenderStatus();
|
||||
if (previousId !== id || !wasShowing) this._chatViewReload({ immediate: true });
|
||||
// A terminal that already has focus fires no new focusin, so hardware-keyboard input would
|
||||
// keep reaching the pane behind the chat view. Move that focus now, whatever the tab-switch
|
||||
// rule says: focusing the conversation opens no soft keyboard.
|
||||
if (this._chatViewFocusInTerminal()) view.scroller.focus({ preventScroll: true });
|
||||
if (focus) requestAnimationFrame(() => view.scroller.focus({ preventScroll: true }));
|
||||
},
|
||||
|
||||
/** Hide everything (home screen, session gone). */
|
||||
_chatViewHide() {
|
||||
if (!this._chatView) return;
|
||||
if (this._chatView.statusTimer) {
|
||||
clearInterval(this._chatView.statusTimer);
|
||||
this._chatView.statusTimer = null;
|
||||
}
|
||||
this._chatView.root.hidden = true;
|
||||
this._chatView.toggle.hidden = true;
|
||||
document.querySelector('.terminal-wrap')?.classList.remove('chat-view-active');
|
||||
document.body.classList.remove('chat-view-showing');
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when a session is deleted (app.js): forget its turn state. The view choice stays, because
|
||||
* a detach sends the same event and the session can be attached again; `_chatViewPruneModes`
|
||||
* drops the choices of sessions that are gone.
|
||||
*/
|
||||
_chatViewForget(sessionId) {
|
||||
this._chatViewTurnStarts?.delete(sessionId);
|
||||
this._chatViewIdleSeen?.delete(sessionId);
|
||||
this._chatViewKeepAliveTurns?.delete(sessionId);
|
||||
if (this._chatView?.sessionId === sessionId) {
|
||||
this._chatView.sessionId = null;
|
||||
this._chatView.keys = [];
|
||||
this._chatView.thread.replaceChildren();
|
||||
}
|
||||
},
|
||||
|
||||
// ─── Events ──────────────────────────────────────────────────
|
||||
|
||||
/** SSE `transcript:update`: new transcript lines for `data.sessionId`. */
|
||||
_onChatViewTranscriptUpdate(data) {
|
||||
if (data?.sessionId && data.sessionId === this._chatView?.sessionId && this._chatViewShowing()) {
|
||||
this._chatViewReload();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* app.js `_onSessionIdle` / `_onSessionWorking`: a turn started or ended. `keepAlive` marks
|
||||
* Codeman's own keep-warm turn, which the conversation hides: the status line stays hidden
|
||||
* for it.
|
||||
*/
|
||||
onChatViewTurnEvent(sessionId, idle, keepAlive) {
|
||||
if (!this._chatViewTurnStarts) this._chatViewTurnStarts = new Map();
|
||||
if (!this._chatViewIdleSeen) this._chatViewIdleSeen = new Set();
|
||||
if (!this._chatViewKeepAliveTurns) this._chatViewKeepAliveTurns = new Set();
|
||||
if (!idle && keepAlive) this._chatViewKeepAliveTurns.add(sessionId);
|
||||
else this._chatViewKeepAliveTurns.delete(sessionId);
|
||||
// A turn's start is "now" only when this page saw the session idle first. A working event
|
||||
// for a session already busy when the page loaded (or the server restarted) says nothing
|
||||
// about when its turn began, so the status line falls back to the last Enter.
|
||||
if (!idle && this._chatViewIdleSeen.has(sessionId)) {
|
||||
this._chatViewIdleSeen.delete(sessionId);
|
||||
this._chatViewTurnStarts.set(sessionId, Date.now());
|
||||
}
|
||||
if (idle) {
|
||||
this._chatViewIdleSeen.add(sessionId);
|
||||
this._chatViewTurnStarts.delete(sessionId);
|
||||
}
|
||||
if (sessionId !== this._chatView?.sessionId || !this._chatViewShowing()) return;
|
||||
this._chatViewRenderStatus();
|
||||
this._chatViewReload();
|
||||
},
|
||||
|
||||
/** app.js updateTabAlertFromHooks(): a dialog appeared or was answered. */
|
||||
onChatViewHooksChanged(sessionId) {
|
||||
if (sessionId !== this._chatView?.sessionId || !this._chatViewShowing()) return;
|
||||
this._chatViewSyncDialog(sessionId);
|
||||
},
|
||||
|
||||
/** Whether the pane shows a dialog (permission, question, plan approval), answered in the terminal. */
|
||||
_chatViewDialogPending(sessionId) {
|
||||
const hooks = this.pendingHooks?.get(sessionId);
|
||||
return !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog'));
|
||||
},
|
||||
|
||||
_chatViewSyncDialog(sessionId) {
|
||||
const view = this._chatView;
|
||||
if (!view) return;
|
||||
view.dialog.hidden = !this._chatViewDialogPending(sessionId);
|
||||
},
|
||||
|
||||
/** Whether `sessionId` runs a turn the chat view shows: busy, and not Codeman's keep-alive turn. */
|
||||
_chatViewBusy(sessionId) {
|
||||
if (this._chatViewKeepAliveTurns?.has(sessionId)) return false;
|
||||
return this.sessions?.get(sessionId)?.status === 'busy';
|
||||
},
|
||||
|
||||
_chatViewRenderStatus() {
|
||||
const view = this._chatView;
|
||||
if (!view) return;
|
||||
const session = this.sessions?.get(view.sessionId);
|
||||
const busy = this._chatViewBusy(view.sessionId);
|
||||
// Keep the view pinned to the bottom when the status line appears under the last message,
|
||||
// if the reader was already there.
|
||||
const scroller = view.scroller;
|
||||
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;
|
||||
view.status.hidden = !busy;
|
||||
if (!busy && view.sessionId) {
|
||||
if (!this._chatViewIdleSeen) this._chatViewIdleSeen = new Set();
|
||||
this._chatViewIdleSeen.add(view.sessionId);
|
||||
}
|
||||
if (busy) {
|
||||
const activity = this._chatViewT('Working');
|
||||
// The turn's start: seen live (session:working after idle), else the last Enter (a page
|
||||
// loaded mid-turn), else unknown and left out.
|
||||
const startedAt = this._chatViewTurnStarts?.get(view.sessionId) || session?.lastSubmitAt || 0;
|
||||
view.statusText.textContent = startedAt
|
||||
? `${activity} · ${window.CodemanChatView.elapsed(Date.now() - startedAt)}`
|
||||
: activity;
|
||||
}
|
||||
// The running time ticks once a second, only while the status line is on screen.
|
||||
const ticking = busy && this._chatViewShowing();
|
||||
if (ticking && !view.statusTimer) view.statusTimer = setInterval(() => this._chatViewRenderStatus(), 1000);
|
||||
if (!ticking && view.statusTimer) {
|
||||
clearInterval(view.statusTimer);
|
||||
view.statusTimer = null;
|
||||
}
|
||||
if (atBottom) scroller.scrollTop = scroller.scrollHeight;
|
||||
},
|
||||
|
||||
// ─── Reading and drawing the conversation ────────────────────
|
||||
|
||||
/** Re-read the conversation, debounced unless `immediate`. One read at a time. */
|
||||
_chatViewReload(opts = {}) {
|
||||
const view = this._chatView;
|
||||
if (!view || !view.sessionId) return;
|
||||
clearTimeout(view.reloadTimer);
|
||||
if (opts.immediate) {
|
||||
this._chatViewFetch();
|
||||
return;
|
||||
}
|
||||
view.reloadTimer = setTimeout(() => this._chatViewFetch(), CHAT_VIEW_RELOAD_DEBOUNCE_MS);
|
||||
},
|
||||
|
||||
async _chatViewFetch() {
|
||||
const view = this._chatView;
|
||||
if (!view || !view.sessionId || !this._chatViewShowing()) return;
|
||||
if (view.loading) {
|
||||
view.reloadAgain = true;
|
||||
return;
|
||||
}
|
||||
const sessionId = view.sessionId;
|
||||
view.loading = true;
|
||||
try {
|
||||
const data = await this._apiJson(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`);
|
||||
// A read that finished after the user moved on is dropped.
|
||||
if (view.sessionId !== sessionId || !this._chatViewShowing()) return;
|
||||
if (data && Array.isArray(data.messages)) this._chatViewRender(data.messages);
|
||||
} finally {
|
||||
view.loading = false;
|
||||
if (view.reloadAgain) {
|
||||
view.reloadAgain = false;
|
||||
this._chatViewReload();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
_chatViewRender(rawMessages) {
|
||||
const view = this._chatView;
|
||||
const helpers = window.CodemanChatView;
|
||||
if (!view || !helpers) return;
|
||||
const messages = helpers.visibleMessages(rawMessages);
|
||||
const keys = messages.map(helpers.messageKey);
|
||||
const plan = helpers.renderPlan(view.keys, keys);
|
||||
view.empty.hidden = messages.length > 0;
|
||||
if (messages.length === 0) view.empty.textContent = this._chatViewT('No messages yet.');
|
||||
if (plan.mode === 'none') return;
|
||||
|
||||
const scroller = view.scroller;
|
||||
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;
|
||||
const firstDraw = view.keys.length === 0;
|
||||
const from = plan.mode === 'append' ? plan.from : 0;
|
||||
if (plan.mode === 'replace') view.thread.replaceChildren();
|
||||
|
||||
const agentLabel = this._getResponseViewerAgentLabel?.() || 'Claude';
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (let i = from; i < messages.length; i++) {
|
||||
const msg = messages[i];
|
||||
const previous = i > 0 ? messages[i - 1] : null;
|
||||
// Same rule as the Response Viewer's full view: one badge per speaker per turn.
|
||||
const continuation =
|
||||
!!previous && previous.role === msg.role && typeof msg.turn === 'number' && previous.turn === msg.turn;
|
||||
fragment.appendChild(this._chatViewBuildMessage(msg, agentLabel, continuation));
|
||||
}
|
||||
view.thread.appendChild(fragment);
|
||||
view.keys = keys;
|
||||
this._bindResponseViewerInteractions?.(view.thread);
|
||||
if (firstDraw || atBottom) scroller.scrollTop = scroller.scrollHeight;
|
||||
},
|
||||
|
||||
/** One drawn message. A long prompt folds to its first lines. */
|
||||
_chatViewBuildMessage(msg, agentLabel, continuation) {
|
||||
const meta = { ...msg, continuation };
|
||||
if (msg.role !== 'user') return this._buildResponseViewerMessage(msg.text, 'assistant', agentLabel, meta);
|
||||
const text = window.CodemanChatView.promptText(msg.text);
|
||||
const fold = window.CodemanChatView.promptFold(text);
|
||||
const el = this._buildResponseViewerMessage(fold.head, 'user', agentLabel, meta);
|
||||
if (!fold.folded) return el;
|
||||
el.classList.add('chat-view-msg-folded');
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'chat-view-show-all';
|
||||
more.textContent = this._chatViewT(`Show all (${fold.totalLines} ${fold.totalLines === 1 ? 'line' : 'lines'})`);
|
||||
// Unfold in place, keeping the badge the element shows now.
|
||||
more.addEventListener('click', () => {
|
||||
const full = this._buildResponseViewerMessage(text, 'user', agentLabel, {
|
||||
...meta,
|
||||
continuation: el.classList.contains('rv-msg-cont'),
|
||||
});
|
||||
el.replaceChildren(...full.childNodes);
|
||||
el.classList.remove('chat-view-msg-folded');
|
||||
});
|
||||
el.appendChild(more);
|
||||
return el;
|
||||
},
|
||||
});
|
||||
@@ -1514,6 +1514,95 @@ function findMarkdownAnchorTarget(root, href) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Chat view (chat-view.js) ─────────────────────────────────────────────────
|
||||
// Pure halves of the chat view, the rendered conversation that replaces the terminal
|
||||
// as a session's main view (docs/chat-view-plan.md). The module owns the DOM; these
|
||||
// decide what it shows, so a test can pin them without a browser.
|
||||
|
||||
/** A prompt longer than this many lines, or characters, is folded. */
|
||||
const CHAT_PROMPT_FOLD_LINES = 12;
|
||||
const CHAT_PROMPT_FOLD_CHARS = 2400;
|
||||
/** What a folded prompt still shows. */
|
||||
const CHAT_PROMPT_HEAD_LINES = 6;
|
||||
const CHAT_PROMPT_HEAD_CHARS = 800;
|
||||
|
||||
/**
|
||||
* The messages the chat view draws, in order: prompts and answers with text, without
|
||||
* the keep-warm turns Codeman sends on its own (`keepAlive`, set by the transcript reader).
|
||||
*/
|
||||
function chatViewVisibleMessages(messages) {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
return messages.filter(
|
||||
(m) =>
|
||||
!!m &&
|
||||
(m.role === 'user' || m.role === 'assistant') &&
|
||||
typeof m.text === 'string' &&
|
||||
m.text.trim() !== '' &&
|
||||
m.keepAlive !== true
|
||||
);
|
||||
}
|
||||
|
||||
/** Identity of a drawn message: a transcript row never changes once written. */
|
||||
function chatViewMessageKey(m) {
|
||||
return `${m.role}\u0000${typeof m.turn === 'number' ? m.turn : ''}\u0000${m.queued ? 'q' : ''}\u0000${m.text}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* How to bring the drawn thread up to date. `none` when nothing changed, `append`
|
||||
* when the new list only adds messages after the drawn ones (the usual case while a
|
||||
* turn runs), else `replace` (a `/clear`, a rewritten transcript, another session).
|
||||
*/
|
||||
function chatViewRenderPlan(drawnKeys, nextKeys) {
|
||||
const drawn = Array.isArray(drawnKeys) ? drawnKeys : [];
|
||||
const next = Array.isArray(nextKeys) ? nextKeys : [];
|
||||
if (drawn.length > next.length) return { mode: 'replace' };
|
||||
for (let i = 0; i < drawn.length; i++) {
|
||||
if (drawn[i] !== next[i]) return { mode: 'replace' };
|
||||
}
|
||||
if (drawn.length === next.length) return { mode: 'none' };
|
||||
return { mode: 'append', from: drawn.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* A prompt as the user wrote it. Claude Code stores a pasted block (which every multi-line
|
||||
* prompt sent through tmux is) inside `<pasted_content id="…">…</pasted_content id="…">` (the
|
||||
* closing tag repeats the id, measured on Claude Code 2.1.331); the markdown
|
||||
* renderer reads that as a raw HTML block and runs its lines together. Only matched pairs are
|
||||
* unwrapped, so a prompt that merely mentions the tag is left alone.
|
||||
*/
|
||||
function chatViewPromptText(text) {
|
||||
return String(text ?? '').replace(
|
||||
/<pasted_content(?:\s[^>]*)?>\n?([\s\S]*?)\n?<\/pasted_content(?:\s[^>]*)?>/g,
|
||||
(_match, body) => body
|
||||
);
|
||||
}
|
||||
|
||||
/** A running turn's length as the CLI shows it: `14s`, `2m 05s`, `1h 03m`. */
|
||||
function chatViewElapsed(ms) {
|
||||
const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
|
||||
const h = Math.floor(total / 3600);
|
||||
const m = Math.floor((total % 3600) / 60);
|
||||
const sec = total % 60;
|
||||
if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m`;
|
||||
if (m > 0) return `${m}m ${String(sec).padStart(2, '0')}s`;
|
||||
return `${sec}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a prompt is folded, and what its folded form shows: the first lines, capped
|
||||
* in characters so one enormous pasted line folds too.
|
||||
*/
|
||||
function chatViewPromptFold(text) {
|
||||
const value = String(text ?? '');
|
||||
const lines = value.split('\n');
|
||||
if (lines.length <= CHAT_PROMPT_FOLD_LINES && value.length <= CHAT_PROMPT_FOLD_CHARS) {
|
||||
return { folded: false, head: value, totalLines: lines.length };
|
||||
}
|
||||
let head = lines.slice(0, CHAT_PROMPT_HEAD_LINES).join('\n');
|
||||
if (head.length > CHAT_PROMPT_HEAD_CHARS) head = `${head.slice(0, CHAT_PROMPT_HEAD_CHARS)}…`;
|
||||
return { folded: true, head, totalLines: lines.length };
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
|
||||
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
|
||||
@@ -1581,6 +1670,14 @@ if (typeof window !== 'undefined') {
|
||||
needle: tabSearchNeedle,
|
||||
filter: filterTabSearchRows,
|
||||
};
|
||||
window.CodemanChatView = {
|
||||
visibleMessages: chatViewVisibleMessages,
|
||||
messageKey: chatViewMessageKey,
|
||||
renderPlan: chatViewRenderPlan,
|
||||
promptFold: chatViewPromptFold,
|
||||
promptText: chatViewPromptText,
|
||||
elapsed: chatViewElapsed,
|
||||
};
|
||||
window.CodemanInputLimit = {
|
||||
FRAME_MAX_CHARS: INPUT_FRAME_MAX_CHARS,
|
||||
PASTE_MAX_CHARS: INPUT_PASTE_MAX_CHARS,
|
||||
@@ -1914,6 +2011,7 @@ const SSE_EVENTS = {
|
||||
TRANSCRIPT_PLAN_MODE: 'transcript:plan_mode',
|
||||
TRANSCRIPT_TOOL_START: 'transcript:tool_start',
|
||||
TRANSCRIPT_TOOL_END: 'transcript:tool_end',
|
||||
TRANSCRIPT_UPDATE: 'transcript:update',
|
||||
|
||||
// Clipboard
|
||||
CLIPBOARD_WRITE: 'clipboard:write',
|
||||
|
||||
+23
-2
@@ -225,6 +225,21 @@
|
||||
// input like Click (单击).
|
||||
Tabs: '标签页',
|
||||
'Toggle Session Sidebar': '切换会话侧边栏',
|
||||
// Chat view (chat-view.js) and its App Settings row.
|
||||
'Toggle Chat / Terminal View': '切换聊天 / 终端视图',
|
||||
Chat: '聊天',
|
||||
'Open terminal': '打开终端',
|
||||
Conversation: '对话',
|
||||
'Session view': '会话视图',
|
||||
'Show the conversation (Alt+Shift+C)': '显示对话 (Alt+Shift+C)',
|
||||
'Show the terminal (Alt+Shift+C)': '显示终端 (Alt+Shift+C)',
|
||||
'No messages yet.': '还没有消息。',
|
||||
'Open Claude sessions in Chat view': '以聊天视图打开 Claude 会话',
|
||||
"Show a session's conversation rendered as text instead of the terminal. Each session remembers its own choice, and Alt+Shift+C or the Chat / Terminal switch changes it. Not on phones.":
|
||||
'以渲染后的文本显示会话的对话,代替终端。每个会话记住自己的选择,可用 Alt+Shift+C 或聊天 / 终端开关切换。手机上不可用。',
|
||||
'Show the Chat / Terminal switch': '显示聊天 / 终端开关',
|
||||
'Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.':
|
||||
'在 Claude 会话右上角显示聊天 / 终端开关。没有它时,Alt+Shift+C 也能切换视图。手机上不可用。',
|
||||
'Copy Selection': '复制选中内容',
|
||||
'Copy Selection (interrupts when nothing is selected)': '复制选中内容(无选中内容时中断)',
|
||||
'Focus Tabs': '聚焦标签页',
|
||||
@@ -1708,6 +1723,8 @@
|
||||
[/^(\d+) running$/, (_m, count) => `${count} 个运行中`],
|
||||
[/^(\d+) active$/, (_m, count) => `${count} 个活动`],
|
||||
[/^Show (\d+) more$/, (_m, count) => `再显示 ${count} 项`],
|
||||
// Chat view (chat-view.js).
|
||||
[/^Show all \((\d+) lines?\)$/, (_m, count) => `显示全部(${count} 行)`],
|
||||
[/^Show (\d+) more \((\d+) remaining\)$/, (_m, count, remaining) => `再显示 ${count} 项(剩余 ${remaining} 项)`],
|
||||
[/^Lifetime: (\d+) sessions created$/, (_m, count) => `累计已创建 ${count} 个会话`],
|
||||
[/^Tunnel active: (.+)$/, (_m, url) => `隧道已启用:${url}`],
|
||||
@@ -1807,8 +1824,12 @@
|
||||
(_m, name, why) => `案例“${name}”的选项已保存到本设备(同步前有效),但未保存到服务器:${ZH_CN[why] || why}`,
|
||||
],
|
||||
// A dialog read off a hook-less CLI's screen (src/web/screen-blocked.ts), as the
|
||||
// notification drawer shows it. The CLI's label passes through.
|
||||
[/^(.+) is waiting for your answer in the terminal$/, (_m, cli) => `${cli} 正在终端中等待你的回答`],
|
||||
// notification drawer shows it, and the chat view's notice, which ends in a period.
|
||||
// The agent's label passes through.
|
||||
[
|
||||
/^(.+) is waiting for your answer in the terminal(\.?)$/,
|
||||
(_m, who, dot) => `${who} 正在终端中等待你的回答${dot ? '。' : ''}`,
|
||||
],
|
||||
[/^The agent exited \(signal (\d+)\)$/, (_m, signal) => `智能体已退出(信号 ${signal})`],
|
||||
// A session header's harness logo (tile grid, split pane): "<harness> · <model>",
|
||||
// and where the model came from when the CLI did not report it. The harness
|
||||
|
||||
@@ -2280,6 +2280,20 @@
|
||||
<label class="set-chip" data-preview="panel" data-preview-order="3"><input type="checkbox" id="appSettingsShowFileBrowser"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg><span>File Browser</span></label>
|
||||
<label class="set-chip" data-preview="panel" data-preview-order="4"><input type="checkbox" id="appSettingsShowSubagents"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="12" r="2.5"/><path d="M8.2 7.2 15.6 11M8.2 16.8 15.6 13"/></svg><span>Subagents</span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="chat view conversation rendered markdown terminal default claude sessions readable">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Open Claude sessions in Chat view</span>
|
||||
<span class="set-row-desc">Show a session's conversation rendered as text instead of the terminal. Each session remembers its own choice, and Alt+Shift+C or the Chat / Terminal switch changes it. Not on phones.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsChatViewDefault"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="chat view terminal switch toggle button show hide claude sessions">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Show the Chat / Terminal switch</span>
|
||||
<span class="set-row-desc">Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowChatViewSwitch"><span class="slider"></span></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4578,6 +4592,7 @@
|
||||
<script defer src="git-status-ui.js"></script>
|
||||
<script defer src="edit-history-ui.js"></script>
|
||||
<script defer src="local-model-ui.js"></script>
|
||||
<script defer src="chat-view.js"></script>
|
||||
<script defer src="entrance-animations.js"></script>
|
||||
<script defer src="api-client.js"></script>
|
||||
<script defer src="subagent-windows.js"></script>
|
||||
|
||||
@@ -616,6 +616,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsGitFetchEnabled').checked = settings.gitFetchEnabled === true;
|
||||
document.getElementById('appSettingsGitFetchIntervalSeconds').value = settings.gitFetchIntervalSeconds ?? 300;
|
||||
document.getElementById('appSettingsShowEditHistory').checked = settings.showEditHistory ?? defaults.showEditHistory ?? false;
|
||||
document.getElementById('appSettingsChatViewDefault').checked = settings.chatViewDefault === true;
|
||||
// Absent means ON: the switch shows until this device turns it off.
|
||||
document.getElementById('appSettingsShowChatViewSwitch').checked = settings.showChatViewSwitch !== false;
|
||||
// Gesture control lives in the Input section (alongside Local Echo / CJK Input)
|
||||
// but is only available when the instance runs with CODEMAN_GESTURE=1 (server sets
|
||||
// window.__codemanGestureAvailable). Hide just this item otherwise so the toggle
|
||||
@@ -3177,6 +3180,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
Math.max(30, parseInt(document.getElementById('appSettingsGitFetchIntervalSeconds').value, 10) || 300)
|
||||
),
|
||||
showEditHistory: document.getElementById('appSettingsShowEditHistory').checked,
|
||||
chatViewDefault: document.getElementById('appSettingsChatViewDefault').checked,
|
||||
showChatViewSwitch: document.getElementById('appSettingsShowChatViewSwitch').checked,
|
||||
gestureControlEnabled: document.getElementById('appSettingsGestureControl').checked,
|
||||
subagentTrackingEnabled: document.getElementById('appSettingsSubagentTracking').checked,
|
||||
subagentActiveTabOnly: document.getElementById('appSettingsSubagentActiveTabOnly').checked,
|
||||
@@ -3405,6 +3410,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._updateTokensImmediate(); // Re-render token display (picks up showCost change)
|
||||
this.applyMonitorVisibility();
|
||||
this.renderApprovals?.(); // Approvals Inbox toggle (hide/show bell + drawer)
|
||||
this._chatViewSync?.(); // Chat view default and the Chat / Terminal switch's visibility
|
||||
this.renderProjectInsightsPanel(); // Re-render to apply visibility setting
|
||||
this.updateSubagentWindowVisibility(); // Apply subagent window visibility setting
|
||||
|
||||
@@ -3491,6 +3497,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
gitStatusTimeoutSeconds: _gst2,
|
||||
// Per-device header button (edit-history-ui.js), likewise absent from the .strict() schema.
|
||||
showEditHistory: _seh,
|
||||
// Which view a session opens in (chat-view.js): per-device, absent from the .strict() schema.
|
||||
chatViewDefault: _cvd,
|
||||
// Whether the Chat / Terminal switch shows (chat-view.js): per-device, absent from the .strict() schema.
|
||||
showChatViewSwitch: _scvs,
|
||||
showTabDetachButton: _tdb,
|
||||
showTabNewButton: _tnb,
|
||||
// Detach Tiles: what a tile drag does is a property of this device's
|
||||
@@ -5217,7 +5227,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
'language',
|
||||
'terminalWheelLocalScrollback',
|
||||
'autoCopySelection', 'copyStripMargin',
|
||||
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
|
||||
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory', 'chatViewDefault', 'showChatViewSwitch',
|
||||
'showTabDetachButton',
|
||||
'showTabNewButton',
|
||||
'mobileOverviewEnabled',
|
||||
|
||||
@@ -4399,6 +4399,9 @@ html[data-tab-logos='off'] .home-sessions-harness {
|
||||
overflow: hidden;
|
||||
/* Anchor for the partial-history banner, which overlays rather than stacks. */
|
||||
position: relative;
|
||||
/* Keeps the chat view's layers (20 and 21) inside the terminal area, so the
|
||||
narrow-width session sidebar drawer (z-index 12, mobile.css) stays above them. */
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
/* Partial-history banner (#258).
|
||||
@@ -19618,6 +19621,15 @@ html[data-session-list="sidebar"][data-sidebar="collapsed"] .btn-sidebar-toggle
|
||||
top: 28px;
|
||||
}
|
||||
|
||||
/* Pane A's split header is the first child of .terminal-wrap, so the chat layer and its switch start below it. */
|
||||
.terminal-pane-a-header ~ .chat-view {
|
||||
top: 28px;
|
||||
}
|
||||
|
||||
.terminal-pane-a-header ~ .chat-view-toggle {
|
||||
top: 36px;
|
||||
}
|
||||
|
||||
.split-harness.run-mode-dot {
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -24025,3 +24037,221 @@ html[data-header-stats='tiles'] .header-plan-usage:not(:has(.pu-row)) {
|
||||
body.keyboard-visible .terminal-container .xterm-screen {
|
||||
transform: translateY(calc(-1 * var(--kb-clip, 0px)));
|
||||
}
|
||||
|
||||
/* ═══ Chat view (chat-view.js) ═══════════════════════════════════════════════
|
||||
A session's conversation as its main view. It covers the terminal inside
|
||||
.terminal-wrap; the terminal stays mounted and sized underneath, so switching
|
||||
views never resizes the PTY. The message list carries .response-viewer-body,
|
||||
so it renders exactly as the Response Viewer does. Theme tokens only. */
|
||||
.chat-view {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg-dark);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.chat-view[hidden],
|
||||
.chat-view-toggle[hidden],
|
||||
.chat-view-dialog[hidden],
|
||||
.chat-view-status[hidden],
|
||||
.chat-view-empty[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chat-view-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding-top: 48px;
|
||||
}
|
||||
|
||||
.chat-view-thread,
|
||||
.chat-view-empty {
|
||||
max-width: 820px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.chat-view-empty {
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
padding-top: 15vh;
|
||||
}
|
||||
|
||||
/* The notice is a paragraph directly inside the scroller, which carries the Response Viewer's
|
||||
`.response-viewer-body > p` margin rule; this one outranks it so the notice stays centred. */
|
||||
.chat-view-scroll > .chat-view-empty {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.chat-view-show-all {
|
||||
margin-top: 8px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chat-view-show-all:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.chat-view-dialog {
|
||||
width: calc(100% - 32px);
|
||||
max-width: 820px;
|
||||
margin-inline: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-inline-start: 3px solid var(--yellow);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.chat-view-dialog-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Sits in the message list, right under the last message. */
|
||||
.chat-view-status {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
max-width: 820px;
|
||||
margin: 4px auto 0;
|
||||
padding-inline-start: 4px;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.chat-view-status-body {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chat-view-status-dot {
|
||||
flex: none;
|
||||
margin-top: 6px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
animation: chat-view-pulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes chat-view-pulse {
|
||||
0%, 100% { opacity: 0.35; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
.chat-view-btn {
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-input);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-view-btn:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.chat-view-btn-primary {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
color: var(--bg-card);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chat-view-btn-primary:hover {
|
||||
background: var(--accent);
|
||||
filter: brightness(1.08);
|
||||
}
|
||||
|
||||
.chat-view-btn:focus-visible,
|
||||
.chat-view-toggle-btn:focus-visible,
|
||||
.chat-view-show-all:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Chat / Terminal switch: top right of the session area, above both views. */
|
||||
.chat-view-toggle {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
inset-inline-end: 18px;
|
||||
z-index: 21;
|
||||
display: flex;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--floating-bg);
|
||||
overflow: hidden;
|
||||
opacity: 0.8;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
|
||||
.chat-view-toggle:hover,
|
||||
.chat-view-toggle:focus-within,
|
||||
.chat-view-toggle--over-chat {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.chat-view-toggle-btn {
|
||||
padding: 4px 10px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chat-view-toggle-btn[aria-pressed="true"] {
|
||||
background: rgba(var(--accent-rgb), 0.16);
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* The partial-history banner draws its Load full history and dismiss buttons at
|
||||
the right end of the top row, where the Chat / Terminal switch sits. */
|
||||
.terminal-wrap:has(> .chat-view-toggle:not([hidden])) .history-trunc-bar {
|
||||
padding-inline-end: 170px;
|
||||
}
|
||||
|
||||
/* The keyboard accessory bar's keys write straight into the pane, which the chat
|
||||
view hides, so the bar stays hidden while the chat view shows. */
|
||||
body.chat-view-showing .keyboard-accessory-bar.visible {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* On touch devices the CJK input field is fixed over the bottom of the chat view, and its text
|
||||
goes into the pane, so it stays hidden while the chat view shows. !important beats the inline
|
||||
display that app.js _updateCjkInputState sets. */
|
||||
body.chat-view-showing.touch-device #cjkInput.cjk-input-visible {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.chat-view-status-dot { animation: none; }
|
||||
.chat-view-toggle { transition: none; }
|
||||
}
|
||||
|
||||
/* The conversation takes focus only so keys never reach the hidden terminal; it draws no ring. */
|
||||
.chat-view-scroll:focus {
|
||||
outline: none;
|
||||
}
|
||||
@@ -338,6 +338,8 @@
|
||||
if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(ev)) {
|
||||
return false;
|
||||
}
|
||||
// Alt+Shift+C flips the main view's chat view, so it must never type into this pane.
|
||||
if (ev.type === 'keydown' && global.app?.shouldToggleChatViewFromShortcut?.(ev)) return false;
|
||||
// Tile grid chords (focus, toggle): acted on by the capture handler, so
|
||||
// they must never reach this tile's PTY. Every event type, and before
|
||||
// the Shift+Enter branch below.
|
||||
|
||||
@@ -920,6 +920,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Chat / Terminal view toggle (default Alt+Shift+C, chat-view.js): the same trap, so the
|
||||
// chord does not also type ESC C into the session. Only while the active session can show
|
||||
// the chat view.
|
||||
if (ev.type === 'keydown' && this.shouldToggleChatViewFromShortcut?.(ev)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ctrl+V / Cmd+V: intercept before xterm sends ^V to PTY.
|
||||
// Route through our paste trap which handles both images and text.
|
||||
if ((ev.ctrlKey || ev.metaKey) && ev.key === 'v' && ev.type === 'keydown') {
|
||||
@@ -2940,6 +2947,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
showWelcome() {
|
||||
this._chatViewHide?.();
|
||||
// Phones get the session overview instead of the welcome screen: on a small
|
||||
// screen "which session is blocked on me" beats "how do I start one". The
|
||||
// gate lives in mobile-overview.js; every other device falls through
|
||||
|
||||
@@ -415,6 +415,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
grid.rows = 0;
|
||||
grid.focusedId = focus;
|
||||
document.querySelector('.main')?.classList.add('tiles-active');
|
||||
// Selecting a tile never reaches selectSession(), so the chat view is told here.
|
||||
this._chatViewSync?.();
|
||||
const section = this._tileGridSection();
|
||||
this.hideWelcome();
|
||||
// Mount every tile and lay the grid out BEFORE any tile connects, so each
|
||||
@@ -504,6 +506,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
grid.zoomedId = null;
|
||||
grid.autoZoom = false;
|
||||
document.querySelector('.main')?.classList.remove('tiles-active');
|
||||
this._chatViewSync?.();
|
||||
const section = document.getElementById('tileGrid');
|
||||
if (section) {
|
||||
section.style.gridTemplateColumns = '';
|
||||
|
||||
@@ -9,10 +9,9 @@
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { ApiErrorCode, createErrorResponse } from '../../types.js';
|
||||
import { HookEventSchema, isValidWorkingDir } from '../schemas.js';
|
||||
import { HookEventSchema } from '../schemas.js';
|
||||
import { sanitizeHookData, parseBody } from '../route-helpers.js';
|
||||
import { persistDockerCaseClaudeSessionId } from '../../docker-hosts.js';
|
||||
import { getDataDir } from '../../config/instance.js';
|
||||
import { noteClaudeConversationReport, takeConversationMove } from '../claude-conversation-report.js';
|
||||
import {
|
||||
sessionWaits,
|
||||
hooksAvailableForMode,
|
||||
@@ -138,56 +137,19 @@ export function registerHookEventRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// Start transcript watching if transcript_path is provided and safe
|
||||
if (data && 'transcript_path' in data) {
|
||||
const transcriptPath = String(data.transcript_path);
|
||||
if (transcriptPath && isValidWorkingDir(transcriptPath)) {
|
||||
ctx.startTranscriptWatcher(sessionId, transcriptPath);
|
||||
}
|
||||
}
|
||||
|
||||
// Sync Claude's current conversation id. Interactive PTY mode never emits
|
||||
// `session_id` on stdout, so hooks are the only reliable way to learn that
|
||||
// the user ran `/clear` (which spins up a new conversation jsonl).
|
||||
let conversationChanged = false;
|
||||
if (data && typeof data.session_id === 'string' && data.session_id) {
|
||||
const session = ctx.sessions.get(sessionId);
|
||||
const prevClaudeSessionId = session?.claudeSessionId;
|
||||
const prevChainLength = session?.claudeSessionChain.length ?? 0;
|
||||
// FIRST-HAND: this payload came from the CLI process itself and reached us
|
||||
// because the pane's own $CODEMAN_SESSION_ID addressed it. No cwd, no
|
||||
// timestamp, nothing a sibling pane on the same folder could win — so the
|
||||
// response viewer can stop guessing entirely (see
|
||||
// resolveActiveClaudeSessionIdFromHistory).
|
||||
session?.adoptClaudeSessionId(data.session_id, { firstHand: true });
|
||||
if (event === 'prompt_submitted') {
|
||||
// Repairs `lastSubmitAt` for a pane driven straight from tmux: it was
|
||||
// bumped only by input that flowed through Codeman's own write path, so
|
||||
// it read 0 forever for those panes and every consumer of "when did this
|
||||
// pane last submit" silently degraded.
|
||||
// The prompt text tells a person's prompt from the keep-alive's (prompt-cache-keepwarm.ts).
|
||||
session?.markPromptSubmitted(typeof data.prompt === 'string' ? data.prompt : undefined);
|
||||
}
|
||||
// Persist when the conversation actually moved: `/clear` emits no
|
||||
// completion event, so without this the successor id is lost on restart
|
||||
// and recovery falls back to the launch conversation.
|
||||
if (
|
||||
session &&
|
||||
(session.claudeSessionId !== prevClaudeSessionId || session.claudeSessionChain.length !== prevChainLength)
|
||||
) {
|
||||
conversationChanged = true;
|
||||
ctx.persistSessionState(session);
|
||||
}
|
||||
// Docker sessions: keep the case's resume seed following the LIVE
|
||||
// conversation (post-/clear id switches), so a container stop/reboot
|
||||
// relaunch resumes the right transcript.
|
||||
if (session?.docker && session.claudeSessionId && session.claudeSessionId !== prevClaudeSessionId) {
|
||||
void persistDockerCaseClaudeSessionId(
|
||||
getDataDir(),
|
||||
session.docker.containerName,
|
||||
session.claudeSessionId
|
||||
).catch(() => {});
|
||||
}
|
||||
// Follow the conversation the pane reports (transcript watcher, conversation id, persistence).
|
||||
// The statusline exporter reports the same two fields (status-telemetry-routes.ts).
|
||||
noteClaudeConversationReport(ctx, sessionId, data);
|
||||
// Whether the conversation moved since the previous prompt. The statusline can adopt a `/clear`
|
||||
// successor before this hook arrives, so this hook's own report may show no change.
|
||||
const conversationMoved = event === 'prompt_submitted' && takeConversationMove(ctx.sessions.get(sessionId));
|
||||
if (event === 'prompt_submitted' && data && typeof data.session_id === 'string' && data.session_id) {
|
||||
// Repairs `lastSubmitAt` for a pane driven straight from tmux: it was
|
||||
// bumped only by input that flowed through Codeman's own write path, so
|
||||
// it read 0 forever for those panes and every consumer of "when did this
|
||||
// pane last submit" silently degraded.
|
||||
// The prompt text tells a person's prompt from the keep-alive's (prompt-cache-keepwarm.ts).
|
||||
ctx.sessions.get(sessionId)?.markPromptSubmitted(typeof data.prompt === 'string' ? data.prompt : undefined);
|
||||
}
|
||||
|
||||
// Sanitize forwarded data: only include known safe fields, limit size
|
||||
@@ -317,7 +279,7 @@ export function registerHookEventRoutes(
|
||||
// left out too: the summary files a `stop` as a warning, which the Away digest lists under
|
||||
// Needs Attention, and that turn is Codeman's own, not the agent's.
|
||||
const summaryTracker = ctx.runSummaryTrackers.get(sessionId);
|
||||
if (summaryTracker && !keepAliveReason && (event !== 'prompt_submitted' || conversationChanged)) {
|
||||
if (summaryTracker && !keepAliveReason && (event !== 'prompt_submitted' || conversationMoved)) {
|
||||
summaryTracker.recordHookEvent(event, safeData);
|
||||
}
|
||||
|
||||
|
||||
@@ -230,6 +230,7 @@ import {
|
||||
import { readDeepSeekLastResponse } from '../../deepseek-transcript.js';
|
||||
import { appendClaudeCustomTitle } from '../../claude-session-title.js';
|
||||
import { UPLOADS_DIR } from '../paste-image-gc.js';
|
||||
import { ClaudeTranscriptReader } from '../claude-response-transcript.js';
|
||||
|
||||
// Path to linked-cases registry (same file used by case-routes resolveCasePath)
|
||||
const LINKED_CASES_FILE = dataPath('linked-cases.json');
|
||||
@@ -1085,6 +1086,14 @@ function wakeableHost(host: RemoteHost): WakeableRemote {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript path a `context=full` read started a session's watcher on, per session.
|
||||
* A hook moves the watcher whenever its own path changes, but a session without working hooks
|
||||
* never does, so after a `/clear` the read moves the watcher it started itself. A watcher whose
|
||||
* path no longer matches the entry was moved by a hook, and from then on the read leaves it alone.
|
||||
*/
|
||||
const readStartedWatchers = new WeakMap<Session, string>();
|
||||
|
||||
export function registerSessionRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort & TabLayoutPort & KeepWarmPort,
|
||||
@@ -2936,160 +2945,9 @@ export function registerSessionRoutes(
|
||||
return best.sessionId;
|
||||
}
|
||||
|
||||
interface ClaudeResponseMessage {
|
||||
kind: 'prompt' | 'response';
|
||||
label: 'Prompt' | 'Response';
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
timestamp?: string;
|
||||
turn: number;
|
||||
queued?: boolean;
|
||||
}
|
||||
|
||||
interface ClaudeTranscriptEntry {
|
||||
type?: string;
|
||||
timestamp?: string;
|
||||
isMeta?: boolean;
|
||||
isSidechain?: boolean;
|
||||
isCompactSummary?: boolean;
|
||||
message?: { content?: unknown };
|
||||
// A prompt typed while Claude is working is absorbed mid-turn and recorded
|
||||
// ONLY here — the CLI never re-emits it as a `user` row. Every field stays
|
||||
// optional and unvalidated: `queued_command` is not a documented CLI
|
||||
// contract, so a missing/renamed field must mean "skip", which is also what
|
||||
// the CLI's own non-human queue entries (commandMode 'task-notification',
|
||||
// no `origin` key) require. Shape observed on Claude Code 2.1.220-2.1.251.
|
||||
attachment?: {
|
||||
type?: string;
|
||||
prompt?: string;
|
||||
commandMode?: string;
|
||||
timestamp?: string;
|
||||
origin?: { kind?: string };
|
||||
};
|
||||
}
|
||||
|
||||
function extractClaudeText(content: unknown, separator: string): string {
|
||||
if (typeof content === 'string') return content;
|
||||
if (!Array.isArray(content)) return '';
|
||||
return content
|
||||
.filter(
|
||||
(block): block is { type: string; text: string } =>
|
||||
!!block &&
|
||||
typeof block === 'object' &&
|
||||
(block as { type?: string }).type === 'text' &&
|
||||
typeof (block as { text?: string }).text === 'string'
|
||||
)
|
||||
.map((block) => block.text)
|
||||
.join(separator);
|
||||
}
|
||||
|
||||
function isClaudeSyntheticUserMessage(entry: ClaudeTranscriptEntry, text: string): boolean {
|
||||
if (entry.isMeta || entry.isCompactSummary) return true;
|
||||
return /^(?:<local-command|<command-name>|<task-notification>|<system-reminder>|<teammate-message\b|Another Claude session sent a message:|Base directory for this skill:)/i.test(
|
||||
text
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude writes an append-only event log: tool results arrive as user rows,
|
||||
* thinking/tool_use rows carry no text, and a prompt typed while the agent is
|
||||
* working is only ever recorded as an `attachment/queued_command` row. But one
|
||||
* assistant row IS one whole model message: measured across ~/.claude/projects
|
||||
* (CLI 2.1.220-2.1.251) no assistant row carries more than one content block
|
||||
* and no message id carries more than one text block, so there is nothing to
|
||||
* reassemble. Emit one card per row and group them with `turn` instead of
|
||||
* concatenating a human turn's replies into a single card (#169), which fused
|
||||
* up to 74 distinct model messages into one card. Splitting is safe for
|
||||
* markdown: no adjacent pair of assistant text rows in the corpus continues a
|
||||
* table, a list, or an open code fence.
|
||||
*/
|
||||
function parseClaudeResponseTranscript(
|
||||
content: string,
|
||||
full: boolean
|
||||
): { text: string; timestamp: string; messages?: ClaudeResponseMessage[] } {
|
||||
let lastText = '';
|
||||
let lastTimestamp = '';
|
||||
const messages: ClaudeResponseMessage[] = [];
|
||||
// #169's replay guards, kept: they now SKIP a duplicated row instead of
|
||||
// concatenating it into the previous card.
|
||||
const currentUserFragments = new Set<string>();
|
||||
const currentAssistantFragments = new Set<string>();
|
||||
// Turn 0 is reserved for anything emitted before the first human prompt.
|
||||
let turn = 0;
|
||||
|
||||
const pushUserMessage = (text: string, timestamp: string | undefined, queued: boolean): void => {
|
||||
// A run of consecutive human inputs (a mid-turn queued burst) is ONE turn,
|
||||
// so the viewer renders it under one badge instead of one badge per line.
|
||||
if (messages.at(-1)?.role !== 'user') turn += 1;
|
||||
const message: ClaudeResponseMessage = { kind: 'prompt', label: 'Prompt', role: 'user', text, timestamp, turn };
|
||||
if (queued) message.queued = true;
|
||||
messages.push(message);
|
||||
currentUserFragments.add(text);
|
||||
currentAssistantFragments.clear();
|
||||
};
|
||||
|
||||
for (const line of content.split('\n')) {
|
||||
if (!line) continue;
|
||||
let entry: ClaudeTranscriptEntry;
|
||||
try {
|
||||
entry = JSON.parse(line) as ClaudeTranscriptEntry;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
// Sidechains belong to agents/forks, not the main conversation. Meta user
|
||||
// rows include repeated image dimensions and other UI-generated context.
|
||||
if (entry.isSidechain) continue;
|
||||
|
||||
// A prompt typed while Claude is working is absorbed mid-turn and lives
|
||||
// ONLY in an attachment row, so it was lost outright. `origin.kind` and
|
||||
// `commandMode` separate the human's queue entries from the CLI's own:
|
||||
// measured over 57 real transcripts on 2026-09-01, 322 queued_command rows
|
||||
// split 163 `prompt`/`human` and 159 `task-notification`, and not one of
|
||||
// those 159 carries an `origin` key. The 163 human rows become 162 user
|
||||
// cards here — one is a verbatim repeat inside a still-unanswered user run
|
||||
// and is collapsed by the dedup guard below — out of 353 user cards total.
|
||||
if (entry.type === 'attachment') {
|
||||
if (!full) continue;
|
||||
const queued = entry.attachment;
|
||||
if (!queued || queued.type !== 'queued_command') continue;
|
||||
if (queued.origin?.kind !== 'human' || queued.commandMode !== 'prompt') continue;
|
||||
const text = typeof queued.prompt === 'string' ? queued.prompt.trim() : '';
|
||||
if (!text || isClaudeSyntheticUserMessage(entry, text)) continue;
|
||||
if (currentUserFragments.has(text)) continue;
|
||||
pushUserMessage(text, queued.timestamp || entry.timestamp, true);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.type === 'user') {
|
||||
const text = extractClaudeText(entry.message?.content, '\n').trim();
|
||||
// A tool_result block has no text block and naturally drops out here.
|
||||
if (!text || isClaudeSyntheticUserMessage(entry, text)) continue;
|
||||
if (!full) continue;
|
||||
// Claude replays the initial user row while restoring a transcript, and
|
||||
// a CLI that also wrote an absorbed prompt as a user row would double it.
|
||||
// Both collapse here. The same prompt sent again AFTER a reply is a
|
||||
// legitimate second turn, because that reply cleared the set.
|
||||
if (currentUserFragments.has(text)) continue;
|
||||
pushUserMessage(text, entry.timestamp, false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.type !== 'assistant') continue;
|
||||
const text = extractClaudeText(entry.message?.content, '\n\n').trim();
|
||||
if (!text) continue;
|
||||
lastText = text;
|
||||
lastTimestamp = entry.timestamp || '';
|
||||
if (!full) continue;
|
||||
|
||||
// Replayed snapshots repeat an identical text block inside one turn.
|
||||
if (currentAssistantFragments.has(text)) continue;
|
||||
messages.push({ kind: 'response', label: 'Response', role: 'assistant', text, timestamp: entry.timestamp, turn });
|
||||
currentAssistantFragments.add(text);
|
||||
currentUserFragments.clear();
|
||||
}
|
||||
|
||||
return full ? { text: lastText, timestamp: lastTimestamp, messages } : { text: lastText, timestamp: lastTimestamp };
|
||||
}
|
||||
// Each transcript's parse so far, so a read parses only what was appended since the last one
|
||||
// (claude-response-transcript.ts). The chat view reads on every `transcript:update`.
|
||||
const claudeTranscripts = new ClaudeTranscriptReader();
|
||||
|
||||
/**
|
||||
* Where THIS session's claude keeps its conversations: `<config dir>/projects` and
|
||||
@@ -3145,33 +3003,59 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// Where each conversation's transcript was last found, keyed by projects folder and id. The scan
|
||||
// below stats one path per project folder, and the chat view reads on every reload, so a hit here
|
||||
// costs one stat. A path that no longer names a file is dropped and the scan runs again.
|
||||
const transcriptPathCache = new LRUMap<string, string>({ maxSize: 256 });
|
||||
|
||||
/** Locate a top-level Claude transcript, including recovered tmux sessions. */
|
||||
async function findClaudeTranscript(
|
||||
projectsDir: string,
|
||||
conversationId: string,
|
||||
codemanSessionId: string
|
||||
): Promise<{ sessionId: string; path: string } | null> {
|
||||
let projectDirs: import('node:fs').Dirent[];
|
||||
try {
|
||||
projectDirs = await fs.readdir(projectsDir, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let projectDirs: import('node:fs').Dirent[] | null = null;
|
||||
const readProjectDirs = async (): Promise<import('node:fs').Dirent[] | null> => {
|
||||
if (projectDirs) return projectDirs;
|
||||
try {
|
||||
projectDirs = await fs.readdir(projectsDir, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return projectDirs;
|
||||
};
|
||||
|
||||
const safeIds = [...new Set([conversationId, codemanSessionId])].filter((value) => /^[a-zA-Z0-9._-]+$/.test(value));
|
||||
for (const candidateId of safeIds) {
|
||||
for (const projectDir of projectDirs) {
|
||||
const cacheKey = `${projectsDir}\0${candidateId}`;
|
||||
const cached = transcriptPathCache.get(cacheKey);
|
||||
if (cached) {
|
||||
const stat = await fs.stat(cached).catch(() => null);
|
||||
if (stat?.isFile()) return { sessionId: candidateId, path: cached };
|
||||
transcriptPathCache.delete(cacheKey);
|
||||
}
|
||||
const dirs = await readProjectDirs();
|
||||
if (!dirs) return null;
|
||||
for (const projectDir of dirs) {
|
||||
if (!projectDir.isDirectory()) continue;
|
||||
const jsonlPath = join(projectsDir, projectDir.name, `${candidateId}.jsonl`);
|
||||
try {
|
||||
const stat = await fs.stat(jsonlPath);
|
||||
if (stat.isFile()) return { sessionId: candidateId, path: jsonlPath };
|
||||
if (stat.isFile()) {
|
||||
transcriptPathCache.set(cacheKey, jsonlPath);
|
||||
return { sessionId: candidateId, path: jsonlPath };
|
||||
}
|
||||
} catch {
|
||||
/* continue */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The fallback below is never cached: it picks among files by a prefix, and a new one can
|
||||
// change the answer.
|
||||
const allProjectDirs = await readProjectDirs();
|
||||
if (!allProjectDirs) return null;
|
||||
|
||||
// If mux-sessions.json was lost or stale, reconcileSessions() historically
|
||||
// recovered `codeman-40568a29` as `restored-40568a29` and used the server cwd.
|
||||
// The tmux name still carries the first eight UUID characters, which safely
|
||||
@@ -3182,7 +3066,7 @@ export function registerSessionRoutes(
|
||||
const candidates: Array<{ sessionId: string; path: string; mtimeMs: number }> = [];
|
||||
const uuidPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
||||
|
||||
for (const projectDir of projectDirs) {
|
||||
for (const projectDir of allProjectDirs) {
|
||||
if (!projectDir.isDirectory()) continue;
|
||||
const dirPath = join(projectsDir, projectDir.name);
|
||||
let files: import('node:fs').Dirent[];
|
||||
@@ -3340,17 +3224,35 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await fs.readFile(transcript.path, 'utf8');
|
||||
const parsed = parseClaudeResponseTranscript(content, wantsMessages);
|
||||
if (context === 'turn') {
|
||||
return {
|
||||
text: parsed.text,
|
||||
timestamp: parsed.timestamp,
|
||||
messages: selectLastAnsweredTurn(parsed.messages ?? []),
|
||||
};
|
||||
// The chat view lives on the watcher's events (tool starts, new lines). A watcher normally
|
||||
// starts at the session's first hook or statusline report, so a session the server picked up
|
||||
// mid-turn (a restart) has none until one of those arrives. Start one from the file just found
|
||||
// when none runs. A watcher this read started itself follows the conversation to its new file
|
||||
// after a `/clear`, since no hook or statusline report moves it. A watcher that a hook or a
|
||||
// statusline report started or moved is never touched: the reported path stays the authority.
|
||||
// A remote session's file is not here. The reads above await, so the session may have been
|
||||
// deleted or detached meanwhile, and a watcher started for it then would never be stopped.
|
||||
if (context === 'full' && !session.remote && ctx.sessions.get(session.id) === session) {
|
||||
const current = ctx.getTranscriptPath(session.id);
|
||||
if (current === null) {
|
||||
ctx.startTranscriptWatcher(session.id, transcript.path);
|
||||
readStartedWatchers.set(session, transcript.path);
|
||||
} else if (readStartedWatchers.get(session) === current) {
|
||||
if (current !== transcript.path) {
|
||||
ctx.startTranscriptWatcher(session.id, transcript.path);
|
||||
readStartedWatchers.set(session, transcript.path);
|
||||
}
|
||||
} else {
|
||||
readStartedWatchers.delete(session);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = await claudeTranscripts.read(transcript.path);
|
||||
if (context === 'turn') {
|
||||
return { text: parsed.text, timestamp: parsed.timestamp, messages: selectLastAnsweredTurn(parsed.messages) };
|
||||
}
|
||||
return wantsMessages ? parsed : { text: parsed.text, timestamp: parsed.timestamp };
|
||||
} catch {
|
||||
return wantsMessages ? { text: '', timestamp: '', messages: [] } : { text: '', timestamp: '' };
|
||||
}
|
||||
|
||||
@@ -29,10 +29,14 @@ import {
|
||||
} from '../../usage-telemetry.js';
|
||||
import { SessionPromptCache, SessionStatusTelemetry } from '../sse-events.js';
|
||||
import { setLatestPlanUsage } from '../plan-usage-latest.js';
|
||||
import type { SessionPort, EventPort, KeepWarmPort } from '../ports/index.js';
|
||||
import type { SessionPort, EventPort, KeepWarmPort, ConfigPort } from '../ports/index.js';
|
||||
import { noteClaudeConversationReport } from '../claude-conversation-report.js';
|
||||
import { getCli } from '../../config/cli-registry/index.js';
|
||||
|
||||
export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: SessionPort & EventPort & KeepWarmPort): void {
|
||||
export function registerStatusTelemetryRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & EventPort & KeepWarmPort & Pick<ConfigPort, 'startTranscriptWatcher'>
|
||||
): void {
|
||||
// Last broadcast telemetry signature per session — the statusline fires on
|
||||
// every assistant message, so we only rebroadcast when the value changes.
|
||||
const lastSig = new Map<string, string>();
|
||||
@@ -65,6 +69,15 @@ export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: Session
|
||||
session.noteReportedModel('statusline', payload?.model?.display_name);
|
||||
}
|
||||
|
||||
// The conversation the pane runs. Claude Code runs the statusline about a second after a
|
||||
// `/clear`, with the new conversation's id and transcript path, so the transcript watcher and
|
||||
// the chat view move to it at once; a hook would report it only with the next prompt.
|
||||
// The exporter can post out of order, so this report moves the session back to an earlier
|
||||
// conversation only when the session's last move is more than a few seconds old (forwardOnly).
|
||||
if (session && reportsStatusLine) {
|
||||
noteClaudeConversationReport(ctx, sessionId, data, { forwardOnly: true });
|
||||
}
|
||||
|
||||
// The context size drives auto-compact and auto-clear. A render without one (the exporter
|
||||
// can post before the first API response) keeps the last report instead of wiping it.
|
||||
const status = reportsStatusLine ? parseSessionStatus(payload) : null;
|
||||
|
||||
@@ -747,6 +747,11 @@ export const StatusTelemetrySchema = z.object({
|
||||
sessionId: z.string().min(1).max(100),
|
||||
data: z
|
||||
.object({
|
||||
// The conversation the pane runs, as every hook reports it (claude-conversation-report.ts).
|
||||
// Claude Code runs the statusline again right after a `/clear`, so this is how the server
|
||||
// learns of the new conversation before the next prompt. Bounded like any path.
|
||||
session_id: z.string().max(200).nullish(),
|
||||
transcript_path: z.string().max(4096).nullish(),
|
||||
rate_limits: z
|
||||
.object({
|
||||
five_hour: RateLimitWindowSchema,
|
||||
|
||||
@@ -186,6 +186,7 @@ import {
|
||||
import {
|
||||
CleanupManager,
|
||||
KeyedDebouncer,
|
||||
KeyedThrottle,
|
||||
StaleExpirationMap,
|
||||
startEventLoopMonitor,
|
||||
isSafePushEndpoint,
|
||||
@@ -280,6 +281,8 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
// while capping growth of `sseClientsById` and blocking pathological inputs.
|
||||
const SSE_CLIENT_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
|
||||
const CODEX_USAGE_POLL_INTERVAL_MS = 5 * 60_000;
|
||||
/** Longest a session's `transcript:update` broadcast waits behind the one before it. */
|
||||
const TRANSCRIPT_UPDATE_THROTTLE_MS = 750;
|
||||
// Copilot's quota is read over the network from GitHub, and a monthly figure moves slowly.
|
||||
const COPILOT_USAGE_POLL_INTERVAL_MS = 10 * 60_000;
|
||||
|
||||
@@ -430,6 +433,13 @@ export class WebServer extends EventEmitter {
|
||||
private respawnTimers: Map<string, { timer: NodeJS.Timeout; endAt: number; startedAt: number }> = new Map();
|
||||
private runSummaryTrackers: Map<string, RunSummaryTracker> = new Map();
|
||||
private transcriptWatchers: Map<string, TranscriptWatcher> = new Map();
|
||||
/**
|
||||
* Per-session throttle for the `transcript:update` broadcast: the first update in a quiet
|
||||
* period goes out at once, and a burst after it collapses into one trailing event per
|
||||
* TRANSCRIPT_UPDATE_THROTTLE_MS. A busy turn writes several lines a second, and every SSE
|
||||
* client gets every broadcast.
|
||||
*/
|
||||
private readonly transcriptUpdateThrottle = new KeyedThrottle(TRANSCRIPT_UPDATE_THROTTLE_MS);
|
||||
// Store session listener references for explicit cleanup (prevents memory leaks)
|
||||
private sessionListenerRefs: Map<string, SessionListenerRefs> = new Map();
|
||||
private scheduledRuns: Map<string, ScheduledRun> = new Map();
|
||||
@@ -1477,6 +1487,9 @@ export class WebServer extends EventEmitter {
|
||||
* Creates a new watcher or updates an existing one with the new transcript path.
|
||||
*/
|
||||
private startTranscriptWatcher(sessionId: string, transcriptPath: string): void {
|
||||
// Cleanup stops the watcher before it removes the session from the map. A hook, statusline
|
||||
// report or full read that lands in between must not start a watcher that nothing would stop.
|
||||
if (this.cleaningUp.has(sessionId)) return;
|
||||
let watcher = this.transcriptWatchers.get(sessionId);
|
||||
|
||||
if (!watcher) {
|
||||
@@ -1503,6 +1516,10 @@ export class WebServer extends EventEmitter {
|
||||
this.broadcast(SseEvent.TranscriptToolStart, { sessionId, toolName, timestamp: Date.now() });
|
||||
});
|
||||
|
||||
watcher.on('transcript:update', () => {
|
||||
this.broadcastTranscriptUpdate(sessionId);
|
||||
});
|
||||
|
||||
watcher.on('transcript:tool_end', (toolName: string, isError: boolean) => {
|
||||
this.broadcast(SseEvent.TranscriptToolEnd, {
|
||||
sessionId,
|
||||
@@ -1548,10 +1565,18 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/** Broadcast `transcript:update` for a session, throttled (see `transcriptUpdateThrottle`). */
|
||||
private broadcastTranscriptUpdate(sessionId: string): void {
|
||||
this.transcriptUpdateThrottle.fire(sessionId, () => {
|
||||
this.broadcast(SseEvent.TranscriptUpdate, { sessionId, timestamp: Date.now() });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the transcript watcher for a session.
|
||||
*/
|
||||
private stopTranscriptWatcher(sessionId: string): void {
|
||||
this.transcriptUpdateThrottle.cancelKey(sessionId);
|
||||
const watcher = this.transcriptWatchers.get(sessionId);
|
||||
if (watcher) {
|
||||
watcher.removeAllListeners(); // Prevent memory leaks from attached listeners
|
||||
@@ -2160,6 +2185,17 @@ export class WebServer extends EventEmitter {
|
||||
'</head>',
|
||||
() => `<script>window.__codemanTranscriptPageKeys=${JSON.stringify(pageKeyClis)};</script>\n</head>`
|
||||
);
|
||||
// Which run modes the chat view can show (chat-view.js): the CLIs whose conversation Codeman
|
||||
// reads from a Claude-format transcript, read off the `transcript` capability, never an id
|
||||
// list here. Disabled entries are kept (`listClis`), like the wheel map below: disabling a CLI
|
||||
// never ends its running sessions. Ids only, so JSON.stringify alone is enough.
|
||||
const chatViewClis = listClis()
|
||||
.filter((entry) => entry.capabilities.transcript === 'claude-jsonl')
|
||||
.map((entry) => entry.id);
|
||||
html = html.replace(
|
||||
'</head>',
|
||||
() => `<script>window.__codemanChatViewModes=${JSON.stringify(chatViewClis)};</script>\n</head>`
|
||||
);
|
||||
// Which run modes keep their PTY rows under a phone keyboard (inline renderers,
|
||||
// the `keyboardHold` capability; `_keyboardHoldEligible` in terminal-ui.js). Same
|
||||
// shape and reasoning as the page-key list above.
|
||||
@@ -4856,6 +4892,7 @@ export class WebServer extends EventEmitter {
|
||||
this.respawnTimers.clear();
|
||||
this.runSummaryTrackers.clear();
|
||||
this.transcriptWatchers.clear();
|
||||
this.transcriptUpdateThrottle.dispose();
|
||||
await this.editHistorySync.flushAll().catch((err) => {
|
||||
console.warn('[EditHistory] Saving on shutdown failed:', getErrorMessage(err));
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* and referenced by the frontend (`SSE_EVENTS` in `constants.js`).
|
||||
* Both files MUST be kept in sync.
|
||||
*
|
||||
* 163 event constants organized by category:
|
||||
* 165 event constants organized by category:
|
||||
* - **Core** (1): init
|
||||
* - **Transport** (1): sse:heartbeat
|
||||
* - **Session lifecycle** (25): created, updated, deleted, terminal, idle, working, ...
|
||||
@@ -21,7 +21,7 @@
|
||||
* - **Scheduled** (6): created, updated, completed, stopped, log, deleted
|
||||
* - **Cron jobs** (4): jobsChanged, jobDeleted, runCreated, runUpdated
|
||||
* - **Teams** (4): created, updated, removed, taskUpdated
|
||||
* - **Transcript** (4): complete, plan_mode, tool_start, tool_end
|
||||
* - **Transcript** (5): complete, plan_mode, tool_start, tool_end, update
|
||||
* - **Plan orchestration** (5): started, progress, subagent, completed, cancelled
|
||||
* - **Tunnel** (7): started, stopped, progress, error, qrRotated, qrRegenerated, qrAuthUsed
|
||||
* - **Image / attachments** (2): image:detected, attachment:detected
|
||||
@@ -326,6 +326,11 @@ export const TranscriptPlanMode = 'transcript:plan_mode' as const;
|
||||
export const TranscriptToolStart = 'transcript:tool_start' as const;
|
||||
/** Tool invocation ended in transcript. */
|
||||
export const TranscriptToolEnd = 'transcript:tool_end' as const;
|
||||
/**
|
||||
* New lines arrived in a session's transcript (throttled per session in server.ts). The chat
|
||||
* view re-reads the conversation on it, so an answer shows while its turn is still running.
|
||||
*/
|
||||
export const TranscriptUpdate = 'transcript:update' as const;
|
||||
|
||||
// ─── Plan Orchestration ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -643,6 +648,7 @@ export const SseEvent = {
|
||||
TranscriptPlanMode,
|
||||
TranscriptToolStart,
|
||||
TranscriptToolEnd,
|
||||
TranscriptUpdate,
|
||||
|
||||
// Plan orchestration
|
||||
PlanStarted,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @fileoverview The chat view's strings in Chinese (zh-CN), run through the real translator.
|
||||
*
|
||||
* chat-view.js looks its strings up itself (`_chatViewT`), because i18n.js skips the
|
||||
* `data-i18n-skip` conversation. Pinned here:
|
||||
* - each string the chat view draws reads in Chinese, and the numbers in it survive;
|
||||
* - the setting that shows or hides the Chat / Terminal switch reads in Chinese.
|
||||
*
|
||||
* Port: N/A.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterAll, describe, expect, it } from 'vitest';
|
||||
|
||||
const I18N = readFileSync(resolve(import.meta.dirname, '../src/web/public/i18n.js'), 'utf8');
|
||||
|
||||
type Api = { t(s: string, vars?: Record<string, string>): string; configure(o: Record<string, string>): void };
|
||||
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
|
||||
runScripts: 'outside-only',
|
||||
url: 'http://localhost/',
|
||||
});
|
||||
vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' });
|
||||
const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n;
|
||||
api.configure({ language: 'zh-CN' });
|
||||
afterAll(() => dom.window.close());
|
||||
|
||||
describe('the chat view in zh-CN', () => {
|
||||
it('translates the fold button, the empty thread and the dialog notice', () => {
|
||||
expect(api.t('No messages yet.')).toBe('还没有消息。');
|
||||
expect(api.t('Show all (3 lines)')).toBe('显示全部(3 行)');
|
||||
expect(api.t('Claude is waiting for your answer in the terminal.')).toBe('Claude 正在终端中等待你的回答。');
|
||||
// The notification drawer shows the same sentence without the period.
|
||||
expect(api.t('Codex is waiting for your answer in the terminal')).toBe('Codex 正在终端中等待你的回答');
|
||||
});
|
||||
|
||||
it('translates the Chat / Terminal switch setting', () => {
|
||||
expect(api.t('Show the Chat / Terminal switch')).toBe('显示聊天 / 终端开关');
|
||||
expect(
|
||||
api.t(
|
||||
'Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.'
|
||||
)
|
||||
).toBe('在 Claude 会话右上角显示聊天 / 终端开关。没有它时,Alt+Shift+C 也能切换视图。手机上不可用。');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,823 @@
|
||||
/**
|
||||
* @fileoverview The chat view (chat-view.js): a session's conversation as its main view.
|
||||
*
|
||||
* What is pinned, and why:
|
||||
* - The pure helpers (`CodemanChatView` in constants.js): keep-warm turns are never drawn, a
|
||||
* growing thread appends instead of redrawing, and long prompts fold.
|
||||
* - Which sessions can show it comes from `window.__codemanChatViewModes` (the transcript
|
||||
* capability), and remote and adopted sessions never do.
|
||||
* - The chat view covers the terminal without removing it, and a session remembers its view.
|
||||
* A focus that lands on the hidden terminal moves to the conversation.
|
||||
* - A dialog in the pane shows the "waiting in the terminal" notice.
|
||||
* - Codeman's own keep-alive turn shows no status line.
|
||||
* - The toggle chord is swallowed by the xterm key handler, so it never types into the session.
|
||||
*
|
||||
* The real constants.js and chat-view.js run inside a JSDOM window.
|
||||
*
|
||||
* Port: none.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const read = (name: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8');
|
||||
|
||||
type Msg = { role: string; text: string; turn?: number; keepAlive?: boolean; queued?: boolean };
|
||||
|
||||
interface ChatHelpers {
|
||||
visibleMessages: (m: unknown) => Msg[];
|
||||
messageKey: (m: Msg) => string;
|
||||
renderPlan: (a: string[], b: string[]) => { mode: string; from?: number };
|
||||
promptFold: (t: string) => { folded: boolean; head: string; totalLines: number };
|
||||
promptText: (t: string) => string;
|
||||
elapsed: (ms: number) => string;
|
||||
}
|
||||
|
||||
function loadHelpers(): ChatHelpers {
|
||||
const context = vm.createContext({ window: {}, globalThis: {} });
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
return (context.window as { CodemanChatView: ChatHelpers }).CodemanChatView;
|
||||
}
|
||||
|
||||
describe('CodemanChatView helpers', () => {
|
||||
const h = loadHelpers();
|
||||
|
||||
it('leaves out keep-warm turns and messages without text', () => {
|
||||
const shown = h.visibleMessages([
|
||||
{ role: 'user', text: 'Fix it', turn: 1 },
|
||||
{ role: 'assistant', text: 'Done.', turn: 1 },
|
||||
{ role: 'user', text: 'nudge', turn: 2, keepAlive: true },
|
||||
{ role: 'assistant', text: 'ok', turn: 2, keepAlive: true },
|
||||
{ role: 'assistant', text: ' ', turn: 3 },
|
||||
null,
|
||||
]);
|
||||
expect(shown.map((m) => m.text)).toEqual(['Fix it', 'Done.']);
|
||||
expect(h.visibleMessages(undefined)).toEqual([]);
|
||||
});
|
||||
|
||||
it('appends when the thread only grew, and redraws when it changed', () => {
|
||||
expect(h.renderPlan(['a', 'b'], ['a', 'b'])).toEqual({ mode: 'none' });
|
||||
expect(h.renderPlan(['a', 'b'], ['a', 'b', 'c'])).toEqual({ mode: 'append', from: 2 });
|
||||
expect(h.renderPlan([], ['a'])).toEqual({ mode: 'append', from: 0 });
|
||||
expect(h.renderPlan(['a', 'b'], ['a', 'x', 'c'])).toEqual({ mode: 'replace' });
|
||||
expect(h.renderPlan(['a', 'b'], ['a'])).toEqual({ mode: 'replace' });
|
||||
});
|
||||
|
||||
it('keys a message by role, turn and text', () => {
|
||||
const a = h.messageKey({ role: 'user', text: 'hi', turn: 1 });
|
||||
expect(h.messageKey({ role: 'user', text: 'hi', turn: 1 })).toBe(a);
|
||||
expect(h.messageKey({ role: 'user', text: 'hi', turn: 2 })).not.toBe(a);
|
||||
expect(h.messageKey({ role: 'assistant', text: 'hi', turn: 1 })).not.toBe(a);
|
||||
});
|
||||
|
||||
it('folds a prompt over 12 lines to its first 6, and one enormous line too', () => {
|
||||
const short = Array.from({ length: 12 }, (_, i) => `line ${i}`).join('\n');
|
||||
expect(h.promptFold(short).folded).toBe(false);
|
||||
const long = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
|
||||
const fold = h.promptFold(long);
|
||||
expect(fold.folded).toBe(true);
|
||||
expect(fold.totalLines).toBe(30);
|
||||
expect(fold.head.split('\n')).toHaveLength(6);
|
||||
const wide = h.promptFold('x'.repeat(5000));
|
||||
expect(wide.folded).toBe(true);
|
||||
expect(wide.head.length).toBeLessThanOrEqual(801);
|
||||
});
|
||||
|
||||
it("unwraps Claude Code's pasted_content tag so a pasted prompt keeps its lines", () => {
|
||||
expect(h.promptText('<pasted_content id="a9da">\nline 1\nline 2\n</pasted_content>')).toBe('line 1\nline 2');
|
||||
expect(h.promptText('before <pasted_content>x</pasted_content> after')).toBe('before x after');
|
||||
// Claude Code 2.1.331 repeats the id on the closing tag.
|
||||
expect(h.promptText('<pasted_content id="a9da">\nA\nB\n</pasted_content id="a9da">')).toBe('A\nB');
|
||||
expect(h.promptText('a <pasted_content id="1"> left open')).toBe('a <pasted_content id="1"> left open');
|
||||
expect(h.promptText('plain')).toBe('plain');
|
||||
});
|
||||
|
||||
it('formats the running time like the CLI', () => {
|
||||
expect(h.elapsed(0)).toBe('0s');
|
||||
expect(h.elapsed(14_900)).toBe('14s');
|
||||
expect(h.elapsed(125_000)).toBe('2m 05s');
|
||||
expect(h.elapsed(3_780_000)).toBe('1h 03m');
|
||||
expect(h.elapsed(-5)).toBe('0s');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── The module in a DOM ──────────────────────────────────────────────────────
|
||||
|
||||
type Api = ReturnType<typeof vi.fn>;
|
||||
|
||||
interface ChatApp {
|
||||
activeSessionId: string | null;
|
||||
sessions: Map<string, Record<string, unknown>>;
|
||||
pendingHooks: Map<string, Set<string>>;
|
||||
_api: Api;
|
||||
_apiJson: Api;
|
||||
showToast: Api;
|
||||
_sendInputAsync: Api;
|
||||
loadAppSettingsFromStorage: () => Record<string, unknown>;
|
||||
_chatViewReload: () => void;
|
||||
onChatViewTurnEvent: (id: string, idle: boolean, keepAlive?: boolean) => void;
|
||||
chatViewEligible: (id: string) => boolean;
|
||||
chatViewModeFor: (id: string) => string;
|
||||
setChatViewMode: (id: string, mode: string) => void;
|
||||
onChatViewActiveSession: (id: string) => void;
|
||||
onChatViewHooksChanged: (id: string) => void;
|
||||
_onChatViewTranscriptUpdate: (d: { sessionId: string }) => void;
|
||||
_chatViewFetch: () => Promise<void>;
|
||||
_chatViewForget: (id: string) => void;
|
||||
_chatViewPruneModes: (ids: Set<string>) => void;
|
||||
_chatViewHide: () => void;
|
||||
_chatViewRenderStatus: () => void;
|
||||
shouldToggleChatViewFromShortcut: (e: Partial<KeyboardEvent>) => boolean;
|
||||
_chatView: {
|
||||
root: HTMLElement;
|
||||
toggle: HTMLElement;
|
||||
thread: HTMLElement;
|
||||
dialog: HTMLElement;
|
||||
scroller: HTMLElement;
|
||||
status: HTMLElement;
|
||||
statusText: HTMLElement;
|
||||
statusTimer: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
function loadModule(opts: { messages?: Msg[][] } = {}) {
|
||||
const dom = new JSDOM(
|
||||
`<!doctype html><body><input type="file" id="attachFileInput" accept="image/*,.pdf">
|
||||
<div class="terminal-wrap"><div id="terminalContainer"></div><textarea id="cjkInput"></textarea></div></body>`,
|
||||
{ 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<string, Record<string, unknown>>([
|
||||
['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<string, Set<string>>(),
|
||||
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<string, Map<string, unknown> | Set<string>>;
|
||||
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<void>((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 <p> 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"'));
|
||||
});
|
||||
});
|
||||
@@ -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<Session, 'docker'>;
|
||||
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<typeof noteClaudeConversationReport>[0];
|
||||
noteClaudeConversationReport(ctx, 's1', { transcript_path: reported });
|
||||
expect(startTranscriptWatcher).toHaveBeenCalledWith(
|
||||
's1',
|
||||
join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl')
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> = {}) =>
|
||||
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('<system-reminder>synthetic</system-reminder>'),
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -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 <script>', async () => {
|
||||
const { server } = makeServer({});
|
||||
const html = await render(server, 'a</script><b>');
|
||||
|
||||
@@ -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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
|
||||
|
||||
// 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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
|
||||
|
||||
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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
|
||||
|
||||
// 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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
|
||||
|
||||
// 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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
|
||||
// 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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
};
|
||||
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<typeof vi.fn>;
|
||||
};
|
||||
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');
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -118,6 +118,8 @@ describe('WebServer index.html <title> 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</title>')[0];
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<string, EventEmitter>;
|
||||
cleaningUp: Set<string>;
|
||||
}
|
||||
|
||||
describe('transcript:update broadcast', () => {
|
||||
const SID = 'transcript-update-session';
|
||||
let server: ServerInternals;
|
||||
let broadcast: ReturnType<typeof vi.spyOn>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user