diff --git a/CLAUDE.md b/CLAUDE.md index ccc5232a..88153684 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -236,7 +236,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Docker Compose deployment** (`docker/`): Codeman runs in a container and spawns Docker cases as **SIBLING** containers via the host socket, never nested. `resolveDockerDaemonMountSource()` maps HOME bind sources into the daemon's namespace (`CODEMAN_DOCKER_HOST_HOME`); `CODEMAN_CASES_PATH` makes workspaces resolve to the same absolute path on both sides. ⚠️ `CODEMAN_CASES_PATH` must move every consumer: resolve it only via `config/cases-dir.ts`. ⚠️ `.dockerignore` matches whole paths: keep `**/.env` or `docker/.env` secrets ship in the image. ⚠️ Long-form binds create missing sources ROOT-OWNED: `Start-Codeman.sh` pre-creates them, and `docker/entrypoint.sh` (root, `cap_add: [CHOWN, DAC_OVERRIDE, KILL, SETGID, SETUID]` against `cap_drop: ALL`, `KILL` for tini; pinned by the test) fixes ownership then drops to `PUID:PGID` via `setpriv`, never re-owning foreign dirs. ⚠️ Append `/opt/codeman-cli` and `~/.local/bin` to `PATH`, never prepend. ⚠️ `server.Dockerfile`, the compose file and `.env.example` feed the self-updater's environment gate (`docs/docker-self-update.md`). → [architecture-invariants#docker-compose-deployment](docs/architecture-invariants.md#docker-compose-deployment), `docs/docker-compose.md` -**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts`, which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md` +**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts`, which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md` **External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All eight **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp) @@ -276,7 +276,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection and drop recovery use a bounded 1 MiB `?tail=`, and a Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay) -**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only, per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME or touch handlers) and NOT persisted across reloads. The planned tile grid reuses `TerminalTile` (`docs/tile-grid-plan.md`). → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) +**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only, per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME or touch handlers) and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) + +**Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default OFF, 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-device persistence (`codeman:tile-grid`, ids only, 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 with the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) of `tileGridOpenSet` (constants.js: the stored grid, else an open split's two, else the tabs in order, the active one focused; trimmed or filled by `tileGridSetForCount`, a stored grid re-formed into its cells by `reformTileCells`), never a menu; right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. Such a tile connects before its pane exists, the server drops that resize and spawns at 120x40, and Run's own resize measures the parked terminal (nothing), so the chrome refresh calls `tile.paneStarted()` when the session's pid appears or changes. ⚠️ An agent that exited in a live pane (`paneExit`) cannot be re-attached in place (both attach routes refuse while the pane's tmux client runs, and say so in a 200 envelope): its tile shows the exit and points at Close session. ⚠️ Each header (a tile's, both split panes': Pane A gets one only while the split is open, fitted through `sendResize`/`syncTerminalGeometry`) names the harness with PR #532's `run-mode-dot ` logo (the id is data, never a branch) and `SessionState.displayModel` (src/session-display-model.ts: custom endpoint, else the newest report from the CLI itself, i.e. claude's statusline or a footer read with `capabilities.modelDetect`, else what its config pins via the named `modelDetect.configResolver` (dsh-TUI's route, `src/deepseek-route-config.ts`: read-only, bounded, nothing on doubt), else the launch model, else nothing), painted by ONE diffing `_paintSessionHarness`; the model is untrusted text (`textContent`, `data-i18n-skip`). ⚠️ zh-CN: every string the grid shows has its own `ZH_CN` entry or `translateDynamic` pattern in i18n.js (`test/tile-grid-i18n.test.ts` harvests them from the real code; add the entry with any new string), and a refresh compares with the last ENGLISH value it set, never the DOM, which holds the translation. → [architecture-invariants#tile-grid](docs/architecture-invariants.md#tile-grid) **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. 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) @@ -325,7 +327,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph ### Frontend -Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order: `constants.js`(1) → `i18n.js`(1.5) → `mobile-handlers.js`(2) → `voice-input.js`(3) → `notification-manager.js`(4) → `keyboard-accessory.js`(5) → `input-cjk.js`(5.5) → `mobile-ime-preview.js`(5.52) → `terminal-keycode229-recovery.js`(5.55) → `sanitize-html.js`(5.6) → `tab-layout-browser.js`(5.9) → `app.js`(6) → `tab-rail-resize.js`(6.5) → `terminal-ui.js`(7) → `terminal-tile.js`(7.4) → `terminal-split.js`(7.5) → `respawn-ui.js`(8) → `ralph-panel.js`(9) → `orchestrator-panel.js`(9.5) → `cron-ui.js`(9.7) → `settings-ui.js`(10) → `panels-ui.js`(11) → `readmymind-ui.js`(11.3) → `ultracode-panel.js`(11.5) → `approvals-ui.js`(11.6) → `reboot-restore-ui.js`(11.65) → `admin-ui.js`(11.7) → `session-ui.js`(12) → `host-wake-ui.js`(12.2) → `webview-tabs.js`(12.5) → `mobile-overview.js`(12.55) → `home-sessions.js`(12.56) → `git-status-ui.js`(12.57) → `entrance-animations.js`(12.6) → `ralph-wizard.js`(13) → `api-client.js`(14) → `subagent-windows.js`(15) → `ultracode-windows.js`(15.5) → `session-lineage.js`(15.6) → `image-input.js`(16). `i18n.js` translates static + newly inserted application DOM while skipping terminal/response/file/user-name surfaces; `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData). `terminal-keycode229-recovery.js` forwards a committed `input` event that xterm's `_inputEvent` guard drops (Chrome-on-Android soft keyboards send `composed: true` after a keydown), and only when xterm emitted no canonical data for that keystroke. ⚠️ **That decision is settled at the NEXT keydown as well as on its own zero-delay timer** (#441): the drain runs from xterm's custom key handler, which fires BEFORE xterm processes that key, so a soft keyboard that commits the last character and sends Enter in one InputConnection transaction puts the character on the wire ahead of the `\r`. On the timer alone that character is not merely late, it is LOST: xterm emits the `\r` first and bumps the canonical counter past the candidate's snapshot, so the candidate stands down (measured, `hell\r` where the user typed `hello`). The trade is that a keydown decides with less evidence than the timer did, since xterm's own keyCode-229 rescue has not run yet; that is safe for Enter, which clears the textarea so the pending diff emits nothing. Ordering is pinned by `test/terminal-keycode229-recovery.browser.test.ts`, which the CI gate does NOT run. `mobile-ime-preview.js` (iOS WebKit only) paints the text an IME is composing: an iOS IME commit is routed into the local-echo overlay through the ordinary printable/paste branch and then `_transferMobileImeCommitToLocalEcho`, and without local echo the preview clears only on output parsed AFTER the commit (or its 2 s fallback). ⚠️ It watches keydown in the capture phase on `terminal.element`, never on the textarea, because xterm finalizes the composition and emits the commit in its own capture listener on the textarea. +Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order: `constants.js`(1) → `i18n.js`(1.5) → `mobile-handlers.js`(2) → `voice-input.js`(3) → `notification-manager.js`(4) → `keyboard-accessory.js`(5) → `input-cjk.js`(5.5) → `mobile-ime-preview.js`(5.52) → `terminal-keycode229-recovery.js`(5.55) → `sanitize-html.js`(5.6) → `tab-layout-browser.js`(5.9) → `app.js`(6) → `tab-rail-resize.js`(6.5) → `terminal-ui.js`(7) → `terminal-tile.js`(7.4) → `terminal-split.js`(7.5) → `tile-grid.js`(7.6) → `respawn-ui.js`(8) → `ralph-panel.js`(9) → `orchestrator-panel.js`(9.5) → `cron-ui.js`(9.7) → `settings-ui.js`(10) → `panels-ui.js`(11) → `readmymind-ui.js`(11.3) → `ultracode-panel.js`(11.5) → `approvals-ui.js`(11.6) → `reboot-restore-ui.js`(11.65) → `admin-ui.js`(11.7) → `session-ui.js`(12) → `host-wake-ui.js`(12.2) → `webview-tabs.js`(12.5) → `mobile-overview.js`(12.55) → `home-sessions.js`(12.56) → `git-status-ui.js`(12.57) → `entrance-animations.js`(12.6) → `ralph-wizard.js`(13) → `api-client.js`(14) → `subagent-windows.js`(15) → `ultracode-windows.js`(15.5) → `session-lineage.js`(15.6) → `image-input.js`(16). `i18n.js` translates static + newly inserted application DOM while skipping terminal/response/file/user-name surfaces; `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData). `terminal-keycode229-recovery.js` forwards a committed `input` event that xterm's `_inputEvent` guard drops (Chrome-on-Android soft keyboards send `composed: true` after a keydown), and only when xterm emitted no canonical data for that keystroke. ⚠️ **That decision is settled at the NEXT keydown as well as on its own zero-delay timer** (#441): the drain runs from xterm's custom key handler, which fires BEFORE xterm processes that key, so a soft keyboard that commits the last character and sends Enter in one InputConnection transaction puts the character on the wire ahead of the `\r`. On the timer alone that character is not merely late, it is LOST: xterm emits the `\r` first and bumps the canonical counter past the candidate's snapshot, so the candidate stands down (measured, `hell\r` where the user typed `hello`). The trade is that a keydown decides with less evidence than the timer did, since xterm's own keyCode-229 rescue has not run yet; that is safe for Enter, which clears the textarea so the pending diff emits nothing. Ordering is pinned by `test/terminal-keycode229-recovery.browser.test.ts`, which the CI gate does NOT run. `mobile-ime-preview.js` (iOS WebKit only) paints the text an IME is composing: an iOS IME commit is routed into the local-echo overlay through the ordinary printable/paste branch and then `_transferMobileImeCommitToLocalEcho`, and without local echo the preview clears only on output parsed AFTER the commit (or its 2 s fallback). ⚠️ It watches keydown in the capture phase on `terminal.element`, never on the textarea, because xterm finalizes the composition and emits the commit in its own capture listener on the textarea. **Entrance animations** (`entrance-animations.js`, all OFF by default): opt-in animations for tabs, terminal, windows and connection lines, chosen via `data-tab-anim` / `data-term-anim` / `data-win-anim` / `data-line-anim` on ``; the default `legacy` theme short-circuits every hook. ⚠️ Tabs and lines are destroyed mid-animation on re-render, so re-apply to the fresh element by id with a negative `animation-delay` (resume, never restart). ⚠️ Terminal-pane styles may animate only transform / opacity / clip-path (anything else resizes the PTY via FitAddon); `blur` is the ONE sanctioned `filter` exception, do not generalise it. ⚠️ Line glow lives in `--line-glow` so blur keyframes interpolate. Persisted per-device in `codeman:*Anim` localStorage keys, never in `SettingsUpdateSchema`; lab at `?animlab=1`. Test: `test/entrance-animations.test.ts`. → [architecture-invariants#entrance-animations](docs/architecture-invariants.md#entrance-animations) @@ -347,7 +349,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L **Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `
` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `Font Size @@ -1913,7 +1932,8 @@ - + + @@ -3920,6 +3940,7 @@ + diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index 9b2bf1b4..63a49be8 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -573,6 +573,10 @@ Object.assign(CodemanApp.prototype, { } if (session?.id) this._onSessionCreated(session); + // A session this tab's Run created joins an open tile grid (tile-grid.js), + // so Run's selectSession() below focuses its tile instead of leaving the + // grid. Only here: sessions created elsewhere arrive by session:created. + this._joinTileGridFromRun?.(sessionId); // session:created normally uses the debounced renderer. The direct POST path // needs the tab in the DOM before selectSession() marks it active. this._renderSessionTabsImmediate?.(); diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index e8fed034..70a6ffd1 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -430,6 +430,7 @@ Object.assign(CodemanApp.prototype, { settings.ultracodeFloatingWindows ?? defaults.ultracodeFloatingWindows ?? false; document.getElementById('appSettingsShowMultiMonitorButton').checked = settings.showMultiMonitorButton ?? defaults.showMultiMonitorButton ?? false; document.getElementById('appSettingsShowSplitButton').checked = settings.showSplitButton ?? defaults.showSplitButton ?? false; + document.getElementById('appSettingsShowTileGridButton').checked = settings.showTileGridButton ?? defaults.showTileGridButton ?? false; document.getElementById('appSettingsShowPlanUsageLimits').checked = this.planUsageChipEnabled(settings); document.getElementById('appSettingsShowRedrawButton').checked = settings.showRedrawButton ?? defaults.showRedrawButton ?? false; // Phone overview home screen: only meaningful under 600px, so the row is @@ -2492,6 +2493,7 @@ Object.assign(CodemanApp.prototype, { ultracodeFloatingWindows: document.getElementById('appSettingsUltracodeFloatingWindows').checked, showMultiMonitorButton: document.getElementById('appSettingsShowMultiMonitorButton').checked, showSplitButton: document.getElementById('appSettingsShowSplitButton').checked, + showTileGridButton: document.getElementById('appSettingsShowTileGridButton').checked, showPlanUsageLimits: document.getElementById('appSettingsShowPlanUsageLimits').checked, showRedrawButton: document.getElementById('appSettingsShowRedrawButton').checked, mobileOverviewEnabled: document.getElementById('appSettingsMobileOverview').checked, @@ -2730,6 +2732,9 @@ Object.assign(CodemanApp.prototype, { // SettingsUpdateSchema (.strict()) — sending it 400s the whole PUT // (moving it into displayKeys alone is not the strip; this is). showSplitButton: _ssp, + // Same as Split: a per-device header button (and the Tiles chord), absent + // from SettingsUpdateSchema (.strict()), so sending it 400s the whole PUT. + showTileGridButton: _stg, webglRendererEnabled: _wgl, terminalWheelLocalScrollback: _twls, // Copy-on-select. Per-device (clipboard access differs by device and by @@ -3420,6 +3425,7 @@ Object.assign(CodemanApp.prototype, { ultracodeFloatingWindows: false, showMultiMonitorButton: false, showSplitButton: false, + showTileGridButton: false, // Desktop defaults this ON (see planUsageChipEnabled); handhelds keep it // OFF so the phone header stays minimal and the mobile-header-buttons // policy guard keeps passing. @@ -3632,6 +3638,10 @@ Object.assign(CodemanApp.prototype, { const showSplitButton = settings.showSplitButton ?? defaults.showSplitButton ?? false; this._applySplitButtonVisibility?.(showSplitButton); + // Tiles button: same gate and backstop as Split (tile-grid.js). + const showTileGridButton = settings.showTileGridButton ?? defaults.showTileGridButton ?? false; + this._applyTileGridButtonVisibility?.(showTileGridButton); + // Ultracode/Workflow agents launcher — hidden by default; reveal when enabled. // Marker class only (base is display:inline-flex !important) so it's auto-excluded // from the mobile-header-buttons-policy guard. @@ -4053,6 +4063,7 @@ Object.assign(CodemanApp.prototype, { 'mobileOverviewEnabled', 'sessionLineageLines', 'showSplitButton', + 'showTileGridButton', ]); // The plan-usage chip is a PER-DEVICE display setting (desktop default ON, // handheld default OFF): desktop can show it while mobile stays hidden. Drop diff --git a/src/web/public/styles.css b/src/web/public/styles.css index b2718c82..344bd49a 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -2450,7 +2450,73 @@ html[data-tab-orientation='vertical'].tab-rail-compact .btn-icon-header:hover { background: rgba(255, 255, 255, 0.07); color: var(--text); - transform: rotate(45deg); +} + +/* Hover motion moves the icon, never the button: turning the whole button used + to swing its hover background into a diamond on every header icon. Now only the + gear turns, the folder opens and the Tiles squares spread apart; every other + icon just takes the hover colour. Pointer devices only (a tap must not leave an + icon stuck mid-motion), and no motion at all under reduced motion. */ +.btn-icon-header.btn-settings svg, +.btn-icon-header.btn-tile-grid svg rect, +.btn-icon-header.btn-file-viewer svg .icon-folder-closed, +.btn-icon-header.btn-file-viewer svg .icon-folder-open { + transition: transform 260ms cubic-bezier(0.34, 1.56, 0.64, 1), opacity 160ms ease; +} + +.btn-icon-header.btn-tile-grid svg rect { + transform-box: fill-box; + transform-origin: center; +} + +.btn-icon-header.btn-file-viewer svg .icon-folder-open { + opacity: 0; + transform: translateY(1px); +} + +@media (hover: hover) { + .btn-icon-header.btn-settings:hover svg { + transform: rotate(45deg); + } + + .btn-icon-header.btn-tile-grid:hover svg rect:nth-of-type(1) { + transform: translate(-1.5px, -1.5px); + } + + .btn-icon-header.btn-tile-grid:hover svg rect:nth-of-type(2) { + transform: translate(1.5px, -1.5px); + } + + .btn-icon-header.btn-tile-grid:hover svg rect:nth-of-type(3) { + transform: translate(-1.5px, 1.5px); + } + + .btn-icon-header.btn-tile-grid:hover svg rect:nth-of-type(4) { + transform: translate(1.5px, 1.5px); + } + + .btn-icon-header.btn-file-viewer:hover svg .icon-folder-closed { + opacity: 0; + } + + .btn-icon-header.btn-file-viewer:hover svg .icon-folder-open { + opacity: 1; + transform: none; + } +} + +@media (prefers-reduced-motion: reduce) { + .btn-icon-header.btn-settings svg, + .btn-icon-header.btn-tile-grid svg rect, + .btn-icon-header.btn-file-viewer svg .icon-folder-closed, + .btn-icon-header.btn-file-viewer svg .icon-folder-open { + transition: none; + } + + .btn-icon-header.btn-settings:hover svg, + .btn-icon-header.btn-tile-grid:hover svg rect { + transform: none; + } } /* Admin Panel header button: only shown to admins in multi-user mode (marker @@ -2510,6 +2576,25 @@ html[data-tab-orientation='vertical'].tab-rail-compact display: none !important; } +/* Tile grid header button: hidden by default (opt-in, `showTileGridButton`), + and hard-gated to desktop widths like Split (the backstop below). */ +.btn-tile-grid--hidden { + display: none !important; +} + +/* While the grid is open the button's click closes it (aria-pressed too). */ +.btn-icon-header.btn-tile-grid.tiles-open, +.btn-icon-header.btn-tile-grid.tiles-open:hover { + background: var(--accent); + color: var(--accent-ink); +} + +/* The tile grid is open (tile-grid.js): the split cannot open beside it. */ +.btn-split.btn-split--blocked { + opacity: 0.4; + cursor: not-allowed; +} + /* While a split is open, the button's own click closes it instead of opening the picker — the accent fill is what tells the user which of its two behaviours the next click will get (aria-pressed carries the same state @@ -2531,7 +2616,8 @@ html[data-tab-orientation='vertical'].tab-rail-compact HOME_SESSIONS_MIN_WIDTH (home-sessions.js) / SPLIT_PANE_MIN_WIDTH (constants.js) — keep the three in sync. */ @media (max-width: 1179px) { - .btn-icon-header.btn-split { + .btn-icon-header.btn-split, + .btn-icon-header.btn-tile-grid { display: none !important; } } @@ -2549,10 +2635,6 @@ html[data-tab-orientation='vertical'].tab-rail-compact font-weight: 600; } -.btn-icon-header.btn-sm:hover { - transform: none; -} - .header-font-controls { display: flex; align-items: center; @@ -2847,6 +2929,7 @@ body.solo-mode .header-tokens, body.solo-mode .btn-notifications, body.solo-mode .btn-multimonitor, body.solo-mode .btn-split, +body.solo-mode .btn-tile-grid, body.solo-mode .header-plan-usage, /* A solo window shows ONE session and has no tab strip to put restored ones in, so offering to rebuild a list of them there is an offer it cannot show the @@ -4340,8 +4423,8 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { transform: translateY(-1px); } -/* Antigravity: cyan identity, matching .btn-toolbar.btn-run.mode-antigravity and - .run-mode-dot.antigravity so the welcome action reads as the same backend. */ +/* Antigravity: cyan identity, matching .btn-toolbar.btn-run.mode-antigravity so + the welcome action reads as the same backend. */ .welcome-btn-antigravity { background: linear-gradient(135deg, #0b2b33 0%, #0e7490 55%, #0891b2 100%); border-color: rgba(34, 211, 238, 0.4); @@ -4357,8 +4440,8 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { transform: translateY(-1px); } -/* Pi (pi.dev): rose identity, matching .btn-toolbar.btn-run.mode-pi and - .run-mode-dot.pi so the welcome action reads as the same backend. */ +/* Pi (pi.dev): rose identity, matching .btn-toolbar.btn-run.mode-pi so the + welcome action reads as the same backend. */ .welcome-btn-pi { background: linear-gradient(135deg, #33121f 0%, #9d174d 55%, #be185d 100%); border-color: rgba(244, 114, 182, 0.4); @@ -4373,8 +4456,8 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { color: #fff1f7; transform: translateY(-1px); } -/* OMP: indigo identity, matching .btn-toolbar.btn-run.mode-omp and - .run-mode-dot.omp so the welcome action reads as the same backend. */ +/* OMP: indigo identity, matching .btn-toolbar.btn-run.mode-omp so the welcome + action reads as the same backend. */ .welcome-btn-omp { background: linear-gradient(135deg, #1e1b4b 0%, #4f46e5 55%, #6366f1 100%); border-color: rgba(129, 140, 248, 0.4); @@ -4391,7 +4474,7 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { } /* Grok (xAI): monochrome charcoal identity, matching .btn-toolbar.btn-run.mode-grok - and .run-mode-dot.grok so the welcome action reads as the same backend. */ + so the welcome action reads as the same backend. */ .welcome-btn-grok { background: linear-gradient(135deg, #131316 0%, #27272a 55%, #3f3f46 100%); border-color: rgba(212, 212, 216, 0.4); @@ -4408,8 +4491,8 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { } /* DeepSeek Harness: the #4d6bfe blue identity, matching - .btn-toolbar.btn-run.mode-deepseek and .run-mode-dot.deepseek so the welcome - action reads as the same backend. */ + .btn-toolbar.btn-run.mode-deepseek so the welcome action reads as the same + backend. */ .welcome-btn-deepseek { background: linear-gradient(135deg, #101a4d 0%, #2740c4 55%, #4d6bfe 100%); border-color: rgba(124, 147, 255, 0.4); @@ -5628,17 +5711,62 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { height: 8px; border-radius: 50%; flex-shrink: 0; + background: var(--text-dim); } -.run-mode-dot.claude { background: #3b82f6; } -.run-mode-dot.opencode { background: #10b981; } -.run-mode-dot.codex { background: #a855f7; } -.run-mode-dot.gemini { background: #8ab4f8; } -.run-mode-dot.antigravity { background: #22d3ee; } -.run-mode-dot.pi { background: #f472b6; } -.run-mode-dot.grok { background: #a1a1aa; } -.run-mode-dot.deepseek { background: #4d6bfe; } -.run-mode-dot.omp { background: #818cf8; } -.run-mode-dot.shell { background: #94a3b8; } +/* Every backend the Run menus know draws its own logo in this slot instead of a + colour dot. The toolbar menu, the phone overview picker, the Custom Endpoint + rows and the model picker all render `.run-mode-dot `, so they pick this + up with no markup change. An id with no rule here (a CLI added through + ~/.codeman/clis.json, say) keeps the plain 8px dot. + Logos: @lobehub/icons-static-svg 1.95.1 (MIT, (c) LobeHub); the OMP mark is + the one omp.sh draws in its own header (oh-my-pi, MIT). The marks are their + owners' trademarks, shown only to name the CLI a row launches. */ +.run-mode-dot.claude, +.run-mode-dot.gemini, +.run-mode-dot.antigravity, +.run-mode-dot.deepseek, +.run-mode-dot.omp, +.run-mode-dot.codex, +.run-mode-dot.opencode, +.run-mode-dot.pi, +.run-mode-dot.grok, +.run-mode-dot.shell, +.run-mode-dot.web { + width: 1.15em; + height: 1.15em; + border-radius: 0; +} +/* Brand-coloured marks read on dark and light skins alike, so they paint as is. */ +.run-mode-dot.claude, +.run-mode-dot.gemini, +.run-mode-dot.antigravity, +.run-mode-dot.deepseek, +.run-mode-dot.omp { + background: var(--run-mode-logo) center / contain no-repeat; +} +/* Monochrome marks are masks over the row's own text colour, so they follow + every skin (light ones included) the way the label next to them does. */ +.run-mode-dot.codex, +.run-mode-dot.opencode, +.run-mode-dot.pi, +.run-mode-dot.grok, +.run-mode-dot.shell, +.run-mode-dot.web { + background-color: currentColor; + -webkit-mask: var(--run-mode-logo) center / contain no-repeat; + mask: var(--run-mode-logo) center / contain no-repeat; +} +.run-mode-dot.claude { --run-mode-logo: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z' fill='%23D97757' fill-rule='nonzero'/%3E%3C/svg%3E"); } +.run-mode-dot.gemini { --run-mode-logo: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z' fill='%233186FF'/%3E%3Cpath d='M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z' fill='url(%23gemini0)'/%3E%3Cpath d='M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z' fill='url(%23gemini1)'/%3E%3Cpath d='M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z' fill='url(%23gemini2)'/%3E%3Cdefs%3E%3ClinearGradient gradientUnits='userSpaceOnUse' id='gemini0' x1='7' x2='11' y1='15.5' y2='12'%3E%3Cstop stop-color='%2308B962'/%3E%3Cstop offset='1' stop-color='%2308B962' stop-opacity='0'/%3E%3C/linearGradient%3E%3ClinearGradient gradientUnits='userSpaceOnUse' id='gemini1' x1='8' x2='11.5' y1='5.5' y2='11'%3E%3Cstop stop-color='%23F94543'/%3E%3Cstop offset='1' stop-color='%23F94543' stop-opacity='0'/%3E%3C/linearGradient%3E%3ClinearGradient gradientUnits='userSpaceOnUse' id='gemini2' x1='3.5' x2='17.5' y1='13.5' y2='12'%3E%3Cstop stop-color='%23FABC12'/%3E%3Cstop offset='.46' stop-color='%23FABC12' stop-opacity='0'/%3E%3C/linearGradient%3E%3C/defs%3E%3C/svg%3E"); } +.run-mode-dot.antigravity { --run-mode-logo: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cmask height='23' id='antigravity0' maskUnits='userSpaceOnUse' width='24' x='0' y='1'%3E%3Cpath d='M21.751 22.607c1.34 1.005 3.35.335 1.508-1.508C17.73 15.74 18.904 1 12.037 1 5.17 1 6.342 15.74.815 21.1c-2.01 2.009.167 2.511 1.507 1.506 5.192-3.517 4.857-9.714 9.715-9.714 4.857 0 4.522 6.197 9.714 9.715z' fill='%23fff'/%3E%3C/mask%3E%3Cg mask='url(%23antigravity0)'%3E%3Cg filter='url(%23antigravity1)'%3E%3Cpath d='M-1.018-3.992c-.408 3.591 2.686 6.89 6.91 7.37 4.225.48 7.98-2.043 8.387-5.633.408-3.59-2.686-6.89-6.91-7.37-4.225-.479-7.98 2.043-8.387 5.633z' fill='%23FFE432'/%3E%3C/g%3E%3Cg filter='url(%23antigravity2)'%3E%3Cpath d='M15.269 7.747c1.058 4.557 5.691 7.374 10.348 6.293 4.657-1.082 7.575-5.653 6.516-10.21-1.058-4.556-5.691-7.374-10.348-6.292-4.657 1.082-7.575 5.653-6.516 10.21z' fill='%23FC413D'/%3E%3C/g%3E%3Cg filter='url(%23antigravity3)'%3E%3Cpath d='M-12.443 10.804c1.338 4.703 7.36 7.11 13.453 5.378 6.092-1.733 9.947-6.95 8.61-11.652C8.282-.173 2.26-2.58-3.833-.848-9.925.884-13.78 6.1-12.443 10.804z' fill='%2300B95C'/%3E%3C/g%3E%3Cg filter='url(%23antigravity4)'%3E%3Cpath d='M-12.443 10.804c1.338 4.703 7.36 7.11 13.453 5.378 6.092-1.733 9.947-6.95 8.61-11.652C8.282-.173 2.26-2.58-3.833-.848-9.925.884-13.78 6.1-12.443 10.804z' fill='%2300B95C'/%3E%3C/g%3E%3Cg filter='url(%23antigravity5)'%3E%3Cpath d='M-7.608 14.703c3.352 3.424 9.126 3.208 12.896-.483 3.77-3.69 4.108-9.459.756-12.883C2.69-2.087-3.083-1.871-6.853 1.82c-3.77 3.69-4.108 9.458-.755 12.883z' fill='%2300B95C'/%3E%3C/g%3E%3Cg filter='url(%23antigravity6)'%3E%3Cpath d='M9.932 27.617c1.04 4.482 5.384 7.303 9.7 6.3 4.316-1.002 6.971-5.448 5.93-9.93-1.04-4.483-5.384-7.304-9.7-6.301-4.316 1.002-6.971 5.448-5.93 9.93z' fill='%233186FF'/%3E%3C/g%3E%3Cg filter='url(%23antigravity7)'%3E%3Cpath d='M2.572-8.185C.392-3.329 2.778 2.472 7.9 4.771c5.122 2.3 11.042.227 13.222-4.63 2.18-4.855-.205-10.656-5.327-12.955-5.122-2.3-11.042-.227-13.222 4.63z' fill='%23FBBC04'/%3E%3C/g%3E%3Cg filter='url(%23antigravity8)'%3E%3Cpath d='M-3.267 38.686c-5.277-2.072 3.742-19.117 5.984-24.83 2.243-5.712 8.34-8.664 13.616-6.592 5.278 2.071 11.533 13.482 9.29 19.195-2.242 5.713-23.613 14.298-28.89 12.227z' fill='%233186FF'/%3E%3C/g%3E%3Cg filter='url(%23antigravity9)'%3E%3Cpath d='M28.71 17.471c-1.413 1.649-5.1.808-8.236-1.878-3.135-2.687-4.531-6.201-3.118-7.85 1.412-1.649 5.1-.808 8.235 1.878s4.532 6.2 3.119 7.85z' fill='%23749BFF'/%3E%3C/g%3E%3Cg filter='url(%23antigravity10)'%3E%3Cpath d='M18.163 9.077c5.81 3.93 12.502 4.19 14.946.577 2.443-3.612-.287-9.727-6.098-13.658-5.81-3.931-12.502-4.19-14.946-.577-2.443 3.612.287 9.727 6.098 13.658z' fill='%23FC413D'/%3E%3C/g%3E%3Cg filter='url(%23antigravity11)'%3E%3Cpath d='M-.915 2.684c-1.44 3.473-.97 6.967 1.05 7.804 2.02.837 4.824-1.3 6.264-4.772 1.44-3.473.97-6.967-1.05-7.804-2.02-.837-4.824 1.3-6.264 4.772z' fill='%23FFEE48'/%3E%3C/g%3E%3C/g%3E%3Cdefs%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='17.587' id='antigravity1' width='19.838' x='-3.288' y='-11.917'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='1.117'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='38.565' id='antigravity2' width='38.9' x='4.251' y='-13.493'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='5.4'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='36.517' id='antigravity3' width='40.955' x='-21.889' y='-10.592'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='4.591'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='36.517' id='antigravity4' width='40.955' x='-21.889' y='-10.592'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='4.591'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='36.595' id='antigravity5' width='36.632' x='-19.099' y='-10.278'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='4.591'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='34.087' id='antigravity6' width='33.533' x='.981' y='8.758'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='4.363'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='35.276' id='antigravity7' width='35.978' x='-6.143' y='-21.659'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='3.954'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='46.523' id='antigravity8' width='45.114' x='-11.96' y='-.46'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='3.531'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='24.054' id='antigravity9' width='25.094' x='10.485' y='.58'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='3.159'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='30.007' id='antigravity10' width='33.508' x='5.833' y='-12.467'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='2.669'/%3E%3C/filter%3E%3Cfilter color-interpolation-filters='sRGB' filterUnits='userSpaceOnUse' height='26.151' id='antigravity11' width='22.194' x='-8.355' y='-8.876'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeBlend in='SourceGraphic' in2='BackgroundImageFix' result='shape'/%3E%3CfeGaussianBlur result='effect1_foregroundBlur_977_115' stdDeviation='3.303'/%3E%3C/filter%3E%3C/defs%3E%3C/svg%3E"); } +.run-mode-dot.deepseek { --run-mode-logo: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z' fill='%234D6BFE'/%3E%3C/svg%3E"); } +.run-mode-dot.omp { --run-mode-logo: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='8 11 48 48'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%23ed4abf'/%3E%3Cstop offset='.5' stop-color='%239b4dff'/%3E%3Cstop offset='1' stop-color='%235ad8e6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cpath fill='url(%23g)' d='M10 14h44v9H43v33h-9V23h-9v22h-9V23H10z'/%3E%3C/svg%3E"); } +.run-mode-dot.codex { --run-mode-logo: url("data:image/svg+xml,%3Csvg fill-rule='evenodd' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath clip-rule='evenodd' d='M8.086.457a6.105 6.105 0 013.046-.415c1.333.153 2.521.72 3.564 1.7a.117.117 0 00.107.029c1.408-.346 2.762-.224 4.061.366l.063.03.154.076c1.357.703 2.33 1.77 2.918 3.198.278.679.418 1.388.421 2.126a5.655 5.655 0 01-.18 1.631.167.167 0 00.04.155 5.982 5.982 0 011.578 2.891c.385 1.901-.01 3.615-1.183 5.14l-.182.22a6.063 6.063 0 01-2.934 1.851.162.162 0 00-.108.102c-.255.736-.511 1.364-.987 1.992-1.199 1.582-2.962 2.462-4.948 2.451-1.583-.008-2.986-.587-4.21-1.736a.145.145 0 00-.14-.032c-.518.167-1.04.191-1.604.185a5.924 5.924 0 01-2.595-.622 6.058 6.058 0 01-2.146-1.781c-.203-.269-.404-.522-.551-.821a7.74 7.74 0 01-.495-1.283 6.11 6.11 0 01-.017-3.064.166.166 0 00.008-.074.115.115 0 00-.037-.064 5.958 5.958 0 01-1.38-2.202 5.196 5.196 0 01-.333-1.589 6.915 6.915 0 01.188-2.132c.45-1.484 1.309-2.648 2.577-3.493.282-.188.55-.334.802-.438.286-.12.573-.22.861-.304a.129.129 0 00.087-.087A6.016 6.016 0 015.635 2.31C6.315 1.464 7.132.846 8.086.457zm-.804 7.85a.848.848 0 00-1.473.842l1.694 2.965-1.688 2.848a.849.849 0 001.46.864l1.94-3.272a.849.849 0 00.007-.854l-1.94-3.393zm5.446 6.24a.849.849 0 000 1.695h4.848a.849.849 0 000-1.696h-4.848z'/%3E%3C/svg%3E"); } +.run-mode-dot.opencode { --run-mode-logo: url("data:image/svg+xml,%3Csvg fill-rule='evenodd' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M16 6H8v12h8V6zm4 16H4V2h16v20z'/%3E%3C/svg%3E"); } +.run-mode-dot.pi { --run-mode-logo: url("data:image/svg+xml,%3Csvg fill-rule='evenodd' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath clip-rule='evenodd' d='M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z'/%3E%3Cpath d='M17.5 12H23v11h-5.5V12z'/%3E%3C/svg%3E"); } +.run-mode-dot.grok { --run-mode-logo: url("data:image/svg+xml,%3Csvg fill-rule='evenodd' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815'/%3E%3C/svg%3E"); } +.run-mode-dot.shell { --run-mode-logo: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2.5' y='3.5' width='19' height='17' rx='3'/%3E%3Cpath d='M7 9.5l3 2.5-3 2.5M12.5 15h4.5'/%3E%3C/svg%3E"); } +.run-mode-dot.web { --run-mode-logo: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2'%3E%3Ccircle cx='12' cy='12' r='10'/%3E%3Cpath d='M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20'/%3E%3C/svg%3E"); } /* Phone-only Enter button (see index.html). Hidden by default at every width; mobile.css turns it on inside @media (max-width: 599px), where it takes over @@ -9129,10 +9257,6 @@ kbd { margin-right: 2px; } -.btn-icon-header.btn-notifications:hover { - transform: none; -} - .notification-badge { position: absolute; top: 2px; @@ -15671,10 +15795,6 @@ html:not([data-skin="og"]) { color: var(--accent-ink); } .btn-toolbar.btn-run-gear:hover { background: var(--gear-hover); box-shadow: none; } -.run-mode-dot.claude { background: var(--accent); } -.run-mode-dot.opencode { background: var(--accent-soft); } -.run-mode-dot.codex { background: var(--accent-grad-b); } -.run-mode-dot.shell { background: var(--text-dim); } /* ---- Shell button: quiet neutral with a calm green tint ---- */ .btn-toolbar.btn-shell { @@ -15971,7 +16091,6 @@ html[data-skin="daylight-blue"] .welcome-btn-tunnel.active:hover { .session-tab--web.active .tab-web-icon { color: var(--accent, #3ec8ee); } .session-tab--web.active { border-bottom-color: var(--accent, #3ec8ee); } -.run-mode-dot.web { background: #38bdf8; } .run-mode-webviews { max-height: 180px; overflow-y: auto; } /* Custom Model Endpoint Profiles' generated entries: `.run-mode-menu.active`'s own `gap: 2px` only spaces its DIRECT children, and this container (like @@ -19111,11 +19230,6 @@ html[data-session-list="sidebar"][data-sidebar="collapsed"] .session-sidebar .ta display: none !important; } -/* .btn-icon-header:hover rotates 45deg globally — a panel glyph must not spin. */ -.btn-sidebar-toggle:hover { - transform: none; -} - html[data-session-list="sidebar"][data-sidebar="collapsed"] .btn-sidebar-toggle svg { transform: scaleX(-1); } @@ -19315,31 +19429,33 @@ html[data-session-list="sidebar"][data-sidebar="collapsed"] .btn-sidebar-toggle overflow: hidden; } +/* A split pane's header strip, Pane B's always and Pane A's while the split is + open: harness logo, name, model, and Pane B's close (a tile button, see + .tile-btn). The tile header's size and layout, FIXED height like it (#464): + the terminal below is fitted to what is left. */ .terminal-pane-b-header { display: flex; align-items: center; - justify-content: space-between; - padding: 4px 8px; + gap: 6px; + flex: 0 0 28px; + height: 28px; + box-sizing: border-box; + padding: 0 2px 0 8px; + overflow: hidden; font-size: 12px; background: var(--bg-secondary, #1a1a1a); border-bottom: 1px solid var(--border-color, #333); - flex: 0 0 auto; + user-select: none; } -.terminal-pane-b-close { - /* A native - -
- `; + // Pane B's header: the harness logo, the name and the model, as on a grid + // tile, and the close button at a tile button's size. + const headerB = this._buildSplitPaneHeader(); + const close = document.createElement('button'); + close.type = 'button'; + close.className = 'tile-btn tile-remove terminal-pane-b-close'; + close.title = 'Close split'; + close.setAttribute('aria-label', 'Close split'); + close.textContent = '\u00D7'; + close.addEventListener('click', () => this.closeSplitPane()); + headerB.el.appendChild(close); + const bodyB = document.createElement('div'); + bodyB.className = 'terminal-pane-b-container'; + paneB.append(headerB.el, bodyB); + // Pane A is the main terminal, which has no header of its own: while the + // split is open it gets the same strip, so each session in the split view + // names its harness and model. It takes height from the main terminal, + // which the opening resize below fits through syncTerminalGeometry (#464); + // closeSplitPane gives it back. + const headerA = this._buildSplitPaneHeader(); + headerA.el.classList.add('terminal-pane-a-header'); + this._splitHeaders = { a: headerA, b: headerB }; parent.insertBefore(container, wrap); + wrap.insertBefore(headerA.el, wrap.firstChild); container.appendChild(wrap); wrap.style.flexBasis = '50%'; container.appendChild(divider); container.appendChild(paneB); paneB.style.flexBasis = '50%'; - this._splitPane = new window.TerminalTile(sessionId, paneB.querySelector('.terminal-pane-b-container'), { + this._splitPane = new window.TerminalTile(sessionId, bodyB, { mode: session?.mode, fontSettings: this.loadAppSettingsFromStorage?.() || {}, detachedSessions: this.detachedSessions, @@ -204,6 +225,7 @@ Object.assign(CodemanApp.prototype, { initial load — live output still arrives once/if the socket connects. */ }); this._splitSessionId = sessionId; + this._renderSplitChrome(); // Pane A just went from full width to 50%, but nothing has told its // session's PTY/tmux window about it yet — the passive ResizeObserver in @@ -231,6 +253,9 @@ Object.assign(CodemanApp.prototype, { this._splitPane.destroy(); this._splitPane = null; this._splitSessionId = null; + // Before the refit below, so the main terminal gets its full height back. + this._splitHeaders?.a.el.remove(); + this._splitHeaders = null; this._updateSplitButtonState(false); const container = document.querySelector('.terminal-split-container'); @@ -241,14 +266,16 @@ Object.assign(CodemanApp.prototype, { parent.insertBefore(wrap, container); container.remove(); - if (this.fitAddon) this.fitAddon.fit(); + // Pane A takes the whole width back and, with its header strip gone, its + // whole height: through syncTerminalGeometry (#464), never a bare + // fitAddon.fit(). sendResize fits that way as its first step. // The Pane-A-ends branch of the _onSessionDeleted wrapper below collapses the split // while activeSessionId is still the id the server just removed, so a // resize from here would be aimed at a session that no longer exists; - // the promoted session gets its own resize from selectSession(). - if (!options.skipPrimaryResize) { - this.sendResize?.(this.activeSessionId, { force: true })?.catch?.(() => {}); - } + // the promoted session gets its own resize from selectSession(), and the + // terminal is only refitted here. + if (options.skipPrimaryResize) this.syncTerminalGeometry?.(); + else this.sendResize?.(this.activeSessionId, { force: true })?.catch?.(() => {}); }, // A click on .btn-split does one of two things — open the picker, or @@ -256,6 +283,92 @@ Object.assign(CodemanApp.prototype, { // nothing on the button said which. `.split-open` + aria-pressed give it // the same active-state language as the codebase's other toggle buttons // (keyboard-accessory's Ctrl key, the voice-input mic). + /** + * A split pane's header strip: the harness logo, the session name and the + * model, the three a grid tile's header shows. Built from nodes (the name + * and the model are untrusted text) and painted by _renderSplitChrome. + */ + _buildSplitPaneHeader() { + const el = document.createElement('div'); + el.className = 'terminal-pane-b-header'; + const harness = document.createElement('span'); + harness.className = 'split-harness run-mode-dot'; + harness.setAttribute('role', 'img'); + const title = document.createElement('span'); + title.className = 'split-title'; + const name = document.createElement('span'); + // `.session-name` is one of the translator's skipped surfaces (user text). + name.className = 'session-name'; + // As on a tile: the name inside is never translated, the tooltip may be, + // and screen readers hear the model once, in the logo's accessible name. + const model = document.createElement('span'); + model.className = 'split-model'; + model.setAttribute('aria-hidden', 'true'); + model.hidden = true; + const modelName = document.createElement('span'); + modelName.setAttribute('data-i18n-skip', ''); + model.appendChild(modelName); + title.append(name, model); + el.append(harness, title); + return { el, harness, name, model, modelName }; + }, + + /** + * Both split headers from their sessions: Pane A shows the active session, + * Pane B its own. Runs after every tab render, so a rename or a model + * change reaches them; unchanged values write nothing. + */ + _renderSplitChrome() { + const headers = this._splitHeaders; + if (!headers || !this._splitPane) return; + for (const [parts, id] of [ + [headers.a, this.activeSessionId], + [headers.b, this._splitSessionId], + ]) { + const session = id ? this.sessions.get(id) : null; + if (!session) continue; + const name = this.getSessionName?.(session) || session.name || 'Session'; + if (parts.nameValue !== name) { + parts.nameValue = name; + parts.name.textContent = name; + } + this._paintSessionHarness(parts, session, 'split-harness'); + } + }, + + /** + * Paints a session header's harness logo and model: a grid tile's, and the + * split panes'. The logo is PR #532's `run-mode-dot ` slot (the id is + * data, never a branch), the model is text (describeSessionHarness, + * constants.js). Diffs against the values it last wrote, kept on `parts`, + * never against the DOM, which the translator may have rewritten: an + * unchanged session writes nothing, and this runs on every tab render. + * + * @param {{harness: HTMLElement, model: HTMLElement, modelName: HTMLElement}} parts - the + * header's nodes (the model's box and the name inside it); the memo lives here too + * @param {object} session - the session the header shows + * @param {string} logoClass - the header's own class for its logo + */ + _paintSessionHarness(parts, session, logoClass) { + const harness = window.CodemanSessionHarness.describeSessionHarness(session, window.__codemanCliCatalog); + const cls = `${logoClass} run-mode-dot${harness.id ? ` ${harness.id}` : ''}`; + if (parts.harnessClass !== cls) { + parts.harnessClass = cls; + parts.harness.className = cls; + } + if (parts.harnessTitle !== harness.title) { + parts.harnessTitle = harness.title; + parts.harness.title = harness.title; + parts.harness.setAttribute('aria-label', harness.title); + parts.model.title = harness.title; + } + if (parts.modelValue !== harness.model) { + parts.modelValue = harness.model; + parts.modelName.textContent = harness.model; + parts.model.hidden = !harness.model; + } + }, + _updateSplitButtonState(open) { const btn = document.querySelector('.btn-split'); if (!btn) return; @@ -276,10 +389,9 @@ Object.assign(CodemanApp.prototype, { // frame). Coalesced to one call per animation frame below — a raw // mousemove stream fires far faster than the browser repaints, and // without the rAF gate each event did a full xterm reflow on BOTH - // panes AND sent Pane B a `{t:'z'}` resize frame (TerminalTile has - // no client-side "dims unchanged" skip), which fanned out into a - // `tmux resize-window` child plus a SIGWINCH per frame — roughly fifty - // of each dragging across half a wide viewport. + // panes AND sent Pane B a `{t:'z'}` resize frame, which fanned out + // into a `tmux resize-window` child plus a SIGWINCH per frame, roughly + // fifty of each dragging across half a wide viewport. const applyDragPercent = (clientX) => { const container = divider.parentElement; // The split can auto-collapse mid-drag (the other pane's session @@ -415,6 +527,15 @@ CodemanApp.prototype._onSessionDeleted = function (data) { // this, Pane A rebinds to a session that Pane B's independent WebSocket is // still attached to — two live WebSockets to one session, each claiming PTY // dimensions via its own `{t:'z',...}` resize frame. +// Every tab render (any session change: a rename, a model switch) refreshes +// the split headers too, the way tile-grid.js refreshes the tile headers. +const _splitOriginalRenderSessionTabsImmediate = CodemanApp.prototype._renderSessionTabsImmediate; +CodemanApp.prototype._renderSessionTabsImmediate = function (...args) { + const result = _splitOriginalRenderSessionTabsImmediate.apply(this, args); + this._renderSplitChrome?.(); + return result; +}; + const _originalSelectSession = CodemanApp.prototype.selectSession; CodemanApp.prototype.selectSession = function (sessionId, ...args) { if (this._splitPane && this._splitSessionId === sessionId) { diff --git a/src/web/public/terminal-tile.js b/src/web/public/terminal-tile.js index f42adea9..240df0fb 100644 --- a/src/web/public/terminal-tile.js +++ b/src/web/public/terminal-tile.js @@ -4,8 +4,10 @@ * @fileoverview TerminalTile: one independent live terminal pane bound to one * session, with its own xterm instance and its own * `/ws/sessions/:id/terminal` WebSocket. The split pane (terminal-split.js) - * uses one as its second pane ("Pane B"); the tile grid planned in - * docs/tile-grid-plan.md reuses the same class for every tile. + * uses one as its second pane ("Pane B"); the tile grid (tile-grid.js, + * docs/tile-grid-plan.md) uses one per tile, and feeds every capture they + * fetch through ONE TileLoadQueue (below), because each capture is a + * synchronous tmux call that blocks the server's event loop. * * Deliberately plainer than the primary pane (this.terminal/this._ws in * terminal-ui.js): no local-echo overlay, no CJK IME, no touch/mobile @@ -13,51 +15,67 @@ * docs/split-pane-sessions-plan.md. * * @dependency vendor/xterm.js, vendor/xterm-addon-fit.js - * @dependency constants.js (window.CodemanTerminalFont, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE) + * @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE) * @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight) * @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js */ (function (global) { - // How long a scroll-to-top history pull may hold Pane B's live output. + // How long a scroll-to-top history pull may hold this pane's live output. const HISTORY_PULL_TIMEOUT_MS = 10000; + // How much of a replay is queued in xterm at once: a 1 MiB load goes in one + // window, and xterm's write queue throws past 50 MB, which an unbounded + // `full=1` capture (up to the server's 32 MB) would otherwise come near. + const REPLAY_WINDOW_BYTES = 1024 * 1024; + /** - * Minimal chunked write for Pane B's own xterm instance — write() in - * TERMINAL_CHUNK_SIZE slices, yielding a frame between each, instead of one - * giant synchronous write that blocks the main thread while parsing a long - * scrollback. Deliberately NOT the primary pane's chunkedTerminalWrite - * (terminal-ui.js): that one is wired into session-switch generation - * counters and the live-output gate this simpler, independently - * created/destroyed pane has no equivalent of. + * Replays a capture into a pane's own xterm: TERMINAL_CHUNK_SIZE slices, all + * of a window queued at once. xterm 6 parses its write queue in 12 ms slices + * and yields between them, so a long scrollback never becomes a long task, + * and it is not held to one slice per animation frame either (that pacing + * took about a second per 1 MiB, with the grid's load queue waiting behind + * it). Queued up front, the capture also stays in one piece: live output + * written during the parse lands after it, not between two of its slices. + * Deliberately NOT the primary pane's chunkedTerminalWrite (terminal-ui.js): + * that one is wired into session-switch generation counters and the + * live-output gate this simpler, independently created/destroyed pane has no + * equivalent of. + * + * Resolves once xterm has parsed the last slice (a write's callback runs once + * everything queued before it is parsed), so _loadBuffer() below holds its + * single-flight flag across the whole replay. A disposed xterm never runs its + * callbacks, so `setCancel` hands the owner a function that settles the + * replay at once: destroy() calls it, or the pane's flag and the grid's load + * queue would wait forever. */ - function writeChunked(terminal, buffer, isDestroyed) { - if (!buffer) return Promise.resolve(); - if (buffer.length <= TERMINAL_CHUNK_SIZE) { - terminal.write(buffer); - return Promise.resolve(); - } - // Resolves once the LAST chunk is written (or the pane was destroyed - // mid-replay), so _loadBuffer() below can hold its single-flight flag - // across the whole replay rather than just the fetch that precedes it. + function writeChunked(terminal, buffer, isDestroyed, setCancel) { + if (!buffer || !terminal) return Promise.resolve(); return new Promise((resolve) => { let offset = 0; - const writeNext = () => { - if (isDestroyed() || !terminal) { - resolve(); + let settled = false; + const settle = () => { + if (settled) return; + settled = true; + setCancel?.(null); + resolve(); + }; + const writeWindow = () => { + if (settled) return; + if (isDestroyed()) { + settle(); return; } - const chunk = buffer.slice(offset, offset + TERMINAL_CHUNK_SIZE); - offset += chunk.length; - terminal.write(chunk); - if (offset < buffer.length) { - if (typeof requestAnimationFrame === 'function') requestAnimationFrame(writeNext); - else setTimeout(writeNext, 16); - } else { - resolve(); + const end = Math.min(buffer.length, offset + REPLAY_WINDOW_BYTES); + while (offset < end) { + const chunk = buffer.slice(offset, Math.min(end, offset + TERMINAL_CHUNK_SIZE)); + offset += chunk.length; + terminal.write(chunk); } + terminal.write('', offset < buffer.length ? writeWindow : settle); }; - writeNext(); + setCancel?.(settle); + writeWindow(); }); } @@ -67,11 +85,25 @@ this.mountEl = mountEl; this.sessionMode = opts.mode; this.fontSettings = opts.fontSettings || {}; - // Live reference (not a snapshot) to the app's detachedSessions Set — - // detaching this session AFTER the split is already open must still be - // seen by _sendResize() below, or it re-creates the exact PTY-size - // fight the split picker already refuses to open at pick time. + // Live reference (not a snapshot) to the app's detachedSessions Set: + // detaching this session AFTER the pane opened must still be seen by + // _sendResize() below, or this pane and the session's own window fight + // over the PTY's size (which the split picker refuses at pick time). this.detachedSessions = opts.detachedSessions; + // Lines of scrollback this pane's xterm keeps (the grid passes its smaller + // TILE_SCROLLBACK) and its font size (the grid's own tile font); absent, + // the primary pane's values. + this.scrollback = Number.isFinite(opts.scrollback) ? opts.scrollback : null; + this.fontSize = Number.isFinite(opts.fontSize) ? opts.fontSize : null; + // `scheduleLoad(tile, kind, run)` runs every capture this pane fetches + // (`kind`: 'initial', 'refresh' or 'history') when its owner says so, and + // resolves once `run` has finished or was dropped. The grid passes its one + // queue so N tiles never fetch at once; absent, a load runs straight away. + this._scheduleLoad = typeof opts.scheduleLoad === 'function' ? opts.scheduleLoad : null; + // Loads a BOUNDED window (`full=1&tail=` for a TUI, `tail=` for a shell) + // instead of a TUI's whole history. Grid tiles do; full history is one + // "leave the grid" away in the primary pane. + this.boundedLoad = opts.boundedLoad === true; this.terminal = null; this.fitAddon = null; this.ws = null; @@ -81,6 +113,15 @@ // Single-flight state for _loadBuffer()/_refreshBuffer() below. this._bufferLoading = false; this._bufferRefreshPending = false; + // True only while a load's work runs, not while it waits in the owner's + // queue (see _runLoad): a close during the wait writes its marker at once. + this._loadRunning = false; + // Aborts the running load's fetch; destroy() uses it so a removed tile + // does not hold the owner's queue for a whole deadline. + this._loadAbort = null; + // Settles a replay xterm is still parsing (writeChunked): destroy() calls + // it, because a disposed xterm never runs the callback the replay awaits. + this._cancelReplay = null; // Scroll-to-top history pull (shell panes only), see _maybeLoadMoreHistory(). // `_liveQueue` is non-null from the pull's response until its finally // block: live frames are held there with their arrival time instead of @@ -119,7 +160,7 @@ } async connect() { - const savedFontSize = parseInt(localStorage.getItem('codeman-font-size'), 10); + const savedFontSize = this.fontSize ?? parseInt(localStorage.getItem('codeman-font-size'), 10); this.terminal = new Terminal({ theme: { ...global.codemanCurrentXtermTheme() }, fontFamily: global.CodemanTerminalFont.resolve(this.fontSettings.terminalFontFamily), @@ -129,7 +170,7 @@ cursorBlink: false, cursorStyle: 'block', minimumContrastRatio: global.codemanCurrentSkinIsLight() ? 4.5 : 1, - scrollback: DEFAULT_SCROLLBACK, + scrollback: this.scrollback ?? DEFAULT_SCROLLBACK, allowTransparency: true, allowProposedApi: true, }); @@ -159,17 +200,18 @@ this.terminal.onData((data) => this._onTerminalData(data)); - // Pane B has no gates of its own by default, so every app-level chord - // that the document capture-phase handler (app.js) only preventDefault()s - // — never stopPropagation()s — reaches xterm here too and writes its raw - // byte/escape sequence into THIS session's PTY on top of whatever the app - // action already did to Pane A (COD-153; mirrors the primary pane's own - // gates at terminal-ui.js's attachCustomKeyEventHandler: command palette, - // Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter - // newline, and smart-copy Ctrl+C/Ctrl+Shift+C). Routed through the same - // registry-aware predicates so a rebind or a disable restores plain - // terminal behavior here too. Ctrl+V goes through the primary pane's - // paste trap (image-input.js), aimed at this pane (below). + // xterm has no gates of its own, so every app-level chord that the + // document capture-phase handler (app.js) only preventDefault()s (never + // stopPropagation()s) would reach this xterm too and write its raw byte + // or escape sequence into THIS session's PTY on top of whatever the app + // action did (COD-153). These are the primary pane's gates + // (terminal-ui.js attachCustomKeyEventHandler): command palette, + // Alt+1-9/[/] tab nav, Alt+B sidebar toggle, the tile grid's chords, + // Ctrl+Z suspend, Shift/Ctrl+Enter newline, and smart-copy + // Ctrl+C/Ctrl+Shift+C. Routed through the same registry-aware + // predicates so a rebind or a disable restores plain terminal behavior + // here too. Ctrl+V goes through the primary pane's paste trap + // (image-input.js), aimed at this pane (below). this.terminal.attachCustomKeyEventHandler((ev) => { if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return true; if ( @@ -186,6 +228,10 @@ if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(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. + if (global.app?.tileShortcutFor?.(ev)) return false; // Ctrl+V / Cmd+V: the primary pane's paste trap, aimed at THIS pane, so // a pasted image uploads to this pane's session and its path is typed // here, and pasted text goes into this xterm with its bracketed-paste @@ -195,13 +241,11 @@ global.app?._handleImagePaste?.({ terminal: this.terminal, sessionId: this.sessionId }); return false; } - // Ctrl+Z (SIGTSTP/job-control suspend): mirrors terminal-ui.js's own - // swallow — in a plain shell session this is the user's own - // job-control tool and must reach the PTY, but in every other mode - // (claude/omp/pi/codex/...) it silently stops an unattended agent - // loop dead. Pane B has its own PTY/session and must not send a - // suspend into a non-shell one just because the primary pane's own - // gate lives elsewhere. + // Ctrl+Z (SIGTSTP/job-control suspend), as terminal-ui.js swallows it: + // in a plain shell session this is the user's own job-control tool and + // must reach the PTY, but in every other mode (claude/omp/pi/codex/...) + // it silently stops an unattended agent loop dead. This pane has its + // own session and applies the same rule to it. if ( ev.type === 'keydown' && ev.key.toLowerCase() === 'z' && @@ -213,15 +257,14 @@ ) { return false; } - // Shift+Enter / Ctrl+Enter: insert a newline instead of submitting. - // Mirrors terminal-ui.js's own handling — xterm sends plain \r for - // every Enter variant, so an Ink app (Claude Code) can't tell a - // newline from a submit. Without this gate, Pane B's onData would - // send that bare \r straight over the WS and submit an incomplete - // prompt instead of adding a line to it. Targets THIS pane's own - // session (this.sessionId), never the primary pane's + // Shift+Enter / Ctrl+Enter: insert a newline instead of submitting, as + // terminal-ui.js does. xterm sends plain \r for every Enter variant, + // so an Ink app (Claude Code) can't tell a newline from a submit, and + // without this gate this pane's onData would send that bare \r and + // submit an incomplete prompt instead of adding a line to it. Targets + // THIS pane's own session (this.sessionId), never the primary pane's // activeSessionId, and has no local-echo overlay of its own to flush - // first (Pane B is deliberately plainer — see the fileoverview). + // first (this pane is deliberately plainer, see the fileoverview). // Swallow keypress/keyup too (xterm would send \r for a Shift-only keypress); only keydown sends. if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)) { if (ev.type === 'keydown') { @@ -235,57 +278,32 @@ } return false; } - // Smart copy (mirrors terminal-ui.js's Ctrl+C gate, #211): with a - // selection, Ctrl+C copies THIS pane's own selection instead of - // sending ^C; with none, plain Ctrl+C must fall through unchanged or - // the interrupt key is lost. Ctrl+Shift+C is different: it is the - // explicit, never-falls-through copy chord, and the predicate above - // does not distinguish it from plain Ctrl+C — ev.shiftKey does, below. - // xterm's own evaluateKeyboardEvent routes a shifted ctrl-letter into - // a branch that assigns c.key only for a couple of special cases - // ("_"->US, "@"->NUL), neither of which is "c", so it emits NOTHING - // for Ctrl+Shift+C either way — this is not about an accidental - // interrupt byte reaching the PTY (verified live: it does not). - // Gating this whole block on hasSelection() (an earlier draft) meant - // that with no selection Ctrl+Shift+C skipped straight to `return - // true`, silently ceding the keystroke to the BROWSER's own handling - // (e.g. Chrome's Inspect-Element binding) with no feedback and no - // attempt to copy, unlike Pane A, which always intercepts it. - // Re-implemented against this.terminal rather than reusing - // app.copyTerminalSelection(), which reads app.terminal — Pane A's — - // and would copy the wrong pane's selection. + // Smart copy, the primary pane's rule (terminal-ui.js's Ctrl+C gate, + // #211) through the SAME helpers, aimed at THIS pane: the gutter width + // comes from this session's run mode, the partial first line from this + // terminal's selection, and the clear and refocus after the copy land + // here. With a selection worth copying, Ctrl+C copies instead of + // sending ^C; with none, plain Ctrl+C falls through unchanged or the + // interrupt key is lost. Ctrl+Shift+C is the explicit copy chord and + // never falls through (ev.shiftKey, below): with nothing to copy it + // would otherwise reach the browser's own binding for that chord. + // As in the primary gate, the CLEANED selection decides and the copy is + // handed the RAW one, because the margin strip is not idempotent. if (ev.type === 'keydown' && global.app?.shouldCopyTerminalSelectionFromShortcut?.(ev)) { + const app = global.app; + const target = { terminal: this.terminal, sessionId: this.sessionId }; const raw = this.terminal?.getSelection?.() || ''; - const isColumnSelection = this.terminal?._core?._selectionService?._activeSelectionMode === 3; - // Both clean options are read for THIS pane, never the primary one: - // the gutter width comes from this.sessionId's own run mode, and the - // partial-first-line flag from this terminal's own selection range. - // Passing neither left Pane B keeping a margin Pane A dropped, on the - // same split and the same keystroke. - const range = global.app?._normalisedSelectionRange?.(this.terminal); - const selection = isColumnSelection - ? raw - : (global.CodemanCopySelection?.clean?.(raw, { - margin: global.app?._cliGutterColumns?.(this.sessionId) ?? 0, - firstLinePartial: !!range && range.start.x > 0, - }) ?? raw); - if (selection.trim()) { + if (app.cleanedTerminalSelection?.(raw, target)?.trim()) { ev.preventDefault(); - void global.app._copyText?.(selection).then((ok) => { - this.terminal?.clearSelection?.(); - global.app.showToast?.(ok ? 'Copied to clipboard' : 'Failed to copy', ok ? 'success' : 'error'); - }); + void app.copyTerminalSelection(raw, target); return false; } - // Nothing worth copying — clear for feedback (a padding-only - // selection cleans to '' and this press still falls through to the - // PTY as 0x03, matching the primary pane's own rule). + // Nothing worth copying: cleared for feedback, and the press still + // reaches the PTY as 0x03, as in the primary pane. if (this.terminal?.hasSelection?.()) { this.terminal.clearSelection?.(); - global.app.showToast?.('Nothing to copy', 'warning'); + app.showToast?.('Nothing to copy', 'warning'); } - // Ctrl+Shift+C never falls through, even with nothing to copy — - // matches terminal-ui.js's own ev.shiftKey branch. if (ev.shiftKey) { ev.preventDefault(); return false; @@ -296,17 +314,13 @@ // Load existing scrollback before going live. The WS below is // subscribe-only (ws-routes.ts sends nothing on connect, only future - // 'terminal' events), so without this Pane B stays blank until the - // target session happens to produce new output. It LOOKED - // intermittent rather than always-broken because _sendResize() below - // often nudges the shared session's real tmux window to a new size, - // and tmux repaints its current screen on resize — that repaint was - // getting captured and streamed here, incidentally populating the - // pane. When Pane B's computed dimensions happened to already match - // the session's last-known size, Session.resize() (session.ts) skips - // the resize as a no-op, no repaint fires, and the pane stayed blank. - // The await covers the whole chunked replay, not just the fetch, so a - // live frame from the socket below can never land in the middle of it. + // 'terminal' events), so without this the pane stays blank until the + // session happens to produce new output. The resize _sendResize() sends + // on open is no substitute: tmux repaints on a resize, but + // Session.resize() (session.ts) skips one that matches the session's + // last size, and then nothing repaints at all. The await covers the + // whole chunked replay, not just the fetch, so a live frame from the + // socket below can never land in the middle of it. await this._loadBuffer(); if (this._destroyed) return; @@ -352,8 +366,8 @@ } else if (msg.t === 'r') { // Server-triggered refresh (SSE backpressure cleared, terminal // data was dropped). The primary pane routes this to - // _onSessionNeedsRefresh (app.js) — Pane B has its own - // buffer loader for the same reason connect() does. + // _onSessionNeedsRefresh (app.js); this pane has its own buffer + // loader for the same reason connect() does. this._refreshBuffer(); } else if (msg.t === 'ia') { // Input ACK. The frame names no session, so it is this pane's. @@ -362,7 +376,7 @@ this._onPtyGeometryReport(msg.c, msg.r); } } catch { - /* Malformed frame — ignore, matches primary pane's tolerance. */ + /* Malformed frame: ignored, as in the primary pane. */ } }; @@ -377,7 +391,7 @@ }; ws.onerror = () => { - // onclose fires after onerror — cleanup happens there. + // onclose fires after onerror: cleanup happens there. }; } @@ -387,8 +401,8 @@ if (!ws) return; ws.onopen = null; ws.onmessage = null; - // onclose fires asynchronously AFTER close(); without this it ran its - // "disconnected" write against a pane already torn down or replaced. + // onclose fires asynchronously AFTER close(); without this it would run + // its "disconnected" write against a pane already torn down or replaced. ws.onclose = null; ws.onerror = null; try { @@ -453,7 +467,7 @@ const code = event?.code; const permanent = TerminalTile.STOP_MARKERS[code]; this._markerText = permanent || TerminalTile.MARKER_RECONNECTING; - if (this._bufferLoading) this._markerOwed = true; + if (this._loadRunning) this._markerOwed = true; else this._writeDisconnectedMarker(); if (this._destroyed) return; if (permanent) { @@ -519,6 +533,8 @@ this._inputHandle = { ws: this.ws, lastRecvAt: 0 }; app._registerInputSocket(this.sessionId, this._inputHandle); app._onWsReady?.(this.sessionId); + // The header's connection dot reads tile sockets while the grid is open. + app._updateConnectionIndicator?.(); } // Leaves the map; only this pane's own handle is removed (a replacement @@ -527,6 +543,7 @@ if (!this._inputHandle) return; global.app?._unregisterInputSocket?.(this.sessionId, this._inputHandle); this._inputHandle = null; + global.app?._updateConnectionIndicator?.(); } // Settles a marker the pane owes: set when a close lands during a load (the @@ -552,7 +569,7 @@ // Fetches and writes the session's current scrollback. Used both by // connect() (initial load) and by the `{t:'r'}` server-refresh frame - // (below) — the primary pane's own _onSessionNeedsRefresh (app.js) is + // (above). The primary pane's own _onSessionNeedsRefresh (app.js) is // scoped to `this.activeSessionId` and clears/rewrites the primary // terminal, neither of which applies to this independent pane, so this is // a standalone equivalent rather than a call into it. @@ -561,31 +578,98 @@ // _onSessionNeedsRefresh): a shell session can retain hundreds of // thousands of plain scrollback lines, so pulling `?full=1` there parses // an unbounded, server-capped (up to terminalBufferMaxBytes, 32MB) body - // into a 50000-line xterm on every load. Non-shell (TUI) sessions still - // get one full replay. `fetch` here goes through the global wrapper - // (constants.js), which already prefixes CodemanBase — unlike the raw - // WebSocket URL above, which does not. + // into this xterm on every load; a shell loads the `tail=` window. A + // non-shell (TUI) session gets one full replay, or the same bounded window + // with `boundedLoad` (grid tiles). `fetch` here goes through the global + // wrapper (constants.js), which already prefixes CodemanBase, unlike the + // raw WebSocket URL above, which does not. // // Single-flight: the flag is held across the fetch AND the chunked write // (writeChunked resolves after its last chunk), so two replays can never // interleave their chunks into one terminal. A second call while one is // in flight is dropped here; _refreshBuffer() is the caller that queues // a trailing re-run instead. - async _loadBuffer() { + async _loadBuffer({ refresh = false } = {}) { if (this._bufferLoading) return; this._bufferLoading = true; - try { - const query = this.sessionMode === 'shell' ? `tail=${TERMINAL_TAIL_SIZE}` : 'full=1'; - const res = await fetch(`/api/sessions/${this.sessionId}/terminal?${query}`); - const payload = (await res.json())?.data ?? {}; - if (payload.terminalBuffer && this.terminal) { - await writeChunked(this.terminal, payload.terminalBuffer, () => this._destroyed); + await this._runLoad(refresh ? 'refresh' : 'initial', async () => { + this._loadRunning = true; + try { + if (this._destroyed) return; + if (refresh) { + // Cleared at the load's turn, not when it was asked for: a grid tile + // waiting in the queue keeps its last frame instead of sitting blank. + this.terminal?.clear(); + // The clear wipes a "disconnected" marker (a `{t:'r'}` frame can queue + // a trailing refresh behind a pull that the socket's close then + // interrupts), so a refresh on a closed socket owes it back once its + // replay is written. + if (this._wsClosed) this._markerOwed = true; + } + const shell = this.sessionMode === 'shell'; + let query = shell ? `tail=${TERMINAL_TAIL_SIZE}` : 'full=1'; + if (this.boundedLoad && !shell) query = `full=1&tail=${TERMINAL_TAIL_SIZE}${this._historyLinesQuery()}`; + // A deadline covering the body as well as the headers (the primary + // pane's budgets, CodemanFetchDeadline): a capture that never answers + // would otherwise hold this pane's single-flight flag, and in the grid + // the one load queue every tile waits behind, forever. + const controller = global.AbortController ? new global.AbortController() : null; + this._loadAbort = controller; + const budget = global.CodemanFetchDeadline?.terminalFetchDeadlineMs?.({ full: !shell }) ?? 45000; + const timer = controller ? setTimeout(() => controller.abort(), budget) : null; + let payload; + try { + const res = await fetch( + `/api/sessions/${this.sessionId}/terminal?${query}`, + controller ? { signal: controller.signal } : undefined + ); + payload = (await res.json())?.data ?? {}; + } finally { + clearTimeout(timer); + this._loadAbort = null; + } + if (payload.terminalBuffer && this.terminal) { + await writeChunked( + this.terminal, + payload.terminalBuffer, + () => this._destroyed, + (cancel) => (this._cancelReplay = cancel) + ); + } + } catch { + /* Best-effort: live output still arrives once the socket connects. */ + } finally { + this._loadRunning = false; + this._stampMarkerIfOwed(); + this._endBufferLoad(); } + }); + } + + // Runs a load's work now, or when the owner's queue gives this pane its turn + // (`scheduleLoad`). The single-flight flag is already set by the caller, so a + // load waiting in the queue still coalesces refreshes and blocks a second + // pull; the work itself sets `_loadRunning`. A load the queue drops (this + // pane was destroyed while it waited) never runs, so its flags are released + // here. + async _runLoad(kind, work) { + let ran = false; + const run = () => { + ran = true; + return work(); + }; + if (!this._scheduleLoad) { + await run(); + return; + } + try { + await this._scheduleLoad(this, kind, run); } catch { - /* Best-effort — live output still arrives once the socket connects. */ - } finally { - this._stampMarkerIfOwed(); - this._endBufferLoad(); + /* The queue never rejects; a load that failed already settled itself. */ + } + if (!ran) { + this._bufferLoading = false; + this._bufferRefreshPending = false; } } @@ -632,20 +716,20 @@ // Wheel-up at the top of a SHELL pane's scrollback. tmux repaints a burst of // output (`cat` of a file longer than the screen) instead of scrolling it, // so this pane's xterm ends up with about one screen of scrollback while - // tmux holds every line — and nothing here ever went back to ask, so the - // history was unreachable. The primary pane has the same pull - // (app.js _maybeRefetchFullHistory); Pane B is a separate xterm and needs its - // own. Shell only: a non-shell CLI's history is out of scope for this pull - // (its load already takes `full=1`; codex and Claude's inline renderer do - // grow tmux history, this just isn't how they recover it). The alternate- - // screen skip (nano, vim, less) only matters for a direct-PTY shell — under - // tmux the browser xterm never enters the alternate buffer. + // tmux holds every line, and without this pull the history is + // unreachable. The primary pane has the same pull + // (app.js _maybeRefetchFullHistory); a tile is a separate xterm and needs + // its own. Shell only: a non-shell CLI's history is out of scope for this + // pull (its load already takes `full=1`; codex and Claude's inline renderer + // do grow tmux history, this just isn't how they recover it). The + // alternate-screen skip (nano, vim, less) only matters for a direct-PTY + // shell: under tmux the browser xterm never enters the alternate buffer. _maybeLoadMoreHistory() { if (this.sessionMode !== 'shell' || this._destroyed || !this.terminal) return; if (this._bufferLoading) return; // Mirrors app.js _maybeRefetchFullHistory and this pane's own // _sendResize(): a detached session's own window already owns its PTY - // size and scrollback, so Pane B has nothing of its own to reconcile. + // size and scrollback, so this pane has nothing of its own to reconcile. if (this.detachedSessions?.has(this.sessionId)) return; const active = this.terminal.buffer.active; if (active.type !== 'normal' || active.viewportY !== 0) return; @@ -656,7 +740,8 @@ const now = Date.now(); if (now - this._historyPullAt < cooldown) return; this._historyPullAt = now; - void this._pullHistory(); + this._bufferLoading = true; + void this._runLoad('history', () => this._pullHistory()); } // Pulls a BOUNDED window of tmux's full history (the same TERMINAL_TAIL_SIZE @@ -665,6 +750,11 @@ // single-flight flag across the fetch AND the replay, like _loadBuffer(). async _pullHistory() { this._bufferLoading = true; + if (this._destroyed) { + this._endBufferLoad(); + return; + } + this._loadRunning = true; let replayed = false; let capturedAt = 0; // Two budgets on one signal. The request itself gets the primary pane's @@ -678,6 +768,7 @@ // be re-armed, hence the controller; without AbortController the pull // simply has no deadline. const controller = global.AbortController ? new global.AbortController() : null; + this._loadAbort = controller; let abortTimer = null; const armDeadline = (ms) => { if (!controller) return; @@ -686,9 +777,10 @@ }; try { armDeadline(global.CodemanFetchDeadline?.terminalFetchDeadlineMs?.({ full: true }) ?? HISTORY_PULL_TIMEOUT_MS); - const res = await fetch(`/api/sessions/${this.sessionId}/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}`, { - signal: controller?.signal, - }); + const res = await fetch( + `/api/sessions/${this.sessionId}/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}${this._historyLinesQuery()}`, + { signal: controller?.signal } + ); armDeadline(HISTORY_PULL_TIMEOUT_MS); // The cutoff below is the response's arrival, the same `since` rule the // primary pane uses (_finishBufferLoad). It is a client clock standing in @@ -698,7 +790,7 @@ capturedAt = performance.now(); // Opened only now: a frame from before the response is either replaced by // the capture or written unchanged, so holding it for the round trip - // bought nothing and froze the pane for as long as the fetch took. + // would buy nothing and freeze the pane for as long as the fetch took. this._liveQueue = []; const payload = (await res.json())?.data; clearTimeout(abortTimer); @@ -728,7 +820,12 @@ term.write('\x1bc'); replayed = true; if (this._wsClosed) this._markerOwed = true; - await writeChunked(term, buffer, () => this._destroyed); + await writeChunked( + term, + buffer, + () => this._destroyed, + (cancel) => (this._cancelReplay = cancel) + ); if (this._destroyed || !this.terminal) return; // xterm parses asynchronously: an empty write's callback fires only // after everything before it, so the row count below is the settled one. @@ -740,9 +837,11 @@ if (delta > 0) this.terminal.scrollToLine(delta); else this.terminal.scrollToTop(); } catch { - /* Best-effort — live output keeps arriving whatever happens here. */ + /* Best-effort: live output keeps arriving whatever happens here. */ } finally { clearTimeout(abortTimer); + this._loadAbort = null; + this._loadRunning = false; const queued = this._liveQueue ?? []; this._liveQueue = null; // After a replay, only frames that arrived after the capture are news; @@ -765,8 +864,18 @@ } } + // A bounded load's `lines=` (grid tiles): tmux history beyond what this + // xterm keeps (its scrollback plus the screen) would only be captured to be + // thrown away, and a full capture is synchronous work on the server, about + // 0.7 s for a 30k-line history. Unbounded panes (the split's Pane B) ask + // for everything, as before. + _historyLinesQuery() { + if (!this.boundedLoad || !Number.isFinite(this.scrollback)) return ''; + return `&lines=${this.scrollback + (this.terminal?.rows || 0)}`; + } + // The `{t:'r'}` server-refresh path: clear, then replay. Two refresh - // frames in a row used to start two concurrent replays, each clearing + // frames in a row must not start two concurrent replays, each clearing // the terminal under the other's chunked write. A refresh that arrives // mid-replay is COALESCED into one trailing re-run rather than ignored: // the in-flight fetch may predate the drop the new frame is reporting, @@ -776,16 +885,11 @@ this._bufferRefreshPending = true; return; } - this.terminal?.clear(); - // The clear wipes a "disconnected" marker (a `{t:'r'}` frame can queue a - // trailing refresh behind a pull that the socket's close then interrupts), - // so a refresh on a closed socket owes it back once its replay is written. - if (this._wsClosed) this._markerOwed = true; - void this._loadBuffer(); + void this._loadBuffer({ refresh: true }); } - // Local reflow only — no PTY resize frame. Split out so a divider drag - // can reflow both panes at the browser's paint rate (rAF) while sending + // Local reflow only, no PTY resize frame. Split out so a divider drag + // can reflow the panes at the browser's paint rate (rAF) while sending // the actual `{t:'z'}` resize once, at drag end, matching the primary // pane's own convention (throttledResize in terminal-ui.js). localFit() { @@ -806,8 +910,8 @@ if (!this._wsReady || !this.fitAddon || !this.terminal) return; // One PTY cannot hold two sizes (mirrors sendResize's own // detachedElsewhere yield in terminal-ui.js): the session got detached - // to its own window AFTER this split was opened, so its own window now - // owns the PTY's size and Pane B must stand aside. + // to its own window AFTER this pane was opened, so its own window now + // owns the PTY's size and this pane must stand aside. if (this.detachedSessions?.has(this.sessionId)) return; // A hidden pane (a web tab over it, a zoomed neighbour) measures NaN, and // fit() then leaves the xterm alone: there is no size worth reporting. @@ -815,9 +919,9 @@ if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) return; // Report what the xterm actually holds, so the PTY gets exactly the size // the pane renders at. Unclamped, unlike the primary pane's 40x10 floor: - // a floor here misreported Pane B's width at the divider's reachable 20% - // position (about 28 columns), causing real output-wrapping bugs, and a - // floored xterm would be wider than its container. The server enforces + // a floor would misreport the split's Pane B at its divider's reachable + // 20% position (about 28 columns) and wrap output wrongly, and a floored + // xterm would be wider than its container. The server enforces // its own valid range ([1,500]/[1,200] in ws-routes.ts). const cols = this.terminal.cols; const rows = this.terminal.rows; @@ -827,6 +931,17 @@ this.ws.send(JSON.stringify({ t: 'z', c: cols, r: rows, v: 'desktop' })); } + // The session's PTY is new: a tile can connect before its session has a + // pane (one Run started while the grid is open joins first), and the + // server drops a resize that arrives with no PTY, then spawns at its own + // default size. Forget what was sent, so the size goes out now, or with + // the next fit() when this tile is hidden right now (a zoomed neighbour): + // _sendResize() returns before recording anything it did not send. + paneStarted() { + this._lastSentDims = null; + this._sendResize(); + } + // The geometry the PTY actually holds (`{t:'zc'}`, the server's answer to // every resize). A PTY and a terminal that disagree on WIDTH render // garbled, so a different column count is adopted; rows stay local, as in @@ -851,6 +966,18 @@ // keystroke loses nothing. clearTimeout(this._reconnectTimer); this._reconnectTimer = null; + // A load still fetching would otherwise hold the owner's queue (and the + // server's attention) for a pane nobody can see any more. + try { + this._loadAbort?.abort(); + } catch { + /* Already settled. */ + } + this._loadAbort = null; + // Likewise a replay still parsing: the xterm is disposed below, so the + // write callback it waits for would never come. + this._cancelReplay?.(); + this._cancelReplay = null; if (this._onWheel) { this.mountEl?.removeEventListener('wheel', this._onWheel, { capture: true }); this._onWheel = null; @@ -883,5 +1010,111 @@ 4010: '[disconnected: another connection took over this pane]', }; + /** + * ONE queue for every capture a set of tiles fetches (`GET + * /api/sessions/:id/terminal`): the initial load, the refresh after a + * reconnect, a server `{t:'r'}` refresh and the shell history pull. Each + * capture runs synchronous tmux calls on the server, so N of them at once do + * not run in parallel, they stall every WebSocket and SSE stream on it back to + * back. After a deploy restart all N tiles reopen within the same second; this + * drains their refreshes one at a time. + * + * Concurrency 1. Next up is a history pull (the user is waiting on it), then + * the lowest `rank(tile)` (the grid ranks the focused tile first, then reading + * order), then arrival order. A destroyed tile's entries are dropped, never run. + * DOM-free, so the grid owns the policy and tests drive it directly. + */ + class TileLoadQueue { + /** + * @param {{rank?: (tile: object) => number, onChange?: (tile: object, state: 'queued'|'running'|'idle') => void}} [opts] + */ + constructor(opts = {}) { + this._rank = typeof opts.rank === 'function' ? opts.rank : () => 0; + this._onChange = typeof opts.onChange === 'function' ? opts.onChange : null; + this._pending = []; + this._active = null; + this._seq = 0; + } + + /** The `scheduleLoad` a TerminalTile takes. Resolves once `run` finished or was dropped; never rejects. */ + schedule(tile, kind, run) { + return new Promise((resolve) => { + this._pending.push({ tile, kind, run, resolve, seq: this._seq++ }); + this._notify(tile, 'queued'); + this._pump(); + }); + } + + /** Drops every load still waiting for `tile` (the running one, if any, finishes on its own). */ + drop(tile) { + const keep = []; + for (const entry of this._pending) { + if (entry.tile === tile) entry.resolve(); + else keep.push(entry); + } + this._pending = keep; + if (this._active?.tile !== tile) this._notify(tile, 'idle'); + } + + /** How many loads are waiting (not counting the running one). */ + get size() { + return this._pending.length; + } + + /** The tile whose load is running, or null. */ + get activeTile() { + return this._active?.tile ?? null; + } + + _notify(tile, state) { + try { + this._onChange?.(tile, state); + } catch { + /* A display callback never stops the queue. */ + } + } + + _takeNext() { + let best = -1; + let bestKey = null; + for (let i = 0; i < this._pending.length; i++) { + const entry = this._pending[i]; + if (entry.tile?._destroyed) continue; + const key = [entry.kind === 'history' ? 0 : 1, this._rank(entry.tile), entry.seq]; + const order = bestKey ? key[0] - bestKey[0] || key[1] - bestKey[1] || key[2] - bestKey[2] : -1; + if (order < 0) { + best = i; + bestKey = key; + } + } + // Destroyed tiles' entries go now, resolved but never run. + const dropped = this._pending.filter((entry) => entry.tile?._destroyed); + const next = best === -1 ? null : this._pending[best]; + this._pending = this._pending.filter((entry) => entry !== next && !entry.tile?._destroyed); + for (const entry of dropped) entry.resolve(); + return next; + } + + async _pump() { + if (this._active) return; + const entry = this._takeNext(); + if (!entry) return; + this._active = entry; + this._notify(entry.tile, 'running'); + try { + await entry.run(); + } catch { + /* A load settles its own failure; the queue only moves on. */ + } finally { + this._active = null; + const stillQueued = this._pending.some((e) => e.tile === entry.tile); + this._notify(entry.tile, stillQueued ? 'queued' : 'idle'); + entry.resolve(); + void this._pump(); + } + } + } + global.TerminalTile = TerminalTile; + global.TileLoadQueue = TileLoadQueue; })(window); diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 88cc6a54..17b934cc 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -590,6 +590,11 @@ Object.assign(CodemanApp.prototype, { return false; } + // Tile grid chords (Ctrl+Shift+G, Alt+Shift+Arrows): the capture handler + // has already acted on one that applies, and its preventDefault() does not + // stop xterm. Every event type, and BEFORE the Shift+Enter branch below. + if (this.tileShortcutFor?.(ev)) return false; + // Smart copy (#211): with a selection, Ctrl+C copies it instead of sending // ^C. With NO selection the branch must fall through (return true, and no // preventDefault) or the interrupt key is lost, which is the whole reason @@ -1328,6 +1333,9 @@ Object.assign(CodemanApp.prototype, { // Same yield as sendResize: never resize a PTY whose session is showing // in its own window. Dragging the dashboard's border must not reshape it. const detachedElsewhere = !this.isSoloWindow && this.detachedSessions?.has(this.activeSessionId); + // The tile grid parks the main terminal: its session is sized by its + // tile, which this same timer refits below (_forEachTile). + const tilesOwnTerminal = this._tilesOwnTerminal?.(); // ⚠️ Whether to fit is the SAME question as whether to send (issue #464). // This block used to fit unconditionally and skip only the SIGWINCH, // which is the one combination that cannot be right: it moves xterm to @@ -1335,7 +1343,9 @@ Object.assign(CodemanApp.prototype, { // repaints from the shape it was told. Withhold both, or neither — // a reflow nothing is rendering for buys nothing and costs correctness. const dims = - this.activeSessionId && !keyboardUp && !detachedElsewhere ? this._geometryForResizeRequest() : null; + this.activeSessionId && !keyboardUp && !detachedElsewhere && !tilesOwnTerminal + ? this._geometryForResizeRequest() + : null; // ⚠️ A null measurement is NOT a reason to report the floor. It used to // fall back to a bare 40x10, which tells the PTY a shape nothing measured // and xterm does not hold — the write-only guess this whole change exists @@ -1418,8 +1428,11 @@ Object.assign(CodemanApp.prototype, { // frame — this observer only ever measured Pane A's container, so // without this call Pane B never learned about a window resize, an // Alt+B sidebar toggle, or a tab-rail drag, and its PTY silently - // stayed at whatever size it was last dragged to. - this._forEachTile?.((tile) => tile.fit()); + // stayed at whatever size it was last dragged to. Grid tiles are left + // out: the grid's own observer (tile-grid.js _scheduleTileGridRefit) + // refits every one of them on the same resize, and a second fit here + // only re-measured six panes to send nothing. + this._forEachTile?.((tile) => tile.fit(), { grid: false }); }, 300); // Trailing-edge: only fire after 300ms of no resize events }; @@ -4512,7 +4525,12 @@ Object.assign(CodemanApp.prototype, { * it from its own terminal's focus; the primary terminal's focus gives it back. */ _focusedPane() { - const tile = this._focusedTile; + let tile = this._focusedTile; + // With the tile grid open the main terminal is parked, so the pane is the + // focused tile even when DOM focus sits on a button or a panel. + if ((!tile || tile._destroyed || !tile.terminal) && this._tilesOwnTerminal?.()) { + tile = this._tileFor(this.activeSessionId); + } if (tile && !tile._destroyed && tile.terminal) { return { terminal: tile.terminal, sessionId: tile.sessionId, isPrimary: false, tile }; } @@ -4525,13 +4543,19 @@ Object.assign(CodemanApp.prototype, { }, /** - * Run `fn(tile)` for every secondary terminal pane on screen: today the split - * pane's second terminal, when one is open. Font, weight, family and skin - * changes go through here so they reach every pane without a special case - * per pane kind. Agent Teams terminals size themselves and are not tiles. + * Run `fn(tile)` for every secondary terminal pane on screen: the split + * pane's second terminal and every tile of the tile grid (never both: the two + * modes are not open together). Font, weight, family and skin changes go + * through here so they reach every pane without a special case per pane kind. + * `{ grid: false }` skips grid tiles (they keep their own font size). + * Agent Teams terminals size themselves and are not tiles. */ - _forEachTile(fn) { + _forEachTile(fn, { grid = true } = {}) { if (this._splitPane?.terminal) fn(this._splitPane); + if (!grid || !this._tileGrid?.open) return; + for (const { tile } of this._tileGrid.tiles.values()) { + if (tile.terminal) fn(tile); + } }, // Clears the pane the keyboard is in. The chord itself also reaches that @@ -4614,6 +4638,9 @@ Object.assign(CodemanApp.prototype, { this.showToast('No active session', 'warning'); return; } + // Backstop: _focusedPane() answers with the focused tile while the grid is + // open, so this is reached only if that tile is gone mid-call. + if (this._tilesOwnTerminal?.()) return; // The pane belongs to the popup showing it, so this window has nothing to // restore. Say so rather than reporting a size that was never sent — the @@ -5742,11 +5769,20 @@ Object.assign(CodemanApp.prototype, { }, increaseFontSize() { + // With the tile grid open, Ctrl +/- sizes the tiles (their own font size). + if (this._tilesOwnTerminal?.()) { + this.setTileFontSize(Math.min(this._tileGridFontSize() + 2, 24)); + return; + } const current = this.terminal.options.fontSize || 14; this.setFontSize(Math.min(current + 2, 24)); }, decreaseFontSize() { + if (this._tilesOwnTerminal?.()) { + this.setTileFontSize(Math.max(this._tileGridFontSize() - 2, 10)); + return; + } const current = this.terminal.options.fontSize || 14; this.setFontSize(Math.max(current - 2, 10)); }, @@ -5759,10 +5795,13 @@ Object.assign(CodemanApp.prototype, { // Update overlay font cache and re-render at new cell dimensions this._localEchoOverlay?.refreshFont(); this._predictiveEcho?.refreshFont(); - this._forEachTile?.((tile) => { - tile.terminal.options.fontSize = size; - tile.fit(); // a font change is a size change: tell its PTY too (#464) - }); + this._forEachTile?.( + (tile) => { + tile.terminal.options.fontSize = size; + tile.fit(); // a font change is a size change: tell its PTY too (#464) + }, + { grid: false } + ); }, /** @@ -6066,6 +6105,9 @@ Object.assign(CodemanApp.prototype, { // settle-time refit through this call and has no fallback, which is correct: // a pane it does not own is not its to refit either. if (!this.isSoloWindow && this.detachedSessions?.has(sessionId)) return false; + // Backstop: while the tile grid owns the terminal, a tile sizes this PTY and + // the parked main terminal measures nothing worth sending. + if (this._tilesOwnTerminal?.()) return false; // Fit, floor, and apply in one step so the numbers below are the numbers // xterm is actually holding (or, while another device holds the width, // the numbers this container would hold if the PTY followed). diff --git a/src/web/public/tile-grid.js b/src/web/public/tile-grid.js new file mode 100644 index 00000000..076e642c --- /dev/null +++ b/src/web/public/tile-grid.js @@ -0,0 +1,2596 @@ +// src/web/public/tile-grid.js + +/** + * @fileoverview The tile grid: 1 to TILE_GRID_MAX (6) live sessions side by + * side in one window, each in its own TerminalTile (terminal-tile.js), laid + * out by count (window.CodemanTileGrid, constants.js). Desktop only; see + * docs/tile-grid-plan.md. + * + * While the grid is open the main terminal (terminal-ui.js) is PARKED: hidden, + * its socket closed, and every path that would write to it, fetch for it or + * reconnect it stands aside (`_tilesOwnTerminal()`). `activeSessionId` always + * names the FOCUSED tile's session, so everything keyed on it (files panel, + * respawn and Ralph panels, subagent windows, voice, image paste, the tab + * highlight) follows focus without knowing tiles exist. + * + * Every capture a tile fetches goes through the grid's one TileLoadQueue, + * because each is a synchronous tmux call on the server. + * + * @dependency terminal-tile.js (window.TerminalTile, window.TileLoadQueue) + * @dependency constants.js (window.CodemanTileGrid, SPLIT_PANE_MIN_WIDTH) + * @loadorder 7.6 of 16, loaded after terminal-split.js and before respawn-ui.js + */ + +// Per-device tile font size (a tile is a fraction of the screen). +const TILE_GRID_FONT_KEY = 'codeman-tile-font-size'; +// The grid this device last had, ids only (sanitizeTileGridState, constants.js): +// `{ v: 1, open, ids, focused, zoomed, colFr, rowFr }`, `ids` being the cells +// in reading order with `null` for an empty one. `open: false` keeps it +// remembered for one-click return; restored on reload inside handleInit. +const TILE_GRID_STORAGE_KEY = 'codeman:tile-grid'; +// How many tiles a click on Tiles opens: the count last picked in its +// right-click menu (2, 4 or 6; owner decision 10), per device. Its own key, so +// the stored grid above stays ids only. +const TILE_GRID_COUNT_KEY = 'codeman:tile-count'; +// The leaving tiles' fade (styles.css .tile--leaving) plus slack: the still +// copy of a closing grid goes even if animationend never comes (a hidden tab, +// a cancelled animation). +const TILE_GHOST_FALLBACK_MS = 450; +// The longest a closing grid's still copy waits for the single view's replay +// before it fades anyway, so a slow load never leaves a stale picture up. +const TILE_GHOST_HOLD_MAX_MS = 700; +// A tile's terminal shows once its first capture has landed (the load queue +// says so); this is the backstop should that never be reported. +const TILE_REVEAL_FALLBACK_MS = 15000; +// How long the pointer (or a keyboard focus) rests on the Tiles button before +// its hover card shows (owner feedback 1). +const TILE_HINT_DELAY_MS = 300; +// Trailing debounce for refitting tiles after the grid area changes size, so a +// window drag sends each tile's PTY one resize, not one per frame. +const TILE_GRID_REFIT_MS = 150; +// Width of the draggable column and row dividers (their own grid tracks), and +// the grid section's padding (styles.css .tile-grid), for the drag math. +const TILE_DIVIDER_PX = 6; +const TILE_GRID_PADDING_PX = 4; + +/** `minmax(0, 1fr) 6px minmax(0, 2fr) ...`: tracks with a divider track between each. */ +function tileGridTracks(fr) { + return fr.map((f) => `minmax(0, ${Math.round(f * 1000) / 1000}fr)`).join(` ${TILE_DIVIDER_PX}px `); +} +// Registry ids of the tile chords (DEFAULT_SHORTCUTS, app.js), and whether each +// needs the grid open. The toggle applies wherever a grid could open. The arrow +// chords (`direction`, `move`) leave a text field its keys (tileShortcutFor). +const TILE_SHORTCUTS = { + 'toggle-tile-grid': { needsOpen: false }, + 'focus-tile-left': { needsOpen: true, direction: 'left' }, + 'focus-tile-right': { needsOpen: true, direction: 'right' }, + 'focus-tile-up': { needsOpen: true, direction: 'up' }, + 'focus-tile-down': { needsOpen: true, direction: 'down' }, + 'move-tile-left': { needsOpen: true, move: 'left' }, + 'move-tile-right': { needsOpen: true, move: 'right' }, + 'move-tile-up': { needsOpen: true, move: 'up' }, + 'move-tile-down': { needsOpen: true, move: 'down' }, + 'remove-tile': { needsOpen: true }, + 'zoom-tile': { needsOpen: true }, +}; + +/** + * A text field other than a terminal's own input (xterm's helper textarea): + * the rename input, the file editor, a settings field. Shifted arrows select + * there (Ctrl+Shift by word; Option+Shift by word on macOS), so the arrow + * chords, focus and move, leave it alone (owner: best practice). + */ +function isTextFieldTarget(target) { + if (!target || target.classList?.contains?.('xterm-helper-textarea')) return false; + const tag = String(target.tagName || '').toUpperCase(); + return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable === true; +} + +/** + * The count menu's picture of `n` tiles: the grid's own layout for that count + * (2x1, 2x2, 3x2) as small rounded cells. + */ +function tileCountGlyph(n) { + const { cols, rows } = window.CodemanTileGrid.computeTileLayout({ count: n }); + const NS = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(NS, 'svg'); + svg.setAttribute('class', 'tile-count-glyph'); + svg.setAttribute('viewBox', '0 0 30 20'); + svg.setAttribute('aria-hidden', 'true'); + const gap = 3; + const w = (30 - gap * (cols - 1)) / cols; + const h = (20 - gap * (rows - 1)) / rows; + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + const rect = document.createElementNS(NS, 'rect'); + rect.setAttribute('x', String(c * (w + gap))); + rect.setAttribute('y', String(r * (h + gap))); + rect.setAttribute('width', String(w)); + rect.setAttribute('height', String(h)); + rect.setAttribute('rx', '1.5'); + svg.appendChild(rect); + } + } + return svg; +} + +/** + * The hover card's mouse: a rounded body with its left or right button filled. + */ +function tileHintMouseGlyph(button) { + const NS = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(NS, 'svg'); + svg.setAttribute('class', `tile-hint-glyph tile-hint-glyph--${button}`); + svg.setAttribute('viewBox', '0 0 10 14'); + svg.setAttribute('aria-hidden', 'true'); + const body = document.createElementNS(NS, 'rect'); + for (const [k, v] of Object.entries({ x: '0.75', y: '0.75', width: '8.5', height: '12.5', rx: '4.25' })) { + body.setAttribute(k, v); + } + const press = document.createElementNS(NS, 'path'); + press.setAttribute('class', 'tile-hint-press'); + press.setAttribute( + 'd', + button === 'left' + ? 'M4.6 1.3 V6 H1.3 V5.2 A3.6 3.6 0 0 1 4.6 1.3 Z' + : 'M5.4 1.3 V6 H8.7 V5.2 A3.6 3.6 0 0 0 5.4 1.3 Z' + ); + svg.append(body, press); + return svg; +} + +/** The grid's state. `has(id)` answers only while it is open. */ +class TileGridModel { + constructor() { + this.open = false; + // The grid's cells in reading order (row-major), cols x rows of them: a + // session id, or null for an empty cell. THE source of truth for where + // each tile is (owner: an empty cell can be any cell); `ids` derives from it. + this.cells = []; + // id -> { tile: TerminalTile, el: HTMLElement } + this.tiles = new Map(); + this.focusedId = null; + // The tile filling the grid (tmux zoom), or null. `autoZoom`: zoomed by the + // grid itself because the window cannot fit the tiles; it follows focus and + // lifts once the window fits again. + this.zoomedId = null; + this.autoZoom = false; + // Track fractions (grid-template fr values) set by the dividers; equal + // again whenever the column or row count changes. + this.colFr = []; + this.rowFr = []; + // 'col-' / 'row-' -> the divider element between track i and i+1. + this.dividers = new Map(); + this.cols = 0; + this.rows = 0; + this.queue = null; + this.resizeObserver = null; + this.refitTimer = null; + } + + has(id) { + return this.open && this.tiles.has(id); + } + + /** The tiled sessions in reading order, holes skipped (a fresh array: change `cells`, never this). */ + get ids() { + return this.cells.filter(Boolean); + } +} + +Object.assign(CodemanApp.prototype, { + /** + * True while the grid owns the terminal area and the main terminal is parked. + * Every main-terminal path that would write, fetch, resize or reconnect checks + * this and stands aside. + */ + _tilesOwnTerminal() { + return !!this._tileGrid?.open; + }, + + /** The open grid's TerminalTile for a session, or null. */ + _tileFor(sessionId) { + return this._tileGrid?.open ? (this._tileGrid.tiles.get(sessionId)?.tile ?? null) : null; + }, + + /** Desktop only, never in a solo (popped-out) window; same gate as the split. */ + canOpenTileGrid() { + return !this.isSoloWindow && window.innerWidth >= SPLIT_PANE_MIN_WIDTH; + }, + + _tileGridFontSize() { + let saved = NaN; + try { + saved = parseInt(localStorage.getItem(TILE_GRID_FONT_KEY), 10); + } catch { + /* Storage unavailable: the default below. */ + } + return saved >= 10 && saved <= 24 ? saved : window.CodemanTileGrid.TILE_FONT_SIZE_DEFAULT; + }, + + /** Ctrl +/- while the grid is open: every tile, then each tile's PTY (a font change is a size change, #464). */ + setTileFontSize(size) { + try { + localStorage.setItem(TILE_GRID_FONT_KEY, String(size)); + } catch { + /* Per-device convenience only. */ + } + for (const { tile } of this._tileGrid?.tiles.values() || []) { + tile.fontSize = size; + if (!tile.terminal) continue; + tile.terminal.options.fontSize = size; + tile.fit(); + } + }, + + _tileLoadQueue() { + const grid = this._tileGrid; + if (!grid.queue) { + grid.queue = new window.TileLoadQueue({ + // The focused tile first, then reading order. + rank: (tile) => (tile.sessionId === grid.focusedId ? -1 : grid.ids.indexOf(tile.sessionId)), + // A quiet "loading" state on a tile until its capture has landed. + onChange: (tile, state) => { + const entry = grid.tiles.get(tile.sessionId); + if (entry?.tile !== tile) return; + entry.el.classList.toggle('tile--loading', state !== 'idle'); + // The first capture has landed (or failed): the terminal fades in, + // whole, instead of showing its replay scroll by. + if (state === 'idle') entry.el.classList.remove('tile--revealing'); + }, + }); + } + return grid.queue; + }, + + _tileGridSection() { + let section = document.getElementById('tileGrid'); + if (!section) { + section = document.createElement('section'); + section.id = 'tileGrid'; + section.className = 'tile-grid'; + section.setAttribute('aria-label', 'Tiled sessions'); + const wrap = document.querySelector('.terminal-wrap'); + wrap?.parentElement?.insertBefore(section, wrap.nextSibling); + } + return section; + }, + + /** + * Opens the grid on `ids` (unknown, detached and duplicate ids are skipped; + * at most TILE_GRID_MAX), focusing `focusedId` or the first. Already open, it + * adds what is missing and moves focus. `auto: false` makes the focus a human + * selection (it acknowledges that session's idle alert). An open split + * closes (the two are never open together); `mergeSplit` (default) makes its + * two sessions the first tiles, false opens exactly `ids` (a stored grid). + * + * Parks the main terminal first: `_cleanupPreviousSession()` runs ONCE, while + * its snapshot of the session it shows is still right, and closes its socket. + * + * @returns {boolean} whether the grid is open afterwards + */ + openTileGrid(ids, { focusedId = null, auto = true, mergeSplit = true } = {}) { + if (!this.canOpenTileGrid()) return false; + const grid = (this._tileGrid ||= new TileGridModel()); + const max = window.CodemanTileGrid.TILE_GRID_MAX; + // The grid and the split are never open together. An open split becomes the + // grid's first two tiles (Pane A focused, Pane B beside it), so "split, then + // want more" is one step. No closing resize for Pane A: it is about to park. + let requested = ids || []; + if (this._splitPane) { + const seed = [this.activeSessionId, this._splitSessionId].filter(Boolean); + this.closeSplitPane({ skipPrimaryResize: true }); + if (mergeSplit) { + requested = [...seed, ...requested]; + if (!requested.includes(focusedId)) focusedId = seed[0] ?? null; + } + } + const wanted = []; + for (const id of requested) { + if (typeof id !== 'string' || wanted.includes(id)) continue; + if (!this.sessions.has(id) || this.detachedSessions?.has(id)) continue; + wanted.push(id); + if (wanted.length === max) break; + } + if (wanted.length === 0) return grid.open; + const focus = wanted.includes(focusedId) ? focusedId : wanted[0]; + + if (grid.open) { + for (const id of wanted) this.addTile(id); + if (grid.has(focus)) this._selectTiledSession(focus, { auto }); + return true; + } + + // No snapshot of a session that becomes a tile: closing the grid drops the + // main terminal's snapshot of every tiled id (stale by then), so taking one + // here (a 1000-line serialize and up to 256 KB of localStorage for a + // non-shell session) only ever produced a copy that was thrown away. + this._cleanupPreviousSession(focus, { skipSnapshot: wanted.includes(this.activeSessionId) }); + // A grid closed a moment ago may still be fading out over the stage. + this._purgeTileGhosts(); + grid.open = true; + grid.cells = []; + grid.cols = 0; + grid.rows = 0; + grid.focusedId = focus; + document.querySelector('.main')?.classList.add('tiles-active'); + const section = this._tileGridSection(); + this.hideWelcome(); + // Mount every tile and lay the grid out BEFORE any tile connects, so each + // first fit measures its real cell. Each tile enters in + // reading order (opacity and transform only: the fit measures the final + // cell, so the animation adds no resize). + wanted.forEach((id, k) => this._mountTile(id, { enterIndex: k })); + // Packed from the first cell (_applyTileLayout pads the shape with empty cells). + grid.cells = wanted.filter((id) => grid.tiles.has(id)); + this._applyTileLayout(); + // The tiles' frames paint first; their terminals are built one per frame + // after it, the focused tile's first, so its capture is the one the queue + // starts with (_connectTilesPaced). + this._connectTilesPaced([focus, ...wanted.filter((id) => id !== focus)]); + if (!grid.resizeObserver && typeof ResizeObserver !== 'undefined') { + // The main terminal's observer watches a node that is now hidden; this one + // catches window resizes, sidebar toggles and rail drags for the grid. + grid.resizeObserver = new ResizeObserver(() => this._scheduleTileGridRefit()); + grid.resizeObserver.observe(section); + } + this._installTileGridWidthGate(); + this._selectTiledSession(focus, { auto }); + this._updateConnectionIndicator?.(); + this._updateSplitButtonForTiles(); + this._updateTileGridButtonState(); + return true; + }, + + /** + * Leaves the grid: every tile destroyed (sockets closed, xterms disposed, + * queued loads dropped), the main terminal unparked. + * + * `keepStored` remembers the grid for one-click return (toggleTileGrid). + * `reselect` shows the focused session in the single view through a forced + * reload; pass false when the caller selects something itself. `animate` + * (the Tiles toggle only, owner answer 4) leaves a still copy of the tiles + * over the stage until the single view has its content (_ghostTileGrid). + * + * The main terminal's cached content for EVERY tiled id is invalidated: it was + * written before the grid opened, possibly hours ago, and selectSession paints + * a snapshot as its first frame. + */ + closeTileGrid({ keepStored = true, reselect = true, animate = false } = {}) { + const grid = this._tileGrid; + if (!grid?.open) return; + const focusedId = grid.focusedId; + const ids = grid.ids.slice(); + // The close itself stays synchronous (every caller relies on the grid + // being gone on return); what the user sees leave is a still copy of the + // tiles, dimmed at once, held until the single view has replayed its + // session (no empty flash), then faded out over it. + const releaseGhosts = animate ? this._ghostTileGrid({ hold: reselect }) : null; + // Remembered (closed) for one-click return, or forgotten. + if (keepStored) this._persistTileGrid({ open: false }); + else this._forgetStoredTileGrid(); + // A divider drag or a header drag in progress ends with the grid. + this._tileDividerDragTeardown?.(); + this._endTileMoveDrag(); + // Closed BEFORE the tiles go: each destroy() updates the header's connection + // state, which must read the main terminal again, not half-destroyed tiles. + grid.open = false; + clearTimeout(grid.refitTimer); + grid.refitTimer = null; + grid.resizeObserver?.disconnect(); + grid.resizeObserver = null; + for (const { tile, el } of grid.tiles.values()) { + this._destroyTerminalTile(tile); + el.remove(); + } + grid.tiles.clear(); + for (const el of grid.dividers.values()) el.remove(); + grid.dividers.clear(); + for (const slot of grid.slots || []) slot.remove(); + grid.slots = []; + grid.colFr = []; + grid.rowFr = []; + grid.cells = []; + grid.cols = 0; + grid.rows = 0; + grid.focusedId = null; + grid.zoomedId = null; + grid.autoZoom = false; + document.querySelector('.main')?.classList.remove('tiles-active'); + const section = document.getElementById('tileGrid'); + if (section) { + section.style.gridTemplateColumns = ''; + section.style.gridTemplateRows = ''; + section.classList.remove('tile-grid--zoomed'); + } + // As _redock does: the tiles sized these PTYs, so the main terminal's + // record of the last size it sent no longer describes them. + this._lastResizeDims = null; + for (const id of ids) { + this._xtermSnapshots?.delete(id); + try { + localStorage.removeItem(`codeman-xs-${id}`); + } catch { + /* Nothing stored. */ + } + this.terminalBufferCache?.delete(id); + } + this._updateConnectionIndicator?.(); + this._updateSplitButtonForTiles(); + this._updateTileGridButtonState(); + // The tabs drop their .in-tiles marker. + this.renderSessionTabs?.(); + if (reselect) { + const shown = this._selectAfterTileGrid(focusedId); + if (releaseGhosts) Promise.resolve(shown).finally(releaseGhosts); + } else { + releaseGhosts?.(); + } + }, + + /** False under prefers-reduced-motion: the grid then opens and closes at once. */ + _tileMotionAllowed() { + return !window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches; + }, + + /** + * A still copy of the open grid over the stage, so the tiles leave calmly + * while closeTileGrid (or a re-form) tears the real ones down at once. + * Clones only: no xterm, socket or listener comes along (the DOM renderer's + * rows and their style elements do, so the copy shows the text), and the + * layer is inert, hidden from assistive tech and takes no pointer. With + * `hold` it dims at once and waits for the returned release() (the single + * view has its content), at most TILE_GHOST_HOLD_MAX_MS; without, it fades + * out straight away. It removes itself when the fade ends (or after + * TILE_GHOST_FALLBACK_MS). Nothing under reduced motion (release is then a + * no-op). + * + * @returns {() => void} release + */ + _ghostTileGrid({ hold = false } = {}) { + const grid = this._tileGrid; + const section = document.getElementById('tileGrid'); + const main = section?.parentElement; + const none = () => {}; + if (!grid?.open || !section || !main || !this._tileMotionAllowed()) return none; + this._purgeTileGhosts(); + const s = section.getBoundingClientRect(); + const m = main.getBoundingClientRect(); + if (!(s.width > 0 && s.height > 0)) return none; + const layer = document.createElement('div'); + layer.className = hold ? 'tile-grid-ghosts' : 'tile-grid-ghosts tile-grid-ghosts--now'; + layer.setAttribute('aria-hidden', 'true'); + layer.inert = true; + layer.style.left = `${s.left - m.left}px`; + layer.style.top = `${s.top - m.top}px`; + layer.style.width = `${s.width}px`; + layer.style.height = `${s.height}px`; + layer.style.gridTemplateColumns = section.style.gridTemplateColumns; + layer.style.gridTemplateRows = section.style.gridTemplateRows; + // Zoomed, only the zoomed tile is on screen (the others are display: none + // under .tile-grid--zoomed, a rule the ghost layer does not carry). + const zoomed = section.classList.contains('tile-grid--zoomed'); + for (const id of grid.ids) { + const el = grid.tiles.get(id)?.el; + if (!el || (zoomed && !el.classList.contains('tile--zoomed'))) continue; + const ghost = el.cloneNode(true); + ghost.classList.remove('tile--entering', 'tile--needs', 'tile--loading', 'tile--drop-target', 'tile--dragging'); + ghost.classList.add('tile--leaving'); + layer.appendChild(ghost); + } + main.appendChild(layer); + let fallback = null; + let holdCap = null; + const done = () => { + clearTimeout(fallback); + clearTimeout(holdCap); + layer.remove(); + if (this._tileGhostLayer === layer) this._tileGhostLayer = null; + }; + const release = () => { + if (fallback !== null || !layer.isConnected) return; + clearTimeout(holdCap); + layer.classList.add('tile-grid-ghosts--release'); + fallback = setTimeout(done, TILE_GHOST_FALLBACK_MS); + }; + layer.addEventListener('animationend', (e) => { + if (/^tile-leave/.test(e.animationName) && e.target === layer.lastElementChild) done(); + }); + if (hold) holdCap = setTimeout(release, TILE_GHOST_HOLD_MAX_MS); + else release(); + this._tileGhostLayer = layer; + return release; + }, + + /** Drops a still copy still showing (the grid reopened, or another close came). */ + _purgeTileGhosts() { + this._tileGhostLayer?.remove(); + this._tileGhostLayer = null; + }, + + /** + * The header Tiles button: shown when its per-device setting is on AND the + * window is desktop-wide (a JS check plus a live media listener, the same + * pair as the Split button; the CSS `@media (max-width: 1179px)` rule is the + * backstop that hides it even if this never runs). + */ + _applyTileGridButtonVisibility(enabled) { + this._installTileGridHint(); + this._tileGridButtonSettingEnabled = !!enabled; + const btn = document.querySelector('.btn-tile-grid'); + const wide = window.innerWidth >= SPLIT_PANE_MIN_WIDTH; + btn?.classList.toggle('btn-tile-grid--hidden', !enabled || !wide || !!this.isSoloWindow); + if (!this._tileGridButtonWidthListener && window.matchMedia) { + this._tileGridButtonWidthListener = true; + const mq = window.matchMedia(`(min-width: ${SPLIT_PANE_MIN_WIDTH}px)`); + mq.addEventListener('change', () => this._applyTileGridButtonVisibility(this._tileGridButtonSettingEnabled)); + } + }, + + // Open grid: the button's click closes it, and says so. + _updateTileGridButtonState() { + const btn = document.querySelector('.btn-tile-grid'); + if (!btn) return; + const open = this._tilesOwnTerminal(); + btn.classList.toggle('tiles-open', open); + btn.setAttribute('aria-pressed', open ? 'true' : 'false'); + // No native title: the hover card says it (two tooltips never stack), and + // aria-describedby gives screen readers the same text. + btn.setAttribute( + 'aria-label', + open + ? 'Tiles: back to a single session (right-click for how many tiles)' + : 'Tiles: show several sessions side by side (right-click for how many)' + ); + this._renderTileHint(); + }, + + /** + * The Tiles button's hover card (owner feedback 1: "give me the hover info + * to right click over the tile button to adjust it"): the title with the + * remembered count, what a click does (open or close the grid), that a + * right-click chooses 2, 4 or 6, what opens when the count does not fit the + * window, and, shown from the keyboard, Shift+F10. It replaces the button's + * native title. The card always exists (hidden) and is kept current, since + * the button's aria-describedby reads it for screen readers without a + * hover. Installed once, from the button's visibility setter; never in a + * solo window. + */ + _installTileGridHint() { + if (this._tileHint || this.isSoloWindow) return; + const btn = document.querySelector('.btn-tile-grid'); + if (!btn) return; + const card = document.createElement('div'); + card.id = 'tileGridHint'; + card.className = 'tile-hint'; + card.setAttribute('role', 'tooltip'); + card.hidden = true; + const title = document.createElement('div'); + title.className = 'tile-hint-title'; + const line = (glyph) => { + const row = document.createElement('div'); + row.className = 'tile-hint-line'; + const text = document.createElement('span'); + if (glyph) row.appendChild(glyph); + row.appendChild(text); + return { row, text }; + }; + const click = line(tileHintMouseGlyph('left')); + const right = line(tileHintMouseGlyph('right')); + right.text.textContent = 'Right-click: choose 2, 4 or 6 tiles'; + const fits = line(null); + fits.row.classList.add('tile-hint-note'); + const keys = line(null); + keys.row.classList.add('tile-hint-keys'); + keys.text.textContent = 'Shift+F10: the same menu from the keyboard'; + card.append(title, click.row, right.row, fits.row, keys.row); + document.body.appendChild(card); + btn.removeAttribute('title'); + btn.setAttribute('aria-describedby', card.id); + const hint = (this._tileHint = { btn, card, title, click: click.text, fits, keys, timer: null, suppressed: false }); + const canHover = () => window.matchMedia?.('(hover: hover)')?.matches !== false; + btn.addEventListener('pointerenter', (e) => { + if (e?.pointerType === 'touch' || !canHover()) return; + this._scheduleTileHint({ keyboard: false }); + }); + btn.addEventListener('pointerleave', () => { + hint.suppressed = false; + this._hideTileHint(); + }); + btn.addEventListener('focus', () => { + // Focus put back by the count menu's Escape: the user was just there. + if (hint.skipFocus) { + hint.skipFocus = false; + return; + } + if (btn.matches?.(':focus-visible')) this._scheduleTileHint({ keyboard: true }); + }); + // Leaving the button ends a click's suppression too: a keyboard focus that + // comes back later is a new arrival, even with the pointer still on it. + btn.addEventListener('blur', () => { + hint.suppressed = false; + this._hideTileHint(); + }); + // Capture: these run before the button's own handlers, so the card is gone + // before a right-click opens the count menu or a click opens the grid; and + // it stays gone while the pointer rests there. + const dismiss = () => { + hint.suppressed = true; + this._hideTileHint(); + }; + for (const type of ['pointerdown', 'click', 'contextmenu']) btn.addEventListener(type, dismiss, true); + // While shown: Escape, a scroll anywhere, a resize. + hint.onKey = (e) => { + if (e.key === 'Escape') this._hideTileHint(); + }; + hint.onAway = () => this._hideTileHint(); + this._renderTileHint(); + }, + + /** + * The card's text, from the remembered count, the grid's state and what the + * window fits. Compared with the last English text set, never the DOM (in + * zh-CN the DOM holds the translation; see _renderTileOverlay). + */ + _renderTileHint() { + const hint = this._tileHint; + if (!hint) return; + const count = this._tileGridCount(); + const open = this._tilesOwnTerminal(); + const capacity = this._tileGridLimit().capacity; + const set = (el, key, text) => { + if (hint[key] === text) return; + hint[key] = text; + el.textContent = text; + }; + set(hint.title, 'titleText', `Tiles \u00B7 ${count}`); + set(hint.click, 'clickText', open ? 'Click: close the grid' : 'Click: open the grid'); + const plural = capacity === 1 ? '' : 's'; + const fitsText = + count <= capacity + ? '' + : open + ? `This window fits ${capacity} tile${plural}` + : `This window fits ${capacity} tile${plural}: a click opens ${capacity}`; + set(hint.fits.text, 'fitsText', fitsText); + hint.fits.row.hidden = !fitsText; + }, + + _scheduleTileHint({ keyboard }) { + const hint = this._tileHint; + if (!hint || hint.suppressed) return; + clearTimeout(hint.timer); + hint.timer = setTimeout(() => this._showTileHint({ keyboard }), TILE_HINT_DELAY_MS); + }, + + /** Under the button, right-aligned as the count menu; never with the menu open or the button hidden. */ + _showTileHint({ keyboard }) { + const hint = this._tileHint; + hint.timer = null; + if (hint.suppressed || this._tileCountMenu || hint.btn.classList.contains('btn-tile-grid--hidden')) return; + this._renderTileHint(); + hint.keys.row.hidden = !keyboard; + const rect = hint.btn.getBoundingClientRect?.(); + if (rect) { + hint.card.style.top = `${rect.bottom + 6}px`; + hint.card.style.right = `${Math.max(8, window.innerWidth - rect.right)}px`; + } + if (!hint.card.hidden) return; + hint.card.hidden = false; + document.addEventListener('keydown', hint.onKey, true); + window.addEventListener('scroll', hint.onAway, true); + window.addEventListener('resize', hint.onAway); + }, + + /** Idempotent: cancels a pending show and hides the card. */ + _hideTileHint() { + const hint = this._tileHint; + if (!hint) return; + clearTimeout(hint.timer); + hint.timer = null; + if (hint.card.hidden) return; + hint.card.hidden = true; + // Hidden, the card is the button's description in full: a hidden line + // inside it would be left out of what a screen reader hears. + hint.keys.row.hidden = false; + document.removeEventListener('keydown', hint.onKey, true); + window.removeEventListener('scroll', hint.onAway, true); + window.removeEventListener('resize', hint.onAway); + }, + + /** + * How many tiles the grid takes here and now: what the terminal area fits + * (the grid section, or the single view it would replace), at most the cap + * (TILE_GRID_MAX), never less than one. `full` says which of the two binds, + * so a large monitor never reads "this window fits 6". + */ + _tileGridLimit() { + const T = window.CodemanTileGrid; + const max = T.TILE_GRID_MAX; + const el = this._tilesOwnTerminal() ? this._tileGridSection() : document.querySelector('.terminal-wrap'); + const rect = el?.getBoundingClientRect?.() || { width: 0, height: 0 }; + const fits = T.tileGridCapacity({ + width: rect.width || window.innerWidth, + height: rect.height || window.innerHeight, + }); + const capacity = Math.max(1, Math.min(fits, max)); + const byCap = fits >= max; + return { + capacity, + full: byCap + ? `The grid holds at most ${max} tiles` + : `The grid already holds what this window fits (${capacity})`, + }; + }, + + /** The tile count a click on Tiles opens (the menu's last pick, per device), default 6. */ + _tileGridCount() { + let raw = null; + try { + raw = localStorage.getItem(TILE_GRID_COUNT_KEY); + } catch { + /* Storage unavailable: the default. */ + } + return window.CodemanTileGrid.sanitizeTileCount(raw); + }, + + _rememberTileGridCount(count) { + try { + localStorage.setItem(TILE_GRID_COUNT_KEY, String(window.CodemanTileGrid.sanitizeTileCount(count))); + } catch { + /* Per-device convenience only. */ + } + // The hover card names the count. + this._renderTileHint(); + }, + + /** + * Right-click on the Tiles button (or Shift+F10 / the Menu key on it, which + * fire the same contextmenu event; its click opens the grid at once, see + * toggleTileGrid): how many tiles, 2, 4 or 6 (owner decision 10), each with + * its shape, the remembered count checked. A count the window cannot fit is + * greyed out, and the menu says why; the keyboard then starts on the largest + * that fits (the count a click opens here). Picking one opens the grid with + * that many tiles, or re-forms the open grid to it, and remembers it for the + * click. Arrows move, Enter or Space picks, Escape closes and gives the + * keyboard back to the Tiles button, Tab closes. + */ + openTileCountMenu(event) { + // The right-click: the browser's own context menu stays away. + event?.preventDefault?.(); + // Never beside a hover card still showing (its own capture listener has + // usually hidden it already). + this._hideTileHint(); + if (this._tileCountMenu) { + this.closeTileCountMenu(); + return; + } + if (!this.canOpenTileGrid()) return; + const T = window.CodemanTileGrid; + const capacity = this._tileGridLimit().capacity; + const fitsText = `This window fits ${capacity} tile${capacity === 1 ? '' : 's'}`; + const current = this._tileGridCount(); + const menu = document.createElement('div'); + menu.id = 'tileCountMenu'; + menu.className = 'tile-count-menu'; + menu.setAttribute('role', 'menu'); + menu.setAttribute('aria-label', 'How many tiles'); + const heading = document.createElement('div'); + heading.className = 'tile-count-heading'; + heading.setAttribute('aria-hidden', 'true'); + heading.textContent = 'Tiles'; + menu.appendChild(heading); + const items = []; + for (const n of T.TILE_GRID_COUNTS) { + const item = document.createElement('button'); + item.type = 'button'; + item.className = 'tile-count-item'; + item.setAttribute('role', 'menuitemradio'); + item.setAttribute('aria-checked', n === current ? 'true' : 'false'); + item.tabIndex = -1; + item.dataset.count = String(n); + if (n > capacity) { + item.disabled = true; + item.setAttribute('aria-disabled', 'true'); + item.title = fitsText; + } + const label = document.createElement('span'); + label.className = 'tile-count-label'; + label.textContent = `${n} tiles`; + const check = document.createElement('span'); + check.className = 'tile-count-check'; + check.setAttribute('aria-hidden', 'true'); + check.textContent = n === current ? '\u2713' : ''; + item.append(tileCountGlyph(n), label, check); + item.addEventListener('click', (e) => { + e.stopPropagation?.(); + if (!item.disabled) this._pickTileCount(n); + }); + item.addEventListener('pointerenter', () => { + if (!item.disabled) item.focus?.(); + }); + menu.appendChild(item); + items.push(item); + } + if (capacity < T.TILE_GRID_MAX) { + const hint = document.createElement('div'); + hint.className = 'tile-count-hint'; + hint.textContent = fitsText; + menu.appendChild(hint); + } + + document.body.appendChild(menu); + const btn = document.querySelector('.btn-tile-grid'); + if (btn?.getBoundingClientRect) { + // Under the Tiles button (.tile-count-menu is position: fixed). + const rect = btn.getBoundingClientRect(); + menu.style.top = `${rect.bottom + 6}px`; + menu.style.right = `${Math.max(8, window.innerWidth - rect.right)}px`; + } + const enabled = () => items.filter((i) => !i.disabled); + const move = (delta) => { + const list = enabled(); + if (list.length === 0) return; + const at = list.indexOf(document.activeElement); + const next = at === -1 ? (delta > 0 ? 0 : list.length - 1) : (at + delta + list.length) % list.length; + list[next].focus?.(); + }; + // A click elsewhere closes it. A click on the Tiles button needs no + // exception: its own handler (toggleTileGrid) closes the menu first. + const onOutside = (e) => { + if (menu.contains?.(e.target)) return; + this.closeTileCountMenu(); + }; + // The menu's keys, in the capture phase while it is open. Escape normally + // reaches the app's global handler first, which closes the menu alone and + // gives the keyboard back (app.js); this one covers the rest. + const onKey = (e) => { + if (e.key === 'Escape') { + e.preventDefault?.(); + this.closeTileCountMenu({ refocus: true }); + } else if (e.key === 'ArrowDown' || e.key === 'ArrowRight') { + e.preventDefault?.(); + move(1); + } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') { + e.preventDefault?.(); + move(-1); + } else if (e.key === 'Home' || e.key === 'End') { + e.preventDefault?.(); + const list = enabled(); + list[e.key === 'Home' ? 0 : list.length - 1]?.focus?.(); + } else if (e.key === 'Enter' || e.key === ' ') { + const item = items.find((i) => i === document.activeElement); + if (!item) return; + // Not the button's own activation too. + e.preventDefault?.(); + if (!item.disabled) this._pickTileCount(Number(item.dataset.count)); + } else if (e.key === 'Tab') { + this.closeTileCountMenu(); + } + }; + // The keyboard leaving the menu for something else closes it, as any menu: + // closing the grid starts a selection that focuses the single view's + // terminal when its replay lands, and a menu left open behind that would + // send the keys meant for it (arrows, Enter, Escape) into the terminal. A + // focus going nowhere (a click on a button in Safari, which does not focus + // it) does not count. + menu.addEventListener('focusout', (e) => { + const to = e.relatedTarget; + if (to && !menu.contains?.(to)) this.closeTileCountMenu({ refocus: false }); + }); + this._tileCountMenu = { menu, onOutside, onKey }; + document.addEventListener('click', onOutside); + document.addEventListener('keydown', onKey, true); + // The checked count, or when the window cannot fit it, the largest that fits. + const start = items.find((i) => !i.disabled && i.getAttribute('aria-checked') === 'true') || enabled().at(-1); + (start || menu).focus?.(); + }, + + /** + * Idempotent: the global Escape handler may call it whether or not the menu + * is open. The keyboard goes back to the Tiles button when it was in the + * menu (`refocus` unset), or when asked (Escape); a click elsewhere has + * already moved it, and a pick passes `refocus: false`. + */ + closeTileCountMenu({ refocus } = {}) { + const menu = this._tileCountMenu; + if (!menu) return; + if (refocus === undefined) refocus = !!menu.menu.contains?.(document.activeElement); + this._tileCountMenu = null; + document.removeEventListener('click', menu.onOutside); + document.removeEventListener('keydown', menu.onKey, true); + menu.menu.remove(); + if (refocus) { + // The user was just in the menu: no hover card for this focus. + if (this._tileHint) this._tileHint.skipFocus = true; + document.querySelector('.btn-tile-grid')?.focus?.(); + if (this._tileHint) this._tileHint.skipFocus = false; + } + }, + + /** + * A count picked in the menu: remembered for the click, then the grid opens + * with that many tiles (what the click opens), or the open grid is re-formed + * to it (_reformTileGrid). Never more than the window fits; fewer open + * sessions than the count give fewer tiles. + */ + _pickTileCount(count) { + this.closeTileCountMenu({ refocus: false }); + this._rememberTileGridCount(count); + const grid = this._tileGrid; + if (!grid?.open) { + this.toggleTileGrid(); + return; + } + const T = window.CodemanTileGrid; + const n = Math.min(T.sanitizeTileCount(count), this._tileGridLimit().capacity); + const all = T.buildTilePickerSessions(this.sessions, this.sessionOrder, this.detachedSessions).map((c) => c.id); + this._reformTileGrid(T.tileGridSetForCount(grid.ids, all, n, grid.focusedId)); + }, + + /** + * The open grid re-formed to the tiles `target` (a count picked in the + * menu): a count change is a shape change, so the cell model's rule applies + * (reformTileCells: the tiles that stay keep their row and column when all + * fit, else they pack in reading order), and the tiles that join fill the + * empty cells in reading order, holes first. The focused tile is always + * among those that stay (tileGridSetForCount). Every tile that joins is + * mounted and the grid laid out ONCE before any of them connects (as in + * openTileGrid): a tile connected into an intermediate layout would fit that + * cell first and resize its PTY twice. A zoom the user chose ends: the grid + * they asked for is meant to be seen. + */ + _reformTileGrid(target) { + const grid = this._tileGrid; + if (!grid?.open) return; + const T = window.CodemanTileGrid; + const leaving = grid.ids.filter((id) => !target.includes(id)); + const joining = target.filter((id) => !grid.tiles.has(id)); + if (leaving.length === 0 && joining.length === 0) return; + // The old grid fades out over the new one as it forms. + this._ghostTileGrid(); + // A divider or header drag in progress measured the old grid. + this._tileDividerDragTeardown?.(); + this._endTileMoveDrag(); + for (const id of leaving) { + const entry = grid.tiles.get(id); + this._destroyTerminalTile(entry.tile); + entry.el.remove(); + grid.tiles.delete(id); + } + if (grid.zoomedId && !grid.autoZoom) grid.zoomedId = null; + const staying = grid.ids.filter((id) => grid.tiles.has(id)); + const mounted = joining.filter((id, k) => this._mountTile(id, { enterIndex: k })); + const { cols, rows } = this._tileShapeFor(grid.tiles.size); + grid.cells = T.reformTileCells(grid.cells, grid.cols, staying, mounted, cols, rows); + grid.cols = cols; + grid.rows = rows; + this._applyTileLayout(); + for (const id of mounted) this._connectTile(id); + this._scheduleTileGridRefit(); + this.renderSessionTabs?.(); + }, + + /** + * A session THIS tab's Run just created (session-ui.js + * _ensureCreatedSessionVisible, reached only from the Run paths): with the + * grid open it joins the next free slot, and Run's own selectSession then + * focuses it through the tile branch. Sessions created elsewhere (agents, + * other devices, cron) arrive only by session:created and never join. A grid + * already holding what the window fits does not take it; Run's selection + * then shows it in the single view (decision 1), and a hint says why. + */ + _joinTileGridFromRun(sessionId) { + const grid = this._tileGrid; + if (!grid?.open || grid.tiles.has(sessionId) || !this.sessions.has(sessionId)) return false; + const limit = this._tileGridLimit(); + if (grid.ids.length >= limit.capacity) { + this.showToast?.(`${limit.full}: the new session opens on its own`, 'info'); + return false; + } + // Run starts the session right after creating it: no Attach overlay + // meanwhile for a pane that is about to exist. + (this._tileAttachPending ||= new Map()).set(sessionId, Date.now()); + return this.addTile(sessionId); + }, + + // The Split button cannot act while the grid is open (openSplitPicker and + // openSplitPane refuse), so it says so: aria-disabled plus a title, the same + // refusal the split already gives for web tabs and the welcome screen. + _updateSplitButtonForTiles() { + const btn = document.querySelector('.btn-split'); + if (!btn) return; + const blocked = this._tilesOwnTerminal(); + btn.classList.toggle('btn-split--blocked', blocked); + btn.setAttribute('aria-disabled', blocked ? 'true' : 'false'); + if (blocked) { + btn.title = 'Split: unavailable while tiles are open'; + btn.setAttribute('aria-label', btn.title); + } else { + this._updateSplitButtonState?.(!!this._splitPane); + } + }, + + /** + * The tile chord `e` asks for, if it applies right now, else null. The + * toggle applies while the grid is open, or where one could open AND the + * per-device `showTileGridButton` setting is on: with it off (the default) + * the chord is inert and reaches the terminal like any unbound key (owner + * decision 6 in docs/tile-grid-plan.md). The focus, move, + * zoom and remove chords apply only while the grid is open, however it was + * opened (a move chord also while a tile is zoomed, as a no-op, so its keys + * never reach the CLI). The arrow chords never apply in a text field, whose + * keys they are. + * Registry-aware (rebinds and disables in App Settings, Shortcuts). + * The capture handler (app.js) dispatches it; every xterm key handler returns + * false for it, so a chord that applies never reaches a PTY. + * + * @returns {string|null} the registry id + */ + tileShortcutFor(e) { + if (!e || (!e.ctrlKey && !e.metaKey && !e.altKey)) return null; + if (typeof this.getShortcutRegistry !== 'function' || typeof this.matchesShortcutEvent !== 'function') return null; + const open = this._tilesOwnTerminal(); + for (const shortcut of this.getShortcutRegistry()) { + const spec = TILE_SHORTCUTS[shortcut.id]; + if (!spec || shortcut.disabled || !this.matchesShortcutEvent(e, shortcut)) continue; + if ((spec.direction || spec.move) && isTextFieldTarget(e.target)) continue; + if (spec.needsOpen) return open ? shortcut.id : null; + const enabled = this.loadAppSettingsFromStorage?.()?.showTileGridButton === true; + return open || (enabled && this.canOpenTileGrid()) ? shortcut.id : null; + } + return null; + }, + + /** Runs a chord tileShortcutFor() matched. */ + runTileShortcut(id) { + const spec = TILE_SHORTCUTS[id]; + if (!spec) return; + if (id === 'toggle-tile-grid') this.toggleTileGrid(); + else if (id === 'remove-tile') this.removeFocusedTile(); + else if (id === 'zoom-tile') this.zoomTile(this._tileGrid?.focusedId); + else if (spec.direction) this.focusTileInDirection(spec.direction); + else if (spec.move) this.moveTileInDirection(spec.move); + }, + + /** + * The Tiles button's click and Ctrl+Shift+G, one function so the two never + * drift (owner decision 8): opens the grid at once, no menu in the way, or + * closes it to the single view of the focused session. What opens is the + * remembered count of tiles (the right-click menu's last pick, default 6, + * at most what the window fits; owner decision 10), chosen by + * `tileGridOpenSet` (constants.js): the grid this tab last had, else an open + * split's two sessions, else the open sessions in tab order, the active one + * focused; then trimmed or filled to the count (the focused one kept). A + * remembered grid comes back with its tiles in their cells, the ones the + * count adds filling its empty cells first (_openStoredTileGrid). + */ + toggleTileGrid() { + this.closeTileCountMenu(); + if (this._tilesOwnTerminal()) { + this.closeTileGrid({ keepStored: true, reselect: true, animate: true }); + return; + } + if (!this.canOpenTileGrid()) return; + const stored = this._readStoredTileGrid(); + const set = this._tileGridOpenSet(stored); + if (!set) { + this.showToast?.('No sessions to show as tiles', 'info'); + return; + } + if (set.source === 'stored') this._openStoredTileGrid(stored, set.ids); + else this.openTileGrid(set.ids, { focusedId: set.focusedId }); + }, + + /** + * What the toggle would open now (see toggleTileGrid): `count` tiles (the + * remembered count), or as many as the window fits; `stored` saves a + * second read. + */ + _tileGridOpenSet(stored = this._readStoredTileGrid(), count = this._tileGridCount()) { + const T = window.CodemanTileGrid; + const n = Math.max(1, Math.min(count, this._tileGridLimit().capacity)); + const set = T.tileGridOpenSet({ + stored, + split: this._splitPane ? [this.activeSessionId, this._splitSessionId] : null, + sessions: this.sessions, + sessionOrder: this.sessionOrder, + detachedIds: this.detachedSessions, + activeId: this.activeSessionId, + limit: n, + }); + if (!set) return null; + const all = T.buildTilePickerSessions(this.sessions, this.sessionOrder, this.detachedSessions).map((c) => c.id); + return { ...set, ids: T.tileGridSetForCount(set.ids, all, n, set.focusedId) }; + }, + + /** Alt+Shift+Arrows: a human selection of the tile in that direction. */ + focusTileInDirection(direction) { + const grid = this._tileGrid; + if (!grid?.open) return; + // Over the cells: focus skips an empty one, never lands on it. + const id = window.CodemanTileGrid.tileInDirection(grid.cells, grid.focusedId, direction, grid.cols); + if (id) this.selectSession(id); + }, + + /** + * Ctrl+Tab / Alt+] (delta 1) and Alt+[ (delta -1) while the grid is open: a + * human selection of the next tile in reading order, wrapping. Returns + * whether the grid took the chord (it is open), so the tab walk is skipped. + */ + _cycleTileFocus(delta) { + const grid = this._tileGrid; + if (!grid?.open) return false; + const id = window.CodemanTileGrid.cycleTile(grid.ids, this.activeSessionId, delta); + if (id) this.selectSession(id); + return true; + }, + + /** Removes the focused tile (the session keeps running); a neighbour takes focus. */ + removeFocusedTile() { + const grid = this._tileGrid; + if (!grid?.open || !grid.focusedId) return; + this.removeTile(grid.focusedId); + }, + + // The single view after the grid closes: the session the grid was focused on, + // replayed fresh (forceReload drops the stale snapshot and nulls + // activeSessionId BEFORE _cleanupPreviousSession, so nothing wrong is saved), + // or, if that session is gone, the same fallback as closing the active tab. + // Returns the selection's promise (it settles once the replay is written), + // or undefined for the welcome screen. + _selectAfterTileGrid(sessionId) { + if (sessionId && this.sessions.has(sessionId)) { + return this.selectSession(sessionId, { forceReload: true, auto: true }); + } + this.activeSessionId = null; + try { + localStorage.removeItem('codeman-active-session'); + } catch { + /* Nothing stored. */ + } + const next = this.sessionOrder.find((id) => this.sessions.has(id)); + if (next) return this.selectSession(next, { auto: true }); + this.terminal?.clear(); + this.showWelcome(); + return undefined; + }, + + /** + * Adds one session as a tile (open grid only), into `cell` when that cell is + * empty (a tab dropped on it), else the first empty cell in reading order + * (_placeTile). It enters as the `enterIndex`-th of a staggered group + * (_mountTile). Returns whether it was added. + */ + addTile(sessionId, { cell = -1, enterIndex = 0 } = {}) { + const grid = this._tileGrid; + if (!grid?.open || grid.tiles.has(sessionId)) return false; + if (grid.ids.length >= window.CodemanTileGrid.TILE_GRID_MAX) return false; + if (!this._mountTile(sessionId, { enterIndex })) return false; + this._placeTile(sessionId, cell); + // A tile added while one is zoomed by hand is meant to be seen. + if (grid.zoomedId && !grid.autoZoom) grid.zoomedId = null; + this._applyTileLayout(); + this._connectTile(sessionId); + this._scheduleTileGridRefit(); + this.renderSessionTabs?.(); + return true; + }, + + /** + * Puts a tile just mounted into a cell. The shape for one more tile comes + * first (fitTileCells: the same shape keeps every cell; 2x2 growing to 3x2 + * keeps each tile where it is), then `cell` if it is empty there, else the + * first empty cell in reading order. + */ + _placeTile(sessionId, cell = -1) { + const grid = this._tileGrid; + const { cols, rows } = this._tileShapeFor(grid.ids.length + 1); + grid.cells = window.CodemanTileGrid.fitTileCells(grid.cells, grid.cols, cols, rows); + grid.cols = cols; + grid.rows = rows; + const k = Number.isInteger(cell) && grid.cells[cell] === null ? cell : grid.cells.indexOf(null); + // (No empty cell cannot happen: the shape for n tiles has at least n cells. + // Appended, the next layout packs it in.) + if (k === -1) grid.cells.push(sessionId); + else grid.cells[k] = sessionId; + }, + + /** Columns x rows (and whether they fit) for `count` tiles in the grid area as it is now. */ + _tileShapeFor(count) { + const rect = this._tileGridSection().getBoundingClientRect?.() || { width: 0, height: 0 }; + return window.CodemanTileGrid.computeTileLayout({ + count, + width: rect.width || window.innerWidth, + height: rect.height || window.innerHeight, + }); + }, + + /** + * Removes one tile; the session keeps running. Its cell becomes empty where + * it was, unless the shape changes with the count (then fitTileCells). When it held focus, `refocus` + * moves focus to the neighbouring tile (next in grid order, else previous), + * as the app's choice (`auto`: no idle alert is spent). The last tile + * leaving closes the grid: with `refocus` the single view then shows that + * session, without it the caller decides what comes next. + */ + removeTile(sessionId, { refocus = true } = {}) { + const grid = this._tileGrid; + const entry = grid?.open ? grid.tiles.get(sessionId) : null; + if (!entry) return false; + if (grid.ids.length === 1) { + this.closeTileGrid({ keepStored: false, reselect: refocus }); + return true; + } + const wasFocused = grid.focusedId === sessionId; + const neighbor = window.CodemanTileGrid.tileNeighbor(grid.ids, sessionId); + // A divider drag in progress was measured against this tile; a header + // drag of this tile has nothing left to drop. + this._tileDividerDragTeardown?.(); + if (this._draggedTileId === sessionId) this._endTileMoveDrag(); + // The zoomed tile leaving restores the grid (an automatic zoom moves to + // the neighbour with focus, below). + if (grid.zoomedId === sessionId) grid.zoomedId = grid.autoZoom && refocus ? neighbor : null; + this._destroyTerminalTile(entry.tile); + entry.el.remove(); + grid.tiles.delete(sessionId); + grid.cells[grid.cells.indexOf(sessionId)] = null; + // Before the layout, which may zoom the focused tile on a small window. + if (wasFocused) grid.focusedId = null; + this._applyTileLayout(); + this._scheduleTileGridRefit(); + this.renderSessionTabs?.(); + if (wasFocused && refocus && neighbor) this._selectTiledSession(neighbor, { auto: true }); + return true; + }, + + /** + * Builds one tile (header, body, TerminalTile); where it goes is the + * caller's (grid.cells). It enters with a short fade and settle + * (styles.css .tile--entering, the `enterIndex`-th of a staggered group), + * and its terminal stays transparent until its first capture lands + * (.tile--revealing, cleared by the load queue, with a backstop timer). + * Opacity and transform only, never anything its fit reads. + */ + _mountTile(sessionId, { enterIndex = 0 } = {}) { + const grid = this._tileGrid; + const session = this.sessions.get(sessionId); + if (!session || this.detachedSessions?.has(sessionId)) return false; + const el = document.createElement('div'); + el.className = 'tile tile--revealing'; + setTimeout(() => el.classList.remove('tile--revealing'), TILE_REVEAL_FALLBACK_MS); + if (this._tileMotionAllowed()) { + el.classList.add('tile--entering'); + el.style.setProperty('--tile-enter-index', String(enterIndex)); + const onEnd = (e) => { + if (e.target !== el || e.animationName !== 'tile-enter') return; + el.removeEventListener('animationend', onEnd); + el.classList.remove('tile--entering'); + }; + el.addEventListener('animationend', onEnd); + } + el.dataset.sessionId = sessionId; + // Header and body are siblings: the chrome is refreshed in place + // (_renderTileHeader), never by rewriting the tile, which would take the + // xterm in the body with it. + const header = this._buildTileHeader(sessionId); + const body = document.createElement('div'); + body.className = 'tile-body'; + el.append(header.el, body); + // Pressing a tile is a human selection: it focuses the tile and + // acknowledges its idle alert (the already-focused tile hits + // selectSession's early return, which acknowledges too). In the body on + // pointerdown, not click, so focus moves before the press reaches xterm, + // and never preventDefault: xterm's own mousedown focuses its textarea and + // starts selections. In the header on click instead (below): a press there + // may become a drag, and a drag that is cancelled changes nothing, focus + // included (owner: best practice). A drag never ends in a click. + el.addEventListener('pointerdown', (e) => { + if (header.el.contains?.(e?.target)) return; + if (this._tileGrid?.has(sessionId)) this.selectSession(sessionId); + }); + header.el.addEventListener('click', () => { + if (this._tileGrid?.has(sessionId)) this.selectSession(sessionId); + }); + // A tile takes any session but its own (_acceptTabDrops). + this._acceptTabDrops(el, (draggedId) => this.dropSessionOnTile(draggedId, sessionId), { + accepts: (id) => id !== sessionId, + }); + this._tileGridSection().appendChild(el); + const tile = this._newTerminalTile(sessionId, body); + grid.tiles.set(sessionId, { + tile, + el, + body, + overlay: null, + header: header.el, + dot: header.dot, + harness: header.harness, + name: header.name, + model: header.model, + modelName: header.modelName, + zoomBtn: header.zoomBtn, + renaming: false, + // The pid this tile last saw, so a pane that starts later is noticed. + pid: this.sessions.get(sessionId)?.pid ?? null, + }); + // Where it goes is the caller's (grid.cells). + this._renderTileHeader(sessionId); + return true; + }, + + /** + * Makes `el` a drop target for a session tab dragged from the strip (the + * strip's own drag sets `draggedTabId`) and for a tile dragged by its header + * (`_draggedTileId`, _installTileMoveDrag). Capture phase, with the event + * stopped: a tab drag carries the session id as text, and xterm's helper + * textarea would otherwise accept that drop and type the id into a PTY. + * `accepts(id)` is the target's own rule (a tile takes any session but its + * own; an empty cell takes any). A session it does not accept + * is held there too, but refused (`dropEffect: 'none'`, no highlight, so no + * drop follows). Any other drag (a file) is left alone. + */ + _acceptTabDrops(el, onDrop, { accepts = () => true } = {}) { + const dragged = () => (this._tileGrid?.open ? this.draggedTabId || this._draggedTileId || null : null); + el.addEventListener( + 'dragover', + (e) => { + const id = dragged(); + if (!id) return; + e.preventDefault?.(); + e.stopPropagation?.(); + const ok = accepts(id); + if (e.dataTransfer) e.dataTransfer.dropEffect = ok ? 'move' : 'none'; + if (ok) el.classList.add('tile--drop-target'); + }, + true + ); + el.addEventListener('dragleave', (e) => { + if (!el.contains?.(e.relatedTarget)) el.classList.remove('tile--drop-target'); + }); + el.addEventListener( + 'drop', + (e) => { + el.classList.remove('tile--drop-target'); + const id = dragged(); + if (!id) return; + e.preventDefault?.(); + e.stopPropagation?.(); + if (accepts(id)) onDrop(id); + }, + true + ); + }, + + /** Whether tiles can be moved now: more than one, and none zoomed (moving is off while one is). */ + _tilesMovable() { + const grid = this._tileGrid; + return !!grid?.open && !grid.zoomedId && grid.ids.length > 1; + }, + + /** + * Puts the tiles in new cells (the same sessions, the same shape): the one + * path every move takes, a header drag, the tab of a tiled session dropped + * on a tile or an empty cell, and the Move Tile chords. Nothing is + * remounted, reconnected or reloaded, and no session joins or leaves. + * Divider sizes belong to the cells, so a moved tile takes its new cell's + * size: each tile whose cell size changed fits once (its xterm and one PTY + * resize together, #464), every other tile is left alone. Refused while a + * tile is zoomed (moving is off then). + * + * @param {(string|null)[]} cells - the new cells + * @returns {boolean} false when refused, true otherwise (also when nothing moved) + */ + _reorderTiles(cells) { + const grid = this._tileGrid; + if (!grid?.open || grid.zoomedId || cells.length !== grid.cells.length) return false; + const tiles = cells.filter(Boolean); + if (tiles.length !== grid.tiles.size || new Set(tiles).size !== tiles.length) return false; + if (tiles.some((id) => !grid.tiles.has(id))) return false; + if (cells.every((id, k) => (id || null) === grid.cells[k])) return true; + // A divider drag in progress measured the tiles at their old places. + this._tileDividerDragTeardown?.(); + const cell = (k) => `${grid.colFr[k % grid.cols]}x${grid.rowFr[Math.floor(k / grid.cols)]}`; + const before = new Map(); + grid.cells.forEach((id, k) => id && before.set(id, cell(k))); + grid.cells = cells.map((id) => id || null); + this._applyTileLayout(); + // Synchronous: the fit's measurement forces the new placement's layout. + grid.cells.forEach((id, k) => { + if (id && before.get(id) !== cell(k)) grid.tiles.get(id).tile.fit(); + }); + return true; + }, + + /** Two tiles trade cells (_reorderTiles). */ + _swapTiles(a, b) { + const cells = this._tileGrid.cells.slice(); + const i = cells.indexOf(a); + const j = cells.indexOf(b); + if (i === -1 || j === -1) return false; + cells[i] = b; + cells[j] = a; + return this._reorderTiles(cells); + }, + + /** + * A tile moves into empty cell `k`, leaving its own cell empty: nothing else + * moves (_reorderTiles). False when `k` is not an empty cell, or moving is off. + */ + _moveTileToCell(sessionId, k) { + const cells = this._tileGrid.cells.slice(); + const from = cells.indexOf(sessionId); + if (from === -1 || !Number.isInteger(k) || cells[k] !== null) return false; + cells[from] = null; + cells[k] = sessionId; + return this._reorderTiles(cells); + }, + + /** + * Move Tile Left/Right/Up/Down: the focused tile goes to the cell next to it + * in that direction (tileCellInDirection, never jumping a cell): into it + * when it is empty, trading places when a tile is there. Focus stays on the + * moved tile. Nothing while a tile is zoomed, or at an edge. + */ + moveTileInDirection(direction) { + const grid = this._tileGrid; + if (!grid?.open || grid.zoomedId || !grid.focusedId) return; + const from = grid.cells.indexOf(grid.focusedId); + const to = window.CodemanTileGrid.tileCellInDirection(from, direction, grid.cols, grid.cells.length); + if (to === -1) return; + if (grid.cells[to]) this._swapTiles(grid.focusedId, grid.cells[to]); + else this._moveTileToCell(grid.focusedId, to); + }, + + /** + * A tab dropped on a tile, or a tile dragged there by its header: a session + * not yet tiled REPLACES that tile (same place; the replaced session keeps + * running); one already tiled swaps places with it (_swapTiles, refused while + * a tile is zoomed). Either way the dropped session takes focus (a human + * selection). + */ + dropSessionOnTile(draggedId, targetId) { + const grid = this._tileGrid; + if (!grid?.open || draggedId === targetId || !grid.tiles.has(targetId)) return; + if (!this.sessions.has(draggedId) || this.detachedSessions?.has(draggedId)) return; + if (grid.tiles.has(draggedId)) { + if (!this._swapTiles(draggedId, targetId)) return; + } else { + this._tileDividerDragTeardown?.(); + if (!this._mountTile(draggedId)) return; + // It takes the replaced tile's cell. + grid.cells[grid.cells.indexOf(targetId)] = draggedId; + const old = grid.tiles.get(targetId); + this._destroyTerminalTile(old.tile); + old.el.remove(); + grid.tiles.delete(targetId); + if (grid.zoomedId === targetId) grid.zoomedId = grid.autoZoom ? draggedId : null; + if (grid.focusedId === targetId) grid.focusedId = null; + this._applyTileLayout(); + this._connectTile(draggedId); + this._scheduleTileGridRefit(); + this.renderSessionTabs?.(); + } + this.selectSession(draggedId); + }, + + /** + * Something dropped on empty cell `cell`: a tab of a session not tiled yet + * joins the grid in that cell; a tiled session (its tab, or the tile dragged + * by its header) moves into it, leaving its own cell empty + * (_moveTileToCell, refused while a tile is zoomed). Either way the dropped + * session takes focus (a human selection). + */ + dropSessionOnSlot(draggedId, cell) { + const grid = this._tileGrid; + if (!grid?.open || !this.sessions.has(draggedId) || this.detachedSessions?.has(draggedId)) return; + if (grid.tiles.has(draggedId)) { + if (!this._moveTileToCell(draggedId, cell)) return; + } else if (!this.addTile(draggedId, { cell })) { + return; + } + this.selectSession(draggedId); + }, + + /** + * Ctrl/Cmd+click on a tab: that session joins the grid and takes focus (a + * human selection: the user clicked its tab). With the grid closed it opens + * what the Tiles toggle would, with this session among the tiles and + * focused: the remembered count in total (owner answer to decision 10's + * questions), never one more. Returns false + * when the grid cannot open here (narrow or solo window), so the click is an + * ordinary one. + */ + addSessionToTiles(sessionId) { + if (!this.canOpenTileGrid() || !this.sessions.has(sessionId) || this.detachedSessions?.has(sessionId)) { + return false; + } + const limit = this._tileGridLimit(); + const capacity = limit.capacity; + const grid = this._tileGrid; + if (grid?.open) { + if (!grid.tiles.has(sessionId)) { + if (grid.ids.length >= capacity) { + this.showToast?.(limit.full, 'info'); + return true; + } + this.addTile(sessionId); + } + this.selectSession(sessionId); + return true; + } + const n = Math.max(1, Math.min(this._tileGridCount(), capacity)); + const base = this._tileGridOpenSet()?.ids || []; + const ids = [...base.filter((id) => id !== sessionId).slice(0, n - 1), sessionId]; + this.openTileGrid(ids, { focusedId: sessionId, auto: false }); + return true; + }, + + /** + * "Open group as tiles" (the tab-group menu of the grouped rail): the + * group's live sessions, as many as the window fits, become the grid, + * replacing whatever it showed. Opening the grid is the app's choice of + * focus, so no idle alert is spent. + */ + openGroupAsTiles(groupId) { + const group = (this.tabLayout?.groups || []).find((g) => g.id === groupId); + if (!group || !this.canOpenTileGrid()) return false; + const capacity = this._tileGridLimit().capacity; + const ids = (group.refs || []) + .filter((ref) => ref.kind === 'session') + .map((ref) => ref.id) + .filter((id) => this.sessions.has(id) && !this.detachedSessions?.has(id)) + .slice(0, capacity); + if (ids.length === 0) { + this.showToast?.('This group has no session to show as tiles', 'info'); + return false; + } + return this._replaceTileGrid(ids); + }, + + /** + * Opens the grid on `ids` in place of whatever it shows ("Open group as + * tiles"): the session in focus keeps focus when `ids` holds + * it, otherwise the first one takes it. Chosen BEFORE an open grid closes, + * because the close drops activeSessionId: as in selectSession's tile + * branch, the parked terminal still holds what it showed before the grid, + * and re-parking must not snapshot it. + * + * @returns {boolean} whether the grid is open afterwards + */ + _replaceTileGrid(ids) { + const focus = ids.includes(this.activeSessionId) ? this.activeSessionId : ids[0]; + if (this._tilesOwnTerminal()) { + this.closeTileGrid({ keepStored: false, reselect: false }); + this.activeSessionId = null; + } + return this.openTileGrid(ids, { focusedId: focus }); + }, + + /** A grid tile's TerminalTile: the grid's one load queue, the tile scrollback, font and bounded load. */ + _newTerminalTile(sessionId, body) { + const session = this.sessions.get(sessionId); + const tile = new window.TerminalTile(sessionId, body, { + mode: session?.mode, + fontSettings: this.loadAppSettingsFromStorage?.() || {}, + detachedSessions: this.detachedSessions, + scheduleLoad: (t, kind, run) => this._tileLoadQueue().schedule(t, kind, run), + scrollback: window.CodemanTileGrid.TILE_SCROLLBACK, + fontSize: this._tileGridFontSize(), + boundedLoad: true, + onExit: (code) => this._onTileExit(sessionId, tile, code), + }); + return tile; + }, + + /** + * A grid tile's TerminalTile goes for good: its loads still waiting in the + * grid's queue are dropped first (resolved, never run, its loading state + * cleared), then the tile itself (socket, xterm, listeners). Its element is + * the caller's. + */ + _destroyTerminalTile(tile) { + this._tileGrid.queue?.drop(tile); + tile.destroy(); + }, + + /** + * Replaces a tile's TerminalTile with a fresh one in the same place (after + * Attach: a tile whose socket stopped for good cannot reconnect, and a fresh + * one loads the new pane from scratch). Keeps the keyboard if it had it. + */ + _remountTile(sessionId) { + const entry = this._tileGrid?.open ? this._tileGrid.tiles.get(sessionId) : null; + if (!entry) return; + const hadKeyboard = this._focusedTile === entry.tile; + this._destroyTerminalTile(entry.tile); + entry.tile = this._newTerminalTile(sessionId, entry.body); + entry.connected = false; + this._connectTile(sessionId); + if (hadKeyboard) this._noteFocusedTile(entry.tile); + }, + + /** + * What the tile's body should say instead of a terminal, or null for none: a + * session with no PTY attached (pid null) or a socket the server closed + * because the session exited (4009), both of which Attach can start again; + * or an agent that exited in a live pane (paneExit), which it cannot: the + * attach and shell routes refuse while the pane's tmux client still runs + * ("already has a running process"), and the single view has no restart for + * it either, so the tile says so and points at Close session instead. Attach + * was just pressed: nothing, while the server catches up. + * + * @returns {{text: string, attachable: boolean}|null} + */ + _tileAttachReason(sessionId, tile) { + const session = this.sessions.get(sessionId); + if (!session) return null; + const pending = this._tileAttachPending?.get(sessionId); + if (pending && Date.now() - pending < 15000) return null; + const exited = typeof paneExitLabel === 'function' ? paneExitLabel(session.paneExit) : ''; + if (exited) return { text: `The agent ${exited}`, attachable: false }; + if (session.pid === null) return { text: 'Not attached', attachable: true }; + if (tile?._stoppedCode === 4009) return { text: 'The session ended', attachable: true }; + return null; + }, + + /** + * The Attach overlay over a tile's body (absolute, so the body and its xterm + * keep their size): why there is no terminal, and an Attach button. + */ + _renderTileOverlay(sessionId) { + const entry = this._tileGrid?.tiles.get(sessionId); + if (!entry?.body) return; + const session = this.sessions.get(sessionId); + if (session && session.pid !== null && !session.paneExit) this._tileAttachPending?.delete(sessionId); + const reason = this._tileAttachReason(sessionId, entry.tile); + const busy = !!this._tileAttachInFlight?.has(sessionId); + if (!reason && !busy) { + if (entry.overlay) entry.overlay.hidden = true; + return; + } + if (!entry.overlay) { + const overlay = document.createElement('div'); + overlay.className = 'tile-attach'; + const text = document.createElement('span'); + text.className = 'tile-attach-text'; + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'tile-attach-btn'; + btn.textContent = 'Attach'; + btn.addEventListener('click', (e) => { + e.stopPropagation(); + void this.attachTileSession(sessionId); + }); + const hint = document.createElement('span'); + hint.className = 'tile-attach-hint'; + hint.textContent = 'It cannot be restarted in place: close it from \u22EF (Close session).'; + overlay.append(text, btn, hint); + entry.body.appendChild(overlay); + entry.overlay = overlay; + entry.overlayText = text; + entry.overlayBtn = btn; + entry.overlayHint = hint; + } + entry.overlay.hidden = false; + const text = busy ? 'Attaching\u2026' : reason.text; + // Compared with the last English text set, never the DOM: with the zh-CN + // translator on, the DOM holds the translation and would never match, so + // every refresh would rewrite English for it to translate again. + if (entry.overlayLabel !== text) { + entry.overlayLabel = text; + entry.overlayText.textContent = text; + } + const attachable = busy || reason.attachable; + entry.overlayBtn.hidden = !attachable; + entry.overlayHint.hidden = attachable; + entry.overlayBtn.disabled = busy; + }, + + /** + * Attach: starts the session's CLI in its pane, exactly as the single view's + * automatic re-attach does: `POST /interactive` (or `/shell` for a shell) + * with NO body, at most one in flight per session (the route has no guard of + * its own). A session whose PTY-exit breaker tripped goes through the same + * confirm the single view asks before `clearBreaker: true`; nothing automatic + * ever sends that. On success the tile is remounted onto the new pane. + */ + async attachTileSession(sessionId) { + const session = this.sessions.get(sessionId); + if (!session) return false; + // An agent that exited in a live pane cannot be started again in place. + if (this._tileAttachReason(sessionId, this._tileFor(sessionId))?.attachable === false) return false; + this._tileAttachInFlight ||= new Set(); + if (this._tileAttachInFlight.has(sessionId)) return false; + let url = `/api/sessions/${sessionId}/${session.mode === 'shell' ? 'shell' : 'interactive'}`; + let init = { method: 'POST' }; + if (session.respawnBlocked) { + const label = session.name || 'Session'; + if (!window.confirm(`${label} was stopped after crashing repeatedly. Restart it?`)) return false; + url = `/api/sessions/${sessionId}/interactive`; + init = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ clearBreaker: true }), + }; + } + this._tileAttachInFlight.add(sessionId); + this._renderTileOverlay(sessionId); + let ok = false; + try { + const res = await fetch(url, init); + // The routes report a refusal in the envelope of a 200. + const body = await res?.json?.().catch(() => null); + ok = !!res?.ok && body?.success !== false; + } catch { + ok = false; + } finally { + this._tileAttachInFlight.delete(sessionId); + } + if (ok) { + if (init.body) session.respawnBlocked = false; + session.status = 'busy'; + (this._tileAttachPending ||= new Map()).set(sessionId, Date.now()); + this._remountTile(sessionId); + } else { + this.showToast?.('Could not attach the session', 'error'); + } + this._renderTileOverlay(sessionId); + return ok; + }, + + /** + * `● [logo] name · model ..... ⋯ ⤢ ×`: the status dot (the six-state + * classifier the tab rows and both home screens share), the harness logo, the + * session name (double-click renames), the model it runs when known, the + * session menu (the tab rail's own), zoom and remove-tile. Its + * buttons stop pointerdown, so acting on a tile that is not focused does not + * also focus it (and spend its idle alert). The rest of it is the handle that + * moves the tile (_installTileMoveDrag). + */ + _buildTileHeader(sessionId) { + const el = document.createElement('div'); + el.className = 'tile-header'; + const dot = document.createElement('span'); + dot.className = 'tile-dot home-sessions-dot home-sessions-dot--idle'; + dot.setAttribute('aria-hidden', 'true'); + // The harness's logo: PR #532's `run-mode-dot ` slot, so the logos, + // the skins and the plain dot for an id without one stay in styles.css. Its + // tooltip and accessible name carry the harness and the model in full + // (_paintSessionHarness). + const harness = document.createElement('span'); + harness.className = 'tile-harness run-mode-dot'; + harness.setAttribute('role', 'img'); + const title = document.createElement('span'); + title.className = 'tile-title'; + const name = document.createElement('span'); + name.className = 'tile-name'; + // A session literally named like a UI string ("Sessions") must not be translated. + name.setAttribute('data-i18n-skip', ''); + name.addEventListener('dblclick', (e) => { + e.stopPropagation(); + this.startTileRename(sessionId); + }); + // The model the session runs, when the server knows it: the name itself is + // never translated (data-i18n-skip on the inner span), the tooltip on the + // outer one may be. Hidden from screen readers: the logo's accessible name + // already says it. + const model = document.createElement('span'); + model.className = 'tile-model'; + model.setAttribute('aria-hidden', 'true'); + model.hidden = true; + const modelName = document.createElement('span'); + modelName.setAttribute('data-i18n-skip', ''); + model.appendChild(modelName); + title.append(name, model); + const actions = document.createElement('span'); + actions.className = 'tile-actions'; + const button = (cls, label, glyph, onClick) => { + const b = document.createElement('button'); + b.type = 'button'; + b.className = `tile-btn ${cls}`; + b.title = label; + b.setAttribute('aria-label', label); + b.textContent = glyph; + b.addEventListener('pointerdown', (e) => e.stopPropagation()); + b.addEventListener('click', (e) => { + e.stopPropagation(); + onClick(e); + }); + return b; + }; + const zoomBtn = button('tile-zoom', 'Zoom this tile', '\u2922', () => this.zoomTile(sessionId)); + zoomBtn.setAttribute('aria-pressed', 'false'); + actions.append( + button('tile-menu', 'Session actions', '\u22EF', (e) => this.openTabRailActionMenu?.(e, sessionId)), + zoomBtn, + // (No + here, owner decision 9: tiles are added from the Tiles button + // and its count menu, Ctrl/Cmd+click, a dragged tab, a tab group or Run.) + // Removes the tile ONLY: the session keeps running. Killing it stays + // behind the menu's Close session and its confirm. + button('tile-remove', 'Remove tile (the session keeps running)', '\u00D7', () => this.removeTile(sessionId)) + ); + el.append(dot, harness, title, actions); + this._installTileMoveDrag(sessionId, el, actions); + return { el, dot, harness, name, model, modelName, zoomBtn }; + }, + + /** + * The header moves its tile: dragged onto another tile the two trade places, + * onto an empty cell it moves there and leaves its own cell empty + * (dropSessionOnTile / dropSessionOnSlot, the path a dragged tab takes, + * through the same capture-phase drop targets, _acceptTabDrops). A native drag, so Escape and a drop anywhere else are the + * browser's own cancel: nothing moves, and dragend clears what the drag + * painted. The drag carries a type of its own and never text, so no text + * field or terminal, in this page or another application, can take it as + * typing; and it is not `draggedTabId`, so the tab strip ignores it. + * + * The handle is the header's free area: a press on a button or the rename + * input starts no drag. dragstart's target is the header whatever was + * pressed, so where the press landed is noted in the capture phase, ahead of + * the buttons' own stopPropagation. `draggable` is off while moving is + * (_paintTileHandle: a zoomed grid, a single tile, a rename in progress). + */ + _installTileMoveDrag(sessionId, header, actions) { + let pressedOnControl = false; + header.addEventListener( + 'pointerdown', + (e) => { + const target = e.target; + pressedOnControl = !!actions.contains?.(target) || /^(INPUT|BUTTON)$/i.test(target?.tagName || ''); + }, + true + ); + header.addEventListener('dragstart', (e) => { + const entry = this._tileGrid?.open ? this._tileGrid.tiles.get(sessionId) : null; + if (!entry || pressedOnControl || entry.renaming || !this._tilesMovable()) { + e.preventDefault?.(); + return; + } + this._draggedTileId = sessionId; + entry.el.classList.add('tile--dragging'); + if (e.dataTransfer) { + e.dataTransfer.effectAllowed = 'move'; + // Firefox starts no drag without data. + e.dataTransfer.setData('application/x-codeman-tile', sessionId); + } + }); + header.addEventListener('dragend', () => this._endTileMoveDrag()); + }, + + /** + * A header drag is over (dropped, cancelled with Escape, dropped outside), + * or its tile or the grid went mid-drag: forget it and clear what it + * painted. The drop targets' highlight too: a cancelled drag does not + * reliably send dragleave. + */ + _endTileMoveDrag() { + this._draggedTileId = null; + const grid = this._tileGrid; + for (const { el } of grid?.tiles.values() || []) el.classList.remove('tile--dragging', 'tile--drop-target'); + for (const slot of grid?.slots || []) slot.classList.remove('tile--drop-target'); + }, + + /** + * The header as a handle: `draggable` while the tile can move (not while a + * tile is zoomed, alone, or being renamed), and its tooltip, the state and + * how long ("working 3m") plus, while it can move, that it drags. Diffs on + * the last English text, never the DOM (translated in zh-CN; see + * _renderTileOverlay). + */ + _paintTileHandle(entry) { + const movable = this._tilesMovable(); + const title = [entry.stateLabel, movable ? 'Drag to move the tile' : ''].filter(Boolean).join('\n'); + if (entry.headerLabel !== title) { + entry.headerLabel = title; + entry.header.title = title; + } + const draggable = movable && !entry.renaming ? 'true' : 'false'; + if (entry.header.getAttribute('draggable') !== draggable) entry.header.setAttribute('draggable', draggable); + }, + + /** + * Refreshes one tile's header from the session: dot state, harness logo, + * name, model, the hover label ("working 3m") and the `needs` border. Diffs on existing nodes only, + * and cheap: it runs on every tab render (every status change). + */ + _renderTileHeader(sessionId) { + const entry = this._tileGrid?.tiles.get(sessionId); + const session = this.sessions.get(sessionId); + if (!entry?.header || !session) return; + const row = this._sidebarRichRow?.(sessionId, session) || null; + const state = row?.state || 'idle'; + const dotClass = `tile-dot home-sessions-dot home-sessions-dot--${row?.exited ? 'done' : state}`; + if (entry.dot.className !== dotClass) entry.dot.className = dotClass; + const since = row?.since?.at ? this._mobileOverviewStampText?.(row.since.at, 'for') : ''; + entry.stateLabel = row ? [row.pill, since].filter(Boolean).join(' ') : ''; + this._paintTileHandle(entry); + // The input of a rename in progress has taken the name's place in the + // header, so updating the detached name never touches what is being typed. + // A rename still in flight shows as already done, as on the tab. + const name = + this._inlineRenamePending?.get(sessionId) || this.getSessionName?.(session) || session.name || 'Session'; + if (entry.name.textContent !== name) entry.name.textContent = name; + this._paintSessionHarness(entry, session, 'tile-harness'); + // A permission prompt is visible across the room. + entry.el.classList.toggle('tile--needs', state === 'needs'); + this._renderTileOverlay(sessionId); + }, + + /** Every tile's header (after a tab render, i.e. any session change). */ + _renderTileChrome() { + const grid = this._tileGrid; + if (!grid?.open) return; + for (const [id, entry] of grid.tiles) { + this._renderTileHeader(id); + // A pane that started after the tile connected (a session Run made + // while the grid is open, an Attach from elsewhere) was spawned at the + // server's default size: the tile's own resize went out before there + // was a PTY to take it, and Run's resize measures the parked main + // terminal (nothing). Keyed on the sessions map, so a handleInit after + // an SSE drop is seen too; a render skipped during an inline tab rename + // is caught up by the rename's own render. + const pid = this.sessions.get(id)?.pid ?? null; + if (pid !== null && pid !== entry.pid) entry.tile.paneStarted?.(); + entry.pid = pid; + } + }, + + /** + * Double-click on a tile's name: an input in its place, Enter or leaving it + * renames through the tab rename's own write queue, Escape cancels. The + * header refresh leaves the name alone meanwhile. + */ + startTileRename(sessionId) { + const entry = this._tileGrid?.tiles.get(sessionId); + const session = this.sessions.get(sessionId); + if (!entry || !session || entry.renaming) return; + entry.renaming = true; + // No drag from the header while its input is in it (_paintTileHandle). + this._paintTileHandle(entry); + const input = document.createElement('input'); + input.type = 'text'; + input.className = 'tile-rename-input'; + input.setAttribute('aria-label', 'Session name'); + // A rename still in flight is the user's last word. + input.value = this._inlineRenamePending?.get(sessionId) ?? session.name ?? ''; + let settled = false; + const finish = (commit) => { + if (settled) return; + settled = true; + input.replaceWith(entry.name); + entry.renaming = false; + const value = input.value.trim(); + if (commit && value && value !== session.name && this.sessions.has(sessionId)) { + entry.name.textContent = value; + void this._queueInlineSessionName?.(sessionId, value); + } + this._renderTileHeader(sessionId); + }; + input.addEventListener('pointerdown', (e) => e.stopPropagation()); + // A click in the input is not the header's click, which would focus the + // terminal away from it. + input.addEventListener('click', (e) => e.stopPropagation()); + input.addEventListener('keydown', (e) => { + // Enter and Escape during an IME composition belong to the IME. + if (e.isComposing || e.keyCode === 229) return; + if (e.key === 'Enter') { + e.preventDefault(); + finish(true); + } else if (e.key === 'Escape') { + e.preventDefault(); + finish(false); + } + }); + input.addEventListener('blur', () => finish(true)); + entry.name.replaceWith(input); + input.focus(); + input.select?.(); + }, + + /** + * Starts a tile's terminal and socket (TerminalTile.connect builds the xterm + * synchronously, then loads through the grid's queue). Once per tile. A + * focus that selected this tile before its terminal existed lands now. + */ + _connectTile(sessionId) { + const grid = this._tileGrid; + const entry = grid?.tiles.get(sessionId); + if (!entry || entry.connected) return; + entry.connected = true; + entry.tile.connect().catch(() => { + /* Best-effort, as the split's Pane B: live output arrives once the socket opens. */ + }); + if (grid.focusOnConnect === sessionId) { + grid.focusOnConnect = null; + entry.tile.terminal?.focus(); + } + }, + + /** + * Opening the grid: the tiles' terminals are built one per animation frame, + * in `order` (the focused tile first), instead of all of them inside the + * click. Building six xterms took about 100 ms of the click's 140 ms before + * the first frame; paced, the click paints its empty frames in about 20 ms + * and the entrance plays while the terminals are built. Nothing waits for + * it: the load queue serves one capture at a time anyway, so only the + * focused tile's connect is on its critical path, one frame later. Each + * tile still fits once, at its final size (laid out before any connect), + * and sends one PTY resize. A tile removed, replaced or already connected + * meanwhile is skipped; a grid closed (or opened again) meanwhile stops it. + */ + _connectTilesPaced(order) { + const grid = this._tileGrid; + const run = (grid.paceRun = (grid.paceRun || 0) + 1); + const step = (k) => { + if (!grid.open || grid.paceRun !== run || k >= order.length) return; + this._connectTile(order[k]); + requestAnimationFrame(() => step(k + 1)); + }; + requestAnimationFrame(() => step(0)); + }, + + /** + * A tile's socket stopped for good. 4009 (the session exited) keeps the tile + * with its "session ended" marker; 4003 (refused), 4004 (session gone) and + * 4010 (another socket took over) remove it. + */ + _onTileExit(sessionId, tile, code) { + if (this._tileGrid?.tiles.get(sessionId)?.tile !== tile) return; + // The session exited: the tile stays, with the Attach overlay over it. + if (code === 4009) { + this._renderTileOverlay(sessionId); + return; + } + this.removeTile(sessionId); + }, + + /** + * Columns x rows for the current tile count, applied to the grid section. + * The shape comes from the count alone; within it each tile sits in its + * cell (grid.cells) and any cell may be empty. When the shape changes, the + * cells follow fitTileCells (each tile keeps its row and column if all fit, + * else the tiles pack in reading order). + */ + _applyTileLayout() { + const grid = this._tileGrid; + const section = this._tileGridSection(); + const { cols, rows, fits } = this._tileShapeFor(grid.ids.length); + grid.cells = window.CodemanTileGrid.fitTileCells(grid.cells, grid.cols, cols, rows); + if (grid.colFr.length !== cols) grid.colFr = new Array(cols).fill(1); + if (grid.rowFr.length !== rows) grid.rowFr = new Array(rows).fill(1); + grid.cols = cols; + grid.rows = rows; + // A window too small for the tiles' minimum size shows the focused tile + // alone, with a hint; once it fits again the grid comes back. A zoom the + // user chose is theirs: it stays until they lift it. + if (!fits && !grid.zoomedId && grid.focusedId) { + grid.zoomedId = grid.focusedId; + grid.autoZoom = true; + this.showToast?.(`The window is too small for ${grid.ids.length} tiles: showing the focused one`, 'info'); + } else if (fits && grid.autoZoom) { + grid.zoomedId = null; + grid.autoZoom = false; + } + const zoomed = grid.zoomedId && grid.tiles.has(grid.zoomedId) ? grid.zoomedId : null; + section.classList.toggle('tile-grid--zoomed', !!zoomed); + this._syncTileZoom(zoomed); + // Moving is off while a tile is zoomed or alone: the headers say so. + for (const entry of grid.tiles.values()) this._paintTileHandle(entry); + // Zoomed: one cell; the other tiles stay connected but hidden (CSS), so + // they measure nothing and send no resize. Otherwise every tile is placed + // explicitly in its cell, with a divider track between columns and between + // rows, and every empty cell holds a drop slot. + section.style.gridTemplateColumns = zoomed ? 'minmax(0, 1fr)' : tileGridTracks(grid.colFr); + section.style.gridTemplateRows = zoomed ? 'minmax(0, 1fr)' : tileGridTracks(grid.rowFr); + const holes = []; + grid.cells.forEach((id, k) => { + if (!id) { + holes.push(k); + return; + } + const el = grid.tiles.get(id)?.el; + if (!el) return; + el.style.gridColumn = id === zoomed ? '1' : String(2 * (k % cols) + 1); + el.style.gridRow = id === zoomed ? '1' : String(2 * Math.floor(k / cols) + 1); + }); + this._syncTileDividers(zoomed ? 0 : cols, zoomed ? 0 : rows); + this._syncTileSlots(zoomed ? [] : holes, cols); + this._persistTileGrid(); + }, + + // Each tile's zoom state: the zoomed one is shown alone (CSS), and every ⤢ + // button says what pressing it does next. + _syncTileZoom(zoomed) { + for (const [id, entry] of this._tileGrid.tiles) { + const on = id === zoomed; + entry.el.classList.toggle('tile--zoomed', on); + const zoomBtn = entry.zoomBtn; + if (!zoomBtn) continue; + zoomBtn.setAttribute('aria-pressed', on ? 'true' : 'false'); + const label = on ? 'Restore the grid' : 'Zoom this tile'; + // Against the last English label, never the DOM (translated in zh-CN). + if (entry.zoomLabel !== label) { + entry.zoomLabel = label; + zoomBtn.title = label; + zoomBtn.setAttribute('aria-label', label); + } + } + }, + + // The empty cells of a layout that is not full (3 tiles in a 2x2, 5 in a + // 3x2), wherever they are: drop targets for a tab (it joins there) and for a + // tile (it moves there). Each slot knows its cell (`data-cell`). + _syncTileSlots(holes, cols) { + const grid = this._tileGrid; + grid.slots ||= []; + while (grid.slots.length > holes.length) grid.slots.pop().remove(); + while (grid.slots.length < holes.length) { + const slot = document.createElement('div'); + slot.className = 'tile-slot'; + slot.textContent = 'Drop a tab or a tile here'; + this._acceptTabDrops(slot, (draggedId) => this.dropSessionOnSlot(draggedId, Number(slot.dataset.cell))); + this._tileGridSection().appendChild(slot); + grid.slots.push(slot); + } + grid.slots.forEach((slot, i) => { + const k = holes[i]; + slot.dataset.cell = String(k); + slot.style.gridColumn = String(2 * (k % cols) + 1); + slot.style.gridRow = String(2 * Math.floor(k / cols) + 1); + }); + }, + + // One divider per gap between columns and between rows, created and dropped + // as the counts change (never rebuilt while they stay, so a drag in progress + // keeps its element). + _syncTileDividers(cols, rows) { + const grid = this._tileGrid; + const section = this._tileGridSection(); + const wanted = new Set(); + for (let i = 0; i < cols - 1; i++) wanted.add(`col-${i}`); + for (let i = 0; i < rows - 1; i++) wanted.add(`row-${i}`); + for (const [key, el] of grid.dividers) { + if (wanted.has(key)) continue; + if (this._tileDividerDrag?.key === key) this._tileDividerDragTeardown?.(); + el.remove(); + grid.dividers.delete(key); + } + for (const key of wanted) { + let el = grid.dividers.get(key); + const [axis, n] = key.split('-'); + const index = Number(n); + if (!el) { + el = document.createElement('div'); + el.className = `tile-divider tile-divider--${axis}`; + el.setAttribute('role', 'separator'); + el.setAttribute('aria-orientation', axis === 'col' ? 'vertical' : 'horizontal'); + el.setAttribute('aria-label', axis === 'col' ? 'Resize tile columns' : 'Resize tile rows'); + el.addEventListener('pointerdown', (e) => this._startTileDividerDrag(e, axis, index, el, key)); + section.appendChild(el); + grid.dividers.set(key, el); + } + el.style.gridColumn = axis === 'col' ? String(2 * index + 2) : '1 / -1'; + el.style.gridRow = axis === 'col' ? '1 / -1' : String(2 * index + 2); + } + }, + + /** + * Drags a column or row divider: the two tracks either side trade size, each + * kept at the minimum tile size (dragTrackFractions, constants.js). The + * affected tiles reflow locally once per animation frame; their PTYs hear + * ONE resize each, at pointer-up, never per move (each one is a tmux resize + * and a SIGWINCH). Pointer capture keeps the drag on the divider whatever is + * under the pointer; closing the grid or removing a tile mid-drag tears it + * down through _tileDividerDragTeardown. + */ + _startTileDividerDrag(e, axis, index, divider, key) { + if (e.button !== undefined && e.button !== 0) return; + const grid = this._tileGrid; + if (!grid?.open) return; + e.preventDefault?.(); + e.stopPropagation?.(); + this._tileDividerDragTeardown?.(); + const T = window.CodemanTileGrid; + const section = this._tileGridSection(); + const rect = section.getBoundingClientRect(); + const isCol = axis === 'col'; + const count = isCol ? grid.cols : grid.rows; + const total = (isCol ? rect.width : rect.height) - 2 * TILE_GRID_PADDING_PX - TILE_DIVIDER_PX * (count - 1); + const startFr = (isCol ? grid.colFr : grid.rowFr).slice(); + const start = isCol ? e.clientX : e.clientY; + const minPx = isCol ? T.TILE_MIN_W : T.TILE_MIN_H; + const affected = []; + grid.cells.forEach((id, k) => { + if (!id) return; + const track = isCol ? k % grid.cols : Math.floor(k / grid.cols); + if (track === index || track === index + 1) affected.push(grid.tiles.get(id).tile); + }); + let raf = null; + let pending = start; + let capturedPointerId = null; + const apply = (pos) => { + if (!grid.open) return; + const fr = T.dragTrackFractions(startFr, index, pos - start, total, minPx); + if (isCol) grid.colFr = fr; + else grid.rowFr = fr; + section.style[isCol ? 'gridTemplateColumns' : 'gridTemplateRows'] = tileGridTracks(fr); + for (const tile of affected) tile.localFit(); + }; + const onMove = (ev) => { + pending = isCol ? ev.clientX : ev.clientY; + if (raf !== null) return; + raf = requestAnimationFrame(() => { + raf = null; + apply(pending); + }); + }; + const endDrag = () => { + divider.classList.remove('dragging'); + document.body.classList.remove('tile-grid-resizing', `tile-grid-resizing--${axis}`); + if (capturedPointerId !== null) { + try { + divider.releasePointerCapture?.(capturedPointerId); + } catch { + /* Already released. */ + } + capturedPointerId = null; + } + divider.removeEventListener('pointermove', onMove); + divider.removeEventListener('pointerup', onUp); + divider.removeEventListener('pointercancel', onUp); + if (raf !== null) { + cancelAnimationFrame(raf); + raf = null; + } + if (this._tileDividerDragTeardown === endDrag) { + this._tileDividerDragTeardown = null; + this._tileDividerDrag = null; + } + }; + const onUp = () => { + // The last queued frame carries the final pointer position. + const queued = raf !== null; + endDrag(); + if (queued) apply(pending); + for (const tile of affected) { + if (!tile._destroyed) tile.fit(); + } + this._persistTileGrid(); + }; + divider.classList.add('dragging'); + document.body.classList.add('tile-grid-resizing', `tile-grid-resizing--${axis}`); + try { + divider.setPointerCapture?.(e.pointerId); + capturedPointerId = e.pointerId ?? null; + } catch { + /* The drag still works through the listeners below. */ + } + divider.addEventListener('pointermove', onMove); + divider.addEventListener('pointerup', onUp); + divider.addEventListener('pointercancel', onUp); + this._tileDividerDragTeardown = endDrag; + this._tileDividerDrag = { key }; + }, + + /** + * Zooms a tile to fill the grid, like tmux zoom, or restores the grid when it + * is the one zoomed. A tile that is not focused is focused first (a human + * selection: the user asked to look at it). Every tile is refitted after, the + * shown ones to their new size and the zoomed one to the whole grid. + */ + zoomTile(sessionId) { + const grid = this._tileGrid; + if (!grid?.open || !grid.tiles.has(sessionId)) return; + if (grid.zoomedId === sessionId) { + grid.zoomedId = null; + grid.autoZoom = false; + } else { + if (grid.focusedId !== sessionId) this.selectSession(sessionId); + grid.zoomedId = sessionId; + grid.autoZoom = false; + } + this._applyTileLayout(); + this._scheduleTileGridRefit(); + }, + + // Refits every tile once the grid area has settled: one xterm resize and one + // PTY resize together per tile (#464), on the trailing edge. + _scheduleTileGridRefit() { + const grid = this._tileGrid; + if (!grid?.open) return; + clearTimeout(grid.refitTimer); + grid.refitTimer = setTimeout(() => { + grid.refitTimer = null; + if (!grid.open) return; + // The 3-tile layout depends on the width (3x1 or 2x2). + this._applyTileLayout(); + for (const { tile } of grid.tiles.values()) tile.fit(); + }, TILE_GRID_REFIT_MS); + }, + + // Narrowing the window past the desktop gate returns to the single view of the + // focused session; the grid is remembered. + _installTileGridWidthGate() { + if (this._tileGridWidthGateInstalled || !window.matchMedia) return; + this._tileGridWidthGateInstalled = true; + const mq = window.matchMedia(`(min-width: ${SPLIT_PANE_MIN_WIDTH}px)`); + mq.addEventListener('change', (e) => { + if (!e.matches && this._tileGrid?.open) this.closeTileGrid({ keepStored: true, reselect: true }); + }); + }, + + _paintTileFocus() { + const grid = this._tileGrid; + for (const [id, { el }] of grid?.tiles || []) el.classList.toggle('focused', id === grid.focusedId); + }, + + /** + * Focuses a tiled session: the tile branch of selectSession. Moving focus is + * an `activeSessionId` change plus `xterm.focus()`: no fetch, no replay. It + * runs the panel refresh a normal switch runs and skips everything bound to + * the main terminal (cleanup, replay, resize, its socket, local echo). Only a + * USER-initiated selection (`auto` not true) acknowledges the idle alert. + * + * @param {string} sessionId + * @param {{auto?: boolean, focus?: boolean}} [options] - `focus: false` leaves + * DOM focus where it is (an app-driven reconcile must not steal it) + */ + _selectTiledSession(sessionId, options = {}) { + const grid = this._tileGrid; + const entry = grid?.open ? grid.tiles.get(sessionId) : null; + if (!entry) return; + const userInitiated = options.auto !== true; + // Aborts any in-flight normal select at its next _isStaleSelect check. + const selectGen = ++this._selectGeneration; + this._hideWebviewLayer?.(); + this.activeSessionId = sessionId; + grid.focusedId = sessionId; + // Moving focus off a zoomed tile restores the grid, as selecting another + // pane does in tmux. An automatic zoom (the window cannot fit the tiles) + // follows focus instead: there is no grid to restore. + if (grid.zoomedId && grid.zoomedId !== sessionId) { + grid.zoomedId = grid.autoZoom ? sessionId : null; + this._applyTileLayout(); + this._scheduleTileGridRefit(); + } + this._activateFileBrowserSession?.(sessionId); + try { + localStorage.setItem('codeman-active-session', sessionId); + } catch { + /* Per-device convenience only. */ + } + // The SSE subscription follows the focused session as in the single view; + // its terminal frames are dropped by the parking guards. + this._updateSseSubscription?.(sessionId); + this.hideWelcome(); + if (userInitiated) this.markIdleAlertSeen(sessionId); + this._paintTileFocus(); + this._updateActiveTabImmediate?.(sessionId); + this.closeSessionSidebarOnHandheld?.(); + this.renderSessionTabs?.(); + const activeTab = document.querySelector(`.session-tab.active[data-id="${sessionId}"]`); + // Not while it still glows: on every skin but OG the glow is `animation: + // none`, so animationend never comes and each tile focus used to leave + // another listener behind on the tab (49 after 50 focus changes). + if (activeTab && !activeTab.classList.contains('tab-glow')) { + activeTab.classList.add('tab-glow'); + activeTab.addEventListener('animationend', () => activeTab.classList.remove('tab-glow'), { once: true }); + } + this.updateAttachmentHistoryBadge?.(); + if (this.attachmentHistoryDrawerOpen) this.loadAttachmentHistory?.(sessionId); + if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.refreshForActiveSession(); + this.refreshHostWakeBanner?.(sessionId); + this.currentSessionWorkingDir = this.sessions.get(sessionId)?.workingDir || null; + const idleCb = typeof requestIdleCallback === 'function' ? requestIdleCallback : (cb) => setTimeout(cb, 16); + idleCb(() => this._refreshSessionPanels(sessionId, selectGen)); + // The keyboard follows focus: shortcuts, voice and paste act on this tile. + // A tile whose terminal is not built yet (the grid just opened, paced) + // takes it as soon as it is (_connectTile). + this._noteFocusedTile(entry.tile); + grid.focusOnConnect = null; + if (options.focus !== false) { + if (entry.connected) entry.tile.terminal?.focus(); + else grid.focusOnConnect = sessionId; + } + this._persistTileGrid(); + }, + + // ── Persistence (codeman:tile-grid, per device, ids only) ──────────────── + + /** + * Writes the open grid: ids, focus, a zoom the user chose (an automatic one + * is worked out again from the window) and the divider fractions. Never + * content. `open: false` is the closed-but-remembered state. Never in a solo + * window; a storage failure only costs the convenience. + */ + _persistTileGrid({ open = true } = {}) { + const grid = this._tileGrid; + if (this.isSoloWindow || !grid || grid.ids.length === 0) return; + if (open && !grid.open) return; + const state = { + v: 1, + open, + // The cells, null for an empty one, so a hole comes back where it was + // (sanitizeTileGridState; a build before cells drops the nulls and reads + // the tiles packed, as it always did). + ids: grid.cells.slice(), + focused: grid.focusedId, + zoomed: grid.autoZoom ? null : grid.zoomedId, + colFr: grid.colFr.slice(), + rowFr: grid.rowFr.slice(), + }; + try { + localStorage.setItem(TILE_GRID_STORAGE_KEY, JSON.stringify(state)); + } catch { + /* Per-device convenience only. */ + } + }, + + _forgetStoredTileGrid() { + try { + localStorage.removeItem(TILE_GRID_STORAGE_KEY); + } catch { + /* Nothing stored. */ + } + }, + + /** The stored grid, sanitized against the sessions this page knows now, or null. */ + _readStoredTileGrid() { + if (this.isSoloWindow) return null; + let raw = null; + try { + raw = localStorage.getItem(TILE_GRID_STORAGE_KEY); + } catch { + return null; + } + if (!raw) return null; + return window.CodemanTileGrid.sanitizeTileGridState(raw, this.sessions, this.detachedSessions); + }, + + /** + * Opens a stored grid: its tiles and focus, then the fractions it had (only + * if they still match the layout) and a zoom the user chose. `auto`: the app + * is putting it back, so no idle alert is spent. `ids` is the set to open, + * the stored one by default (a reload); the Tiles button passes it trimmed + * or filled to the remembered count, a shape change the cell model's rule + * handles (reformTileCells). + */ + _openStoredTileGrid(stored, ids = stored.ids) { + const focus = stored.zoomed || stored.focused; + // The stored set (an open split closes without joining it, decision 8, + // case a), trimmed or filled to the count by the caller. + if (!this.openTileGrid(ids, { focusedId: focus, auto: true, mergeSplit: false })) return false; + const grid = this._tileGrid; + const T = window.CodemanTileGrid; + // openTileGrid packed the tiles from the first cell. The stored tiles go + // back to their cells (a session gone since leaves its cell empty): as + // they were when this is the stored set in the shape it was stored with, + // otherwise by the cell model's rule, the tiles the count adds filling the + // empty cells in reading order, holes first. + const storedCells = (stored.cells || []).map((id) => (id && grid.tiles.has(id) ? id : null)); + const kept = storedCells.filter(Boolean); + const sameSet = ids.length === stored.ids.length && ids.every((id) => stored.ids.includes(id)); + const cells = sameSet + ? storedCells + : T.reformTileCells( + storedCells, + T.tileCellCols(storedCells.length), + kept, + grid.ids.filter((id) => !kept.includes(id)), + grid.cols, + grid.rows + ); + if (cells.length === grid.cols * grid.rows && cells.filter(Boolean).length === grid.tiles.size) { + grid.cells = cells; + } + // openTileGrid laid the grid out with equal tracks. The stored ones go back + // on; _applyTileLayout drops them again if they do not match the column or + // row count (the window may have changed the layout since). + if (stored.colFr) grid.colFr = stored.colFr.slice(); + if (stored.rowFr) grid.rowFr = stored.rowFr.slice(); + if (stored.zoomed && grid.tiles.has(stored.zoomed)) { + grid.zoomedId = stored.zoomed; + grid.autoZoom = false; + } + this._applyTileLayout(); + this._scheduleTileGridRefit(); + return true; + }, + + /** + * Page load (handleInit, in place of selecting the session to restore): a + * grid stored OPEN on this device comes back, ids sanitized against the + * session list (deleted, detached and duplicate ids dropped). The main + * terminal then never loads on this page load, so no `full=1` capture is + * paid for a terminal about to be parked. Not in a solo window (nothing is + * read there), nor on a window too narrow for the grid (openTileGrid + * refuses; the stored grid waits for a wide one). + * + * @returns {boolean} whether the grid was restored + */ + _restoreTileGrid() { + if (this._tilesOwnTerminal()) return false; + const stored = this._readStoredTileGrid(); + if (!stored?.open || stored.ids.length === 0) return false; + return this._openStoredTileGrid(stored); + }, + + /** A followed `#session=` link took the screen on load: the stored grid stays remembered, closed. */ + _closeStoredTileGrid() { + const stored = this._readStoredTileGrid(); + if (!stored?.open) return; + // Stored as it was read, holes included (`ids` carries the cells). + const { cells, ...rest } = stored; + try { + localStorage.setItem(TILE_GRID_STORAGE_KEY, JSON.stringify({ ...rest, ids: cells, open: false })); + } catch { + /* Per-device convenience only. */ + } + }, + + /** Header connection state while tiles own the terminal: every live tile socket open, or not. */ + _tileGridSocketState() { + for (const { tile } of this._tileGrid?.tiles.values() || []) { + // A tile stopped for good (its session exited) has nothing to reconnect. + if (tile._stoppedCode !== null && tile._stoppedCode !== undefined) continue; + if (!tile._wsReady) return 'reconnecting'; + } + return 'connected'; + }, + + /** + * handleInit (page state reloaded, or SSE back after a server restart) with + * the grid open: tiles whose sessions are gone or popped out are removed, the + * rest are KEPT (never rebuilt) and told to reconnect now instead of waiting + * out their backoff, and focus stays on a live tile. + * + * @returns {boolean} whether the grid is still open (handleInit then skips + * restoring the main terminal) + */ + _reconcileTileGrid() { + const grid = this._tileGrid; + if (!grid?.open) return false; + for (const id of grid.ids.slice()) { + if (!this.sessions.has(id) || this.detachedSessions?.has(id)) this.removeTile(id, { refocus: false }); + } + if (!grid.open) return false; + // Only a focus that is gone moves: re-selecting the same tile would hide an + // active web tab on every SSE blip (_selectTiledSession hides the web layer), + // which the single view's reconnect never does. + if (!grid.has(grid.focusedId)) this._selectTiledSession(grid.ids[0], { auto: true }); + for (const { tile } of grid.tiles.values()) tile.reconnectNow(); + return true; + }, +}); + +// A tiled session deleted (here or elsewhere) loses its tile; if it held focus, +// the neighbouring tile takes it (`auto`: the app chose, so no idle alert is +// spent). Done BEFORE the original handler, so activeSessionId no longer names +// the deleted id and its welcome-screen handoff stays out of it. The last tile +// closes the grid without a reselect, and the original handler then shows the +// welcome screen as in the single view. A close started from this tab +// (closeSession, in _closingSessions) owns its own follow-up: only the tile goes. +const _tileGridOriginalOnSessionDeleted = CodemanApp.prototype._onSessionDeleted; +CodemanApp.prototype._onSessionDeleted = function (data) { + const grid = this._tileGrid; + if (grid?.has(data.id)) { + const wasFocused = grid.focusedId === data.id; + const neighbor = window.CodemanTileGrid.tileNeighbor(grid.ids, data.id); + this.removeTile(data.id, { refocus: false }); + if (wasFocused && grid.open && neighbor && !this._closingSessions?.has(data.id)) { + this._selectTiledSession(neighbor, { auto: true }); + } + } + return _tileGridOriginalOnSessionDeleted.call(this, data); +}; + +// Every tab render (any session change: status, hooks, name) refreshes the +// tile headers too, so a tile's dot, name and needs border follow the same +// state the tab shows. +const _tileGridOriginalRenderSessionTabsImmediate = CodemanApp.prototype._renderSessionTabsImmediate; +CodemanApp.prototype._renderSessionTabsImmediate = function (...args) { + const result = _tileGridOriginalRenderSessionTabsImmediate.apply(this, args); + this._renderTileChrome?.(); + return result; +}; diff --git a/src/web/routes/session-routes.ts b/src/web/routes/session-routes.ts index a21b19f4..1292d00e 100644 --- a/src/web/routes/session-routes.ts +++ b/src/web/routes/session-routes.ts @@ -775,6 +775,20 @@ export function resolveOmpConfigForCreate( return resolvedId ? { ...ompConfig, resumeSessionId: resolvedId } : ompConfig; } +/** + * The tmux history lines a full capture may read (`capture-pane -S -`): the + * optional `lines` query parameter, an integer of at least 1, never more than + * the configured history limit; absent or malformed, the limit itself, as + * before. A grid tile sends its own scrollback size: its xterm keeps no more + * than that, while a capture of the whole history (tens of thousands of lines, + * cut to `tail` only afterwards) is synchronous work on this event loop. + */ +function captureHistoryLines(raw: string | undefined, historyLimit: number): number { + if (typeof raw !== 'string' || !/^\d{1,9}$/.test(raw)) return historyLimit; + const lines = Number(raw); + return lines >= 1 ? Math.min(lines, historyLimit) : historyLimit; +} + /** * `RemoteHost` → the wake registry's host shape. They differ in one field name only * (`id` in host config vs `hostId` on a session's `remote`), but the rename is load- @@ -2986,7 +3000,7 @@ export function registerSessionRoutes( app.get('/api/sessions/:id/terminal', async (req, reply) => { const routeStartedAt = performance.now(); const { id } = req.params as { id: string }; - const query = req.query as { tail?: string; full?: string }; + const query = req.query as { tail?: string; full?: string; lines?: string }; const session = findSessionOrFail(ctx, id, req); // `full=1` is the EXPLICIT full-history signal (COD-47): capture the ENTIRE @@ -3010,8 +3024,14 @@ export function registerSessionRoutes( // single reason: `capturedGeometry` comes BACK on it, and the response has // to tell the client what size the frame it is about to render was built // for. See PaneCaptureOptions.capturedGeometry. + // `lines` bounds only the history a FULL capture reads; the visible-frame + // path reads no history and is untouched by it. const captureOpts: PaneCaptureOptions = isFullReload - ? { fullHistory: true, historyLimitLines: tmuxHistoryLimit, maxCaptureBytes: terminalBufferMaxBytes } + ? { + fullHistory: true, + historyLimitLines: captureHistoryLines(query.lines, tmuxHistoryLimit), + maxCaptureBytes: terminalBufferMaxBytes, + } : {}; const liveMuxBuffer = muxName && typeof ctx.mux.captureActivePaneBuffer === 'function' diff --git a/src/web/routes/status-telemetry-routes.ts b/src/web/routes/status-telemetry-routes.ts index 86aa8437..b7074c6c 100644 --- a/src/web/routes/status-telemetry-routes.ts +++ b/src/web/routes/status-telemetry-routes.ts @@ -7,6 +7,9 @@ * the header "Plan Usage Limits" chip. Auth-exempt like `/api/hook-event` * (localhost-only; hook-secret-gated while a tunnel runs — see middleware/auth). * + * Also records the session's model (`model.display_name`) as its reported model, which + * `session:updated` publishes as `displayModel` for the session headers. + * * Returns a compact plain-text status string for the exporter to print as the * in-terminal footer (print-through) when it has no statusline of the user's * own to wrap. An unknown session gets an EMPTY body: the old brand-word @@ -26,6 +29,7 @@ import { import { SessionStatusTelemetry } from '../sse-events.js'; import { setLatestPlanUsage } from '../plan-usage-latest.js'; import type { SessionPort, EventPort } from '../ports/index.js'; +import { getCli } from '../../config/cli-registry/index.js'; export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: SessionPort & EventPort): void { // Last broadcast telemetry signature per session — the statusline fires on @@ -46,6 +50,15 @@ export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: Session const payload = data as RawStatuslinePayload | undefined; + // The model the CLI says it is running, for the session headers (displayModel). It + // rides every render, so it follows an in-session `/model`; the session dedupes and + // broadcasts only a change. Only a CLI that has a statusline exporter at all may + // report one here. + const session = ctx.sessions.get(sessionId); + if (session && getCli(session.mode)?.capabilities.statusLineTelemetry) { + session.noteReportedModel('statusline', payload?.model?.display_name); + } + // Plan-usage limits (account-wide) → broadcast to the header chip, when // present and changed (the statusline fires on every assistant message). const telemetry = parseStatusTelemetry(payload); diff --git a/src/web/server.ts b/src/web/server.ts index 4442e544..8d7fe698 100644 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -3542,6 +3542,10 @@ export class WebServer extends EventEmitter { // pane-exit watcher's own tick replaces it with a first-hand // reading (not the stats collector — see `startPaneExitWatcher`). paneExit: savedState?.paneExit, + // The model the CLI last reported (statusline or its own footer), so a + // tile header keeps naming it until the next report; an idle claude + // session re-renders its statusline only on its next turn. + displayModel: savedState?.displayModel, // A record rebuilt from the socket has no provenance, so its // apparent locality is a guess (see `MuxSession.discovered`). discoveredMuxSession: muxSession.discovered, diff --git a/src/web/session-listener-wiring.ts b/src/web/session-listener-wiring.ts index 55bb0152..6f773698 100644 --- a/src/web/session-listener-wiring.ts +++ b/src/web/session-listener-wiring.ts @@ -44,6 +44,7 @@ export interface SessionListenerRefs { working: () => void; idle: () => void; watchingChanged: () => void; + displayModelChanged: () => void; taskCreated: (task: BackgroundTask) => void; taskUpdated: (task: BackgroundTask) => void; taskCompleted: (task: BackgroundTask) => void; @@ -275,6 +276,16 @@ export function createSessionListeners(session: Session, deps: SessionListenerDe deps.broadcastSessionStateDebounced(session.id); }, + /** + * Pushes the session state when the model the CLI reports changes (its statusline, + * or its own footer), which the status does not reflect. Persisted too: a restart + * restores the last reported model until the next report. + */ + displayModelChanged: () => { + deps.broadcastSessionStateDebounced(session.id); + deps.persistSessionState(session); + }, + // ─── Background Task Events ────────────────────────────── /** Broadcasts `task:created` — new background task discovered */ @@ -508,6 +519,7 @@ export function attachSessionListeners(session: Session, refs: SessionListenerRe session.on('working', refs.working); session.on('idle', refs.idle); session.on('watchingChanged', refs.watchingChanged); + session.on('displayModelChanged', refs.displayModelChanged); session.on('taskCreated', refs.taskCreated); session.on('taskUpdated', refs.taskUpdated); session.on('taskCompleted', refs.taskCompleted); @@ -545,6 +557,7 @@ export function detachSessionListeners(session: Session, refs: SessionListenerRe session.off('working', refs.working); session.off('idle', refs.idle); session.off('watchingChanged', refs.watchingChanged); + session.off('displayModelChanged', refs.displayModelChanged); session.off('taskCreated', refs.taskCreated); session.off('taskUpdated', refs.taskUpdated); session.off('taskCompleted', refs.taskCompleted); diff --git a/test/deepseek-route-config.test.ts b/test/deepseek-route-config.test.ts new file mode 100644 index 00000000..d6ab76db --- /dev/null +++ b/test/deepseek-route-config.test.ts @@ -0,0 +1,275 @@ +/** + * The model a dsh session's TUI route config pins (src/deepseek-route-config.ts), + * shown in a session header when the TUI's screen names none. + * + * Fixture dsh homes are built in a temp directory. The two user layers below are the + * owner's real files on 2026-10-07, verbatim apart from the comment text: the + * profile layer pins the dsh-tui row's route (provider AND model), the home layer + * pins `agent-default-model`, which is the headless default and NOT the TUI's. + * + * Port: N/A. + */ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + DSH_TUI_PACKAGE, + MAX_ROUTE_FILE_BYTES, + effectiveDshHome, + parseDshTuiPatches, + readDeepSeekRouteModel, + resolveDshTuiRouteModel, +} from '../src/deepseek-route-config.js'; + +const PROFILE_LAYER = `# Your patch layer for this dsh profile, applied after every bundle layer: +# a top-level YAML array of loader patch entries (id-targeted config +# overrides, disables, and insert lists; \`!!js\` expressions allowed). +# +# Route the TUI at the 5090 box's live serve. A config route counts only +# when it names BOTH provider and model. +- id: dsh-tui + config: + provider: qwen5090 + model: qwen3.8-27b + effort: medium + preset: qwen5090 +`; +const HOME_LAYER = `# Home-level patch layer. The default model is a composition entry, +# not a settings key. +- id: agent-default-model + config: + provider: qwen5090 + model: qwen3.8-27b +`; +const SETTINGS = `agent-default-model: + provider: qwen5090 + model: qwen3.8-27b +`; +const TUI_BUNDLES = ['@deepseek-ai/dsh-base', DSH_TUI_PACKAGE]; + +const homes: string[] = []; +afterEach(() => { + for (const dir of homes.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +/** A fixture dsh home: profiles (bundles + optional patch layer), a home layer, settings.yaml. */ +function makeHome(spec: { + profiles?: Record; + homePatch?: string; + settings?: string; +}): string { + const root = mkdtempSync(join(tmpdir(), 'dsh-route-')); + homes.push(root); + const home = join(root, 'dsh'); + mkdirSync(join(home, 'profiles'), { recursive: true }); + for (const [name, p] of Object.entries(spec.profiles ?? {})) { + mkdirSync(join(home, 'profiles', name), { recursive: true }); + writeFileSync( + join(home, 'profiles', name, 'package.json'), + JSON.stringify({ name: `dsh-profile-${name}`, dsh: { profile: { bundles: p.bundles ?? TUI_BUNDLES } } }) + ); + if (p.patch !== undefined) writeFileSync(join(home, 'profiles', name, 'cordis.patch.yml'), p.patch); + } + if (spec.homePatch !== undefined) writeFileSync(join(home, 'cordis.patch.yml'), spec.homePatch); + if (spec.settings !== undefined) writeFileSync(join(home, 'settings.yaml'), spec.settings); + return home; +} + +const read = (home: string, profile: string | undefined = 'dsh-tui', serverHome: string | null = home) => + readDeepSeekRouteModel({ profile, home, serverHome }); + +describe('readDeepSeekRouteModel', () => { + it('a route pinned with both provider and model: the model', async () => { + const home = makeHome({ + profiles: { 'dsh-tui': { patch: PROFILE_LAYER } }, + homePatch: HOME_LAYER, + settings: SETTINGS, + }); + expect(await read(home)).toBe('qwen3.8-27b'); + }); + + it('a half-pinned route (provider alone): nothing, the TUI drops it whole', async () => { + const half = '- id: dsh-tui\n config:\n provider: qwen5090\n effort: medium\n'; + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch: half } } }))).toBeNull(); + const modelOnly = '- id: dsh-tui\n config:\n model: qwen3.8-27b\n'; + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch: modelOnly } } }))).toBeNull(); + }); + + it('no profile layer: nothing (the bundle pins a provider alone, by design)', async () => { + expect(await read(makeHome({ profiles: { 'dsh-tui': {} }, homePatch: HOME_LAYER, settings: SETTINGS }))).toBeNull(); + }); + + it("settings.yaml and the home layer's agent-default-model are the headless default, never the TUI's", async () => { + expect(await read(makeHome({ profiles: { 'dsh-tui': {} }, settings: SETTINGS }))).toBeNull(); + expect(await read(makeHome({ profiles: { 'dsh-tui': {} }, homePatch: HOME_LAYER }))).toBeNull(); + }); + + it('a layer that does not parse: nothing', async () => { + const broken = [ + '- id: dsh-tui\n config:\n\tprovider: qwen5090\n\tmodel: x\n', // tab indentation + '- id: dsh-tui\n config:\n \tprovider: qwen5090\n \tmodel: x\n', // a tab inside the indentation + "- id: dsh-tui\n config:\n provider: 'qwen5090\n model: x\n", // unterminated quote + '- id: dsh-tui\n config:\n provider: qwen5090\n model: qwen3.8-27b\n model: other\n', // duplicate key + 'dsh-tui:\n provider: qwen5090\n', // not a sequence + ]; + for (const patch of broken) { + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch } } })), patch).toBeNull(); + } + // The home layer is read too: a broken one blanks a good profile layer. + const home = makeHome({ profiles: { 'dsh-tui': { patch: PROFILE_LAYER } }, homePatch: '- id: [\n' }); + expect(await read(home)).toBeNull(); + }); + + it('a layer that is a symlink out of the dsh home: nothing; one inside it is followed', async () => { + const home = makeHome({ profiles: { 'dsh-tui': {} } }); + const outside = join(home, '..', 'outside.yml'); + writeFileSync(outside, PROFILE_LAYER); + symlinkSync(outside, join(home, 'profiles', 'dsh-tui', 'cordis.patch.yml')); + expect(await read(home)).toBeNull(); + + const inside = makeHome({ profiles: { 'dsh-tui': {} } }); + writeFileSync(join(inside, 'shared-route.yml'), PROFILE_LAYER); + symlinkSync(join(inside, 'shared-route.yml'), join(inside, 'profiles', 'dsh-tui', 'cordis.patch.yml')); + expect(await read(inside)).toBe('qwen3.8-27b'); + }); + + it("a session's own DSH_HOME is the one read", async () => { + const server = makeHome({ profiles: { 'dsh-tui': { patch: PROFILE_LAYER } } }); + const own = makeHome({ + profiles: { + 'dsh-tui': { patch: '- id: dsh-tui\n config:\n provider: deepseek-official\n model: deepseek-v4-pro\n' }, + }, + }); + expect(await read(own, 'dsh-tui', server)).toBe('deepseek-v4-pro'); + expect(await read(server, 'dsh-tui', server)).toBe('qwen3.8-27b'); + // The status bar can be switched off in that home without touching the route. + expect(effectiveDshHome((k) => (k === 'DSH_HOME' ? own : undefined))).toBe(own); + }); + + it('the home layer outranks the profile layer, and replaces its whole config', async () => { + const pin = '- id: dsh-tui\n config:\n provider: deepseek-official\n model: deepseek-v4-flash\n'; + const homeWins = makeHome({ profiles: { 'dsh-tui': { patch: PROFILE_LAYER } }, homePatch: pin }); + expect(await read(homeWins)).toBe('deepseek-v4-flash'); + const half = '- id: dsh-tui\n config:\n effort: high\n'; + const halved = makeHome({ profiles: { 'dsh-tui': { patch: PROFILE_LAYER } }, homePatch: half }); + expect(await read(halved)).toBeNull(); + }); + + it('no profile named: the one the launch would boot (the first terminal profile)', async () => { + const home = makeHome({ + profiles: { + web: { bundles: ['@deepseek-ai/dsh-web-app'] }, + 'dsh-tui': { patch: PROFILE_LAYER }, + }, + }); + expect(await read(home, undefined)).toBe('qwen3.8-27b'); + // An invalid name reads as unset at launch, so the default applies here too. + expect(await read(home, '../web')).toBe('qwen3.8-27b'); + }); + + it('a profile that does not compose dsh-TUI: nothing (its route is not this reader’s to know)', async () => { + const home = makeHome({ profiles: { other: { bundles: ['@someone/other-tui'], patch: PROFILE_LAYER } } }); + expect(await read(home, 'other')).toBeNull(); + }); + + it('a disabled row, a name mismatch, a missing home or profile: nothing', async () => { + const disabled = `${PROFILE_LAYER}- id: dsh-tui\n disabled: true\n`; + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch: disabled } } }))).toBeNull(); + const mismatch = '- id: dsh-tui\n name: "@someone/else"\n config:\n provider: a\n model: b\n'; + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch: mismatch } } }))).toBeNull(); + expect(await read(join(tmpdir(), 'no-such-dsh-home-xyz'))).toBeNull(); + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch: PROFILE_LAYER } } }), 'missing')).toBeNull(); + }); + + it('an oversized layer: nothing', async () => { + const big = PROFILE_LAYER + `# ${'x'.repeat(MAX_ROUTE_FILE_BYTES)}\n`; + expect(await read(makeHome({ profiles: { 'dsh-tui': { patch: big } } }))).toBeNull(); + }); +}); + +describe('effectiveDshHome', () => { + it("the session's, else ~/.dsh; a relative value names no place", () => { + expect(effectiveDshHome(() => '/srv/dsh')).toBe('/srv/dsh'); + expect(effectiveDshHome(() => ' ')).toMatch(/\.dsh$/); + expect(effectiveDshHome(() => undefined)).toMatch(/\.dsh$/); + expect(effectiveDshHome(() => 'dsh-copy')).toBeNull(); + expect(effectiveDshHome(() => '~/dsh')).toBeNull(); + }); +}); + +describe('parseDshTuiPatches (the narrow YAML subset)', () => { + it("reads the owner's two layers", () => { + expect(parseDshTuiPatches(PROFILE_LAYER)).toEqual([{ config: { provider: 'qwen5090', model: 'qwen3.8-27b' } }]); + expect(parseDshTuiPatches(HOME_LAYER)).toEqual([]); + }); + + it('an empty list, comments only, and a leading document marker', () => { + expect(parseDshTuiPatches('[]\n')).toEqual([]); + expect(parseDshTuiPatches('# nothing yet\n')).toEqual([]); + expect(parseDshTuiPatches(`---\n${PROFILE_LAYER}`)).toHaveLength(1); + }); + + it('quoted scalars, a key on its own line under `-`, a wider item indent', () => { + expect( + parseDshTuiPatches('- id: "dsh-tui"\n config:\n provider: "qwen5090"\n model: \'qwen3.8-27b\'\n') + ).toEqual([{ config: { provider: 'qwen5090', model: 'qwen3.8-27b' } }]); + expect(parseDshTuiPatches('-\n id: dsh-tui\n config:\n provider: p\n model: m # trailing\n')).toEqual([ + { config: { provider: 'p', model: 'm' } }, + ]); + expect(parseDshTuiPatches('- id: dsh-tui\n config:\n provider: p\n model: m\n')).toEqual([ + { config: { provider: 'p', model: 'm' } }, + ]); + }); + + it('anything that could change the answer and is beyond the subset: null', () => { + const cases = [ + '- id: dsh-tui\n config:\n provider: !!js process.env.P\n model: m\n', // a tag + '- id: dsh-tui\n config: &route\n provider: p\n model: m\n', // an anchor + '- id: other\n config: &r { provider: p, model: m }\n- id: dsh-tui\n config: *r\n', // an alias + '- id: dsh-tui\n config:\n <<: { provider: p, model: m }\n', // a merge key + '- id: dsh-tui\n config: { provider: p, model: m }\n', // a flow config + '- id: dsh-tui\n config:\n provider: p\n model: 12\n', // a number, not a string + '- id: dsh-tui\n config:\n provider: p\n model: |\n m\n', // a block scalar + '- insert:\n - id: dsh-tui\n name: x\n', // re-inserting the row + `${PROFILE_LAYER}---\n- id: dsh-tui\n`, // a second document + '%YAML 1.2\n---\n- id: dsh-tui\n', // a directive + // A quoted scalar spanning lines swallows the next "key": YAML reads note as + // "start model: m" and the route as half-pinned. + '- id: dsh-tui\n config:\n note: "start\n model: m"\n provider: p\n', + // A plain scalar continued on the next line is one value ("m continued"). + '- id: dsh-tui\n config:\n provider: p\n model: m\n continued\n', + // A group row whose config re-defines a dsh-tui row inside it. + '- id: tui-group\n config:\n - id: dsh-tui\n config:\n provider: p\n model: m\n', + '- id: tui-group\n config:\n - id: dsh-tui\n config:\n provider: p\n model: m\n', + ]; + for (const text of cases) expect(parseDshTuiPatches(text), text).toBeNull(); + }); + + it('an unrelated item it cannot follow is skipped, one about dsh-tui is not', () => { + // `rules`' sequence at its key's own indent is valid YAML but beyond the subset. + const odd = '- id: approval\n rules:\n - a\n config:\n policy: |\n line one\n'; + expect(parseDshTuiPatches(`${odd}${PROFILE_LAYER}`)).toEqual([ + { config: { provider: 'qwen5090', model: 'qwen3.8-27b' } }, + ]); + expect(parseDshTuiPatches(`- id: dsh-tui\n config:\n rules:\n - a\n`)).toBeNull(); + }); + + it('a disabled flag, a name, and an empty config', () => { + expect(parseDshTuiPatches('- id: dsh-tui\n disabled: true\n name: x\n config: {}\n')).toEqual([ + { disabled: true, name: 'x', config: {} }, + ]); + }); +}); + +describe('resolveDshTuiRouteModel', () => { + it('the last config wins whole; a layer that could not be read blanks the answer', () => { + const full = { config: { provider: 'p', model: 'm' } }; + expect(resolveDshTuiRouteModel([[full], []])).toBe('m'); + expect(resolveDshTuiRouteModel([[full], [{ config: { provider: 'p' } }]])).toBeNull(); + expect(resolveDshTuiRouteModel([[full], null])).toBeNull(); + expect(resolveDshTuiRouteModel([[], []])).toBeNull(); + expect(resolveDshTuiRouteModel([[full, { disabled: true }]])).toBeNull(); + expect(resolveDshTuiRouteModel([[full, { name: '@someone/else', config: {} }]])).toBe('m'); + }); +}); diff --git a/test/frontend-cli-no-id-branching.test.ts b/test/frontend-cli-no-id-branching.test.ts index 5c98efde..ba098bc7 100644 --- a/test/frontend-cli-no-id-branching.test.ts +++ b/test/frontend-cli-no-id-branching.test.ts @@ -1,6 +1,9 @@ /** * @fileoverview Static guard: no NEW CLI-id branch in the two files PR B2 touched - * (`session-ui.js`, `mobile-overview.js`), mirroring + * (`session-ui.js`, `mobile-overview.js`), plus the files that draw a session + * header's harness logo and model (`constants.js`, `terminal-split.js`, + * `tile-grid.js`: the logo's `run-mode-dot ` class is the id as DATA), + * mirroring * `test/cli-registry-no-id-branching.test.ts` for the backend registry. * * Deliberately scoped to ONLY these two files, not all of `src/web/public/`. @@ -21,7 +24,7 @@ import { fileURLToPath } from 'node:url'; import { STOCK_CLIS } from '../src/config/cli-registry/stock.js'; const PUBLIC = fileURLToPath(new URL('../src/web/public/', import.meta.url)); -const SCANNED_FILES = ['session-ui.js', 'mobile-overview.js']; +const SCANNED_FILES = ['session-ui.js', 'mobile-overview.js', 'constants.js', 'terminal-split.js', 'tile-grid.js']; /** * Every currently-surviving branch, each with the COUNT of physical call @@ -90,6 +93,13 @@ const ALLOWED_BRANCHES: Record = { reason: 'display filter: the "CLIs found inside the container" summaries omit shell, which is not an agent CLI', }, + // tile-grid.js: a tile's Attach re-attaches through the same route pair the + // primary pane uses, and that pair is split by mode on the server side. + "tile-grid.js::mode === 'shell'": { + count: 1, + reason: 'attach route: a shell session attaches through /shell, an agent through /interactive', + }, + // mobile-overview.js: shell is exempt from the isCliAvailable() gate the // same way the toolbar's #runModeMenu exempts it (shell needs no CLI). "mobile-overview.js::mode !== 'shell'": { @@ -177,7 +187,7 @@ function actualCounts(): Map { return counts; } -describe('no NEW CLI-id branching in session-ui.js / mobile-overview.js (PR B2)', () => { +describe('no NEW CLI-id branching in the scanned frontend files', () => { it('scans both files (sanity)', () => { // If this drops to zero the scanner or the file list drifted and every // assertion below would pass vacuously. diff --git a/test/header-icon-hover.test.ts b/test/header-icon-hover.test.ts new file mode 100644 index 00000000..74088b80 --- /dev/null +++ b/test/header-icon-hover.test.ts @@ -0,0 +1,125 @@ +/** + * @fileoverview Header icon buttons: hover motion moves the icon, never the button. + * + * A global `.btn-icon-header:hover { transform: rotate(45deg) }` (meant for the + * settings gear) turned EVERY header icon button on hover, so the folder, Tiles, + * Split and the rest swung their rounded hover background into a diamond. Three + * buttons had already been patched one by one with `transform: none`. The owner + * asked for a nicer hover on the folder and Tiles buttons; this file pins the + * shape of the fix: + * + * 1. No rule on a header icon button transforms the BUTTON on hover. + * 2. Only the gear's icon turns; the Tiles squares spread apart; the folder + * cross-fades from closed to open (two drawings in its SVG). + * 3. Those motions live inside `@media (hover: hover)`, so a tap on a touch + * screen cannot leave an icon stuck mid-motion, and reduced motion turns the + * transitions off. + */ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import postcss, { type AtRule, type Rule } from 'postcss'; + +const ROOT = resolve(__dirname, '..'); +const css = readFileSync(resolve(ROOT, 'src/web/public/styles.css'), 'utf8'); +const html = readFileSync(resolve(ROOT, 'src/web/public/index.html'), 'utf8'); +const root = postcss.parse(css); + +interface FoundRule { + selector: string; + decls: Record; + media: string[]; +} + +function rules(): FoundRule[] { + const out: FoundRule[] = []; + root.walkRules((rule: Rule) => { + const media: string[] = []; + for (let p = rule.parent; p && p.type !== 'root'; p = p.parent) { + if (p.type === 'atrule' && (p as AtRule).name === 'media') media.push((p as AtRule).params); + } + const decls: Record = {}; + rule.walkDecls((d) => { + decls[d.prop] = d.value; + }); + for (const selector of rule.selectors) out.push({ selector, decls, media }); + }); + return out; +} + +const all = rules(); +const iconRules = all.filter((r) => r.selector.includes('btn-icon-header')); + +function buttonTag(cls: string): string { + const i = html.indexOf(`class="btn-icon-header ${cls}`); + expect(i, `${cls} button in index.html`).toBeGreaterThan(-1); + return html.slice(i, html.indexOf('', i)); +} + +describe('header icon hover', () => { + it('never transforms the button itself on hover', () => { + const offenders = iconRules.filter( + (r) => /:hover\s*$/.test(r.selector) && r.decls.transform && r.decls.transform !== 'none' + ); + expect(offenders.map((r) => `${r.selector} { transform: ${r.decls.transform} }`)).toEqual([]); + }); + + it('turns only the gear icon, and only on pointer devices', () => { + const rotations = iconRules.filter((r) => /rotate\(/.test(r.decls.transform || '')); + expect(rotations.map((r) => r.selector)).toEqual(['.btn-icon-header.btn-settings:hover svg']); + expect(rotations[0].media).toContain('(hover: hover)'); + }); + + it('spreads the four Tiles squares apart, each toward its own corner', () => { + const svg = buttonTag('btn-tile-grid'); + expect(svg.match(/ { + const rule = iconRules.find( + (r) => r.selector === `.btn-icon-header.btn-tile-grid:hover svg rect:nth-of-type(${i + 1})` + ); + expect(rule?.decls.transform, `rect ${i + 1}`).toBe(`translate${offset}`); + expect(rule?.media).toContain('(hover: hover)'); + }); + const box = iconRules.find( + (r) => r.selector === '.btn-icon-header.btn-tile-grid svg rect' && r.decls['transform-box'] + ); + expect(box?.decls['transform-origin']).toBe('center'); + }); + + it('opens the folder: the open drawing is hidden at rest and replaces the closed one on hover', () => { + const svg = buttonTag('btn-file-viewer'); + expect(svg).toContain('class="icon-folder-closed"'); + expect(svg).toContain('class="icon-folder-open"'); + const rest = iconRules.find( + (r) => r.selector === '.btn-icon-header.btn-file-viewer svg .icon-folder-open' && r.decls.opacity + ); + expect(rest?.decls.opacity).toBe('0'); + expect(rest?.media).toEqual([]); + const hoverClosed = iconRules.find( + (r) => r.selector === '.btn-icon-header.btn-file-viewer:hover svg .icon-folder-closed' + ); + const hoverOpen = iconRules.find( + (r) => r.selector === '.btn-icon-header.btn-file-viewer:hover svg .icon-folder-open' + ); + expect(hoverClosed?.decls.opacity).toBe('0'); + expect(hoverOpen?.decls.opacity).toBe('1'); + expect(hoverClosed?.media).toContain('(hover: hover)'); + expect(hoverOpen?.media).toContain('(hover: hover)'); + }); + + it('turns the motion off under reduced motion', () => { + const reduced = iconRules.filter((r) => r.media.includes('(prefers-reduced-motion: reduce)')); + for (const sel of [ + '.btn-icon-header.btn-settings svg', + '.btn-icon-header.btn-tile-grid svg rect', + '.btn-icon-header.btn-file-viewer svg .icon-folder-closed', + '.btn-icon-header.btn-file-viewer svg .icon-folder-open', + ]) { + expect(reduced.find((r) => r.selector === sel)?.decls.transition, sel).toBe('none'); + } + for (const sel of ['.btn-icon-header.btn-settings:hover svg', '.btn-icon-header.btn-tile-grid:hover svg rect']) { + expect(reduced.find((r) => r.selector === sel)?.decls.transform, sel).toBe('none'); + } + }); +}); diff --git a/test/help-modal-shortcuts.test.ts b/test/help-modal-shortcuts.test.ts index 0d54e95d..20e54c94 100644 --- a/test/help-modal-shortcuts.test.ts +++ b/test/help-modal-shortcuts.test.ts @@ -31,7 +31,7 @@ function escapeRegExp(value: string): string { function expectShortcut(html: string, keys: string[], label: string): void { const keyPattern = keys.map((key) => `${escapeRegExp(key)}`).join('\\s*\\+\\s*'); - expect(html).toMatch(new RegExp(`${keyPattern}.*?${label}`, 'i')); + expect(html).toMatch(new RegExp(`${keyPattern}.*?${escapeRegExp(label)}`, 'i')); } describe('help modal shortcuts', () => { @@ -53,6 +53,14 @@ describe('help modal shortcuts', () => { expectShortcut(helpModal, ['Escape'], 'Close Panels'); }); + it('documents the tile grid chords', () => { + expectShortcut(helpModal, ['Ctrl', 'Shift', 'G'], 'Toggle Tile Grid'); + expectShortcut(helpModal, ['Alt/Option', 'Shift', 'Arrows'], 'Focus Tile Left / Right / Up / Down'); + expectShortcut(helpModal, ['Alt/Option', 'Shift', 'Enter'], 'Zoom Focused Tile'); + expectShortcut(helpModal, ['Ctrl/Cmd', 'Click'], 'Add the Session to the Tile Grid'); + expectShortcut(helpModal, ['Right-click'], 'Choose How Many Tiles (2, 4 or 6)'); + }); + it('documents terminal input shortcuts without advertising stale run shortcuts', () => { expectShortcut(helpModal, ['Ctrl', 'C'], 'Copy Selection'); expectShortcut(helpModal, ['Ctrl', 'Shift', 'C'], 'Copy Selection'); diff --git a/test/i18n-branding.test.ts b/test/i18n-branding.test.ts index 8ffff762..8638d214 100644 --- a/test/i18n-branding.test.ts +++ b/test/i18n-branding.test.ts @@ -91,6 +91,100 @@ describe('custom display name and browser localization', () => { dom.window.close(); }); + it('does not walk what a terminal renders: one check per mutation inside a skipped surface', async () => { + const dom = makeDom('
'); + const { window } = dom; + const api = window.CodemanI18n; + api.start(); + api.configure({ language: 'zh-CN' }); + // i18n.js also starts itself on DOMContentLoaded (one walk of the body). + await new Promise((resolve) => window.setTimeout(resolve, 0)); + let walks = 0; + const createTreeWalker = window.document.createTreeWalker.bind(window.document); + window.document.createTreeWalker = (...args: Parameters) => { + walks++; + return createTreeWalker(...args); + }; + + // What xterm's DOM renderer does every frame: replace the rows. + const rows = window.document.getElementById('rows')!; + for (let frame = 0; frame < 3; frame++) { + const fresh = Array.from({ length: 20 }, () => { + const row = window.document.createElement('div'); + row.innerHTML = 'Settings savedRun'; + return row; + }); + rows.replaceChildren(...fresh); + } + rows.firstElementChild!.firstChild!.firstChild!.nodeValue = 'Settings saved'; + await new Promise((resolve) => window.setTimeout(resolve, 0)); + expect(walks).toBe(0); + expect(rows.firstElementChild?.textContent).toBe('Settings savedRun'); + expect(rows.querySelector('[title]')?.getAttribute('title')).toBe('Run'); + + // Application DOM next to it is still translated. + const button = window.document.createElement('button'); + button.textContent = 'Settings saved'; + window.document.getElementById('app')!.appendChild(button); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + expect(button.textContent).toBe('设置已保存'); + expect(walks).toBe(1); + dom.window.close(); + }); + + it('decides an xterm row by its rows container, with the verdict closest() gives', async () => { + // A terminal (rows inside .xterm) and a stray `.xterm-rows` outside any + // skipped surface, which the full check translates. + const dom = makeDom( + '
' + + '
' + ); + const { window } = dom; + const api = window.CodemanI18n; + api.start(); + api.configure({ language: 'zh-CN' }); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + const rowsOf = (id: string) => + Array.from({ length: 20 }, () => { + const row = window.document.createElement('div'); + window.document.getElementById(id)!.appendChild(row); + return row; + }); + const rows = rowsOf('rows'); + const stray = rowsOf('stray'); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + let closest = 0; + const original = window.Element.prototype.closest; + window.Element.prototype.closest = function (this: Element, selector: string) { + closest++; + return original.call(this, selector); + }; + + // What xterm's DOM renderer does every frame: replace each row's children. + const frames = (list: Element[]) => { + for (let frame = 0; frame < 3; frame++) { + for (const row of list) { + const span = window.document.createElement('span'); + span.textContent = 'Settings saved'; + row.replaceChildren(span); + } + } + }; + frames(rows); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + // 60 row records, ONE closest(): the container's own verdict, then kept. + expect(closest).toBe(1); + expect(rows.every((row) => row.textContent === 'Settings saved')).toBe(true); + + // A rows container outside any skipped surface keeps the full check, and + // with it the verdict closest() gives: its rows are translated. + frames(stray); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + window.Element.prototype.closest = original; + expect(stray.every((row) => row.textContent === '设置已保存')).toBe(true); + dom.window.close(); + }); + it('keeps a quoted group name apart from the fixed "Move to" entries in zh-CN', () => { const dom = makeDom(''); const api = dom.window.CodemanI18n; diff --git a/test/i18n-exit-run-help.test.ts b/test/i18n-exit-run-help.test.ts new file mode 100644 index 00000000..d96b7836 --- /dev/null +++ b/test/i18n-exit-run-help.test.ts @@ -0,0 +1,185 @@ +/** + * @fileoverview zh-CN coverage for the tab's exited-agent badge (and the tab's + * accessible name that carries it). + * + * Every form `paneExitLabel()` produces (plain, an exit code, a negative code, + * a signal) must translate fully through i18n.js's real `t()`, with the + * session name in the accessible name passed through untranslated (a name + * that is itself a dictionary word included), and read unchanged in English. + * + * Port: N/A. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { JSDOM } from 'jsdom'; +import { afterAll, describe, expect, it } from 'vitest'; + +const PUBLIC = resolve(import.meta.dirname, '../src/web/public'); +const read = (f: string) => readFileSync(resolve(PUBLIC, f), 'utf8'); +const I18N = read('i18n.js'); +const APP = read('app.js'); + +type Api = { t(s: string): string; configure(o: Record): void }; +function translator(language: string) { + const dom = new JSDOM('', { + runScripts: 'outside-only', + url: 'http://localhost/', + }); + vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' }); + const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n; + api.configure({ language }); + return { api, dom }; +} +const zh = translator('zh-CN'); +const en = translator('en'); +afterAll(() => { + zh.dom.window.close(); + en.dom.window.close(); +}); + +/** Latin words left after removing what may stay: key names, the AI acronym, the N placeholder. */ +const leftover = (text: string) => + text + .replace(/\b(Ctrl|Cmd|Shift|Alt|Option)\+\w+/g, '') + .replace(/\b(Ctrl|Cmd|Shift|Alt|Option|Enter|Tab|Space|End|Home|Escape|G|AI|N)\b/g, '') + .match(/[A-Za-z]+/g) ?? []; + +const helpers = new Function( + `${APP.match(/function paneExitLabel\([\s\S]*?\n\}/)![0]}\n${APP.match(/function paneExitAriaLabel\([\s\S]*?\n\}/)![0]}\n` + + 'return { paneExitLabel, paneExitAriaLabel };' +)() as { paneExitLabel(p: unknown): string; paneExitAriaLabel(name: string, label: string): string }; + +const EXITS = [{}, { status: 0 }, { status: 3 }, { status: 137 }, { status: -1 }, { signal: 9 }]; + +describe('the exited-agent badge in zh-CN', () => { + const labels = EXITS.map((p) => helpers.paneExitLabel({ ...p, at: 1 })); + + it('produces the forms this test covers', () => { + expect(labels).toEqual(['exited', 'exited (0)', 'exited (3)', 'exited (137)', 'exited (-1)', 'exited (signal 9)']); + }); + + it('every badge form translates fully, and reads the same in English', () => { + const bad = labels.filter((l) => { + const text = zh.api.t(l); + return text === l || leftover(text).length > 0 || en.api.t(l) !== l; + }); + expect(bad).toEqual([]); + expect(zh.api.t('exited (3)')).toBe('已退出(3)'); + expect(zh.api.t('exited (signal 9)')).toBe('已退出(信号 9)'); + }); + + it("the tab's accessible name translates around the session name, which stays as typed", () => { + for (const name of ['w1-case', 'Open tiles', 'Tiles']) { + for (const label of labels) { + const source = helpers.paneExitAriaLabel(name, label); + const text = zh.api.t(source); + expect(text.startsWith(`${name} 会话,智能体已退出`), `${source} -> ${text}`).toBe(true); + expect(leftover(text.slice(name.length))).toEqual([]); + expect(en.api.t(source)).toBe(source); + } + } + }); +}); + +describe('the Run button family in zh-CN', () => { + const SESSION_UI = read('session-ui.js'); + const STOCK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../config/clis.stock.json'), 'utf8')) as Array<{ + shortBadge: string; + }>; + // What _applyRunMode can show: its hard-coded labels, and `Run ` for any registry CLI. + const applyRunMode = SESSION_UI.slice( + SESSION_UI.indexOf(' _applyRunMode() {'), + SESSION_UI.indexOf(' sendEnterKey() {') + ); + const hardCoded = [...applyRunMode.matchAll(/'(Run(?: [A-Z]+)?)'/g)].map((m) => m[1]); + const fromRegistry = STOCK.map((e) => `Run ${e.shortBadge}`); + + it('covers the hard-coded labels and every stock mode code', () => { + expect(hardCoded).toEqual(expect.arrayContaining(['Run SH', 'Run OC', 'Run CX', 'Run OMP', 'Run'])); + expect(fromRegistry).toEqual(expect.arrayContaining(['Run CC', 'Run SH', 'Run OM'])); + }); + + it('"Run" becomes 运行, the mode code and product names stay, English unchanged', () => { + for (const label of new Set([...hardCoded, ...fromRegistry])) { + const text = zh.api.t(label); + const code = label.slice(4); + // A code that is also a product name has its own entry, matched without + // case ("Run PI" -> the "Run Pi" entry, 运行 Pi): the code survives either way. + expect(text.startsWith('运行'), label).toBe(true); + expect(text.slice(2).trim().toLowerCase(), label).toBe(code.toLowerCase()); + expect(en.api.t(label)).toBe(label); + } + }); + + it('the toolbar around it: titles and the Shell button', () => { + for (const s of [ + 'Run Shell', + 'Select AI backend', + 'Terminal / Shell', + 'Send Enter', + 'Instance count', + 'Stop (Ctrl+C)', + ]) { + const text = zh.api.t(s); + expect(text, s).not.toBe(s); + // "Shell" stays, as the table already had it (运行 Shell). + expect(leftover(text.replace(/Shell/g, '')), s).toEqual([]); + expect(en.api.t(s)).toBe(s); + } + }); +}); + +describe('the Help modal and the shortcut overlay in zh-CN', () => { + const dom = new JSDOM(read('index.html'), { runScripts: 'outside-only', url: 'http://localhost/' }); + vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' }); + const doc = dom.window.document; + const control = doc.createElement('button'); + control.textContent = 'Home'; + doc.body.appendChild(control); + const api = (dom.window as unknown as { CodemanI18n: Api & { start(): void } }).CodemanI18n; + api.start(); + api.configure({ language: 'zh-CN' }); + + it('no English left in the Help modal outside the key names', () => { + const left: string[] = []; + const walk = (el: Element) => { + for (const node of el.childNodes) { + if (node.nodeType === 3) { + if (node.parentElement?.tagName !== 'KBD' && leftover(node.nodeValue ?? '').length) + left.push(node.nodeValue!.trim()); + } else if (node.nodeType === 1) walk(node as Element); + } + }; + walk(doc.getElementById('helpModal')!); + expect(left).toEqual([]); + }); + + it('the Home KEY stays Home, while the word Home elsewhere still translates', () => { + const homeKey = [...doc.querySelectorAll('#helpModal kbd')].find((k) => k.closest('div')?.nextElementSibling); + const keys = [...doc.querySelectorAll('#helpModal kbd')].map((k) => k.textContent); + expect(keys).toContain('Home'); + expect(keys).not.toContain('主页'); + // Mouse inputs in the key column do translate (as Click / Right-click do). + expect(keys).toContain('滚轮'); + expect(homeKey).toBeTruthy(); + expect(control.textContent).toBe('主页'); + }); + + it('every shortcut registry group and label translates (the overlay and the App Settings list)', () => { + const start = APP.indexOf('const DEFAULT_SHORTCUTS = ['); + const registry = APP.slice(start, APP.indexOf('\n];', start)); + const pairs = [...registry.matchAll(/group: '([^']+)',\s*label: '([^']+)'/g)]; + expect(pairs.length).toBeGreaterThan(20); + const bad = pairs.flatMap(([, group, label]) => + [group, label].filter((s) => zh.api.t(s) === s || leftover(zh.api.t(s)).length > 0) + ); + expect([...new Set(bad)]).toEqual([]); + }); + + it("the overlay's key column is never translated", () => { + const overlay = APP.slice(APP.indexOf(' renderShortcutOverlay() {'), APP.indexOf(' closeShortcutOverlay() {')); + expect(overlay.match(//g)).toHaveLength(2); + expect(overlay).not.toMatch(//); + }); +}); diff --git a/test/mocks/mock-session.ts b/test/mocks/mock-session.ts index 5f04d97e..17c838ae 100644 --- a/test/mocks/mock-session.ts +++ b/test/mocks/mock-session.ts @@ -383,6 +383,14 @@ export class MockSession extends EventEmitter { ); restartCli = vi.fn(async () => true); getCustomModelForPersist = vi.fn(() => this._mockCustomModel); + /** Mirrors Session.noteReportedModel: the statusline route records the CLI's model. */ + reportedModel: { model: string; source: 'statusline' | 'screen' } | null = null; + noteReportedModel = vi.fn((source: 'statusline' | 'screen', raw: unknown): boolean => { + if (typeof raw !== 'string' || !raw.trim()) return false; + if (this.reportedModel?.model === raw && this.reportedModel.source === source) return false; + this.reportedModel = { model: raw, source }; + return true; + }); /** Stub for sendInput */ sendInput = vi.fn(); diff --git a/test/mocks/terminal-tile-fakes.ts b/test/mocks/terminal-tile-fakes.ts new file mode 100644 index 00000000..63eb82b9 --- /dev/null +++ b/test/mocks/terminal-tile-fakes.ts @@ -0,0 +1,133 @@ +/** + * @fileoverview Fakes for driving a real TerminalTile (terminal-tile.js) in a + * `vm` context: its WebSocket, its xterm and the fit addon. A test puts them in + * the context as `WebSocket`, `Terminal` and `FitAddon.FitAddon`, and runs + * `connect()` and the socket handlers for real. + */ +import { vi } from 'vitest'; + +export type Frame = { t: string; d?: string; seq?: number; cid?: string; c?: number; r?: number }; + +/** A WebSocket the test opens, feeds and closes by hand; `sent` holds every frame the tile sent. */ +export class FakeSocket { + static OPEN = 1; + static instances: FakeSocket[] = []; + readyState = 0; + sent: Frame[] = []; + onopen: (() => void) | null = null; + onmessage: ((ev: { data: string }) => void) | null = null; + onclose: ((ev?: { code: number }) => void) | null = null; + onerror: (() => void) | null = null; + constructor(public url: string) { + FakeSocket.instances.push(this); + } + send(data: string) { + this.sent.push(JSON.parse(data) as Frame); + } + close = vi.fn(() => { + this.readyState = 3; + }); + open() { + this.readyState = 1; + this.onopen?.(); + } + receive(msg: object) { + this.onmessage?.({ data: JSON.stringify(msg) }); + } + inputFrames() { + return this.sent.filter((f) => f.t === 'i'); + } + /** The connection drops: closed, and the tile hears `code`. */ + drop(code = 1006) { + this.readyState = 3; + this.onclose?.({ code }); + } +} + +/** The fit addon: proposes `FakeFit.proposed` and, like the real one, resizes to it (NaN = hidden pane). */ +export class FakeFit { + static proposed = { cols: 80, rows: 24 }; + term: FakeTerminal | null = null; + fit() { + const { cols, rows } = FakeFit.proposed; + if (!Number.isFinite(cols) || !Number.isFinite(rows)) return; + this.term?.resize(cols, rows); + } + proposeDimensions() { + return { ...FakeFit.proposed }; + } +} + +/** An xterm that records writes, resizes and its handlers; `type()` feeds onData like a keystroke. */ +export class FakeTerminal { + static last: FakeTerminal | null = null; + options: Record; + cols = 80; + rows = 24; + dataCb: ((data: string) => void) | null = null; + buffer = { active: { type: 'normal', viewportY: 0, length: 24 } }; + constructor(options: Record) { + this.options = { ...options }; + FakeTerminal.last = this; + } + loadAddon(addon: FakeFit) { + addon.term = this; + } + open() {} + onData(cb: (data: string) => void) { + this.dataCb = cb; + } + keyHandler: ((ev: Record) => boolean) | null = null; + focusListeners: Array<() => void> = []; + textarea = { + addEventListener: (type: string, fn: () => void) => { + if (type === 'focus') this.focusListeners.push(fn); + }, + removeEventListener: (type: string, fn: () => void) => { + if (type === 'focus') this.focusListeners = this.focusListeners.filter((f) => f !== fn); + }, + }; + focusTextarea() { + for (const fn of this.focusListeners) fn(); + } + attachCustomKeyEventHandler(fn: (ev: Record) => boolean) { + this.keyHandler = fn; + } + registerLinkProvider() {} + writes: string[] = []; + /** Set by a test: write callbacks never run, as on a disposed xterm. */ + holdParse = false; + write(data: string, cb?: () => void) { + // An empty write puts nothing on screen; the replay queues one only to hear + // (its callback) that everything before it has been parsed. + if (data) this.writes.push(data); + if (!this.holdParse) cb?.(); + } + clear() { + this.writes.push(''); + } + resizes: Array<[number, number]> = []; + resize(cols: number, rows: number) { + this.resizes.push([cols, rows]); + this.cols = cols; + this.rows = rows; + } + scrollToLine() {} + scrollToTop() {} + dispose() {} + type(data: string) { + this.dataCb?.(data); + } + /** What a drag selected; '' is no selection. */ + selection = ''; + hasSelection() { + return this.selection !== ''; + } + getSelection() { + return this.selection; + } + clearSelection = vi.fn(() => { + this.selection = ''; + }); + focus = vi.fn(); +} diff --git a/test/mocks/tile-grid-vm.ts b/test/mocks/tile-grid-vm.ts new file mode 100644 index 00000000..d39c5956 --- /dev/null +++ b/test/mocks/tile-grid-vm.ts @@ -0,0 +1,387 @@ +/** + * @fileoverview A `vm` harness for the tile grid (tile-grid.js) with the real + * app around it: constants.js + app.js + terminal-ui.js + terminal-split.js + + * tile-grid.js in one context, a small fake DOM (just what the grid touches) and a fake + * TerminalTile that records what the grid asks of it. + * + * `makeGridApp()` returns an app instance with everything around the grid that + * a test does not exercise stubbed as `vi.fn()`; a test overrides what it needs + * (or deletes a stub to run the real method from the prototype). + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { vi } from 'vitest'; + +/** What has the keyboard: the last FakeEl focused (document.activeElement). */ +let focusedEl: unknown = null; +export const activeElement = () => focusedEl; + +/** Just enough DOM for tile-grid.js: elements with classes, children, styles and listeners. */ +export class FakeEl { + id = ''; + className = ''; + dataset: Record = {}; + /** Inline style; `setProperty` (custom properties) writes into it too. */ + style: Record = Object.defineProperty({} as Record, 'setProperty', { + value(this: Record, name: string, value: string) { + this[name] = value; + }, + enumerable: false, + }); + inert = false; + children: FakeEl[] = []; + parentElement: FakeEl | null = null; + attrs: Record = {}; + listeners: Record void>> = {}; + classList = { + add: (...names: string[]) => names.forEach((n) => this._setClass(n, true)), + remove: (...names: string[]) => names.forEach((n) => this._setClass(n, false)), + toggle: (n: string, on?: boolean) => this._setClass(n, on ?? !this.classList.contains(n)), + contains: (n: string) => this.className.split(/\s+/).includes(n), + }; + _setClass(name: string, on: boolean) { + const set = new Set(this.className.split(/\s+/).filter(Boolean)); + if (on) set.add(name); + else set.delete(name); + this.className = [...set].join(' '); + return on; + } + append(...children: FakeEl[]) { + for (const child of children) this.appendChild(child); + } + replaceWith(other: FakeEl) { + const parent = this.parentElement; + if (!parent) return; + other.remove(); + const i = parent.children.indexOf(this); + parent.children.splice(i, 1, other); + other.parentElement = parent; + this.parentElement = null; + } + title = ''; + hidden = false; + disabled = false; + checked = false; + contains(other: FakeEl | null): boolean { + for (let n: FakeEl | null = other; n; n = n.parentElement) if (n === this) return true; + return false; + } + textContent = ''; + value = ''; + type = ''; + /** Records itself as `document.activeElement` (see activeElement()). */ + focus = vi.fn(() => { + focusedEl = this; + }); + select = vi.fn(); + setPointerCapture = vi.fn(); + releasePointerCapture = vi.fn(); + removeEventListener(type: string, fn: (ev: unknown) => void) { + this.listeners[type] = (this.listeners[type] ?? []).filter((f) => f !== fn); + } + appendChild(child: FakeEl) { + child.remove(); + child.parentElement = this; + this.children.push(child); + return child; + } + insertBefore(child: FakeEl, ref: FakeEl | null) { + child.remove(); + child.parentElement = this; + const i = ref ? this.children.indexOf(ref) : -1; + if (i === -1) this.children.push(child); + else this.children.splice(i, 0, child); + return child; + } + get firstChild() { + return this.children[0] ?? null; + } + get lastElementChild() { + return this.children.at(-1) ?? null; + } + /** In the fake document: its ancestors end at `main` or `body`. */ + get isConnected(): boolean { + let n: FakeEl = this; + while (n.parentElement) n = n.parentElement; + return n === main || n === body; + } + /** A copy of this element and (deep) its subtree: classes, data, style, attributes, text; no listeners. */ + cloneNode(deep = false): FakeEl { + const copy = new FakeEl(); + copy.id = this.id; + copy.className = this.className; + copy.dataset = { ...this.dataset }; + for (const [k, v] of Object.entries(this.style)) copy.style[k] = v; + copy.attrs = { ...this.attrs }; + copy.textContent = this.textContent; + copy.title = this.title; + copy.hidden = this.hidden; + if (deep) for (const child of this.children) copy.appendChild(child.cloneNode(true)); + return copy; + } + get nextSibling() { + const siblings = this.parentElement?.children ?? []; + return siblings[siblings.indexOf(this) + 1] ?? null; + } + remove() { + if (!this.parentElement) return; + const siblings = this.parentElement.children; + const i = siblings.indexOf(this); + if (i !== -1) siblings.splice(i, 1); + this.parentElement = null; + } + setAttribute(k: string, v: string) { + this.attrs[k] = v; + } + getAttribute(k: string) { + return this.attrs[k] ?? null; + } + removeAttribute(k: string) { + delete this.attrs[k]; + if (k === 'title') this.title = ''; + } + /** Per event type, whether each listener was registered for the capture phase. */ + captureFlags: Record = {}; + addEventListener(type: string, fn: (ev: unknown) => void, opts?: boolean | { capture?: boolean }) { + (this.listeners[type] ||= []).push(fn); + (this.captureFlags[type] ||= []).push(opts === true || (typeof opts === 'object' && !!opts?.capture)); + } + dispatch(type: string, ev: unknown = {}) { + for (const fn of this.listeners[type] ?? []) fn(ev); + } + getBoundingClientRect() { + return { width: 2400, height: 1200, top: 0, left: 0, right: 2400, bottom: 1200 }; + } + /** `.class` selectors only: the first descendant carrying that class. */ + querySelector(sel: string): FakeEl | null { + if (!sel.startsWith('.') || /[\s[>:]/.test(sel)) return null; + const cls = sel.slice(1); + for (const child of this.children) { + if (child.classList.contains(cls)) return child; + const deeper = child.querySelector(sel); + if (deeper) return deeper; + } + return null; + } +} + +/** A TerminalTile stand-in: records what the grid asks of it. */ +export class FakeTile { + static all: FakeTile[] = []; + _wsReady = false; + _stoppedCode: number | null = null; + _destroyed = false; + fontSize: number | null; + terminal = { focus: vi.fn(), options: { fontSize: 0 } as Record }; + connect = vi.fn(async () => {}); + reconnectNow = vi.fn(); + fit = vi.fn(); + localFit = vi.fn(); + paneStarted = vi.fn(); + destroy = vi.fn(() => { + this._destroyed = true; + }); + onExit: ((code: number) => void) | null; + constructor( + public sessionId: string, + public mountEl: FakeEl, + public opts: Record + ) { + this.fontSize = (opts.fontSize as number) ?? null; + this.onExit = (opts.onExit as (code: number) => void) ?? null; + FakeTile.all.push(this); + } +} + +export const main = new FakeEl(); +main.className = 'main'; +/** The main terminal's `.terminal-wrap` (Pane A while a split is open). */ +export const wrap = new FakeEl(); +wrap.className = 'terminal-wrap'; +main.appendChild(wrap); +export const section = new FakeEl(); +section.id = 'tileGrid'; +section.className = 'tile-grid'; +main.appendChild(section); +/** The grid's element for one tiled session (its `.tile`), found by its data-session-id. */ +export const tileEl = (id: string) => section.children.find((el) => el.dataset.sessionId === id) as FakeEl; + +/** Extra elements `document.querySelector` finds, by exact selector (e.g. '.btn-split'). */ +export const bySelector = new Map(); +export const body = new FakeEl(); +/** The context's `fetch`; a test sets what it answers. */ +export const fetchSpy = vi.fn(async (..._args: unknown[]) => ({ ok: true, json: async () => ({}) })); +/** `document.addEventListener`, so a test can find a listener the app installed. */ +export const documentAddEventListener = vi.fn(); +export const documentRemoveEventListener = vi.fn(); +export const localStore = new Map(); +/** The clock behind `performance.now` inside the context; tests move it with advanceClock(). */ +let clock = 100_000; +export function advanceClock(ms: number) { + clock += ms; +} +export const clockNow = () => clock; +/** Every callback the code under test handed a PerformanceObserver, newest last. */ +export const perfObserverCallbacks: Array<(list: { getEntries(): unknown[] }) => void> = []; +/** Animation-frame callbacks the code under test queued (id = index + 1); a test runs them. */ +export const rafCallbacks: Array<() => void> = []; +/** + * Runs every queued animation frame, and the frames those queue in turn (the + * grid builds its tiles' terminals one per frame), until none is left. + */ +export function flushFrames(limit = 100) { + for (let n = 0; n < limit && rafCallbacks.length; n++) for (const cb of rafCallbacks.splice(0)) cb(); +} +/** What the code under test deferred with requestIdleCallback; a test runs them. */ +export const idleCallbacks: Array<() => void> = []; +export const windowStub: Record = { + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + CodemanBase: { base: '' }, + innerWidth: 2400, + innerHeight: 1200, +}; + +const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../../src/web/public/${f}`), 'utf8'); +const context = vm.createContext({ + console: { ...console, log: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }, + performance: { now: () => clock }, + PerformanceObserver: class { + constructor(cb: (list: { getEntries(): unknown[] }) => void) { + perfObserverCallbacks.push(cb); + } + observe() {} + disconnect() {} + }, + setInterval: vi.fn(), + clearInterval: vi.fn(), + setTimeout: (fn: () => void, ms?: number) => globalThis.setTimeout(fn, ms), + clearTimeout: (id: ReturnType) => globalThis.clearTimeout(id), + requestAnimationFrame: (cb: () => void) => rafCallbacks.push(cb), + cancelAnimationFrame: (id: number) => { + if (id > 0) rafCallbacks[id - 1] = () => {}; + }, + requestIdleCallback: (cb: () => void) => idleCallbacks.push(cb), + HTMLCanvasElement: class HTMLCanvasElement {}, + WebSocket: { OPEN: 1 }, + fetch: (...args: unknown[]) => fetchSpy(...args), + navigator: { onLine: true }, + location: { protocol: 'http:', host: 'codeman.test', pathname: '/', search: '', hash: '' }, + history: { replaceState: vi.fn(), state: null }, + document: { + addEventListener: documentAddEventListener, + removeEventListener: documentRemoveEventListener, + documentElement: { dataset: {} }, + createElement: () => new FakeEl(), + createElementNS: () => new FakeEl(), + get activeElement() { + return focusedEl; + }, + getElementById: (id: string) => (id === 'tileGrid' ? section : (bySelector.get(`#${id}`) ?? null)), + body, + querySelector: (sel: string) => + bySelector.get(sel) ?? (sel === '.main' ? main : sel === '.terminal-wrap' ? wrap : null), + querySelectorAll: () => [], + }, + localStorage: { + getItem: (k: string) => localStore.get(k) ?? null, + setItem: (k: string, v: string) => localStore.set(k, String(v)), + removeItem: (k: string) => localStore.delete(k), + }, + window: windowStub, + VoiceInput: { cleanup: vi.fn() }, + MobileDetection: { isTouchDevice: () => false, isHandheldDevice: () => false, getDeviceType: () => 'desktop' }, +}); +vm.runInContext( + `${read('constants.js')}\n${read('app.js')}\n${read('terminal-ui.js')}\n${read('terminal-split.js')}\n` + + `${read('tile-grid.js')}\n` + + 'globalThis.__CodemanApp = CodemanApp;', + context +); +windowStub.TerminalTile = FakeTile; +windowStub.TileLoadQueue = class { + schedule(_t: unknown, _k: string, run: () => Promise) { + return run(); + } + drop() {} +}; + +export const CodemanApp = (context as unknown as { __CodemanApp: { prototype: Record } }).__CodemanApp; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type GridApp = Record; + +/** Stubbed around the grid: panels, tabs, the main terminal's own select path. */ +const STUBS = [ + '_cleanupPreviousSession', + 'hideWelcome', + 'showWelcome', + 'markIdleAlertSeen', + 'renderSessionTabs', + 'renderRalphStatePanel', + 'renderProjectInsightsPanel', + '_updateActiveTabImmediate', + '_refreshSessionPanels', + '_updateSseSubscription', + '_updateConnectionIndicator', + '_activateFileBrowserSession', + '_hideWebviewLayer', + 'closeSessionSidebarOnHandheld', + 'updateAttachmentHistoryBadge', + 'refreshHostWakeBanner', + '_connectWs', + 'sendResize', + 'showToast', + '_cleanupSessionData', + 'stopSystemStatsPolling', +]; + +/** + * An app with sessions `ids` plus one more (`s-other`, FIRST in sessionOrder and + * never tiled), `s-a` active, nothing open. + */ +export function makeGridApp(ids: string[] = ['s-a', 's-b', 's-c']): GridApp { + const app = Object.create(CodemanApp.prototype) as GridApp; + app.sessions = new Map( + [...ids, 's-other'].map((id) => [id, { id, name: id, mode: 'claude', pid: 1, workingDir: '/w' }]) + ); + app.sessionOrder = ['s-other', ...ids]; + app.detachedSessions = new Set(); + app.isSoloWindow = false; + app.activeSessionId = ids[0]; + app._selectGeneration = 0; + app._xtermSnapshots = new Map(); + app.terminalBufferCache = new Map(); + app._pendingDeliveries = new Map(); + app._closingSessions = new Set(); + app.pendingHooks = new Map(); + app.terminal = { writeln: vi.fn(), clear: vi.fn(), focus: vi.fn(), options: { fontSize: 14 } }; + for (const name of STUBS) app[name] = vi.fn(); + app.loadAppSettingsFromStorage = () => ({}); + return app; +} + +/** Resets the shared fake DOM and tile registry between tests. */ +export function resetGridHarness() { + FakeTile.all = []; + // A test's prefers-reduced-motion answer (window.matchMedia) goes with it. + delete windowStub.matchMedia; + focusedEl = null; + idleCallbacks.length = 0; + rafCallbacks.length = 0; + localStore.clear(); + windowStub.innerWidth = 2400; + // The CLI catalog the server injects (labels for the harness logos); a test sets its own. + delete windowStub.__codemanCliCatalog; + section.children = []; + main.className = 'main'; + // A split a test left open moved .terminal-wrap into its container, with + // Pane A's header strip in it. + main.children = []; + wrap.children = []; + main.appendChild(wrap); + main.appendChild(section); + bySelector.clear(); + body.children = []; +} diff --git a/test/routes/session-routes.test.ts b/test/routes/session-routes.test.ts index 11b1e755..8db8703b 100644 --- a/test/routes/session-routes.test.ts +++ b/test/routes/session-routes.test.ts @@ -1037,6 +1037,62 @@ describe('session-routes', () => { expect(body.data.terminalBuffer.endsWith(`${newestMarker}${cursorRestore}`)).toBe(true); }); + it('`lines=` bounds the history a full capture reads, clamped to the configured limit', async () => { + // Grid tiles send it (TerminalTile._historyLinesQuery): without it a full + // capture reads the whole history limit synchronously, and `tail` cuts it + // only afterwards. Absent or malformed, the limit itself, as before. + const limit = (await harness.ctx.getTerminalHistoryConfig()).tmuxHistoryLimit; + harness.ctx._session.mode = 'claude'; + const captureSpy = vi.fn((_name: string, _opts?: { historyLimitLines?: number }) => 'captured frame'); + (harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = captureSpy; + const linesFor = async (query: string) => { + captureSpy.mockClear(); + await harness.app.inject({ method: 'GET', url: `/api/sessions/${harness.ctx._sessionId}/terminal?${query}` }); + return captureSpy.mock.calls[0]?.[1]?.historyLimitLines; + }; + + expect(await linesFor(`full=1&tail=${1024 * 1024}&lines=10040`)).toBe(10040); + expect(await linesFor('full=1&lines=1')).toBe(1); + expect(await linesFor('full=1')).toBe(limit); + expect(await linesFor(`full=1&lines=${limit + 5}`)).toBe(limit); + for (const bad of ['0', '-5', 'abc', '1.5', '', '1e4', '9999999999']) { + expect(await linesFor(`full=1&lines=${bad}`), `lines=${bad}`).toBe(limit); + } + }); + + it('`lines=` leaves a visible-frame capture (no full=1) exactly as it was', async () => { + harness.ctx._session.mode = 'shell'; + const captureSpy = vi.fn(() => 'only the visible frame'); + (harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = captureSpy; + await harness.app.inject({ + method: 'GET', + url: `/api/sessions/${harness.ctx._sessionId}/terminal?tail=${1024 * 1024}&lines=500`, + }); + expect(captureSpy).toHaveBeenCalledWith(harness.ctx._session.muxName, {}); + }); + + it('a capture bounded by `lines=` is still a full capture: rows kept, cursor restore last', async () => { + // Only how much history tmux reads changes. The row-preserving skips key + // on isFullCapture, and the relative cursor move must still end it. + const cursorRestore = '\x1b[3A\r\x1b[2C'; + const capture = `\r\n${['first row', 'second row', 'last row'].join('\r\n')}${cursorRestore}`; + harness.ctx._session.mode = 'claude'; + harness.ctx._session.terminalBuffer = 'byte history that must not be prepended'; + const captureSpy = vi.fn((_name: string, opts?: { fullHistory?: boolean }) => + opts?.fullHistory ? capture : 'only the visible frame' + ); + (harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = captureSpy; + const res = await harness.app.inject({ + method: 'GET', + url: `/api/sessions/${harness.ctx._sessionId}/terminal?full=1&tail=${1024 * 1024}&lines=40`, + }); + const body = JSON.parse(res.body); + expect(body.data.source).toBe('mux-full-history'); + expect(body.data.terminalBuffer.startsWith('\r\nfirst row')).toBe(true); + expect(body.data.terminalBuffer.endsWith(`last row${cursorRestore}`)).toBe(true); + expect(body.data.terminalBuffer).not.toContain('byte history'); + }); + it('full reload (?full=1) returns the tmux capture ALONE — byte history is not duplicated', async () => { // The full-history capture is the rendered form of everything already in // the byte buffer; prepending the byte history would replay the whole diff --git a/test/routes/status-telemetry-routes.test.ts b/test/routes/status-telemetry-routes.test.ts index a126f431..f85b8c69 100644 --- a/test/routes/status-telemetry-routes.test.ts +++ b/test/routes/status-telemetry-routes.test.ts @@ -6,12 +6,14 @@ * skip, per-session change-detection (dedup), rebroadcast on a displayed change, * NO rebroadcast on context-only drift, null-tolerance of Claude's undocumented * fields (the .nullish() schema — the project's recurring .optional()/null trap), - * and 400 on a malformed body. + * and 400 on a malformed body. Also the session's model (`displayModel`) the route + * records off the same payload. */ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js'; import { registerStatusTelemetryRoutes } from '../../src/web/routes/status-telemetry-routes.js'; import { SessionStatusTelemetry } from '../../src/web/sse-events.js'; +import { Session } from '../../src/session.js'; const SID = 'test-session-1'; // default id created by createMockRouteContext @@ -100,3 +102,56 @@ describe('POST /api/status-telemetry', () => { expect(res.statusCode).toBe(400); }); }); + +describe('POST /api/status-telemetry: the session model (displayModel)', () => { + let h: RouteTestHarness; + + beforeEach(async () => { + h = await createRouteTestHarness(registerStatusTelemetryRoutes, { sessionId: SID }); + }); + + const post = (body: unknown) => h.app.inject({ method: 'POST', url: '/api/status-telemetry', payload: body }); + + /** A real claude session in the route's map, so displayModel is the shipped resolver's. */ + function realSession(mode: 'claude' | 'codex', id: string): Session { + const session = new Session({ id, workingDir: '/tmp', mode } as ConstructorParameters[0]); + (h.ctx.sessions as unknown as Map).set(id, session); + return session; + } + + it('records the model the statusline names, from the first render (no rate limits yet)', async () => { + const session = realSession('claude', 'claude-1'); + const changed = vi.fn(); + session.on('displayModelChanged', changed); + const res = await post({ sessionId: 'claude-1', data: { model: { display_name: 'Haiku 4.5' } } }); + expect(res.statusCode).toBe(200); + expect(session.toState().displayModel).toEqual({ model: 'Haiku 4.5', source: 'statusline' }); + expect(changed).toHaveBeenCalledTimes(1); + }); + + it('follows a model switch, and says nothing for an unchanged one', async () => { + const session = realSession('claude', 'claude-2'); + const changed = vi.fn(); + session.on('displayModelChanged', changed); + await post({ sessionId: 'claude-2', data: REAL }); + await post({ sessionId: 'claude-2', data: REAL }); + expect(changed).toHaveBeenCalledTimes(1); + await post({ sessionId: 'claude-2', data: { ...REAL, model: { display_name: 'Sonnet 4.6' } } }); + expect(session.toState().displayModel).toEqual({ model: 'Sonnet 4.6', source: 'statusline' }); + expect(changed).toHaveBeenCalledTimes(2); + }); + + it('keeps a model name with markup as text, and a null name changes nothing', async () => { + const session = realSession('claude', 'claude-3'); + await post({ sessionId: 'claude-3', data: { model: { display_name: 'Opus' } } }); + expect(session.toState().displayModel?.model).toBe('Opus'); + await post({ sessionId: 'claude-3', data: { model: { display_name: null } } }); + expect(session.toState().displayModel?.model).toBe('Opus'); + }); + + it('takes no model from a CLI that has no statusline exporter', async () => { + const session = realSession('codex', 'codex-1'); + await post({ sessionId: 'codex-1', data: { model: { display_name: 'Opus 4.8' } } }); + expect(session.toState().displayModel).toBeUndefined(); + }); +}); diff --git a/test/run-menu-cli-logos.test.ts b/test/run-menu-cli-logos.test.ts new file mode 100644 index 00000000..1013f4b7 --- /dev/null +++ b/test/run-menu-cli-logos.test.ts @@ -0,0 +1,85 @@ +/** + * @fileoverview Static guard for the Run menus' per-CLI logos (styles.css). + * + * Every launch surface (toolbar Run menu, phone overview picker, Custom Endpoint + * rows, model picker) renders ``, and styles.css + * turns that slot into the CLI's logo through a `--run-mode-logo` data URI plus + * one of two paint groups: brand-coloured marks paint as a background image, + * monochrome marks as a mask over the row's text colour. Three ways that breaks + * silently, each pinned here: + * - a new stock CLI lands with no logo rule (its row shows a bare grey dot); + * - a logo rule exists but the id is in neither paint group (the variable is + * set and never painted, so the slot is a blank 15px gap); + * - a later `background:` shorthand on `.run-mode-dot.` (e.g. a skin + * override like the ones the non-og block used to carry) resets + * background-image and wipes the logo. + * + * Port: none (pure static analysis). + */ + +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { STOCK_CLIS } from '../src/config/cli-registry/stock.js'; + +// Comments stripped: they sit between rules and carry commas, which would bleed +// into the selector lists split below. +const styles = readFileSync(resolve('src/web/public/styles.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ''); + +/** Every id a Run menu renders as `.run-mode-dot `: the stock agents, Shell, and web tabs. */ +const RUN_MENU_IDS = [ + ...STOCK_CLIS.filter((cli) => cli.kind === 'agent').map((cli) => cli.id as string), + 'shell', + 'web', +]; + +/** The selector list of the one rule whose body contains `marker`. */ +function groupIds(marker: string): string[] { + const rule = [...styles.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter((m) => m[2].includes(marker)); + expect(rule, `exactly one rule paints via "${marker}"`).toHaveLength(1); + return rule[0][1] + .split(',') + .map((s) => s.trim().match(/^\.run-mode-dot\.([a-z0-9-]+)$/)?.[1]) + .filter((id): id is string => Boolean(id)); +} + +function logoSvg(id: string): string { + const m = styles.match( + new RegExp(`\\.run-mode-dot\\.${id} \\{ --run-mode-logo: url\\("data:image/svg\\+xml,([^"]+)"\\); \\}`) + ); + expect(m, `.run-mode-dot.${id} has a --run-mode-logo rule`).not.toBeNull(); + return decodeURIComponent(m![1]); +} + +describe('Run menu CLI logos', () => { + const colourIds = groupIds('background: var(--run-mode-logo)'); + const maskIds = groupIds('mask: var(--run-mode-logo)'); + + it.each(RUN_MENU_IDS)('%s has a logo that one paint group draws', (id) => { + const svg = logoSvg(id); + expect(svg.startsWith(' { + expect([...colourIds, ...maskIds].sort()).toEqual([...RUN_MENU_IDS].sort()); + }); + + it('carries no script or event handler inside a data URI', () => { + for (const id of RUN_MENU_IDS) { + const svg = logoSvg(id); + expect(svg).not.toMatch(/ { + const offenders = [...styles.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter( + ([, selector, body]) => + /\.run-mode-dot\.[a-z]/.test(selector) && + /(^|[;\s])background\s*:/.test(body) && + !body.includes('var(--run-mode-logo)') + ); + expect(offenders.map((m) => m[1].trim())).toEqual([]); + }); +}); diff --git a/test/session-config-model.test.ts b/test/session-config-model.test.ts new file mode 100644 index 00000000..78159340 --- /dev/null +++ b/test/session-config-model.test.ts @@ -0,0 +1,180 @@ +/** + * The config source of a session's `displayModel`: the model its CLI's own config pins + * (`capabilities.modelDetect.configResolver`), read at each pane start, attach or + * relaunch, ranked below any report from the running CLI. + * + * The reader is mocked here so the session's own rules are what is tested: when it + * reads, with what, and which answer wins. The reader itself (dsh-TUI's route) is + * `test/deepseek-route-config.test.ts`; one end-to-end read over a fixture dsh home + * is in `test/session-display-model.test.ts`. + * + * Port: N/A. + */ +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'; + +const resolveConfigModel = vi.fn(); +vi.mock('../src/model-config-resolvers.js', () => ({ + resolveConfigModel: (...a: unknown[]) => resolveConfigModel(...a), +})); + +const { Session } = await import('../src/session.js'); + +type Internals = { + _withPaneLifecycle(op: () => Promise): Promise; + _isStopped: boolean; +}; + +/** A deferred answer, so a test decides when (and in which order) reads land. */ +function deferred() { + let resolve!: (v: string | null) => void; + const promise = new Promise((r) => (resolve = r)); + return { promise, resolve }; +} + +function session(extra: Record = {}, mode = 'deepseek') { + return new Session({ workingDir: '/tmp', mode, ...extra } as ConstructorParameters[0]); +} +/** One pane start: what triggers the read. */ +const start = (s: InstanceType) => (s as unknown as Internals)._withPaneLifecycle(async () => {}); +const flush = () => new Promise((r) => setTimeout(r, 0)); + +beforeEach(() => { + resolveConfigModel.mockReset(); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("a session's config model", () => { + it("is read at each pane start, with the session's own config and env", async () => { + resolveConfigModel.mockResolvedValue('qwen3.8-27b'); + // The server has a dsh home of its own; the session's override is the one its CLI gets. + const before = process.env.DSH_HOME; + process.env.DSH_HOME = '/srv/server-dsh'; + onTestFinished(() => { + if (before === undefined) delete process.env.DSH_HOME; + else process.env.DSH_HOME = before; + }); + const s = session({ deepSeekConfig: { profile: 'dsh-tui' }, envOverrides: { DSH_HOME: '/srv/dsh-copy' } }); + const changed = vi.fn(); + s.on('displayModelChanged', changed); + expect(resolveConfigModel).not.toHaveBeenCalled(); + await start(s); + await flush(); + expect(resolveConfigModel).toHaveBeenCalledTimes(1); + const [name, ctx] = resolveConfigModel.mock.calls[0]; + expect(name).toBe('deepseek-route'); + expect(ctx.config).toEqual({ profile: 'dsh-tui' }); + expect(ctx.env('DSH_HOME')).toBe('/srv/dsh-copy'); + expect(s.toState().displayModel).toEqual({ model: 'qwen3.8-27b', source: 'config' }); + expect(changed).toHaveBeenCalledTimes(1); + // A relaunch reads again; the same answer announces nothing new. + await start(s); + await flush(); + expect(resolveConfigModel).toHaveBeenCalledTimes(2); + expect(changed).toHaveBeenCalledTimes(1); + }); + + it('without a session DSH_HOME the server one is what the CLI inherits', async () => { + resolveConfigModel.mockResolvedValue(null); + const before = process.env.DSH_HOME; + process.env.DSH_HOME = '/srv/server-dsh'; + try { + const s = session(); + await start(s); + expect(resolveConfigModel.mock.calls[0][1].env('DSH_HOME')).toBe('/srv/server-dsh'); + } finally { + if (before === undefined) delete process.env.DSH_HOME; + else process.env.DSH_HOME = before; + } + }); + + it('the screen wins over the config whenever it names a model, in either order', async () => { + resolveConfigModel.mockResolvedValue('qwen3.8-27b'); + const s = session(); + await start(s); + await flush(); + s.noteReportedModel('screen', 'deepseek-v4-flash'); + expect(s.toState().displayModel).toEqual({ model: 'deepseek-v4-flash', source: 'screen' }); + await start(s); + await flush(); + expect(s.toState().displayModel).toEqual({ model: 'deepseek-v4-flash', source: 'screen' }); + }); + + it('a screen value restored after a restart outranks a fresh config read', async () => { + resolveConfigModel.mockResolvedValue('qwen3.8-27b'); + const s = session({ displayModel: { model: 'deepseek-v4-flash', source: 'screen' } }); + await start(s); + await flush(); + expect(s.toState().displayModel).toEqual({ model: 'deepseek-v4-flash', source: 'screen' }); + }); + + it('the config outranks the launch model, and a config that pins nothing leaves it', async () => { + resolveConfigModel.mockResolvedValue('qwen-from-config'); + const codex = session({ codexConfig: { model: 'gpt-5.5' } }, 'codex'); + await start(codex); + await flush(); + // codex declares no config reader: nothing is read, the launch model stays. + expect(resolveConfigModel).not.toHaveBeenCalled(); + expect(codex.toState().displayModel).toEqual({ model: 'gpt-5.5', source: 'launch' }); + resolveConfigModel.mockResolvedValue(null); + const s = session(); + await start(s); + await flush(); + expect(s.toState().displayModel).toBeUndefined(); + }); + + it('a read that lands after a newer one is dropped, and so is one after the session stopped', async () => { + const first = deferred(); + const second = deferred(); + resolveConfigModel.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise); + const s = session(); + await start(s); + await start(s); + second.resolve('newer'); + await flush(); + first.resolve('older'); + await flush(); + expect(s.toState().displayModel?.model).toBe('newer'); + + const late = deferred(); + resolveConfigModel.mockReturnValueOnce(late.promise); + const stopped = session(); + await start(stopped); + (stopped as unknown as Internals)._isStopped = true; + late.resolve('too late'); + await flush(); + expect(stopped.toState().displayModel).toBeUndefined(); + }); + + it('a remote or docker session reads nothing locally', async () => { + resolveConfigModel.mockResolvedValue('qwen3.8-27b'); + await start(session({ remote: { hostId: 'h', label: 'h', host: 'h', username: 'u', remotePath: '/w' } })); + await start( + session({ + docker: { + hostId: 'd', + label: 'd', + engine: 'docker', + image: 'i', + containerName: 'c', + hostWorkspacePath: '/w', + containerWorkdir: '/w', + }, + }) + ); + await flush(); + expect(resolveConfigModel).not.toHaveBeenCalled(); + }); + + it('a config model is untrusted text: control characters dropped, length capped', async () => { + resolveConfigModel.mockResolvedValue(`\x1b[31mqwen\x1b[0m${'x'.repeat(200)}`); + const s = session(); + await start(s); + await flush(); + const dm = s.toState().displayModel!; + expect(dm.source).toBe('config'); + expect(dm.model.startsWith('qwenx')).toBe(true); + expect(dm.model.length).toBe(64); + }); +}); diff --git a/test/session-display-model.test.ts b/test/session-display-model.test.ts new file mode 100644 index 00000000..d40a8b09 --- /dev/null +++ b/test/session-display-model.test.ts @@ -0,0 +1,454 @@ +/** + * Which model a session runs (`SessionState.displayModel`), for the tile grid's and the + * split pane's headers: the pure resolver, the screen read with each CLI's registry + * pattern, and the session that feeds them. + * + * The pane fixtures are verbatim `capture-pane -p` rows (trailing blanks trimmed) from + * live panes on 2026-10-07: dsh-TUI 0.10.0-beta.1 on the owner's qwen route, and codex + * 0.147.0. The codex 0.154.0 footer is the one `session-watching.test.ts` pins. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { Session } from '../src/session.js'; +import { getCli } from '../src/config/cli-registry/index.js'; +import { compileVersionRegex, countCaptureGroups } from '../src/config/cli-registry/patterns.js'; +import { CliEntrySchema } from '../src/config/cli-registry/schema.js'; +import { + MAX_DISPLAY_MODEL_CHARS, + launchModelFor, + readScreenModel, + resolveDisplayModel, + restoredReportedModel, + sanitizeModelName, +} from '../src/session-display-model.js'; +import { IDLE_SILENCE_MS } from '../src/session-activity.js'; + +const detectOf = (mode: string) => getCli(mode)!.capabilities.modelDetect!; +const DSH = compileVersionRegex(detectOf('deepseek').screenLine)!; +const DSH_ROWS = detectOf('deepseek').screenLines; +const DSH_REJECT = detectOf('deepseek').rejectWords; +const CODEX = compileVersionRegex(detectOf('codex').screenLine)!; +const CODEX_ROWS = detectOf('codex').screenLines; + +const DSH_BORDER_TOP = '╭' + '─'.repeat(95) + '╮'; +const DSH_BORDER_BOTTOM = '╰' + '─'.repeat(95) + '╯'; +const DSH_COMPOSER = '❯' + ' '.repeat(95) + '⛶'; +/** The foot of a dsh-TUI pane: transcript, the composer's rounded box, the status line. */ +function dshPane(statusLine: string | null, transcript: string[] = []): string { + return [ + ' Tip: Footer compact on = one merged line; off = metric…', + ' Explore the uncharted!', + ' ▶ (Ctrl+P to expand) Context loaded · System prompt 16 sections · Runtime context 2 items · …', + ...transcript, + DSH_BORDER_TOP, + DSH_COMPOSER, + DSH_BORDER_BOTTOM, + ...(statusLine === null ? [] : [statusLine]), + '', + ].join('\n'); +} +const DSH_LIVE = dshPane(' qwen3.8-27b · medium · th-scratch'); + +/** The foot of a codex pane: transcript, composer, then the status line on the last row. */ +function codexPane(statusLine: string | null, transcript: string[] = []): string { + return [ + '│ directory: ~/codeman-cases/th-scratch │', + '│ permissions: YOLO mode │', + '╰───────────────────────────────────────────────╯', + ' Tip: New For a limited time, Codex is included in your', + ' plan for free – let’s build together.', + ...transcript, + '› Explain this codebase', + ...(statusLine === null ? [] : [statusLine]), + '', + ].join('\n'); +} +const CODEX_LIVE = codexPane(' gpt-5.6-terra default · ~/codeman-cases/th-scratch'); +const CODEX_154 = codexPane( + ' gpt-5.6-sol medium · Context 98% left · ~/codeman-cases/codex-probe · 5h 99% left · weekly 94% left' +); + +describe('the registry patterns', () => { + it('compile through compileVersionRegex() with exactly one capture group', () => { + for (const mode of ['deepseek', 'codex']) { + const { screenLine } = detectOf(mode); + expect(compileVersionRegex(screenLine), mode).not.toBeNull(); + expect(countCaptureGroups(screenLine), mode).toBe(1); + } + }); + + it('are declared only where a footer was measured (claude reports through its statusline)', () => { + expect(getCli('claude')!.capabilities.modelDetect).toBeUndefined(); + expect(getCli('shell')!.capabilities.modelDetect).toBeUndefined(); + }); + + it('the schema refuses a pattern with no capture group, two of them, or one it will not run', () => { + const codex = getCli('codex')!; + const withDetect = (modelDetect: unknown) => + CliEntrySchema.safeParse({ ...codex, capabilities: { ...codex.capabilities, modelDetect } }).success; + expect(withDetect({ screenLine: '^ {2}([a-z]+) · ' })).toBe(true); + expect(withDetect({ screenLine: '^ {2}[a-z]+ · ' })).toBe(false); + expect(withDetect({ screenLine: '^ {2}([a-z]+) (high) · ' })).toBe(false); + expect(withDetect({ screenLine: '(a+)+$' })).toBe(false); + expect(withDetect({ screenLine: '^(x)', screenLines: 9 })).toBe(false); + }); + + it("dsh declares what its footer's first field can be when it is not the model", () => { + // Every effort id dsh's adapters offer, and the shipped mode ids. + expect(DSH_REJECT).toEqual( + expect.arrayContaining(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'default', 'plan', 'full']) + ); + expect(detectOf('codex').rejectWords).toBeUndefined(); + }); + + it('the schema takes single-token reject words with a screenLine only, and bounds them', () => { + const codex = getCli('codex')!; + const withDetect = (modelDetect: unknown) => + CliEntrySchema.safeParse({ ...codex, capabilities: { ...codex.capabilities, modelDetect } }).success; + const screenLine = '^ {2}([a-z]+) · '; + expect(withDetect({ screenLine, rejectWords: ['medium'] })).toBe(true); + expect(withDetect({ configResolver: 'deepseek-route', rejectWords: ['medium'] })).toBe(false); + expect(withDetect({ screenLine, rejectWords: ['two words'] })).toBe(false); + expect(withDetect({ screenLine, rejectWords: Array.from({ length: 33 }, (_, i) => `w${i}`) })).toBe(false); + }); + + it('dsh also names a config reader for while its screen names no model', () => { + expect(detectOf('deepseek').configResolver).toBe('deepseek-route'); + expect(detectOf('codex').configResolver).toBeUndefined(); + }); + + it('the schema takes a known config reader alone, and refuses an empty or unknown one', () => { + const codex = getCli('codex')!; + const withDetect = (modelDetect: unknown) => + CliEntrySchema.safeParse({ ...codex, capabilities: { ...codex.capabilities, modelDetect } }).success; + expect(withDetect({ configResolver: 'deepseek-route' })).toBe(true); + expect(withDetect({ configResolver: 'read-anything' })).toBe(false); + expect(withDetect({})).toBe(false); + expect(withDetect({ configResolver: 'deepseek-route', screenLines: 2 })).toBe(false); + }); + + it('countCaptureGroups counts named groups and ignores non-capturing ones', () => { + expect(countCaptureGroups('a(?:b)(?c)')).toBe(1); + expect(countCaptureGroups('(a)(b)')).toBe(2); + expect(countCaptureGroups('abc')).toBe(0); + expect(countCaptureGroups('(')).toBe(-1); + }); +}); + +describe('readScreenModel', () => { + it("reads dsh's model off the row under its composer", () => { + expect(readScreenModel(DSH_LIVE, DSH, DSH_ROWS)).toBe('qwen3.8-27b'); + // A footer with the model alone, and one with a row below it (the activity line). + expect(readScreenModel(dshPane(' deepseek-v4-flash'), DSH, DSH_ROWS)).toBe('deepseek-v4-flash'); + expect(readScreenModel(dshPane(' qwen3.8-27b · medium · th-scratch') + ' ⠋ Thinking… 3s\n', DSH, DSH_ROWS)).toBe( + 'qwen3.8-27b' + ); + }); + + it("never reads the field after a switched-off model as the model (dsh's effort, mode, folder)", () => { + // dsh-TUI with `statusBar.model: false` (live capture: ` medium · th-config`): the + // effort id comes first, then the mode, then the folder name. + const at = (cwdBasename: string) => ({ rejectWords: DSH_REJECT, cwdBasename }); + for (const effort of ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']) { + expect(readScreenModel(dshPane(` ${effort} · x`), DSH, DSH_ROWS, at('x')), effort).toBeUndefined(); + } + expect(readScreenModel(dshPane(' default · x'), DSH, DSH_ROWS, at('x'))).toBeUndefined(); + // The words compare ignoring case (the banner capitalizes effort; the footer does not). + expect(readScreenModel(dshPane(' Medium · x'), DSH, DSH_ROWS, at('x'))).toBeUndefined(); + // A mode's drawn label is two words: never one field the pattern takes. + expect(readScreenModel(dshPane(' plan mode · x'), DSH, DSH_ROWS, at('x'))).toBeUndefined(); + // The session's own folder name first, with and without a digit. + expect(readScreenModel(dshPane(' th-config'), DSH, DSH_ROWS, at('th-config'))).toBeUndefined(); + expect(readScreenModel(dshPane(' project2 · main'), DSH, DSH_ROWS, at('project2'))).toBeUndefined(); + // A field that is none of those IS read: the same `project2` in another folder. + expect(readScreenModel(dshPane(' project2'), DSH, DSH_ROWS, at('elsewhere'))).toBe('project2'); + }); + + it('reads the official DeepSeek ids, which carry no digit, with the model field on', () => { + const at = { rejectWords: DSH_REJECT, cwdBasename: 'th-config' }; + expect(readScreenModel(dshPane(' deepseek-chat · max · th-config'), DSH, DSH_ROWS, at)).toBe('deepseek-chat'); + expect(readScreenModel(dshPane(' deepseek-reasoner · high · th-config'), DSH, DSH_ROWS, at)).toBe( + 'deepseek-reasoner' + ); + // The live qwen footer still reads. + expect(readScreenModel(dshPane(' qwen3.8-27b · medium · th-scratch'), DSH, DSH_ROWS, at)).toBe('qwen3.8-27b'); + }); + + it("reads codex's model off its status line (0.147.0 and 0.154.0 layouts)", () => { + expect(readScreenModel(CODEX_LIVE, CODEX, CODEX_ROWS)).toBe('gpt-5.6-terra'); + expect(readScreenModel(CODEX_154, CODEX, CODEX_ROWS)).toBe('gpt-5.6-sol'); + }); + + it('never takes a transcript line shaped like the footer', () => { + // The agent printed a line exactly like each CLI's footer, and the real footer is + // hidden (a dsh status bar switched off; a codex popup over its last row). The + // transcript sits above the composer, so neither may be read as the model. + const dshForged = dshPane(null, [DSH_BORDER_BOTTOM, ' evil-model · medium · th-scratch']); + expect(readScreenModel(dshForged, DSH, DSH_ROWS)).toBeUndefined(); + const codexForged = codexPane(null, [' evil-model high · ~/codeman-cases/th-scratch']); + // A codex screen whose last row is the composer: nothing to read. + expect(readScreenModel(codexForged, CODEX, CODEX_ROWS)).toBeUndefined(); + // With the real footer back, the real model wins over the forged line above it. + const dshBoth = dshPane(' qwen3.8-27b · medium · th-scratch', [ + DSH_BORDER_BOTTOM, + ' evil-model · medium · th-scratch', + ]); + expect(readScreenModel(dshBoth, DSH, DSH_ROWS)).toBe('qwen3.8-27b'); + const codexBoth = codexPane(' gpt-5.6-terra default · ~/codeman-cases/th-scratch', [ + ' evil-model high · ~/codeman-cases/th-scratch', + ]); + expect(readScreenModel(codexBoth, CODEX, CODEX_ROWS)).toBe('gpt-5.6-terra'); + }); + + it('does not read a popup under the composer as a model', () => { + const slash = dshPane(' /model Switch the model route'); + expect(readScreenModel(slash, DSH, DSH_ROWS)).toBeUndefined(); + const codexSlash = codexPane(' /model choose what model and reasoning effort to use'); + expect(readScreenModel(codexSlash, CODEX, CODEX_ROWS)).toBeUndefined(); + // A last row without codex's ` ·` shape names no model, even one + // whose first word could pass for a model id. + const codexNoModel = codexPane(' default · ~/codeman-cases/th-scratch'); + expect(readScreenModel(codexNoModel, CODEX, CODEX_ROWS)).toBeUndefined(); + }); + + it('says nothing about an empty or unreadable frame', () => { + expect(readScreenModel('', DSH, DSH_ROWS)).toBeUndefined(); + expect(readScreenModel(null, CODEX, CODEX_ROWS)).toBeUndefined(); + }); +}); + +describe('sanitizeModelName', () => { + it('keeps markup as text: sanitizing is not escaping, the browser renders text', () => { + expect(sanitizeModelName('')).toBe(''); + }); + + it('drops escape sequences and control characters, and collapses whitespace', () => { + expect(sanitizeModelName('\x1b[31mOpus\x1b[0m\t 4.8‮\n')).toBe('Opus 4.8'); + expect(sanitizeModelName('\x00\x07')).toBeUndefined(); + expect(sanitizeModelName(' ')).toBeUndefined(); + expect(sanitizeModelName(42)).toBeUndefined(); + }); + + it(`caps the name at ${MAX_DISPLAY_MODEL_CHARS} characters`, () => { + expect(sanitizeModelName('m'.repeat(500))).toHaveLength(MAX_DISPLAY_MODEL_CHARS); + }); +}); + +describe('resolveDisplayModel', () => { + const reported = { model: 'Sonnet 4.6', source: 'statusline' as const }; + + it('the custom endpoint wins, then the newest report, then the launch model', () => { + expect(resolveDisplayModel({ customModelId: 'qwen3.8-27b', reported, launchModel: 'opus' })).toEqual({ + model: 'qwen3.8-27b', + source: 'custom-endpoint', + }); + expect(resolveDisplayModel({ reported, launchModel: 'opus' })).toEqual(reported); + expect(resolveDisplayModel({ launchModel: 'opus' })).toEqual({ model: 'opus', source: 'launch' }); + }); + + it("the config ranks below the CLI's own report and above the launch model", () => { + expect(resolveDisplayModel({ reported, configModel: 'qwen3.8-27b', launchModel: 'opus' })).toEqual(reported); + expect(resolveDisplayModel({ configModel: 'qwen3.8-27b', launchModel: 'opus' })).toEqual({ + model: 'qwen3.8-27b', + source: 'config', + }); + expect(resolveDisplayModel({ customModelId: 'm', configModel: 'qwen3.8-27b' })?.source).toBe('custom-endpoint'); + expect(resolveDisplayModel({ configModel: null, launchModel: 'opus' })?.source).toBe('launch'); + }); + + it('knows nothing when nothing is known: no placeholder', () => { + expect(resolveDisplayModel({})).toBeUndefined(); + expect(resolveDisplayModel({ customModelId: ' ', reported: null, launchModel: '' })).toBeUndefined(); + }); +}); + +describe('restoredReportedModel', () => { + it('restores what the CLI reported, never a derived answer', () => { + expect(restoredReportedModel({ model: 'qwen3.8-27b', source: 'screen' })).toEqual({ + model: 'qwen3.8-27b', + source: 'screen', + }); + expect(restoredReportedModel({ model: 'Opus 4.8', source: 'statusline' })?.source).toBe('statusline'); + expect(restoredReportedModel({ model: 'opus', source: 'launch' })).toBeUndefined(); + expect(restoredReportedModel({ model: 'qwen3.8-27b', source: 'config' })).toBeUndefined(); + expect(restoredReportedModel({ model: 'x', source: 'custom-endpoint' })).toBeUndefined(); + expect(restoredReportedModel({ model: '', source: 'screen' })).toBeUndefined(); + expect(restoredReportedModel('screen')).toBeUndefined(); + expect(restoredReportedModel(undefined)).toBeUndefined(); + }); +}); + +describe('launchModelFor', () => { + it("reads the model param where each CLI's registry entry keeps it", () => { + expect(launchModelFor('claude', { model: 'haiku' })).toBe('haiku'); + expect(launchModelFor('codex', { codexConfig: { model: 'gpt-5.5' } })).toBe('gpt-5.5'); + expect(launchModelFor('grok', { grokConfig: { model: 'grok-code-fast' } })).toBe('grok-code-fast'); + // Another CLI's config, or a top-level model, is not this CLI's launch model. + expect(launchModelFor('codex', { model: 'opus', grokConfig: { model: 'x' } })).toBeUndefined(); + }); + + it('has none for a CLI whose model is not a launch param', () => { + expect(launchModelFor('deepseek', { model: 'opus', deepSeekConfig: { profile: 'dsh-tui' } })).toBeUndefined(); + expect(launchModelFor('shell', { model: 'opus' })).toBeUndefined(); + expect(launchModelFor('no-such-cli', { model: 'opus' })).toBeUndefined(); + }); +}); + +describe('a session', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + type Internals = { + _handleTerminalOutput(data: string): void; + _detectInteractiveActivity(data: string): void; + _customModel?: { endpointId: string; modelId: string; envKeys: string[] }; + }; + + function withFakePane(mode: string, screen: () => string | null, extra: Record = {}): Session { + const mux = { isAvailable: () => true, capturePaneText: () => screen() } as unknown as NonNullable< + ConstructorParameters[0] + >['mux']; + return new Session({ + workingDir: '/tmp', + mode, + mux, + muxSession: { muxName: 'codeman-test', sessionId: 'test', createdAt: Date.now() }, + ...extra, + } as ConstructorParameters[0]); + } + + /** A composer repaint (arms the idle confirmation), then quiet: the probe reads the screen. */ + function settle(session: Session, glyph: string): void { + const internals = session as unknown as Internals; + for (let i = 0; i < 3; i++) { + const frame = `\x1b[31;1H${glyph}\xa0`; + internals._handleTerminalOutput(frame); + internals._detectInteractiveActivity(frame); + vi.advanceTimersByTime(1000); + } + vi.advanceTimersByTime(IDLE_SILENCE_MS + 2000); + } + + it('publishes the model its footer names, and follows the footer when it changes', () => { + vi.useFakeTimers(); + let screen = DSH_LIVE; + const session = withFakePane('deepseek', () => screen); + const changed = vi.fn(); + session.on('displayModelChanged', changed); + expect(session.toState().displayModel).toBeUndefined(); + settle(session, '❯'); + expect(session.toState().displayModel).toEqual({ model: 'qwen3.8-27b', source: 'screen' }); + expect(changed).toHaveBeenCalledTimes(1); + // The same footer again: nothing new to say. + settle(session, '❯'); + expect(changed).toHaveBeenCalledTimes(1); + // An in-session switch redraws the footer. + screen = dshPane(' deepseek-v4-flash · high · th-scratch'); + settle(session, '❯'); + expect(session.toState().displayModel).toEqual({ model: 'deepseek-v4-flash', source: 'screen' }); + expect(changed).toHaveBeenCalledTimes(2); + }); + + it("a footer field equal to the session's folder is not its model; the official ids are", () => { + vi.useFakeTimers(); + let screen = dshPane(' th-config'); + const session = withFakePane('deepseek', () => screen, { workingDir: '/w/th-config' }); + settle(session, '❯'); + expect(session.toState().displayModel).toBeUndefined(); + screen = dshPane(' medium · th-config'); + settle(session, '❯'); + expect(session.toState().displayModel).toBeUndefined(); + screen = dshPane(' deepseek-chat · max · th-config'); + settle(session, '❯'); + expect(session.toState().displayModel).toEqual({ model: 'deepseek-chat', source: 'screen' }); + }); + + it('keeps the last model when the footer cannot be read', () => { + vi.useFakeTimers(); + let screen: string | null = CODEX_LIVE; + const session = withFakePane('codex', () => screen); + settle(session, '›'); + expect(session.toState().displayModel?.model).toBe('gpt-5.6-terra'); + screen = codexPane(' /model choose what model and reasoning effort to use'); + settle(session, '›'); + screen = null; + settle(session, '›'); + expect(session.toState().displayModel).toEqual({ model: 'gpt-5.6-terra', source: 'screen' }); + }); + + it('a CLI without a footer pattern never reads one (a claude pane says nothing)', () => { + vi.useFakeTimers(); + const session = withFakePane('claude', () => '❯ \n Haiku 4.5 in:0 out:0\n'); + settle(session, '❯'); + expect(session.toState().displayModel).toBeUndefined(); + }); + + it('shows the launch model until the CLI reports, and a custom endpoint over both', () => { + const session = withFakePane('claude', () => null, { model: 'haiku' }); + expect(session.toState().displayModel).toEqual({ model: 'haiku', source: 'launch' }); + expect(session.noteReportedModel('statusline', 'Haiku 4.5')).toBe(true); + expect(session.toState().displayModel).toEqual({ model: 'Haiku 4.5', source: 'statusline' }); + expect(session.noteReportedModel('statusline', 'Haiku 4.5')).toBe(false); + expect(session.noteReportedModel('statusline', '')).toBe(false); + (session as unknown as Internals)._customModel = { endpointId: 'e', modelId: 'qwen3.8-27b', envKeys: [] }; + expect(session.toState().displayModel).toEqual({ model: 'qwen3.8-27b', source: 'custom-endpoint' }); + (session as unknown as Internals)._customModel = undefined; + expect(session.toState().displayModel?.model).toBe('Haiku 4.5'); + }); + + it("an external CLI's launch model is its own config's, never the inert top-level one", () => { + const codex = withFakePane('codex', () => null, { model: 'opus', codexConfig: { model: 'gpt-5.5' } }); + expect(codex.toState().displayModel).toEqual({ model: 'gpt-5.5', source: 'launch' }); + const dsh = withFakePane('deepseek', () => null, { model: 'opus', deepSeekConfig: { profile: 'dsh-tui' } }); + expect(dsh.toState().displayModel).toBeUndefined(); + }); + + it('restores a reported model after a restart, until the next report replaces it', () => { + const session = withFakePane('deepseek', () => null, { + displayModel: { model: 'qwen3.8-27b', source: 'screen' }, + }); + expect(session.toState().displayModel).toEqual({ model: 'qwen3.8-27b', source: 'screen' }); + session.noteReportedModel('screen', 'deepseek-v4-flash'); + expect(session.toState().displayModel?.model).toBe('deepseek-v4-flash'); + // A launch answer from the previous run is derived again, not restored. + const claude = withFakePane('claude', () => null, { displayModel: { model: 'opus', source: 'launch' } }); + expect(claude.toState().displayModel).toBeUndefined(); + }); +}); + +describe('a dsh session over a fixture dsh home (end to end, no mocks)', () => { + it('names the route its profile pins until the screen names one, then the screen', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-e2e-')); + try { + const home = join(root, 'dsh'); + mkdirSync(join(home, 'profiles', 'dsh-tui'), { recursive: true }); + writeFileSync( + join(home, 'profiles', 'dsh-tui', 'package.json'), + JSON.stringify({ dsh: { profile: { bundles: ['@deepseek-ai/dsh-base', '@deepseek-harness-tui/dsh-tui'] } } }) + ); + writeFileSync( + join(home, 'profiles', 'dsh-tui', 'cordis.patch.yml'), + '- id: dsh-tui\n config:\n provider: qwen5090\n model: qwen3.8-27b\n' + ); + const session = new Session({ + workingDir: '/tmp', + mode: 'deepseek', + deepSeekConfig: { profile: 'dsh-tui' }, + envOverrides: { DSH_HOME: home }, + } as ConstructorParameters[0]); + await (session as unknown as { _withPaneLifecycle(op: () => Promise): Promise })._withPaneLifecycle( + async () => {} + ); + await vi.waitFor(() => + expect(session.toState().displayModel).toEqual({ model: 'qwen3.8-27b', source: 'config' }) + ); + session.noteReportedModel('screen', 'deepseek-v4-flash'); + expect(session.toState().displayModel).toEqual({ model: 'deepseek-v4-flash', source: 'screen' }); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/session-listener-wiring.test.ts b/test/session-listener-wiring.test.ts index 3345c25d..cc54ff00 100644 --- a/test/session-listener-wiring.test.ts +++ b/test/session-listener-wiring.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it, vi } from 'vitest'; import { Session } from '../src/session.js'; -import { createSessionListeners } from '../src/web/session-listener-wiring.js'; +import { + attachSessionListeners, + createSessionListeners, + detachSessionListeners, +} from '../src/web/session-listener-wiring.js'; import { SseEvent } from '../src/web/sse-events.js'; describe('session listener wiring', () => { @@ -37,6 +41,27 @@ describe('session listener wiring', () => { expect(broadcastSessionStateDebounced).toHaveBeenCalledWith('wiring-watching-test'); }); + it('pushes and persists the session state when the reported model changes', () => { + // A model switch changes nothing the status reflects, so without its own broadcast + // every header would keep naming the old model; persisting it is what lets a restart + // restore it. + const session = new Session({ id: 'wiring-model-test', workingDir: '/tmp', mode: 'claude' }); + const broadcastSessionStateDebounced = vi.fn(); + const persistSessionState = vi.fn(); + const deps = { broadcastSessionStateDebounced, persistSessionState } as unknown as Parameters< + typeof createSessionListeners + >[1]; + + const refs = createSessionListeners(session, deps); + attachSessionListeners(session, refs); + session.noteReportedModel('statusline', 'Sonnet 4.6'); + + expect(broadcastSessionStateDebounced).toHaveBeenCalledWith('wiring-model-test'); + expect(persistSessionState).toHaveBeenCalledWith(session); + detachSessionListeners(session, refs); + expect(session.listenerCount('displayModelChanged')).toBe(0); + }); + /** The listener reads the setting asynchronously; let its promise chain settle. */ const flush = () => new Promise((resolve) => setTimeout(resolve, 5)); diff --git a/test/session-pane-exit-ui.test.ts b/test/session-pane-exit-ui.test.ts index cd7ffeb1..b673f052 100644 --- a/test/session-pane-exit-ui.test.ts +++ b/test/session-pane-exit-ui.test.ts @@ -92,10 +92,27 @@ describe('the exited-agent badge in a tab', () => { expect(tab.querySelector('.tab-name')?.nextElementSibling?.className).toBe('tab-exited-badge'); }); - it('marks the badge data-i18n-skip, like the other generated status text', () => { + it('leaves the badge to the translator (zh-CN) and remembers its English', () => { const tab = makeTab(); applyPaneExitBadge(tab, { status: 0, at: 1 }); - expect(badge(tab)?.hasAttribute('data-i18n-skip')).toBe(true); + expect(badge(tab)?.hasAttribute('data-i18n-skip')).toBe(false); + expect((badge(tab) as unknown as HTMLElement).dataset.label).toBe('exited (0)'); + }); + + it('a translated badge and accessible name survive an unchanged pass; a change writes the new English', () => { + // The translator rewrites both in zh-CN. Comparing with the DOM would write + // the English back on every incremental pass for it to translate again. + const tab = makeTab(); + applyPaneExitBadge(tab, { status: 3, at: 1 }); + const el = badge(tab) as unknown as HTMLElement; + el.textContent = '已退出(3)'; + tab.setAttribute('aria-label', 'w1-case 会话,智能体已退出(3)'); + applyPaneExitBadge(tab, { status: 3, at: 1 }); + expect(el.textContent).toBe('已退出(3)'); + expect(tab.getAttribute('aria-label')).toBe('w1-case 会话,智能体已退出(3)'); + applyPaneExitBadge(tab, { signal: 9, at: 2 }); + expect(el.textContent).toBe('exited (signal 9)'); + expect(tab.getAttribute('aria-label')).toBe('w1-case session, agent exited (signal 9)'); }); it('hides the badge from assistive technology, like its sibling badges', () => { @@ -115,8 +132,12 @@ describe('the exited-agent badge in a tab', () => { }); it('builds the full render path accessible name from the same helper', () => { - expect(appJs).toContain('aria-label="${escapeHtml(paneExitAriaLabel(name, paneExitBadge))}"'); - expect(appJs).toContain('