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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user