mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-09 08:59:40 +02:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
310f20b288 | ||
|
|
55cafc282f | ||
|
|
bb5fd5ee97 | ||
|
|
bebf0db792 | ||
|
|
e3dfbf6591 | ||
|
|
9b0d305223 |
@@ -274,9 +274,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph--pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit)
|
||||
|
||||
**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)
|
||||
**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 (`SplitTerminalPane._pullHistory`, terminal-split.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 its own `SplitTerminalPane` (terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Deliberately plainer than the primary pane — no local-echo overlay, CJK IME, or touch handlers — and NOT persisted across reloads. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions)
|
||||
|
||||
**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 +325,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-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.
|
||||
|
||||
**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 `<html>`; 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)
|
||||
|
||||
@@ -333,6 +333,10 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Session list layout: header strip or left sidebar** (`sessionListLayout`, default `header`; per-device via `displayKeys`, also in `SettingsUpdateSchema`): the list can move into a collapsible `<aside>` (Alt+B, `toggleSessionSidebar`) or, via `tabOrientation`, a resizable vertical `#tabRail` (desktop/tablet only). ⚠️ There is ONE `#sessionTabs`, MOVED between hosts, never a second list: `applySessionListLayout()` runs first, then `applyTabOrientation()`, both BEFORE `applyTabWrapSettings()`, and both arm/disarm `_startSidebarRichClock()`. ⚠️ Axis decisions use `_isVerticalTabList()`, never `isSessionSidebarActive()` alone. ⚠️ Rich rows share one gate, `isRichTabRows()`; rich CSS pairs sidebar+rail with comma-grouped selectors, never `:is()`, and card rules stay rail-scoped. ⚠️ Rail sort (`tabRailSort`, default `activity`) is the flex `order` property only, never a DOM reorder; the arrow-key walk alone follows computed `order`. ⚠️ Leaving sidebar mode clears `_sidebarFilter`; the handheld overlay drawer is `inert` when closed, the docked rail never. → [architecture-invariants#session-list-layout-header-strip-vs-left-sidebar](docs/architecture-invariants.md#session-list-layout-header-strip-vs-left-sidebar)
|
||||
|
||||
**Tab layouts** (`tabArrangement`, per-device, default `state`; Discussion #426): `state` (option C) splits the list into needs you / waiting / working / idle (idle is `quiet`: its heading stays as the row's anchor but draws no label; `tabStateOrder: 'urgent-last'` flips the order, needs you at the bottom): rows in the desktop header strip with left-aligned labels in a measured column (the brand sits over the strip's corner, so the rows after the first start under "Codeman"), sections in the flat rail and the sidebar, inline dividers on the tablet strip, group order with no headings on phones. `case` (option A) wraps each case's tabs in one `.tab-cluster` box and hides the `-<case>` of a generated name (`.tab-name-case`). `ledger` (option B) is a CSS-only grid on the desktop header strip. `classic` is the old strip. Pure cores: `CodemanTabTriage` and `CodemanTabClusters` (constants.js). ⚠️ `state` is the flex `order` property plus `aria-hidden` heading/break elements reconciled in place by `_syncTabTriageChrome()` after BOTH render paths, never a DOM reorder (a state change is an incremental pass). ⚠️ `case` boxes ARE a DOM grouping, so the incremental path rebuilds whenever `_tabClusterLayout().key` changes; membership follows `_mobileOverviewCaseFor()` like the home screens. ⚠️ Drag only reorders within a group or box (`_isTabDropAcrossGroups()`). ⚠️ Named groups in the vertical rail win over both groupings. ⚠️ `classic` must leave no trace (no headings, no inline order, no boxes, no name split), and the ledger must not change the markup. Tests: `test/tab-triage.test.ts`, `test/tab-clusters.test.ts`. → [architecture-invariants#tab-layouts-by-state-by-case-ledger](docs/architecture-invariants.md#tab-layouts-by-state-by-case-ledger)
|
||||
|
||||
**Header stats styles** (`headerStatsStyle`, per-device, desktop only, default `tiles`; Discussion #426 option G): `tiles` / `compact` (two pills, a ring beside every value) / `classic` (as before), keyed on `data-header-stats` (pre-paint + `applyHeaderStatsStyle()`), forced to `classic` below 768px and in a solo window. ⚠️ The clustered styles MOVE `#connectionIndicator` into `#headerSystemStats` and `#planUsageChip` right after it; `classic` moves them back to comment anchors. ⚠️ WS joins the pill only while System Stats is shown. ⚠️ The extra parts (stat rings, tile words, plan rings, meters) are always rendered and hidden by default in CSS, which is what keeps `classic` unchanged; tile words are derived beside the connection descriptor, never added to it (`test/connection-indicator.test.ts` pins its shape). ⚠️ A tile is a three-row grid (label, value, bar) with pixel line-heights and the bundled JetBrains Mono; never lay the bar over a fixed-height tile (a taller system mono put the value on top of it). The WS tile's grid lives on the inner `.connection-tile`, because JS writes the indicator's `display` inline. Tests: `test/header-stats-style.test.ts`. → [architecture-invariants#header-stats-styles](docs/architecture-invariants.md#header-stats-styles)
|
||||
|
||||
**Phone overview home screen** (`mobile-overview.js`, per-device `mobileOverviewEnabled`, default ON): under 600px the "C" logo shows NEEDS YOU / CURRENT / PAST SESSIONS instead of the welcome overlay, branched in `showWelcome()`/`hideWelcome()` via width-driven `shouldUseMobileOverview()`. ⚠️ The container ships `hidden` and only this module removes it: never give `.mobile-overview` a bare `display` rule (desktop does not load `mobile.css`). ⚠️ The split Run button must carry the toolbar's own classes (`btn-toolbar btn-run mode-<backend>` / `btn-run-gear`) and mobile.css must set no `background`/`color` on it; row status must mirror the session-tab alert language. PAST rows resume through the shared `resumeHistorySession()`. Status pills carry `data-i18n-skip`. → [architecture-invariants#phone-overview-home-screen](docs/architecture-invariants.md#phone-overview-home-screen)
|
||||
|
||||
**Desktop home tab rail** (`home-sessions.js`, desktop only): the welcome overlay's left gutter carries the open tabs as a rail docked flush left, full height, in overview order, each row showing `created … · <state> <duration>` from `_mobileOverviewSince()`; state classification is reused from mobile-overview.js (so it loads after it). ⚠️ The number badge is the Alt+1..9 tab-strip index, never renumber it to row position. ⚠️ The width gate lives in two places that must stay equal: `HOME_SESSIONS_MIN_WIDTH` (1180) and a `max-width: 1179px` media query. ⚠️ `.home-sessions[hidden]` must re-assert `display: none`. ⚠️ Size all children in `em` off the one `clamp()` knob, never `rem`/px. Age stamps tick in place (`_tickHomeSessionsTimes()`), never by re-render. Test: `test/home-sessions.test.ts`. → [architecture-invariants#desktop-home-tab-rail](docs/architecture-invariants.md#desktop-home-tab-rail)
|
||||
@@ -389,7 +393,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Respawn presets**: `solo-work` (3s/60min), `subagent-workflow` (45s/240min), `team-lead` (90s/480min), `ralph-todo` (8s/480min), `overnight-autonomous` (10s/480min).
|
||||
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`).
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+W (kill), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry.
|
||||
|
||||
### Security
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4,14 +4,6 @@
|
||||
**Author**: Claude (session with Tim), 2026-09-15
|
||||
**Scope**: v1 only. v2 items are named and explicitly deferred, not designed.
|
||||
|
||||
> **Update (tile grid, PR 1):** Pane B is now a `TerminalTile`
|
||||
> (`terminal-tile.js`) and is no longer as plain as this spec describes: it
|
||||
> reconnects after a drop, delivers input exactly once, has clickable paths
|
||||
> and image paste, sizes its PTY without a floor and adopts `zc` columns, and
|
||||
> the app-level terminal shortcuts follow the focused pane. Ctrl+W no longer
|
||||
> closes anything (Close Session has no default key).
|
||||
> See `docs/tile-grid-plan.md` and `architecture-invariants#split-pane-sessions`.
|
||||
|
||||
## Problem
|
||||
|
||||
Codeman's terminal area shows exactly one active session (pane) at a time —
|
||||
|
||||
@@ -1,860 +0,0 @@
|
||||
# Tile Grid: Design Spec
|
||||
|
||||
**Status**: PR 1 (tile foundation) implemented on `feat/terminal-tile`, local only; PR 2 (the grid) proposed. Builds on `docs/split-pane-sessions-plan.md`; the split pane stays.
|
||||
**Author**: Claude (planning session with the maintainer), 2026-10-06
|
||||
**Branches**: PR 1 `feat/terminal-tile`, PR 2 `feat/tile-grid` stacked on it (worktree `claudeman-tiles`)
|
||||
**Scope**: v1 is fully designed here; follow-ups are named at the end and explicitly deferred.
|
||||
|
||||
## Problem
|
||||
|
||||
Codeman's terminal area shows exactly one session at a time. The split pane
|
||||
(`showSplitButton`, `src/web/public/terminal-split.js`) added a second live
|
||||
session beside the active one, but stops at two, gives the second pane
|
||||
("Pane B") a deliberately reduced feature set, and has no reconnect: every
|
||||
Codeman restart (every release deploy) leaves Pane B dead until the split is
|
||||
closed and reopened.
|
||||
|
||||
The goal is a dashboard of agents: four, six or nine live Claude sessions on
|
||||
one monitor, each readable and typeable, with its state visible at a glance.
|
||||
The target picture is a 3x2 grid of tiles, each tile a full terminal with a
|
||||
small header: status dot, session name, a `⋯` menu, maximize, `+` and `×`.
|
||||
|
||||
## Goal (v1)
|
||||
|
||||
- A **tile grid** of 1 to 9 live sessions in one Codeman window, laid out
|
||||
automatically by count, with draggable column and row dividers.
|
||||
- Every tile is equal: same terminal class, same features, same header. One
|
||||
tile is **focused** and receives the keyboard.
|
||||
- The rest of the app follows the focused tile: files panel, git status,
|
||||
respawn and Ralph panels, subagent windows, voice, image paste.
|
||||
- Tiles survive a Codeman restart (reconnect) and a page reload (per-device
|
||||
persistence).
|
||||
- The split pane stays as it is for now (decided). The grid is a separate
|
||||
mode that shares the same tile class with it; the two are never open at the
|
||||
same time (see "Coexistence with the split pane").
|
||||
|
||||
## Non-goals (v1)
|
||||
|
||||
- Phones and tablets. The grid is desktop-only, gated at 1180 px like the
|
||||
split (`SPLIT_PANE_MIN_WIDTH`) and the home rail (`HOME_SESSIONS_MIN_WIDTH`).
|
||||
- More than 9 tiles.
|
||||
- WebGL rendering inside tiles (see "Rendering" below).
|
||||
- Full parity with the main terminal's touch and IME features: local-echo
|
||||
overlay, the CJK input textarea, the keyboard accessory bar, touch gestures,
|
||||
mouse-wheel forwarding to Claude's fullscreen renderer, the "Load full
|
||||
history" banner. These exist for touch devices or rare cases; a desktop
|
||||
keyboard user types straight into xterm, which is how Codeman behaved before
|
||||
those features existed.
|
||||
- Server-side persistence of grids (named presets per owner).
|
||||
- Pop-out windows (`/session/:id`, solo mode) showing a grid.
|
||||
|
||||
## Current architecture (why this is not a CSS change)
|
||||
|
||||
`terminal-ui.js` is built around ONE terminal: `this.terminal` (one xterm),
|
||||
`this._ws` / `this._wsSessionId` (one WebSocket, rebound on every tab switch
|
||||
via `_disconnectWs()` + `_connectWs(id)`), `this._xtermSnapshots` (scrollback
|
||||
snapshots restored into that one terminal), and about 280 references to that
|
||||
singleton across input handling, sizing, link providers, local echo, IME,
|
||||
touch handling and the keyboard accessory bar.
|
||||
|
||||
The split pane works around it with a second, independent object,
|
||||
`SplitTerminalPane`: its own xterm, its own fit addon, its own
|
||||
`/ws/sessions/:id/terminal` socket. That class is the seed of this feature.
|
||||
It already handles, and this design keeps:
|
||||
|
||||
- single-flight buffer loads (`_loadBuffer` / `_refreshBuffer` /
|
||||
`_endBufferLoad`), so two replays never interleave;
|
||||
- the "disconnected" marker that must be the LAST thing on screen
|
||||
(`_markerOwed`, `_stampMarkerIfOwed`);
|
||||
- the bounded scroll-to-top history pull for shell sessions (`_pullHistory`);
|
||||
- its own key handler gating app chords (palette, Alt nav, Ctrl+Z, Shift/Ctrl+Enter
|
||||
via `send-key`, smart copy);
|
||||
- divider drag with pointer capture, rAF-coalesced local fit, one PTY resize at
|
||||
pointer-up, and teardown when the split collapses mid-drag.
|
||||
|
||||
## Key decision: equal tiles, main terminal parked
|
||||
|
||||
Three ways to put N sessions on screen were evaluated:
|
||||
|
||||
| Approach | How | Verdict |
|
||||
|---|---|---|
|
||||
| A. Anchor plus light tiles | The main terminal stays as tile 1; other tiles are Pane-B style | Rejected. Tile 1 is privileged. The panels follow tile 1, not the tile you are typing in. Making another tile the "main" one costs two buffer reloads per click. |
|
||||
| B. Equal tiles, main parked | Every tile is a `TerminalTile`. The main terminal is hidden and disconnected while the grid is open. `activeSessionId` always equals the focused tile's session. | **Chosen** |
|
||||
| C. iframes of solo windows | Each tile is `/session/:id` in an iframe | Rejected. All frames share `codeman:clientId` (localStorage), and `SseStreamManager.addClient` evicts the previous stream with the same clientId, so frames knock each other's SSE offline about every 45 s (the staleness watchdog reconnects, evicting the next one). They also share `codeman:pendingInput`, load N full copies of the app, and play N notification sounds. |
|
||||
|
||||
Why B:
|
||||
|
||||
- **Focus changes are instant.** Moving focus is `xterm.focus()` plus an
|
||||
`activeSessionId` update. No fetch, no replay, no flicker.
|
||||
- **Panels follow focus for free.** Everything keyed on `activeSessionId`
|
||||
(files panel, git status poll, respawn and Ralph panels, subagent window
|
||||
visibility, voice, image upload, kill/close, tab highlight) follows the
|
||||
focused tile once the tile branch of `selectSession` runs the same panel
|
||||
refresh as a normal switch.
|
||||
- **Hiding the main terminal is already proven safe.** Web tabs set
|
||||
`display:none` on `.terminal-wrap` today (`.main.webview-active`). With the
|
||||
container hidden, FitAddon's `proposeDimensions()` reads `auto` widths and
|
||||
returns NaN, `clampTerminalDimensions` returns null, and no resize is sent.
|
||||
- **The end state is clean.** Long term, the main terminal can itself become a
|
||||
1x1 grid of the same class, which deletes the singleton. B moves toward that;
|
||||
A entrenches it.
|
||||
|
||||
The cost of B is that tiles must reach desktop parity with the main terminal
|
||||
on the features that matter at a desk: reliable input, reconnect, file-path
|
||||
links, copy, image paste, voice. Those are listed under "Seams". Most of that
|
||||
work also fixes gaps the split pane has today.
|
||||
|
||||
## User-facing behavior
|
||||
|
||||
### Entry points
|
||||
|
||||
- **Header Tiles button** (its own button, beside Split). Opens a picker with
|
||||
checkboxes over open sessions, ordered like the tab strip. When the grid is
|
||||
open, the button toggles it closed.
|
||||
- **Ctrl/Cmd+click a tab**: add that session to the grid (opens the grid if
|
||||
closed).
|
||||
- **Drag a tab** from the strip onto a tile to replace it, or onto an empty
|
||||
slot to add it.
|
||||
- **"Open group as tiles"** in the tab-group menu (vertical rail, where group
|
||||
menus exist).
|
||||
- **New sessions started from this browser tab's Run button** while the grid is
|
||||
open join the next free slot and take focus. Sessions created elsewhere
|
||||
(agents, other devices, cron) do not join.
|
||||
- **Toggle shortcut** (registry action `toggleTileGrid`).
|
||||
|
||||
### Layout
|
||||
|
||||
Automatic by tile count, computed by a pure helper:
|
||||
|
||||
| Tiles | Layout |
|
||||
|---|---|
|
||||
| 1 | 1x1 |
|
||||
| 2 | 2x1 |
|
||||
| 3 | 3x1 if the grid area is at least ~1800 px wide, else 2x2 with one empty slot |
|
||||
| 4 | 2x2 |
|
||||
| 5-6 | 3x2 |
|
||||
| 7-9 | 3x3 |
|
||||
|
||||
Hard cap 9. Capacity is also bounded by a minimum tile size (about 480x240 px,
|
||||
roughly 60 columns at the default tile font), so the picker disables additions
|
||||
the window cannot fit.
|
||||
|
||||
Column and row dividers are draggable (generalizing the split divider): the
|
||||
grid stores track fractions (`grid-template-columns: <a>fr <b>fr …`), each
|
||||
drag clamps both neighbors to the minimum tile size, reflows locally per
|
||||
animation frame, and sends one resize per affected tile at pointer-up.
|
||||
|
||||
### Tile header
|
||||
|
||||
`● name ……… ⋯ ⤢ + ×`
|
||||
|
||||
- **●** status dot from the existing six-state classifier
|
||||
(`app._sidebarRichRow(id, session)`, built on `_mobileOverviewState`):
|
||||
`needs`, `error`, `waiting`, `working`, `idle`, `done`, styled with the
|
||||
existing unscoped `.home-sessions-dot--*` classes. A `needs` tile also gets a
|
||||
pulsing red border so a permission prompt is visible across the room. The
|
||||
label ("working 3m") shows on hover via `_mobileOverviewSince` /
|
||||
`_mobileOverviewStampText`.
|
||||
- **name** via `textContent` with `data-i18n-skip` (a session literally named
|
||||
"Sessions" must not be translated). Double-click renames through
|
||||
`_queueInlineSessionName(id, name)`.
|
||||
- **⋯** reuses `openTabRailActionMenu(event, id)` (tab-rail-resize.js): Session
|
||||
options, Open in a new window, Close session.
|
||||
- **⤢** zooms the tile to fill the grid, like tmux zoom. The other tiles stay
|
||||
connected but hidden; hidden tiles measure NaN and send no resizes. Pressing
|
||||
it again (or the shortcut) restores the grid.
|
||||
- **+** adds a session: a picker of open sessions not yet tiled, plus "New
|
||||
session in this case", which runs the normal quick-start for the tile's case
|
||||
and drops the result into the next slot.
|
||||
- **×** removes the tile ONLY. The session keeps running. Killing stays behind
|
||||
`⋯ → Close session` and its existing confirm modal (`requestCloseSession`).
|
||||
|
||||
### Focus and keyboard
|
||||
|
||||
- The focused tile gets an accent border; its session is `activeSessionId`.
|
||||
- Tabs of tiled sessions carry an `.in-tiles` marker; the focused one is
|
||||
`.active` as usual.
|
||||
- Clicking a tile focuses it (a human selection, see "Focus and alert rules").
|
||||
- New registry actions (all rebindable, all swallowed in every xterm key
|
||||
handler so the chord never reaches a PTY):
|
||||
- `toggleTileGrid` (proposed Ctrl+Shift+G)
|
||||
- `focusTileLeft/Right/Up/Down` (proposed Alt+Shift+Arrows)
|
||||
- `zoomTile` (proposed Alt+Shift+Enter)
|
||||
- `removeTile` (unbound by default)
|
||||
|
||||
The defaults must be checked against xterm passthrough, Claude Code's own
|
||||
bindings and browser chords before they are fixed.
|
||||
- While the grid is open, Ctrl+Tab and Alt+[ / Alt+] cycle through tiles.
|
||||
- A USER-initiated selection of a session that is NOT tiled (clicking its tab,
|
||||
Alt+1-9 onto it, the command palette) leaves the grid and shows that session
|
||||
in the normal single view; the grid is remembered and one click on Tiles
|
||||
brings it back (decision 1). An app-driven selection (`auto: true`)
|
||||
never collapses the grid; see "Selections while the grid is open".
|
||||
- Ctrl+L clears the focused tile; Ctrl+W is delete-word in the focused tile
|
||||
(it is not an app shortcut, decision 5); Ctrl +/-
|
||||
changes the tile font size; Ctrl+Shift+R restores the focused tile's size.
|
||||
|
||||
### Persistence
|
||||
|
||||
Decided: per device, restored on reload. Stored in localStorage key
|
||||
`codeman:tile-grid`:
|
||||
|
||||
```json
|
||||
{ "v": 1, "open": true, "ids": ["…", "…"], "focused": "…", "zoomed": null,
|
||||
"colFr": [1, 1, 1], "rowFr": [1, 1] }
|
||||
```
|
||||
|
||||
Ids only, never content. A pure sanitizer drops unknown, deleted, detached and
|
||||
duplicate ids on load. Never restored in a solo window.
|
||||
|
||||
The restore runs INSIDE `handleInit`, in place of its initial
|
||||
`selectSession(restoreId, { auto: true })` (the non-`keepTerminal` branch), not
|
||||
after it. Otherwise the page first selects the active session in the main
|
||||
terminal, whose first non-shell select per page pulls an unbounded `?full=1`
|
||||
capture, only to park that terminal a moment later. With a stored open grid,
|
||||
the main terminal never loads on that page load. A later `handleInit` (SSE
|
||||
reconnect after a server restart, the `keepTerminal` branch) reconciles ids
|
||||
against the live list without rebuilding tiles that are still alive.
|
||||
|
||||
### Gating
|
||||
|
||||
- Setting `showTileGridButton`, per device (in `displayKeys`, stripped from the
|
||||
settings PUT, NOT in `SettingsUpdateSchema`), default OFF. Independent of
|
||||
`showSplitButton`, which is unchanged; a desk can show both buttons.
|
||||
- Hidden below 1180 px by both a JS width check with a `matchMedia` listener and
|
||||
a CSS `@media (max-width: 1179px)` backstop, exactly like the split button.
|
||||
Narrowing the window while the grid is open returns to the single view and
|
||||
keeps the stored grid.
|
||||
- Hidden in solo windows (`body.solo-mode`).
|
||||
- `test/mobile-header-buttons-policy.test.ts` keeps it off phones.
|
||||
|
||||
## Components
|
||||
|
||||
### 1. `TerminalTile` (`terminal-tile.js`, load order 7.4, PR 1)
|
||||
|
||||
The `SplitTerminalPane` class moves out of `terminal-split.js` into a new
|
||||
`src/web/public/terminal-tile.js` and is renamed `TerminalTile`, keeping every
|
||||
behavior listed under "Current architecture". The split orchestration stays in
|
||||
`terminal-split.js` and constructs a `TerminalTile` for Pane B; the grid (PR 2)
|
||||
constructs one per tile. New in the class:
|
||||
|
||||
**Reconnect.** The primary pane's backoff ladder (`CodemanWsReconnect`,
|
||||
constants.js: 0, 250 ms, 500 ms, ... capped at 10 s) plus up to 250 ms of
|
||||
jitter, the attempt count reset only by a successful open. A reconnect is also kicked when SSE `handleInit` reports the
|
||||
server is back. After every reopen the tile runs a bounded refresh (the same
|
||||
in-stream `\x1bc` clear plus replay as `_refreshBuffer`), because output
|
||||
frames carry no sequence number and a gap cannot be replayed otherwise. That
|
||||
refresh goes through the grid's load queue like every other load (see "Load
|
||||
cost"): after a deploy restart all N tiles reopen within the same second, and
|
||||
N unqueued refreshes are exactly the capture storm the queue exists to
|
||||
prevent. Close codes that must NOT reconnect:
|
||||
|
||||
| Code | Meaning | Tile does | Owner decides (via `onExit`) |
|
||||
|---|---|---|---|
|
||||
| 4009 | Session exited | Stops reconnecting, reports the code | PR 1 split: an "exited" marker in Pane B (the split's existing delete path collapses it if the session is removed). PR 2 grid: the Attach overlay |
|
||||
| 4003 / 4004 | Forbidden / session gone | Stops reconnecting, reports the code (4003 is stopped by the tile itself: `CodemanWsReconnect` classes it as transient) | PR 1 split: a marker saying why. PR 2 grid: removes the tile |
|
||||
| 4010 | Superseded by a socket with the same cid | Stops, but only for the CURRENT socket (see below) | Same marker as 4003 |
|
||||
|
||||
The class never decides what happens to its container; it reports the close
|
||||
code through the `onExit` callback and the owner (split or grid) acts.
|
||||
|
||||
**Replacing a socket is race-free.** A reconnect can be kicked (by
|
||||
`handleInit`) while the old socket still looks open on the client: a half-open
|
||||
connection whose `onclose` has not fired yet. The new socket carries the same
|
||||
cid, so the server supersedes the old one with a 4010, and that late `onclose`
|
||||
would run the "4010: stop" branch on a perfectly healthy tile. So before
|
||||
opening a replacement the tile detaches the old socket's handlers (as
|
||||
`destroy()` already does: null `onopen`/`onmessage`/`onclose`/`onerror`, then
|
||||
`close()`), and every handler checks `event.target === this.ws` and ignores
|
||||
events from any socket that is no longer current.
|
||||
|
||||
The marker text becomes `[disconnected, reconnecting…]` (a stop writes
|
||||
`[disconnected: <why>]`, `TerminalTile.STOP_MARKERS`) and keeps its "last
|
||||
thing on screen" rule. On reopen the closed state is cleared BEFORE the gap
|
||||
refresh, or the refresh re-owes the marker and stamps it under a healthy
|
||||
pane. `reconnectNow()` skips the backoff and never replaces an open socket.
|
||||
|
||||
**Client id on the upgrade URL.** `cid=${clientId}:${tabNonce}:tile`. The
|
||||
connection registry supersedes by cid PER SESSION, so a distinct suffix means a
|
||||
tile can never evict the main terminal's socket in a 4010 loop even if the same
|
||||
session were ever on both. Input frames keep the BARE `clientId` (that is what
|
||||
the server dedups on).
|
||||
|
||||
**Reliable input.** `terminal.onData` calls
|
||||
`app._sendInputAsync(this.sessionId, data)`, which rides the tile's own socket
|
||||
through the input-socket map (see "Seams"). This gives the tile the same
|
||||
exactly-once delivery as the main terminal (per-session `seq`, ACKed, persisted
|
||||
until ACK), and through `_ackDelivery` it clears the session's idle alert when
|
||||
you type, which Pane B never did.
|
||||
|
||||
**Geometry** (rules from #464, see `docs/architecture-invariants.md`):
|
||||
|
||||
- One method, `syncGeometry()`, measures (`proposeDimensions()`), resizes the
|
||||
xterm and sends `{t:'z', c, r, v:'desktop'}` with THE SAME raw dimensions.
|
||||
The xterm and the PTY never disagree. There is deliberately NO 40x10 floor
|
||||
(unlike the main terminal's `clampTerminalDimensions`): commit `57406f6c`
|
||||
removed it from Pane B because the split's 20% divider clamp can leave Pane
|
||||
B at about 240 px, roughly 28 columns, and a floored xterm is wider than its
|
||||
container and clips columns. The server's own range (columns 1-500, rows
|
||||
1-200) is the only bound. Grid tiles never get that narrow anyway (the
|
||||
minimum tile size keeps them near 60 columns).
|
||||
- Unchanged dimensions are not resent (Pane B had no such dedupe and fanned out
|
||||
a `tmux resize-window` per animation frame during drags before the rAF fix).
|
||||
- The `{t:'zc'}` reply is handled: adopt the PTY's COLUMNS only, keep local
|
||||
rows, via the pure `reconcilePtyGeometry` (constants.js). Pane B ignores
|
||||
`zc` today.
|
||||
- A hidden tile (zoomed out, web tab active) measures NaN and does nothing; it
|
||||
syncs when shown again.
|
||||
- Detached sessions are never tiled, so the split's `detachedSessions` yield in
|
||||
`_sendResize` becomes a removal (see "Edge cases").
|
||||
|
||||
**Rendering.** DOM renderer, no WebGL addon, as Pane B does today. Chrome
|
||||
allows roughly 16 live WebGL contexts per page and the main terminal keeps
|
||||
one. Measure nine busy tiles on the DOM renderer before considering WebGL
|
||||
(follow-up).
|
||||
|
||||
**Scrollback.** Tiles use their own cap, `TILE_SCROLLBACK` (proposed 10,000
|
||||
lines), not `DEFAULT_SCROLLBACK` (50,000). Nine DOM-rendered xterms at 50k
|
||||
lines each is a real memory cost, and a tile's initial load is already bounded
|
||||
to a 1 MiB window, so a larger buffer only fills with live output over time.
|
||||
The shell history pull's "pane full" check reads `term.options.scrollback`, so
|
||||
it adapts to the lower cap unchanged.
|
||||
|
||||
**Key handler.** Pane B's `attachCustomKeyEventHandler` stays in
|
||||
`TerminalTile` (every tile IS a `TerminalTile`, so no separate factory is
|
||||
needed), plus:
|
||||
|
||||
- Ctrl+V routes into the image-paste trap with this tile's terminal and session;
|
||||
- the new tile chords are swallowed (return false) so they never reach the PTY.
|
||||
|
||||
**Links and copy.** The tile registers the file-path link provider and uses the
|
||||
shared copy helper (see "Seams"), so clicking a path printed in a tile opens the
|
||||
file preview for THAT session.
|
||||
|
||||
**Disposal.** `destroy()` closes the socket (handlers nulled first, as today),
|
||||
unregisters from the input-socket map, removes listeners and disposes the
|
||||
xterm. Nothing may outlive a removed tile (24-hour sessions rule).
|
||||
|
||||
### 2. `TileGrid` controller and layout helper
|
||||
|
||||
- `computeTileLayout({ count, width, height, minTileW, minTileH })` and
|
||||
`tileGridCapacity(...)`: pure, in `constants.js`, exported on
|
||||
`window.CodemanTileGrid` beside the existing helper namespaces.
|
||||
`sanitizeTileGridState(raw, liveSessions, detachedIds)`: pure, same place.
|
||||
- The controller (in a new `src/web/public/tile-grid.js`, load order 7.6, as
|
||||
`CodemanApp.prototype` methods like the split code) owns: the ordered tile list, `focusedId`,
|
||||
`zoomedId`, track fractions, the `<section class="tile-grid">` element, one
|
||||
`ResizeObserver` on that section (the main terminal's observer watches a
|
||||
hidden node and stops firing), the divider drags and the load queue.
|
||||
- DOM: the grid is a NEW sibling of `.terminal-wrap` inside `.main`, toggled by
|
||||
`.main.tiles-active`. Unlike the split there is no reparenting of
|
||||
`.terminal-wrap`. CSS adds `.main.webview-active .tile-grid { display: none }`
|
||||
beside the existing `.terminal-split-container` rule.
|
||||
|
||||
### 3. Parking the main terminal
|
||||
|
||||
**Enter:**
|
||||
|
||||
1. `_cleanupPreviousSession()` once. Its snapshot of the current session is
|
||||
correct at that moment, and it disconnects the main socket and flushes local
|
||||
echo.
|
||||
2. Add `.main.tiles-active`: `.terminal-wrap` hidden, `.tile-grid` shown.
|
||||
3. `hideWelcome()`.
|
||||
|
||||
**Guards.** With the main socket closed, `_wsReady` is false and the SSE
|
||||
terminal fallback would start writing the focused session's output into the
|
||||
hidden xterm (every handler keys on `activeSessionId`). One predicate,
|
||||
`_tilesOwnTerminal()`, turns these into no-ops while the grid is open:
|
||||
|
||||
- `_onSessionTerminal`, `_onSessionClearTerminal`, `_onSessionNeedsRefresh`
|
||||
(it would fetch `?full=1` for nothing), `_scheduleDroppedOutputRecovery`;
|
||||
- the `terminal.writeln` calls in `_onSessionCompletion` and `_onSessionError`;
|
||||
- `retryConnection` and the `keepTerminal` branch of `handleInit`, which would
|
||||
reconnect the main socket;
|
||||
- as a backstop, beside the existing `detachedSessions` checks in
|
||||
`sendResize`, `throttledResize`, `_maybeRefetchFullHistory` and
|
||||
`restoreTerminalSize`;
|
||||
- the WebGL long-task guard (`_installWebGLLongTaskGuard`). Its
|
||||
`PerformanceObserver` watches the WHOLE page and counts every long task while
|
||||
the main terminal's WebGL addon exists, so long tasks caused by tile rendering
|
||||
or tile replays would trip it and write the sticky `codeman-webgl-disabled`
|
||||
marker (7 days), silently moving the main terminal to the DOM renderer for
|
||||
reasons that have nothing to do with WebGL. While tiles own the terminal the
|
||||
observer callback must not count entries.
|
||||
|
||||
A missed guard is mostly harmless (exit replays from scratch) but costs fetches
|
||||
and CPU, so the guard test enumerates them.
|
||||
|
||||
`_computeConnectionDescriptor` must derive the header connection state from the
|
||||
tile sockets while the grid is open (all open: connected; any reconnecting:
|
||||
degraded), or the header shows "Connecting" forever.
|
||||
|
||||
The SSE subscription stays `[activeSessionId]` as in single view. Those frames
|
||||
are dropped by the guards. (An empty list means "all sessions", so there is no
|
||||
"none" to subscribe to; this matches today's single-view duplication anyway.)
|
||||
|
||||
**Exit:**
|
||||
|
||||
1. Destroy every tile, remove `.main.tiles-active`.
|
||||
2. `this._lastResizeDims = null` (as `_redock` does).
|
||||
3. Invalidate the main terminal's cached content for EVERY tiled id, not just
|
||||
the focused one: the `_xtermSnapshots` entry, the `codeman-xs-<id>`
|
||||
localStorage key and the buffer-cache entry. Those were written before the
|
||||
grid opened, possibly hours earlier, and `selectSession` paints a snapshot as
|
||||
a first frame before its fetch replaces it, so the next switch to a formerly
|
||||
tiled session would flash content from before the grid.
|
||||
4. `selectSession(focusedId, { forceReload: true, auto: true })`. For the
|
||||
already-active id that path drops the stale snapshot and nulls
|
||||
`activeSessionId` BEFORE `_cleanupPreviousSession`, so nothing wrong is
|
||||
saved, then reconnects and replays normally.
|
||||
|
||||
### 4. The tile branch of `selectSession`
|
||||
|
||||
Placed in `app.js` directly after the "already active" early return (~7876),
|
||||
so tapping the focused tab still acknowledges its alert and the detached-window
|
||||
check (~7855) still runs first:
|
||||
|
||||
```js
|
||||
if (this._tileGrid?.open) {
|
||||
if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options);
|
||||
// Decision 1: only a USER-initiated pick (or an explicit leaveTiles) of a
|
||||
// non-tiled session leaves the grid. An app-driven one never collapses it.
|
||||
if (options.auto === true && !options.leaveTiles) return;
|
||||
this.closeTileGrid({ keepStored: true });
|
||||
}
|
||||
```
|
||||
|
||||
`_selectTiledSession` keeps:
|
||||
|
||||
- `++this._selectGeneration` (aborts any in-flight normal select at its next
|
||||
`_isStaleSelect` check);
|
||||
- `_hideWebviewLayer()`; `activeSessionId = id`; `_activateFileBrowserSession`;
|
||||
the `codeman-active-session` key; `hideWelcome()`;
|
||||
- `markIdleAlertSeen(id)` only when user-initiated (`options.auto !== true`);
|
||||
- `_updateActiveTabImmediate`, tab glow, `renderSessionTabs`,
|
||||
`closeSessionSidebarOnHandheld`;
|
||||
- `updateAttachmentHistoryBadge`, `KeyboardAccessoryBar.refreshForActiveSession`,
|
||||
`refreshHostWakeBanner`, `currentSessionWorkingDir`;
|
||||
- the deferred panel block (respawn banner and countdown, action log, task
|
||||
panel, Ralph state, CLI info, project insights, subagent window visibility,
|
||||
file browser). That block (~8452-8523) is first extracted into
|
||||
`_refreshSessionPanels(id, generation)` so both paths share one copy;
|
||||
- focusing the tile's xterm.
|
||||
|
||||
It skips everything bound to the main terminal: `terminal.focus()`,
|
||||
`_cleanupPreviousSession`, the truncation banner, `playTerminalEntrance`,
|
||||
local-echo state, `_beginBufferLoad`, `syncTerminalGeometry`, both
|
||||
`sendResize` calls, snapshot/cache/fetch replay, `_fullHistoryLoaded`,
|
||||
`_markTerminalBufferReconciled`, `_connectWs`, scroll-to-bottom, the resize
|
||||
retry, and the `pid === null` attach POST (the tile's Attach overlay owns it).
|
||||
|
||||
The split's own `selectSession` and `_onSessionDeleted` wrappers stay. They
|
||||
act only while `this._splitPane` is set, and the grid never opens alongside a
|
||||
split (see "Coexistence with the split pane"), so the two never compete.
|
||||
|
||||
#### Selections while the grid is open
|
||||
|
||||
Several app-driven paths call `selectSession` on their own, and without the
|
||||
`auto` rule above each of them would land on a non-tiled session and collapse
|
||||
the grid. Each one gets an explicit grid-aware behavior:
|
||||
|
||||
| Path | Today | With the grid open |
|
||||
|---|---|---|
|
||||
| Close session on the focused tile (`closeSession`, from its menu or a user-bound key) | Reads `wasActive` before its `await`, adds the id to `_closingSessions`, then selects the first remaining `sessionOrder` entry with `auto: true`, which is often NOT tiled | A grid-aware fallback picker: remove the tile, then focus the neighboring tile (next in grid order, else previous). Only with no tiles left does it fall back to the `sessionOrder` pick, which closes the grid. Note the split's `_onSessionDeleted` wrapper deliberately skips selection for ids in `_closingSessions`, so the fallback MUST live in `closeSession` itself, not in the delete wrapper. |
|
||||
| Session deleted elsewhere (`_onSessionDeleted`) | The handoff selects the first remaining `sessionOrder` entry | If it was tiled: remove the tile and focus a neighbor with `auto: true`. If it was not tiled it was not active, so there is no handoff. |
|
||||
| Boot restore (`handleInit`) | `selectSession(restoreId, { auto: true })` | Replaced by the grid restore when a stored grid is open (see "Persistence") |
|
||||
| URL `#session=<id>` link | `selectSession(id, { auto: true })` | Following a link is navigation, so this path passes `leaveTiles: true`: a tiled id focuses its tile, a non-tiled id opens the single view (grid kept in storage) |
|
||||
| Pane promotion after a delete (split) | `selectSession(promoted, { auto: true })` | Unchanged for the split; unreachable while the grid is open, since no split can be open then |
|
||||
| Auto-join of a session created by this tab's Run | Run selects the new session | The session joins the grid first, then is selected through the tile branch |
|
||||
|
||||
### 5. Focus and alert rules
|
||||
|
||||
These follow the Approvals Inbox acknowledgement rule
|
||||
(`docs/architecture-invariants.md#approvals-inbox`):
|
||||
|
||||
| Event | Acknowledges the idle alert? |
|
||||
|---|---|
|
||||
| Pointerdown on a tile, a tile-nav chord, a click on its tab | Yes (human selection) |
|
||||
| Typing into a tile | Yes, via `_ackDelivery` on the input ACK |
|
||||
| Opening the grid, restoring it, promoting a neighbor after a delete, auto-join of a new session | No (`auto: true`) |
|
||||
| A tile merely being visible | No |
|
||||
| Anything | Never clears permission/question (action) alerts; those clear only on resolution |
|
||||
|
||||
Notifications are unchanged: a visible but unfocused tile still raises its
|
||||
sound/title/desktop notification, so nothing is silently swallowed.
|
||||
|
||||
### 6. Seams (small refactors, no behavior change on their own)
|
||||
|
||||
| Feature | Today | Change |
|
||||
|---|---|---|
|
||||
| Input socket | `_drainSession`, `_sendInputEphemeral`, `_redeliverSweep` and `_onWsInputAck` assume the single `_ws` / `_wsSessionId` / `_wsLastRecvAt` | An `_inputSocketFor(sessionId)` map that the main terminal and each tile register into (`{ ws, ready(), lastRecvAt }`). `{t:'ia'}` acks carry no session id, so each socket's `onmessage` passes its own: `_onWsInputAck(seq, msg, sessionId)`. Without the map, tile input still works through the HTTP POST fallback (durable, but one awaited POST per record). |
|
||||
| File-path links | `registerFilePathLinkProvider()` reads `self.terminal` and opens with `self.activeSessionId` | `registerFilePathLinkProvider(terminal = this.terminal, getSessionId = () => this.activeSessionId)` returning the provider; about five references change |
|
||||
| Copy | `copyTerminalSelection` / `cleanedTerminalSelection` read `this.terminal`; Pane B re-implements them | Both take `(terminal, sessionId)`; Pane B's copy is deleted |
|
||||
| Image paste | `_handleImagePaste()` uses the main terminal; `_uploadAndInsertImages` inserts with `sendInput()`, which re-reads `activeSessionId` AFTER the upload (an existing bug: switch tabs mid-upload and the paths land in the wrong session) | `_handleImagePaste({ terminal, sessionId })`; insert with `_sendInputAsync(sessionId, paths, { useMux: true })` |
|
||||
| Voice | `_insertText` re-reads `app.activeSessionId` at insert time and appends to the main local-echo overlay | Capture the target in `start()`; send with `_sendInputAsync(target, …)`; skip the overlay when the target is not the main terminal |
|
||||
| Shortcuts | Ctrl+L (`clearTerminal`) and Ctrl+Shift+R (`restoreTerminalSize`) act on `this.terminal` | Resolve through `_focusedPane()` returning `{ terminal, sessionId, isPrimary }`; Close Session (no default key) already takes an id |
|
||||
| Font, family, weight, skin | `setFontSize` / `setFontFamily` / `setFontWeight` / `applyTerminalSkin` special-case `this._splitPane` | Loop over all tiles |
|
||||
|
||||
### 7. Fonts
|
||||
|
||||
Tiles get their own per-device font size, `codeman-tile-font-size` (default
|
||||
13), because a tile is a fraction of the screen. While the grid is open,
|
||||
Ctrl +/- changes the tile font for all tiles. A font change is a geometry
|
||||
change (#464): every tile re-runs `syncGeometry()` afterwards.
|
||||
|
||||
### 8. Load cost
|
||||
|
||||
`GET /api/sessions/:id/terminal` runs three SYNCHRONOUS tmux calls
|
||||
(`list-panes`, `capture-pane`, `display-message` via `execSync`, each with a
|
||||
5 s timeout). Nine `full=1` loads at once would not run in parallel; they would
|
||||
run back to back on the event loop and stall every WS and SSE stream on the
|
||||
server for seconds.
|
||||
|
||||
So EVERY tile load goes through ONE grid-level client queue (PR 2, plugged in
|
||||
through a `scheduleLoad` option PR 2 adds to `TerminalTile`): the initial load,
|
||||
the refresh after a reconnect, a server `{t:'r'}` refresh, and the shell
|
||||
history pull. No tile calls `fetch('/terminal…')` on its own. The tile's
|
||||
single-flight flag stays (it is what keeps one tile's replays from
|
||||
interleaving); the queue sits in front of it and bounds the whole grid.
|
||||
|
||||
- concurrency 1, focused tile first, then reading order (a user-triggered
|
||||
history pull jumps ahead of background refreshes);
|
||||
- after a deploy restart, the N reconnect refreshes drain one at a time
|
||||
instead of hitting the server together;
|
||||
- each load uses the BOUNDED window `?full=1&tail=TERMINAL_TAIL_SIZE` (1 MiB)
|
||||
for TUI sessions and `?tail=…` for shells, never an unbounded `full=1`;
|
||||
- a tile shows a quiet "loading" state until its turn;
|
||||
- full history is one action away: zoom then exit tiles, or exit tiles.
|
||||
|
||||
### 9. Coexistence with the split pane
|
||||
|
||||
Decided: the split pane stays for now. The two modes are mutually exclusive
|
||||
and share one tile class:
|
||||
|
||||
- Opening the grid while a split is open closes the split first and seeds the
|
||||
grid with both of its sessions (Pane A's focused, Pane B's beside it), so
|
||||
"split, then want more" is one click.
|
||||
- While the grid is open, `openSplitPicker` and `openSplitPane` refuse and the
|
||||
Split button shows as disabled (`aria-disabled`), the same refusal pattern
|
||||
`openSplitPane` already uses for web tabs and the welcome screen.
|
||||
- Closing the grid never reopens a split.
|
||||
- The split's wrappers (`selectSession`, `_onSessionDeleted`) key on
|
||||
`this._splitPane`, which is null whenever the grid is open, so they stay
|
||||
inert there without changes.
|
||||
- Shared code lives in `TerminalTile` and the seams from PR 1, so a fix to tile
|
||||
behavior reaches both modes. Whether to retire the split later (a 2-tile grid
|
||||
covers it) is left for after the grid has been used for a while.
|
||||
|
||||
## Edge cases
|
||||
|
||||
| Situation | Behavior |
|
||||
|---|---|
|
||||
| A tiled session is deleted (here or elsewhere) | Tile removed; a neighbor gets focus with `auto: true`; the last tile gone falls through to the normal handoff |
|
||||
| Closing the focused tile's session | The grid stays open and the neighboring tile takes focus (grid-aware fallback in `closeSession`, see "Selections while the grid is open") |
|
||||
| A tiled session is popped out to its own window | Tile removed: that window now owns the PTY size |
|
||||
| Session exited or not attached (`pid === null`, `paneExit`) | The tile body shows "Not attached" with an Attach button: `POST /interactive` (or `/shell` for shell mode) with NO body, at most one in flight per session (the route has no in-flight guard of its own). A tripped PTY-exit breaker goes through the existing confirm before `clearBreaker: true`; no automatic path ever sends it |
|
||||
| A web tab is opened | Grid hidden by CSS; sockets stay up; hidden tiles send no resizes. Selecting a tiled session's tab brings the grid back |
|
||||
| Window narrower than 1180 px | Back to single view of the focused session; stored grid kept |
|
||||
| Window shrinks below the tiles' minimum size | The focused tile zooms with a short hint; widening restores the grid |
|
||||
| Codeman restarts (deploy) | Tiles reconnect; their refreshes drain through the load queue one at a time; `handleInit` reconciles ids without rebuilding live tiles |
|
||||
| A half-open tile socket when a reconnect is kicked | The old socket's handlers are detached before the replacement opens, so its late 4010 close is ignored |
|
||||
| A phone opens a tiled session | Its resize is declined while the desktop holds a sizing claim and was active in the last 90 s (existing `Session.resize` arbitration) |
|
||||
| A second desktop browser shows a tiled session full-size | Last resize wins and only the resizing socket hears `zc` (existing behavior, see follow-up 2) |
|
||||
| Split collapses or a tile is removed mid-divider-drag | Drag teardown first (carried over from the split's mid-drag fix) |
|
||||
| Remote (SSH) and Docker sessions | Work unchanged: their pane is a local tmux pane like any other |
|
||||
| Multi-user mode | The picker lists only visible sessions (the client map is already scoped); the socket upgrade checks ownership server-side |
|
||||
| Solo window | Tiles unavailable |
|
||||
|
||||
## Server
|
||||
|
||||
**No server change is required.**
|
||||
|
||||
- N sockets to N different sessions each use one slot of that session's
|
||||
`MAX_WS_PER_SESSION = 5` (`ws-routes.ts`). There is no per-client or global WS
|
||||
cap.
|
||||
- One `/api/events` SSE stream already carries every session's lifecycle and
|
||||
hook events, so tiles need no extra stream for their status dots.
|
||||
- `v:'desktop'` resizes already register a sizing claim, so a phone cannot
|
||||
shrink a tiled session while the desktop is active.
|
||||
- The WS sends nothing on connect, which is why each tile loads its buffer
|
||||
first (already true for Pane B).
|
||||
|
||||
Separate follow-up PRs worth doing (see "Follow-ups").
|
||||
|
||||
## Invariants this feature must keep
|
||||
|
||||
- **#464 geometry**: a tile's xterm and its PTY never disagree; one function
|
||||
sizes both; `zc` adoption is columns only; withhold the fit wherever the
|
||||
resize is withheld.
|
||||
- **Grid and split are never open together**: opening the grid closes a split;
|
||||
the split refuses to open while the grid is open.
|
||||
- **One place per session in this browser tab**: the main terminal is parked
|
||||
while the grid is open, a session is in at most one tile, detached sessions
|
||||
are never tiled.
|
||||
- **App-driven selections never collapse the grid**: only a user-initiated pick
|
||||
(or an explicit `leaveTiles`) of a non-tiled session leaves it; every
|
||||
app-driven fallback (close, delete, restore) picks a tile.
|
||||
- **One load queue**: no tile fetches `/terminal` outside the grid's queue
|
||||
(initial, reconnect, `{t:'r'}`, history pull), because each capture blocks
|
||||
the server's event loop.
|
||||
- **Only the current socket counts**: a tile ignores events from any socket
|
||||
that is no longer `this.ws`, and detaches handlers before replacing one.
|
||||
- **Tiles never touch main-terminal state**: no long tasks counted against the
|
||||
main terminal's WebGL, and its snapshots for tiled ids are invalidated on
|
||||
exit.
|
||||
- **Alerts**: visible is not acknowledged; only a human selection or delivered
|
||||
input acknowledges idle; action alerts are never cleared by view or input;
|
||||
app-driven selections pass `auto: true`.
|
||||
- **PTY-exit breaker**: never `clearBreaker` from an automatic path.
|
||||
- **Replay clears are in-stream** (`\x1bc` queued in the write stream), never
|
||||
`reset()`.
|
||||
- **Capture fetches carry deadlines that cover the body** (reuse
|
||||
`CodemanFetchDeadline`, as `_pullHistory` does).
|
||||
- **Per-device setting**: in `displayKeys`, stripped from the PUT, not in the
|
||||
`.strict()` schema; the `--hidden` marker class has a `display: none` rule.
|
||||
- **Palette chords** are swallowed in every xterm key handler.
|
||||
- **Escape**: the picker's close method returns early when the picker is not
|
||||
open (the global Escape handler calls every close method).
|
||||
- **User text** (names) via `textContent` / attributes, never `innerHTML`.
|
||||
- **No secrets in localStorage**: the stored grid holds ids only.
|
||||
- **Memory**: everything a tile creates is released in `destroy()`.
|
||||
|
||||
## Delivery: two PRs
|
||||
|
||||
Decided: the work ships as two PRs. PR 1 stands on its own: it builds the tile
|
||||
class and the seams, and the existing split pane runs on them, so users get a
|
||||
better split before the grid exists. PR 2 adds the grid on top.
|
||||
|
||||
### PR 1: tile foundation (the split pane gets better)
|
||||
|
||||
Commits:
|
||||
|
||||
1. **Seams.** The input-socket map; the parameterized link provider, copy,
|
||||
image paste and voice target; `_focusedPane()`; a `_forEachTile()` helper
|
||||
that replaces the `this._splitPane` special cases in the font, family,
|
||||
weight and skin setters. No behavior change on its own. Unit tests for each.
|
||||
2. **`TerminalTile`.** The class moves out of `terminal-split.js` into a new
|
||||
`src/web/public/terminal-tile.js` (load order 7.4, before
|
||||
`terminal-split.js` at 7.5) and is renamed from `SplitTerminalPane`. The
|
||||
split's orchestration (`openSplitPane`, `closeSplitPane`, the picker, the
|
||||
divider drag, the wrappers) stays in `terminal-split.js` and constructs a
|
||||
`TerminalTile` for Pane B. New in the class: reconnect with race-free socket
|
||||
replacement and the close-code table, the `:tile` cid suffix, reliable input
|
||||
through the socket map, `zc` handling with one geometry method, the
|
||||
file-path link provider and image paste, and an `onExit` callback. The
|
||||
`scrollback` and `scheduleLoad` options were deferred to PR 2, which
|
||||
introduces them together with the grid's load queue, their first user.
|
||||
3. **Split pane follows focus.** `_focusedPane()` returns Pane B while its
|
||||
xterm has focus, so Ctrl+L, Ctrl+Shift+R, voice and image paste act on the
|
||||
pane you are typing in. This removes most of the asymmetry the split-pane
|
||||
spec documented and accepted for its v1 ("Ctrl+L or Ctrl+W typed while Pane
|
||||
B has focus clears or closes Pane A"). Typing into Pane B now clears its
|
||||
idle alert through `_ackDelivery`, which it never did.
|
||||
**Ctrl+W no longer closes anything** (decision 5): Close Session has no
|
||||
default key, so Ctrl+W reaches the focused pane as delete-word.
|
||||
4. **Docs.** Update the split-pane paragraph in CLAUDE.md and
|
||||
`docs/architecture-invariants.md#split-pane-sessions` (Pane B now
|
||||
reconnects, delivers input exactly once, has links and image paste, and
|
||||
follows focus; the "deliberately plainer" list shrinks accordingly), add
|
||||
`terminal-tile.js`(7.4) to the frontend load order, add a note at the top of
|
||||
`docs/split-pane-sessions-plan.md` pointing here.
|
||||
|
||||
What users get from PR 1 alone: a split pane that survives deploys, never
|
||||
loses or doubles a keystroke across a reconnect, has clickable file paths and
|
||||
image paste, and whose shortcuts act on the pane that has focus.
|
||||
|
||||
PR 1 tests (gate):
|
||||
|
||||
- `test/terminal-tile-unit.test.ts`, moved from
|
||||
`split-pane-terminal-unit.test.ts` with every existing case kept
|
||||
(single-flight, marker-last including the async-parse fake, history pull),
|
||||
plus: reconnect backoff and each close code, a late `onclose` (4010) from a
|
||||
replaced socket is ignored and the tile keeps running, `zc` columns-only
|
||||
adoption, the cid suffix, input routed through `_sendInputAsync` (as built:
|
||||
`test/terminal-tile-input.test.ts`, which runs `connect()` for real).
|
||||
- `test/input-socket-map.test.ts`: acks routed to the right session's queue,
|
||||
redelivery per socket, POST fallback when no socket is registered.
|
||||
- `test/focused-pane-shortcuts.test.ts`: with Pane B focused, Ctrl+L clears
|
||||
Pane B, Ctrl+Shift+R restores Pane B's size, voice and image paste target
|
||||
Pane B's session, and a user-bound Close Session still targets the active
|
||||
session; `test/ctrl-w-never-closes.test.ts` pins that no default shortcut
|
||||
answers Ctrl+W;
|
||||
with Pane A focused nothing changes.
|
||||
- Geometry: with the split divider at its 20% clamp, Pane B's xterm and the
|
||||
size it sends are both under 40 columns and equal (no floor regression).
|
||||
- `onExit`: each close code is reported once to the owner and stops
|
||||
reconnecting; the split shows the matching marker.
|
||||
- The image-paste wrong-session fix: an upload that finishes after a tab switch
|
||||
still inserts into the session it started in.
|
||||
- Every existing `split-pane-*` test keeps passing (class name updated where it
|
||||
is referenced).
|
||||
|
||||
PR 1 browser tests: the existing `split-pane-*.browser.test.ts` files (they
|
||||
match master, one pre-existing environmental failure in both). Pane B
|
||||
reconnecting after a server restart and a click on a printed path opening
|
||||
Pane B's file preview are covered by unit tests and checked live on the beta
|
||||
instance rather than as browser tests (the harness cannot restart its own
|
||||
server).
|
||||
|
||||
PR 1 verification: a split with two real Claude sessions on the beta instance;
|
||||
restart the server mid-typing in Pane B (reconnect, refresh, no lost or doubled
|
||||
input); type into Pane B while it has an idle alert (the alert clears); Ctrl+L
|
||||
in Pane B; image paste into Pane B.
|
||||
|
||||
### PR 2: tile grid
|
||||
|
||||
Commits:
|
||||
|
||||
1. **Grid core.** `_refreshSessionPanels()` extraction from `selectSession`
|
||||
(no behavior change, its own commit first), layout helpers, the grid section
|
||||
and CSS, parking with guards (SSE handlers, reconnect paths, WebGL long-task
|
||||
observer), the `selectSession` tile branch with the `auto` rule, the
|
||||
grid-aware `closeSession` fallback, focus rules, tile chords in the shortcut
|
||||
registry, the single grid-level load queue that every tile load goes
|
||||
through (a new `scheduleLoad` option on `TerminalTile`, plus a `scrollback`
|
||||
option for `TILE_SCROLLBACK`), coexistence with the split.
|
||||
2. **Tile chrome and entry points.** Header (dot, name, menu, zoom, add,
|
||||
remove), the Attach overlay, picker, dividers, drag-a-tab, Ctrl/Cmd+click,
|
||||
"Open group as tiles".
|
||||
3. **Persistence.** `codeman:tile-grid` restore inside `handleInit` (in place
|
||||
of the initial select), snapshot invalidation on exit, auto-join of new
|
||||
sessions from this tab, the `showTileGridButton` setting.
|
||||
4. **Docs.** A tile-grid paragraph in CLAUDE.md beside the split-pane one,
|
||||
`tile-grid.js`(7.6) in the load order, header-button and z-index notes,
|
||||
`docs/architecture-invariants.md#tile-grid`, a wiki page under
|
||||
`docs/wiki/`.
|
||||
|
||||
## Testing (PR 2)
|
||||
|
||||
**Gate (`npm test`):**
|
||||
|
||||
- `test/tile-grid-layout.test.ts`: `computeTileLayout`, `tileGridCapacity`,
|
||||
`sanitizeTileGridState` (unknown, deleted, detached, duplicate ids).
|
||||
- `test/tile-grid-select-branch.test.ts` and an extension of
|
||||
`test/session-select-ack-gate.test.ts`: the branch never calls `_connectWs` or
|
||||
`_cleanupPreviousSession`; acknowledgement only when user-initiated; an
|
||||
`auto: true` selection of a non-tiled session leaves the grid open; a
|
||||
user-initiated one closes it; `leaveTiles: true` closes it.
|
||||
- `test/tile-grid-close-fallback.test.ts`: closing (`closeSession`) the
|
||||
focused tile keeps the grid open and focuses the neighboring tile, even when
|
||||
the first `sessionOrder` entry is not tiled; closing the last tile falls back
|
||||
to the normal pick.
|
||||
- `test/tile-grid-park-guards.test.ts`: every guarded SSE handler is a no-op
|
||||
while tiles own the terminal, and the WebGL long-task observer counts nothing
|
||||
while tiles own the terminal.
|
||||
- `test/tile-grid-load-queue.test.ts`: N tiles reconnecting together produce at
|
||||
most one in-flight `/terminal` fetch at a time; `{t:'r'}` and history pulls go
|
||||
through the same queue; a destroyed tile's queued load is dropped.
|
||||
- `test/tile-grid-restore.test.ts`: with a stored open grid, `handleInit`
|
||||
restores the grid and never calls the main terminal's buffer load; on exit,
|
||||
snapshot and cache entries for every tiled id are invalidated.
|
||||
- `test/tile-grid-split-coexistence.test.ts`: opening the grid closes an open
|
||||
split and seeds the grid with both of its sessions; the split cannot open
|
||||
while the grid is open; the split's wrappers do nothing while the grid is
|
||||
open.
|
||||
- `test/tile-grid-per-device-setting.test.ts` and a hidden-button CSS case, in
|
||||
the shape of the split-pane ones: `showTileGridButton` is in `displayKeys`,
|
||||
stripped from the PUT, not in the schema, and `.btn-tile-grid--hidden` has a
|
||||
`display: none` rule.
|
||||
- Shortcut tests: the new chords are swallowed in the main and tile key
|
||||
handlers; `mobile-header-buttons-policy` keeps the button off phones.
|
||||
|
||||
**Browser (`npm run test:browser -- <file>`, NOT in the gate):**
|
||||
|
||||
- Open 4 tiles; all render live output independently.
|
||||
- Click-to-focus routes keystrokes to the right PTY (assert with
|
||||
`tmux capture-pane`, never on HTTP 200).
|
||||
- Ctrl+L clears only the focused tile; Shift+Enter inserts a newline in a tile.
|
||||
- Zoom and unzoom refit; a divider drag sends exactly one resize per affected
|
||||
tile at pointer-up.
|
||||
- Deleting a tiled session removes its tile and moves focus.
|
||||
- Reload restores the grid; a server restart reconnects every tile.
|
||||
- Narrowing below 1180 px returns to the single view.
|
||||
|
||||
Reminder: `npm test -- <browser file>` matches nothing, runs zero tests and
|
||||
exits green. Use the browser runner for those files and read the file count.
|
||||
|
||||
## Verification before merging PR 2
|
||||
|
||||
- Build in the worktree and run an isolated beta instance (its own
|
||||
`CODEMAN_INSTANCE`, so its own data dir and tmux socket), reached through
|
||||
`tailscale serve` on a never-used port.
|
||||
- Six throwaway Claude sessions, as in the target picture; Playwright captures
|
||||
at `deviceScaleFactor: 1`, unique filenames.
|
||||
- A Chrome performance trace with all six tiles working at once for 60 s,
|
||||
recorded in the PR, with pass/fail bars:
|
||||
- p95 frame time at or below 25 ms (40 fps or better);
|
||||
- no long task of 200 ms or more after the initial load settles (three of
|
||||
those in 30 s is what trips the WebGL fallback, so the bar matches the
|
||||
codebase's own threshold);
|
||||
- JS heap within ±10% between minute 1 and minute 10 of a ten-minute run
|
||||
(no growth from tile churn: add and remove tiles and zoom a few times in
|
||||
between);
|
||||
- the initial load of six tiles completes with the server's event loop never
|
||||
blocked for more than one capture at a time (check `Server-Timing` on each
|
||||
`/terminal` response).
|
||||
|
||||
Missing a bar blocks the merge or lowers the tile cap, not the bar.
|
||||
- A server restart while typing into a tile: reconnect, refresh, no lost or
|
||||
doubled input.
|
||||
- A phone opened on one tiled session: the desktop tile keeps its size while
|
||||
active.
|
||||
|
||||
## Follow-ups (not in these PRs)
|
||||
|
||||
1. Make `captureActivePaneBuffer` async (`execFile`) and add a server-side limit
|
||||
on concurrent captures, so no client can stall the event loop with captures.
|
||||
2. When a session's PTY size changes, send `zc` to EVERY socket on that
|
||||
session. Today only the resizing socket hears back, so a second desktop
|
||||
viewer keeps a stale width and renders garbled output (#464).
|
||||
3. WebSocket backpressure (`bufferedAmount` threshold, drop and send `{t:'r'}`
|
||||
on drain) for grids over slow links.
|
||||
4. Tile parity extras: mouse-wheel forwarding for Claude's fullscreen renderer,
|
||||
a "Load full history" action inside a tile.
|
||||
5. WebGL in tiles, after measuring the DOM renderer with nine busy tiles.
|
||||
6. Named grid presets, possibly per owner on the server.
|
||||
7. The end state: the main terminal becomes a 1x1 grid of `TerminalTile`,
|
||||
which removes the singleton from `terminal-ui.js`.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **Clicking a tab that is not tiled.** Decided: a user-initiated pick
|
||||
leaves the grid and shows that session in the single
|
||||
view; the grid is kept for one-click return. App-driven selections never
|
||||
leave it either way. Alternative: swap that session into the focused tile.
|
||||
2. **The split pane.** Decided: keep it alongside the grid for now; the two
|
||||
share `TerminalTile` and never open together.
|
||||
3. **Persistence.** Decided: per device, restored on reload.
|
||||
4. **PR shape.** Decided: two PRs. PR 1 is the tile foundation (the split
|
||||
improves on its own), PR 2 is the grid.
|
||||
5. **Ctrl+W.** Decided: it never closes a session. Close Session has no
|
||||
default key (Ctrl+W is delete-word in every shell and agent CLI, and it
|
||||
killed sessions with no confirm); it stays bindable in App Settings →
|
||||
Shortcuts.
|
||||
|
||||
## Code anchors
|
||||
|
||||
Line numbers are approximate (as of 1.35.0) and drift; the names are stable.
|
||||
|
||||
| Area | Where |
|
||||
|---|---|
|
||||
| Split pane class and orchestration | `src/web/public/terminal-split.js` (`SplitTerminalPane`, `openSplitPane`, `closeSplitPane`, `_installSplitDividerDrag`, the `selectSession` and `_onSessionDeleted` wrappers) |
|
||||
| Split helpers | `src/web/public/constants.js` ~1592-1634 (`SPLIT_PANE_MIN_WIDTH`, `clampDividerPercent`, `buildSplitPickerSessions`), exported as `window.CodemanSplitPane` |
|
||||
| `selectSession` | `src/web/public/app.js` ~7844-8644; early return ~7868-7876; deferred panels ~8452-8523 |
|
||||
| `_cleanupPreviousSession` | `app.js` ~7377 |
|
||||
| Reliable input | `app.js` ~3558-3920 (`_sendInputAsync`, `_reliableSend`, `_nextSeq`, `_drainSession`, `_ackDelivery`, `_onWsInputAck`, `_redeliverSweep`); main socket URL ~3341 |
|
||||
| SSE terminal fallback | `app.js` `_onSessionTerminal` ~2192, `_onSessionNeedsRefresh` ~2916, `_onSessionClearTerminal` ~3020 |
|
||||
| Geometry | `terminal-ui.js` `syncTerminalGeometry` ~5894, `sendResize` ~5981, `_onPtyGeometryReport` ~6072, `throttledResize` ~1292-1429; `constants.js` `reconcilePtyGeometry` ~1850 |
|
||||
| Link provider | `terminal-ui.js` `registerFilePathLinkProvider` ~1831 |
|
||||
| Main key handler | `terminal-ui.js` ~552-718 |
|
||||
| Shortcut registry | `app.js` `DEFAULT_SHORTCUTS` ~406-557, `SHORTCUT_ACTIONS` ~1248, capture handler ~1263-1363 |
|
||||
| Status classifier | `app.js` `_sidebarRichRow` ~5058; `mobile-overview.js` `_mobileOverviewState` ~130; dot CSS `.home-sessions-dot--*` in styles.css |
|
||||
| Session action menu | `tab-rail-resize.js` `openTabRailActionMenu` ~318 |
|
||||
| Tab drag | `app.js` `setupTabDragHandlers` ~7137 |
|
||||
| Tab-group menu | `app.js` `openTabGroupMenu` ~6737 |
|
||||
| Image paste | `image-input.js` `_handleImagePaste` ~53, `_uploadAndInsertImages` ~130 |
|
||||
| Voice target | `voice-input.js` `start` ~666, `_insertText` ~962 |
|
||||
| WS route and caps | `src/web/routes/ws-routes.ts` (`MAX_WS_PER_SESSION`, frame handling), `src/web/ws-connection-registry.ts` |
|
||||
| Resize arbitration | `src/session.ts` `resize` / `claimDesktopSizing` ~4339-4426 |
|
||||
| Terminal capture | `src/web/routes/session-routes.ts` `GET /api/sessions/:id/terminal` ~2986; `src/tmux-manager.ts` `captureActivePaneBuffer` ~3825 |
|
||||
| Attach | `session-routes.ts` `POST /api/sessions/:id/interactive` ~1566 |
|
||||
@@ -9,16 +9,13 @@ Press `Ctrl+?` in the app for the same list in a floating overlay.
|
||||
| Shortcut | Action |
|
||||
| ------------------------------- | --------------------------------------------------------------- |
|
||||
| `Ctrl+K` (also `Cmd+K`, `Alt+K`)| Find an open session or start a new one. |
|
||||
| `Ctrl+W` | Kill the active session. |
|
||||
| `Ctrl+Tab` | Next session. |
|
||||
| `Alt+[` / `Alt+]` | Previous / next tab. |
|
||||
| `Alt+1` to `Alt+9` | Switch to tab N. Physical keys, so macOS Option layouts work. |
|
||||
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move the active tab left / right. |
|
||||
| `Alt+B` | Collapse / expand the session sidebar, when that layout is on. |
|
||||
|
||||
`Ctrl+W` is not a Codeman shortcut: it goes to the terminal, where shells and agent CLIs
|
||||
use it to delete the previous word. **Close Session** has no key by default; close a session
|
||||
from its tab, or bind a key to it in App Settings → Shortcuts.
|
||||
|
||||
## Terminal
|
||||
|
||||
| Shortcut | Action |
|
||||
|
||||
@@ -131,7 +131,7 @@ the tmux server or rebooting the machine.
|
||||
| To do this | Do that |
|
||||
| ------------------------- | ------------------------------------------------------------------- |
|
||||
| Interrupt the current turn | `Ctrl+C` with nothing selected, or the **Stop** button. |
|
||||
| Close one session | The tab's close control (`Ctrl+W` is delete-word in the terminal). |
|
||||
| Close one session | `Ctrl+W`, or the tab's close control. |
|
||||
| Stop the server, keep agents | `codeman web --stop`. The tmux sessions stay alive. |
|
||||
| Stop everything | `tmux -L codeman kill-server`. |
|
||||
|
||||
|
||||
@@ -69,6 +69,8 @@ by folder** (per device, on by default) shows changed files under collapsed fold
|
||||
window; off lists every file by its full path.
|
||||
|
||||
Most default to off. The stock desktop header is system stats, File Viewer, and the gear.
|
||||
**Header Stats Style** picks how the system stats and plan usage are drawn: *Tiles*
|
||||
(default; label over value with a bar underneath), *Compact* (two pills with a ring beside every value) or *As before* (the bars and the `5H · 7D` chip). Desktop only, per device.
|
||||
New header controls never appear on phones. Split is desktop-only regardless of this
|
||||
setting — the button and the feature both stay off below a ~1180px viewport, where two
|
||||
resizable panes plus their divider have nowhere to go.
|
||||
@@ -86,7 +88,9 @@ every session or only the active tab.
|
||||
| Interface Language | English or Simplified Chinese. Per device. |
|
||||
| Session List Layout | Header tab strip (default), a collapsible left sidebar, or the sidebar with detailed rows. See [The Dashboard](The-Dashboard#session-list-layout). |
|
||||
| Tab Orientation | Keeps the header list but turns the strip vertical beside the terminal, resizable, with detailed rows by default. Desktop and tablet only. |
|
||||
| Vertical Rail Order | *By activity* (default) sorts the rail the way the home screens are sorted; *Manual* keeps your tab order and drag-reordering. |
|
||||
| Tab Layout | *By state* (default): a row each for needs you, waiting, working and idle, sections in the rail and sidebar. *By case*: one box per case. *Ledger*: an aligned column grid. *Classic*: the single list as before. See [The Dashboard](The-Dashboard#tab-layouts). |
|
||||
| State Order | For *By state*: needs you on top (default) or at the bottom, right above the terminal. |
|
||||
| Vertical Rail Order | *By activity* (default) sorts the rail the way the home screens are sorted; *Manual* keeps your tab order and drag-reordering. With *By state* or *By case* it orders the rows inside each section. |
|
||||
| Tall Tabs | Taller tab strip. |
|
||||
| Pop-out Button on Tabs | Adds the detach control to tabs, with a per-tab override. |
|
||||
| Spawn Lineage Lines | Arcs from a parent tab to sessions it spawned. Desktop only, on by default. |
|
||||
|
||||
@@ -27,7 +27,7 @@ Session List Layout** can move it into a vertical sidebar on the left instead, a
|
||||
|
||||
| Layout | Behaviour |
|
||||
| -------------------- | --------------------------------------------------------------------------------- |
|
||||
| **Header tab strip** | The default. Wraps to a second row on desktop, scrolls sideways on a phone. |
|
||||
| **Header tab strip** | The default. On desktop it is one row per state by default (see [Tab layouts](#tab-layouts)); it scrolls sideways on a phone. |
|
||||
| **Left sidebar** | A vertical list with a filter box and a live session count. `Alt+B` collapses it to a narrow rail that keeps the status dots and task badges visible. On a phone it is an off-canvas drawer rather than a docked rail. A detailed variant adds the home screen's per-session line (`created 3d ago · working 12m`) and a status pill. |
|
||||
| **Vertical rail** | The strip turned vertical beside the terminal, resizable, with detailed rows by default. **Vertical Rail Order** sorts it by activity (blocked on you first, then longest running, then most recently quiet), the same order as the home screens; pick *Manual* to get your own order and drag-reordering back. **Tab groups:** pick *Move to new group* from a row's ⋯ menu (or Shift+F10 on it) to make the first one; a group header's menu (right-click, Shift+F10 or its ⋯ glyph) renames it (also F2), reorders or deletes it, rows move between groups from their own menu or by dragging with a mouse or pen, and a collapsed group stays collapsed on that device. Desktop and tablet only. |
|
||||
|
||||
@@ -35,6 +35,40 @@ It is the same list either way, just re-hosted: tab order, drag-to-reorder, the
|
||||
to `Alt+9` numbers and every status colour below behave identically in both. The setting is
|
||||
per device, so a sidebar on your desktop does not force one onto your phone.
|
||||
|
||||
## Tab layouts
|
||||
|
||||
**App Settings → Appearance → Tabs → Tab Layout** picks how the tabs are arranged. Per device.
|
||||
|
||||
| Layout | What it does |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------ |
|
||||
| **By state** (default) | Groups the tabs by what each session needs from you (below). |
|
||||
| **By case** | One box per case, labelled with the case and its tab count. Inside a box, `w75-api-gateway` reads just `w75`. A case with one tab gets a box with a colour swatch. |
|
||||
| **Ledger** | The same list on an aligned column grid: equal cells, monospace names, a coloured bar on the left of each cell instead of the dot (yellow waiting, red needs you). Desktop header only. |
|
||||
| **Classic** | The single list in tab order, as before. |
|
||||
|
||||
**By state** groups the tabs like this, most urgent on top:
|
||||
|
||||
| Group | Who is in it |
|
||||
| ------------- | ----------------------------------------------------------------------------------- |
|
||||
| **Needs you** | Red: a question or permission prompt is blocking the agent. A failed session too. |
|
||||
| **Waiting** | Yellow: the agent finished its turn and is waiting for your next prompt. |
|
||||
| **Working** | A turn is running. |
|
||||
| **Idle** | Everything quiet, including ended sessions, agents that exited inside their pane, and web tabs. |
|
||||
|
||||
In the header each group is a row with its name and count on the left (Idle, the quiet
|
||||
default, carries no label); a group with more tabs than fit on one line continues on the
|
||||
next line. **State Order → Needs you at the
|
||||
bottom** turns the rows the other way up, so the needs-you row sits right above the
|
||||
terminal. Empty groups are not shown. These are the same states the phone overview and the
|
||||
desktop home rail use, and tabs move between groups on their own as their state changes.
|
||||
|
||||
Both groupings also apply to the vertical rail and the left sidebar, as labelled sections.
|
||||
Inside a group or a box tabs keep your tab order (on a rail sorted *By activity*, the
|
||||
activity order), and the `Alt+1` to `Alt+9` numbers never change. Dragging reorders tabs
|
||||
within a group or box. On a phone the strip stays a single scrolling row in group order,
|
||||
without labels or boxes. If you have named tab groups in the vertical rail, those take
|
||||
precedence there.
|
||||
|
||||
## Session tabs
|
||||
|
||||
One tab per session, in your order, and that order syncs across your devices.
|
||||
@@ -64,7 +98,7 @@ reloading while a permission prompt is blocking does not lose the red tab.
|
||||
| Jump to tab N | `Alt+1` to `Alt+9` (the number on the tab) |
|
||||
| Next / previous | `Ctrl+Tab`, `Alt+[`, `Alt+]` |
|
||||
| Move the active tab | `Ctrl+Shift+{`, `Ctrl+Shift+}` |
|
||||
| Close | The tab's close control (no key by default) |
|
||||
| Close | `Ctrl+W` |
|
||||
| Find any session, open or past | `Ctrl+K` (also `Cmd+K` and `Alt+K`) |
|
||||
|
||||
Tabs can also be dragged to reorder.
|
||||
@@ -102,7 +136,7 @@ The right side of the header. Almost all of these are off until you enable them
|
||||
| ---------------------- | ------------------ | ------------------------------------------------------------------------------- |
|
||||
| Connection dot | Always on | SSE connection health. Green is connected. |
|
||||
| Font size `-` / `+` | Always on | `Ctrl +` / `Ctrl -` do the same. |
|
||||
| CPU / MEM bars | On | Server resource use. |
|
||||
| CPU / MEM | On | Server resource use. Drawn as tiles by default; see Header Stats Style below. |
|
||||
| File Viewer | On | Toggles the file browser panel. |
|
||||
| Settings gear | Always on | App Settings. |
|
||||
| Plan usage chip | On, desktop only | Live Claude subscription usage. Claude-only, and needs its telemetry exporter, which the same setting installs. |
|
||||
@@ -121,6 +155,19 @@ The right side of the header. Almost all of these are off until you enable them
|
||||
| Tunnel indicator | When a tunnel runs | Cloudflare tunnel status. |
|
||||
| Admin panel | Multi-user only | User administration. |
|
||||
|
||||
### Header Stats Style
|
||||
|
||||
The connection readout, CPU, MEM and the plan usage windows can be drawn three ways
|
||||
(**App Settings → Header & Panels → Header Stats Style**, per device, desktop only):
|
||||
|
||||
| Style | Look |
|
||||
| -------------- | -------------------------------------------------------------------------------------- |
|
||||
| **Tiles** | The default. One small tile each (`WS live`, `CPU 22%`, `MEM 14.4G`, `5H 28%`, `7D 35%`): label over value, a thin bar underneath, no icons. |
|
||||
| **Compact** | Two slim pills, `WS · CPU · MEM` and the plan windows, with a small ring beside every value. Hands the tabs back the most room. |
|
||||
| **As before** | The bars and the `5H · 7D` chip, exactly as they were. |
|
||||
|
||||
Hiding System Stats or Plan Usage still hides them in every style.
|
||||
|
||||
New header controls never appear on phones. Phone layout is deliberately minimal and is
|
||||
covered in [Mobile Guide](Mobile-Guide).
|
||||
|
||||
|
||||
+455
-95
@@ -419,14 +419,7 @@ const DEFAULT_SHORTCUTS = [
|
||||
id: 'close-session',
|
||||
group: 'Session',
|
||||
label: 'Close Session',
|
||||
// ⚠️ No default key. This used to be Ctrl+W, which is "delete the previous
|
||||
// word" in every shell, readline prompt and agent CLI, so muscle memory
|
||||
// killed the session (tmux and the CLI, with no confirm) mid-sentence, and
|
||||
// with the split open it was not even the pane being typed in. Ctrl+W now
|
||||
// reaches the terminal like any other key. Closing stays on the tab's close
|
||||
// control and menu (with their confirm), and anyone who wants a key binds
|
||||
// one in App Settings → Shortcuts.
|
||||
bindings: [],
|
||||
bindings: [{ modifiers: ['ctrl'], key: 'w' }],
|
||||
action: 'killActiveSession',
|
||||
},
|
||||
{
|
||||
@@ -874,11 +867,6 @@ class CodemanApp {
|
||||
// writes when the freshly computed descriptor is identical (COD-136).
|
||||
this._lastIndicatorDescriptor = null;
|
||||
this._postDraining = new Set(); // sessionIds with an in-flight POST drainer
|
||||
// Terminal sockets OTHER than the primary one (`this._ws`), keyed by the
|
||||
// session they are bound to: the split pane's second terminal registers its
|
||||
// socket here so its input rides the same exactly-once queue. Values are
|
||||
// `{ ws, lastRecvAt }` handles owned by that terminal (see _inputSocketFor).
|
||||
this._extraInputSockets = new Map();
|
||||
this._persistReliableTimer = null;
|
||||
this._reliableAckTimeoutMs = 4000; // unacked WS frame older than this ⇒ socket likely dead
|
||||
this._reliableMaxBytes = 256 * 1024; // cap on the persisted backlog
|
||||
@@ -3241,14 +3229,20 @@ class CodemanApp {
|
||||
// broken feature rather than as an idle window (reported 2026-09-01). A
|
||||
// missing CODEX bucket means the opposite — that plan has no such limit —
|
||||
// so those stay omitted rather than showing a dash forever.
|
||||
// Every window also carries a ring (the Compact header style) and a meter
|
||||
// (Tiles). styles.css hides both in the classic style, so the chip there
|
||||
// reads exactly as before. `fill` is clamped for the two graphics only; the
|
||||
// label keeps the real number.
|
||||
const seg = (label, p, idle) => {
|
||||
if (p === null) {
|
||||
if (!idle) return '';
|
||||
return `<span class="pu-win pu-win-idle"><span class="pu-label">${label}</span><span class="pu-val">—</span></span>`;
|
||||
return `<span class="pu-win pu-win-idle"><span class="pu-ring" style="--pu:0"></span><span class="pu-label">${label}</span><span class="pu-val">—</span><span class="pu-meter"><i style="width:0%"></i></span></span>`;
|
||||
}
|
||||
const n = Math.round(Number(p));
|
||||
if (!Number.isFinite(n)) return '';
|
||||
return `<span class="pu-win"><span class="pu-label">${label}</span><span class="pu-val ${colorClass(n)}">${n}%</span></span>`;
|
||||
const fill = Math.min(100, Math.max(0, n));
|
||||
const cls = colorClass(n);
|
||||
return `<span class="pu-win"><span class="pu-ring ${cls}" style="--pu:${fill}"></span><span class="pu-label">${label}</span><span class="pu-val ${cls}">${n}%</span><span class="pu-meter ${cls}"><i style="width:${fill}%"></i></span></span>`;
|
||||
};
|
||||
// The provider label only earns its space when there is more than one
|
||||
// provider to tell apart: a machine with Claude alone shows bare windows.
|
||||
@@ -3409,7 +3403,7 @@ class CodemanApp {
|
||||
} else if (msg.t === 'ia') {
|
||||
// Input ACK — the server applied (or deduped) this seq; drop it from
|
||||
// the durable queue so it can never be re-delivered/lost.
|
||||
this._onWsInputAck(msg.seq, msg, sessionId);
|
||||
this._onWsInputAck(msg.seq, msg);
|
||||
} else if (msg.t === 'zc') {
|
||||
// Resize confirm — the geometry the PTY actually holds, which is not
|
||||
// always the one this client asked for (issue #464).
|
||||
@@ -3591,49 +3585,6 @@ class CodemanApp {
|
||||
this._reliableSend(sessionId, input, useMux);
|
||||
}
|
||||
|
||||
/**
|
||||
* The OPEN terminal socket bound to `sessionId`, or null: the primary socket
|
||||
* first, then one registered by a second terminal (the split pane). The
|
||||
* delivery layer below asks this instead of reading `this._ws` directly, so a
|
||||
* second terminal's input gets the same exactly-once queue, ACKs and
|
||||
* half-open detection as the primary's.
|
||||
*
|
||||
* Returns `{ ws, lastRecvAt }`: `lastRecvAt` is the socket's last received
|
||||
* frame, which `_redeliverSweep` reads to tell a dead socket from a slow ACK.
|
||||
*/
|
||||
_inputSocketFor(sessionId) {
|
||||
if (!sessionId) return null;
|
||||
if (this._ws && this._ws.readyState === WebSocket.OPEN && this._wsSessionId === sessionId) {
|
||||
return { ws: this._ws, lastRecvAt: this._wsLastRecvAt };
|
||||
}
|
||||
const handle = this._extraInputSockets?.get(sessionId);
|
||||
if (handle && handle.ws && handle.ws.readyState === WebSocket.OPEN) return handle;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a second terminal's socket for `sessionId` (call from its onopen).
|
||||
* `handle` is `{ ws, lastRecvAt }`, owned by the caller, which must bump
|
||||
* `handle.lastRecvAt` on every received frame. Stamped here so a socket that
|
||||
* just opened does not look silent to the redelivery sweep, which would
|
||||
* otherwise force-close it as half-open on the first stale record.
|
||||
*/
|
||||
_registerInputSocket(sessionId, handle) {
|
||||
if (!sessionId || !handle) return;
|
||||
handle.lastRecvAt = Date.now();
|
||||
if (!this._extraInputSockets) this._extraInputSockets = new Map();
|
||||
this._extraInputSockets.set(sessionId, handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a registration, but only the one `handle` made: a replacement socket
|
||||
* registers its own handle before the old one's close lands, and that late
|
||||
* close must not unregister the socket that replaced it.
|
||||
*/
|
||||
_unregisterInputSocket(sessionId, handle) {
|
||||
if (this._extraInputSockets?.get(sessionId) === handle) this._extraInputSockets.delete(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget input for EPHEMERAL, loss-tolerant streams (e.g. wheel-scroll
|
||||
* reports). Unlike _sendInputAsync, this never enters the durable seq/ACK queue,
|
||||
@@ -3645,10 +3596,9 @@ class CodemanApp {
|
||||
*/
|
||||
_sendInputEphemeral(sessionId, input) {
|
||||
if (!sessionId || !input) return;
|
||||
const sock = this._inputSocketFor(sessionId);
|
||||
if (sock) {
|
||||
if (this._ws && this._ws.readyState === WebSocket.OPEN && this._wsSessionId === sessionId) {
|
||||
try {
|
||||
sock.ws.send(JSON.stringify({ t: 'i', d: input }));
|
||||
this._ws.send(JSON.stringify({ t: 'i', d: input }));
|
||||
return;
|
||||
} catch {
|
||||
// socket died mid-send — fall through to a best-effort POST
|
||||
@@ -3702,12 +3652,11 @@ class CodemanApp {
|
||||
// over the single ordered stream. They stay pending until the server ACKs
|
||||
// them ({t:'ia'}); a frame swallowed by a half-open socket is re-sent after
|
||||
// the sweep force-reconnects (which resets sentAt=0 in _onWsReady).
|
||||
const sock = this._inputSocketFor(sessionId);
|
||||
if (sock) {
|
||||
if (this._ws && this._ws.readyState === WebSocket.OPEN && this._wsSessionId === sessionId) {
|
||||
for (const rec of list) {
|
||||
if (rec.sentAt !== 0) continue;
|
||||
try {
|
||||
sock.ws.send(JSON.stringify({ t: 'i', d: rec.data, seq: rec.seq, cid: this._clientId }));
|
||||
this._ws.send(JSON.stringify({ t: 'i', d: rec.data, seq: rec.seq, cid: this._clientId }));
|
||||
rec.sentAt = Date.now();
|
||||
rec.tries++;
|
||||
} catch {
|
||||
@@ -3728,7 +3677,7 @@ class CodemanApp {
|
||||
if (!cur || cur.length === 0) break;
|
||||
// If the WebSocket came back mid-drain, yield to it (the acked stream)
|
||||
// so we don't redundantly re-POST what onopen is already re-sending.
|
||||
if (this._inputSocketFor(sessionId)) {
|
||||
if (this._ws && this._ws.readyState === WebSocket.OPEN && this._wsSessionId === sessionId) {
|
||||
break;
|
||||
}
|
||||
const rec = cur[0];
|
||||
@@ -3816,10 +3765,8 @@ class CodemanApp {
|
||||
* called a duplicate is the mechanism working as designed — the original did
|
||||
* land — and re-sending it would type the same thing twice.
|
||||
*/
|
||||
_onWsInputAck(seq, msg, sessionId = this._wsSessionId) {
|
||||
// `sessionId` is the session of the socket the ACK arrived on: `{t:'ia'}`
|
||||
// frames carry none, and with a second terminal's socket in play
|
||||
// `this._wsSessionId` is no longer the only candidate.
|
||||
_onWsInputAck(seq, msg) {
|
||||
const sessionId = this._wsSessionId;
|
||||
if (!sessionId || !Number.isInteger(seq)) return;
|
||||
if (msg && msg.err) {
|
||||
// Refused for good (e.g. over the size limit): retrying cannot help.
|
||||
@@ -3864,20 +3811,19 @@ class CodemanApp {
|
||||
for (const sessionId of [...this._pendingDeliveries.keys()]) {
|
||||
const list = this._pendingDeliveries.get(sessionId);
|
||||
if (!list || list.length === 0) continue;
|
||||
const sock = this._inputSocketFor(sessionId);
|
||||
if (sock) {
|
||||
const isActiveWs =
|
||||
this._ws && this._ws.readyState === WebSocket.OPEN && this._wsSessionId === sessionId;
|
||||
if (isActiveWs) {
|
||||
const oldest = list[0];
|
||||
// Only tear the socket down when the oldest unacked frame is stale AND the
|
||||
// socket has been silent for the timeout: a connection still delivering
|
||||
// output/ACKs is alive (the ACK is just behind), so force-closing it would
|
||||
// cause needless WS↔HTTP flapping. A truly half-open socket goes quiet.
|
||||
// Silence is measured on THIS socket: the primary's last frame says
|
||||
// nothing about a second terminal's connection, and the reverse.
|
||||
const stale = oldest && oldest.sentAt && Date.now() - oldest.sentAt > this._reliableAckTimeoutMs;
|
||||
const silent = Date.now() - (sock.lastRecvAt || 0) > this._reliableAckTimeoutMs;
|
||||
const silent = Date.now() - this._wsLastRecvAt > this._reliableAckTimeoutMs;
|
||||
if (stale && silent) {
|
||||
try {
|
||||
sock.ws.close(); // half-open: never recovers on its own — force reconnect
|
||||
this._ws.close(); // half-open: never recovers on its own — force reconnect
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@@ -4081,6 +4027,36 @@ class CodemanApp {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The two words the Tiles header style shows for the connection indicator
|
||||
* (label over value), derived from the descriptor rather than added to it,
|
||||
* so the descriptor and its pinned strings stay exactly what they were. The
|
||||
* classic text line (queued bytes and all) stays in the DOM and the full
|
||||
* detail stays in the tooltip.
|
||||
* @param {{dotClass: string, text: string}} desc
|
||||
* @returns {{label: string, value: string, state: string}}
|
||||
*/
|
||||
_connectionTileWords(desc) {
|
||||
const state = (desc.dotClass || '').replace('connection-dot', '').trim();
|
||||
const text = desc.text || '';
|
||||
switch (state) {
|
||||
case 'connected':
|
||||
return { label: 'WS', value: 'live', state };
|
||||
case 'fallback':
|
||||
return { label: 'HTTP', value: 'fallback', state };
|
||||
case 'offline':
|
||||
return { label: 'NET', value: 'offline', state };
|
||||
case 'draining':
|
||||
return { label: 'SEND', value: 'queued', state };
|
||||
case 'reconnecting':
|
||||
// The same dot covers the terminal WebSocket and, with no session
|
||||
// open, the SSE event stream; the classic text already tells them apart.
|
||||
return { label: text.startsWith('WS') ? 'WS' : 'SSE', value: 'retry', state };
|
||||
default:
|
||||
return { label: '', value: '', state };
|
||||
}
|
||||
}
|
||||
|
||||
_updateConnectionIndicator() {
|
||||
const indicator = this.$('connectionIndicator');
|
||||
const dot = this.$('connectionDot');
|
||||
@@ -4108,6 +4084,14 @@ class CodemanApp {
|
||||
dot.className = next.dotClass;
|
||||
text.textContent = next.text;
|
||||
indicator.title = next.title;
|
||||
const tileLabel = this.$('connectionTileLabel');
|
||||
const tileValue = this.$('connectionTileValue');
|
||||
if (tileLabel && tileValue) {
|
||||
const words = this._connectionTileWords(next);
|
||||
tileLabel.textContent = words.label;
|
||||
tileValue.textContent = words.value;
|
||||
tileValue.className = `connection-tile-value ${words.state}`.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4588,10 +4572,6 @@ class CodemanApp {
|
||||
// a give-up) nothing else would re-establish it from here.
|
||||
if (this._wsSessionId !== restoreId) this._connectWs(restoreId);
|
||||
void this._onSessionNeedsRefresh({ id: restoreId });
|
||||
// The split pane's second terminal reconnects on its own backoff (up to
|
||||
// 10 s between tries); the server is back now, so skip the wait. A no-op
|
||||
// while its socket is open, stopped for good, or destroyed.
|
||||
this._splitPane?.reconnectNow?.();
|
||||
} else {
|
||||
this.activeSessionId = null;
|
||||
// `auto`: the app is restoring a session on load, not a human opening
|
||||
@@ -4816,6 +4796,333 @@ class CodemanApp {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the tab list groups by state (`tabArrangement: 'state'`, the default;
|
||||
* Discussion #426 option C): a row per state in the header strip, a section
|
||||
* per state in the flat side rail and the sidebar, most urgent on top.
|
||||
*
|
||||
* Read off <html> like the rail gates (applyTabOrientation() owns the
|
||||
* attribute). Named groups in the vertical rail still win, because they are
|
||||
* the user's own structure: `_tabTriageLayout()` returns null while the
|
||||
* grouped projection is on, and the grouped tree renders as it always did.
|
||||
*/
|
||||
isTabTriage() {
|
||||
return document.documentElement.dataset.tabArrangement === 'state';
|
||||
}
|
||||
|
||||
/**
|
||||
* Order values and visible groups for one render pass, or null when the list
|
||||
* is not grouped by state. The pure core is `CodemanTabTriage.layout()`
|
||||
* (constants.js); this only feeds it the same classification both home
|
||||
* screens and the sorted rail use.
|
||||
*
|
||||
* Inside a group a row keeps its tab order on the header strip, so the strip
|
||||
* only moves a tab when its state changes. A sorted rail ranks rows inside
|
||||
* each section the way it ranks the whole flat rail (`railSortOrder`).
|
||||
*
|
||||
* @param {Array<string>} ids live session ids, in tab order
|
||||
* @param {object|null} groupProjection the grouped rail's projection, if any
|
||||
* @param {Map<string, number>|null} railSortOrder `_tabRailSortOrder(ids)`
|
||||
*/
|
||||
_tabTriageLayout(ids, groupProjection, railSortOrder) {
|
||||
if (groupProjection || !this.isTabTriage()) return null;
|
||||
if (!window.CodemanTabTriage || typeof this._mobileOverviewState !== 'function') return null;
|
||||
const rows = [];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const session = this.sessions.get(ids[i]);
|
||||
if (!session) continue;
|
||||
const state = this._mobileOverviewState(session, this.pendingHooks?.get(ids[i]));
|
||||
rows.push({
|
||||
id: ids[i],
|
||||
state,
|
||||
exited: !!this._mobileOverviewExit?.(state, session),
|
||||
pos: railSortOrder?.has(ids[i]) ? railSortOrder.get(ids[i]) : i,
|
||||
});
|
||||
}
|
||||
const webviewIds = (this.webviewOrder || []).filter((wid) => this.webviews?.has(wid));
|
||||
const reverse = document.documentElement.dataset.tabStateOrder === 'urgent-last';
|
||||
return window.CodemanTabTriage.layout(rows, webviewIds, { reverse });
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the state headings, the row breaks and the web tabs' `order` in step
|
||||
* with one pass's triage layout. Runs after BOTH render paths, because a
|
||||
* session changing state is an incremental pass (no tab is added or removed)
|
||||
* and can still empty a group or fill a new one.
|
||||
*
|
||||
* Headings and breaks are keyed by group and reconciled in place, never
|
||||
* rebuilt, so an SSE tick that changes nothing writes nothing. They are
|
||||
* direct children of #sessionTabs placed purely by `order`, so where they sit
|
||||
* in the DOM does not matter, and `aria-hidden` keeps them out of the tablist,
|
||||
* whose children must all be tabs. (A tab's state is not announced either way:
|
||||
* its status dot is aria-hidden, as before.) With `triage` null this removes
|
||||
* them all and clears the web tabs' inline order, which is what leaves the
|
||||
* ungrouped strip exactly as it was.
|
||||
*/
|
||||
_syncTabTriageChrome(container, triage) {
|
||||
if (!container) return;
|
||||
this._lastTabTriage = triage;
|
||||
container.classList.toggle('tabs-triage', !!triage);
|
||||
const wanted = new Map((triage?.groups || []).map((group) => [group.key, group]));
|
||||
for (const el of [...container.querySelectorAll(':scope > .tab-triage-head, :scope > .tab-triage-break')]) {
|
||||
if (!wanted.has(el.dataset.triageGroup)) el.remove();
|
||||
}
|
||||
const ensure = (className, key) => {
|
||||
let el = container.querySelector(`:scope > .${className}[data-triage-group="${key}"]`);
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.className = className === 'tab-triage-head' ? `tab-triage-head tab-triage-head--${key}` : className;
|
||||
el.dataset.triageGroup = key;
|
||||
el.setAttribute('aria-hidden', 'true');
|
||||
container.appendChild(el);
|
||||
}
|
||||
return el;
|
||||
};
|
||||
for (const group of wanted.values()) {
|
||||
const head = ensure('tab-triage-head', group.key);
|
||||
// A quiet group (idle) keeps its heading as the row's anchor but draws
|
||||
// no label or count.
|
||||
head.classList.toggle('tab-triage-head--quiet', !!group.quiet);
|
||||
if (!group.quiet && !head.firstElementChild) {
|
||||
const label = document.createElement('span');
|
||||
label.className = 'tab-triage-label';
|
||||
label.textContent = group.label;
|
||||
const count = document.createElement('span');
|
||||
count.className = 'tab-triage-count';
|
||||
head.append(label, count);
|
||||
}
|
||||
const count = String(group.count);
|
||||
if (!group.quiet && head.lastElementChild.textContent !== count) head.lastElementChild.textContent = count;
|
||||
// The first row's heading is the one that starts beside the brand in the
|
||||
// header strip (styles.css); every later row starts under it.
|
||||
head.classList.toggle('tab-triage-head--lead', group === triage.groups[0]);
|
||||
const headOrder = String(group.headOrder);
|
||||
if (head.style.order !== headOrder) head.style.order = headOrder;
|
||||
const brk = ensure('tab-triage-break', group.key);
|
||||
const breakOrder = String(group.breakOrder);
|
||||
if (brk.style.order !== breakOrder) brk.style.order = breakOrder;
|
||||
}
|
||||
for (const web of container.querySelectorAll(':scope > .session-tab[data-webview-id]')) {
|
||||
const wid = web.dataset.webviewId;
|
||||
const value = triage?.webOrder.has(wid) ? String(triage.webOrder.get(wid)) : '';
|
||||
if (web.style.order !== value) web.style.order = value;
|
||||
}
|
||||
this._sizeTabTriageGutter(container, triage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Size the header strip's two measured lengths (styles.css, "Header strip,
|
||||
* wrapping"): `--tab-triage-gutter`, the label column, as wide as the widest
|
||||
* label on screen so a row never carries a fixed gutter's worth of empty
|
||||
* space; and `--tab-triage-brand`, the brand's width, because the brand sits
|
||||
* over the strip's top-left corner and only the FIRST row starts beside it,
|
||||
* every later row starting under it.
|
||||
*
|
||||
* The labels are measured only when their text changes (a group appears,
|
||||
* goes, or its count gains a digit) and once more when the web fonts finish
|
||||
* loading. The brand is watched by a ResizeObserver (a display-name change,
|
||||
* the sidebar toggle appearing), so a render pass never forces a layout read
|
||||
* for it. The vertical lists use neither length and are never measured.
|
||||
*/
|
||||
_sizeTabTriageGutter(container, triage) {
|
||||
const inHeader = !!container.parentElement?.classList.contains('session-tabs-host');
|
||||
if (!triage || !inHeader) {
|
||||
if (container.style.getPropertyValue('--tab-triage-gutter')) container.style.removeProperty('--tab-triage-gutter');
|
||||
if (container.style.getPropertyValue('--tab-triage-brand')) container.style.removeProperty('--tab-triage-brand');
|
||||
this._tabTriageGutterKey = null;
|
||||
return;
|
||||
}
|
||||
this._watchTabTriageBrand(container);
|
||||
if (Number.isFinite(this._tabTriageBrandWidth)) {
|
||||
const brand = `${this._tabTriageBrandWidth}px`;
|
||||
if (container.style.getPropertyValue('--tab-triage-brand') !== brand) {
|
||||
container.style.setProperty('--tab-triage-brand', brand);
|
||||
}
|
||||
}
|
||||
const key = triage.groups.map((g) => `${g.key}:${g.count}`).join('|');
|
||||
if (key === this._tabTriageGutterKey) return;
|
||||
let widest = 0;
|
||||
for (const head of container.querySelectorAll(':scope > .tab-triage-head')) {
|
||||
let width = 0;
|
||||
for (const part of head.children) width += part.getBoundingClientRect().width;
|
||||
widest = Math.max(widest, width + 5 * Math.max(0, head.children.length - 1));
|
||||
}
|
||||
// Hidden (display: none on phones, or a detached strip): nothing to size.
|
||||
if (!widest) return;
|
||||
this._tabTriageGutterKey = key;
|
||||
container.style.setProperty('--tab-triage-gutter', `${Math.ceil(widest + 10)}px`);
|
||||
if (!this._tabTriageFontsHooked && document.fonts?.ready) {
|
||||
this._tabTriageFontsHooked = true;
|
||||
document.fonts.ready.then(() => {
|
||||
this._tabTriageGutterKey = null;
|
||||
this._sizeTabTriageGutter(this.$('sessionTabs'), this._lastTabTriage);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep `_tabTriageBrandWidth` (the header brand plus the gap after it) in
|
||||
* step with the brand, once per page. The first observation arrives right
|
||||
* after `observe()`, so the width is known from the first frame on.
|
||||
*/
|
||||
_watchTabTriageBrand(container) {
|
||||
if (this._tabTriageBrandObserver !== undefined) return;
|
||||
const brand = container.closest('.header')?.querySelector(':scope > .header-brand');
|
||||
if (!brand || typeof ResizeObserver !== 'function') {
|
||||
this._tabTriageBrandObserver = null;
|
||||
return;
|
||||
}
|
||||
const gap = 8;
|
||||
this._tabTriageBrandWidth = Math.ceil(brand.getBoundingClientRect().width + gap);
|
||||
this._tabTriageBrandObserver = new ResizeObserver((entries) => {
|
||||
const box = entries[0]?.borderBoxSize?.[0];
|
||||
const width = Math.ceil((box ? box.inlineSize : brand.getBoundingClientRect().width) + gap);
|
||||
if (width === this._tabTriageBrandWidth) return;
|
||||
this._tabTriageBrandWidth = width;
|
||||
this._sizeTabTriageGutter(this.$('sessionTabs'), this._lastTabTriage);
|
||||
});
|
||||
this._tabTriageBrandObserver.observe(brand);
|
||||
}
|
||||
|
||||
/**
|
||||
* A drag in a grouped strip (by state or by case) may only reorder WITHIN a
|
||||
* group. Inside a group the rows sit in tab order, so a drop there moves the
|
||||
* tab exactly where it was dropped; across groups the dragged tab would stay
|
||||
* in its own group (its state or case did not change) and land somewhere the
|
||||
* user did not put it. State groups are bands of `order` values, so comparing
|
||||
* bands is enough; case clusters are boxes, so the box decides.
|
||||
*/
|
||||
_isTabDropAcrossGroups(targetTab) {
|
||||
const container = this.$('sessionTabs');
|
||||
if (!container || !this.draggedTabId || !targetTab) return false;
|
||||
const triage = container.classList.contains('tabs-triage');
|
||||
const clusters = container.classList.contains('tabs-clusters');
|
||||
if (!triage && !clusters) return false;
|
||||
const dragged = container.querySelector(`.session-tab[data-id="${this.draggedTabId}"]`);
|
||||
if (!dragged) return false;
|
||||
// Clusters are real boxes: a drop belongs to the box it lands in.
|
||||
if (clusters) return dragged.closest('.tab-cluster') !== targetTab.closest('.tab-cluster');
|
||||
const stride = window.CodemanTabTriage?.STRIDE || 10000;
|
||||
const band = (el) => Math.floor((Number(el.style.order) || 0) / stride);
|
||||
return band(dragged) !== band(targetTab);
|
||||
}
|
||||
|
||||
/** True when the tab list is clustered by case (`tabArrangement: 'case'`, Discussion #426 option A). */
|
||||
isTabClusters() {
|
||||
return document.documentElement.dataset.tabArrangement === 'case';
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the header strip is drawn as a ledger (`tabArrangement: 'ledger'`,
|
||||
* Discussion #426 option B): the flat list on an aligned column grid with a
|
||||
* status bar per cell. Pure CSS on `.tabs-ledger`, scoped to the desktop
|
||||
* header strip; the rail and the sidebar keep their flat list.
|
||||
*/
|
||||
isTabLedger() {
|
||||
return document.documentElement.dataset.tabArrangement === 'ledger';
|
||||
}
|
||||
|
||||
/**
|
||||
* Which case a session belongs to, for clustering: the case whose path is the
|
||||
* longest prefix of its working directory (`_mobileOverviewCaseFor()`, the
|
||||
* home screens' own match), else the directory itself, else the session alone.
|
||||
*/
|
||||
_tabClusterIdentity(session, id) {
|
||||
const dir = (session.workingDir || '').replace(/\/+$/, '');
|
||||
const match =
|
||||
dir && typeof this._mobileOverviewCaseFor === 'function' ? this._mobileOverviewCaseFor(dir, this.cases) : null;
|
||||
if (match) return { key: match.path, label: match.name || '' };
|
||||
if (dir) return { key: dir, label: dir.split('/').pop() || dir };
|
||||
return { key: `session:${id}`, label: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The cluster layout for one render pass, or null when the list is not
|
||||
* clustered. Named groups in the vertical rail win, exactly as for the state
|
||||
* grouping. `key` is the whole structure as a string: the incremental render
|
||||
* path compares it with the last full render's and rebuilds when it differs,
|
||||
* because a cluster is a real box and a patch in place cannot move a tab into
|
||||
* another one. Membership only changes when sessions come and go (already a
|
||||
* full rebuild) or when the case list arrives, so this rarely fires.
|
||||
*
|
||||
* @param {Array<string>} ids live session ids, in tab order
|
||||
* @param {object|null} groupProjection the grouped rail's projection, if any
|
||||
*/
|
||||
_tabClusterLayout(ids, groupProjection) {
|
||||
if (groupProjection || !this.isTabClusters() || !window.CodemanTabClusters) return null;
|
||||
const rows = [];
|
||||
for (const id of ids) {
|
||||
const session = this.sessions.get(id);
|
||||
if (session) rows.push({ id, ...this._tabClusterIdentity(session, id) });
|
||||
}
|
||||
const clusters = window.CodemanTabClusters.compute(rows);
|
||||
// Only a cluster with company drops the case from its tab names.
|
||||
const labelFor = new Map();
|
||||
for (const cluster of clusters) {
|
||||
if (cluster.ids.length > 1) for (const id of cluster.ids) labelFor.set(id, cluster.label);
|
||||
}
|
||||
const webviewIds = (this.webviewOrder || []).filter((wid) => this.webviews?.has(wid));
|
||||
const key = JSON.stringify([clusters.map((c) => [c.key, c.label, c.ids]), webviewIds]);
|
||||
return { clusters, labelFor, webviewIds, key };
|
||||
}
|
||||
|
||||
/**
|
||||
* The cluster boxes for the full render: one box per case, labelled with its
|
||||
* colour swatch, name and count, and a box per open web tab, which has no
|
||||
* case. The header strip shows only the swatch for a case with one tab
|
||||
* (styles.css); the rail and the sidebar label every case. Rows are the
|
||||
* caller's own markup, so a tab is byte-identical to the flat strip's apart
|
||||
* from its name split.
|
||||
*/
|
||||
_renderTabClusters(layout, rowHtml, webviewSlotStart) {
|
||||
const parts = [];
|
||||
for (const cluster of layout.clusters) {
|
||||
const rows = cluster.ids.map((id) => rowHtml.get(id) || '').join('');
|
||||
const single = cluster.ids.length < 2;
|
||||
const head =
|
||||
'<span class="tab-cluster-label" aria-hidden="true"><span class="tab-cluster-swatch"></span>' +
|
||||
`<span class="tab-cluster-name" data-i18n-skip>${escapeHtml(cluster.label)}</span>` +
|
||||
`<span class="tab-cluster-count">${cluster.ids.length}</span></span>`;
|
||||
parts.push(
|
||||
`<div class="tab-cluster${single ? ' tab-cluster--single' : ''}" role="presentation" data-cluster-key="${escapeHtml(cluster.key)}" style="--cluster-color: var(--session-${cluster.color})">${head}${rows}</div>`
|
||||
);
|
||||
}
|
||||
layout.webviewIds.forEach((wid, i) => {
|
||||
const tab = this.renderWebviewTab?.(wid, webviewSlotStart + i) || '';
|
||||
if (tab) parts.push(`<div class="tab-cluster tab-cluster--single tab-cluster--web" role="presentation">${tab}</div>`);
|
||||
});
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab label, as markup. #232: a described name (`w3-x: fix login`) shows
|
||||
* just the description, the generated id kept in a hidden prefix span. Inside
|
||||
* a case cluster a generated `w75-api-gateway` shows `w75`, the `-api-gateway`
|
||||
* kept in a `.tab-name-case` span that only `.tabs-clusters` hides, so the full
|
||||
* name stays in the DOM (copy, find-in-page, the rename editor).
|
||||
*/
|
||||
_tabNameHtml(name, clusterLabel) {
|
||||
const parsed = parseSessionPrefix(name);
|
||||
if (parsed && parsed.suffix) {
|
||||
return `<span class="tab-name-prefix">${escapeHtml(parsed.prefix)}: </span>${escapeHtml(parsed.suffix)}`;
|
||||
}
|
||||
const split = clusterLabel ? window.CodemanTabClusters?.nameSplit(name, clusterLabel) : null;
|
||||
if (split) return `${escapeHtml(split.shown)}<span class="tab-name-case">${escapeHtml(split.hidden)}</span>`;
|
||||
return escapeHtml(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* The arrangement classes on #sessionTabs that are not owned by a sync of
|
||||
* their own (`tabs-triage` is `_syncTabTriageChrome()`'s): `tabs-clusters`
|
||||
* while case clusters are drawn, `tabs-ledger` while the ledger is on. The
|
||||
* ledger never applies inside the grouped rail.
|
||||
*/
|
||||
_syncTabArrangementClasses(container, { clusters, groupProjection }) {
|
||||
if (!container) return;
|
||||
container.classList.toggle('tabs-clusters', !!clusters);
|
||||
container.classList.toggle('tabs-ledger', this.isTabLedger() && !groupProjection);
|
||||
}
|
||||
|
||||
/**
|
||||
* True where the sidebar is a MODAL off-canvas drawer over the terminal
|
||||
* instead of a docked column.
|
||||
@@ -5068,6 +5375,9 @@ class CodemanApp {
|
||||
const reachable =
|
||||
this.isSessionSidebarActive() && document.documentElement.dataset.sidebar !== 'collapsed';
|
||||
const needle = reachable ? this._sidebarFilter : '';
|
||||
// State headings count the whole group, so they step aside while a filter
|
||||
// is narrowing the rows under them (styles.css, .tabs-filtering).
|
||||
container.classList.toggle('tabs-filtering', !!needle);
|
||||
for (const tab of container.querySelectorAll('.session-tab')) {
|
||||
if (!needle) {
|
||||
tab.classList.remove('tab-filtered-out');
|
||||
@@ -5476,10 +5786,16 @@ class CodemanApp {
|
||||
// The grouped rail's structure (sections, collapse, the shown exception) can
|
||||
// change while the id sets stay equal; the in-place patch below cannot move
|
||||
// or hide a row, so any structural change takes the full rebuild.
|
||||
// Case clusters are boxes too: the same rule, keyed on their structure.
|
||||
const clusterLayout = this._tabClusterLayout(
|
||||
this.sessionOrder.filter((sid) => this.sessions.has(sid)),
|
||||
groupProjection
|
||||
);
|
||||
const canIncremental = existingIds.size === currentIds.size &&
|
||||
[...existingIds].every(id => currentIds.has(id)) &&
|
||||
webTabsUnchanged &&
|
||||
!this._isTabGroupStructureStale(groupProjection);
|
||||
!this._isTabGroupStructureStale(groupProjection) &&
|
||||
(clusterLayout ? clusterLayout.key : null) === (this._lastTabClusterKey ?? null);
|
||||
|
||||
if (canIncremental) {
|
||||
// Read once for the whole pass, like the full-rebuild path: this touches
|
||||
@@ -5489,7 +5805,13 @@ class CodemanApp {
|
||||
// that sees one — a session going working→idle never adds or removes a
|
||||
// tab, so the full rebuild below is not reached. Recomputed per pass for
|
||||
// the same reason the rich meta line is: the order IS the state.
|
||||
const railSortOrder = this._tabRailSortOrder(this.sessionOrder.filter((sid) => this.sessions.has(sid)));
|
||||
const liveIds = this.sessionOrder.filter((sid) => this.sessions.has(sid));
|
||||
const railSortOrder = this._tabRailSortOrder(liveIds);
|
||||
// Grouped by state: same reasoning, a state change moves a tab between
|
||||
// rows. Its order values replace the rail sort's (which it already folded
|
||||
// in as the rank inside each section).
|
||||
const triage = this._tabTriageLayout(liveIds, groupProjection, railSortOrder);
|
||||
const listOrder = triage ? triage.order : railSortOrder;
|
||||
// Incremental update - only modify changed properties
|
||||
for (const [id, session] of this.sessions) {
|
||||
const tab = container.querySelector(`.session-tab[data-id="${id}"]`);
|
||||
@@ -5497,7 +5819,7 @@ class CodemanApp {
|
||||
|
||||
// An empty string clears the property, which is also what un-sorts the
|
||||
// rail when the setting (or the layout) flips without a full rebuild.
|
||||
const railOrder = railSortOrder?.has(id) ? String(railSortOrder.get(id)) : '';
|
||||
const railOrder = listOrder?.has(id) ? String(listOrder.get(id)) : '';
|
||||
if (tab.style.order !== railOrder) tab.style.order = railOrder;
|
||||
|
||||
// A web tab owns the active state while one is open. activeSessionId stays
|
||||
@@ -5596,11 +5918,17 @@ class CodemanApp {
|
||||
const _p = parseSessionPrefix(name);
|
||||
if (nameEl.dataset.fullName !== name) {
|
||||
nameEl.replaceChildren();
|
||||
const _split = _p && _p.suffix ? null : window.CodemanTabClusters?.nameSplit(name, clusterLayout?.labelFor.get(id));
|
||||
if (_p && _p.suffix) {
|
||||
const prefix = document.createElement('span');
|
||||
prefix.className = 'tab-name-prefix';
|
||||
prefix.textContent = `${_p.prefix}: `;
|
||||
nameEl.append(prefix, document.createTextNode(_p.suffix));
|
||||
} else if (_split) {
|
||||
const caseSpan = document.createElement('span');
|
||||
caseSpan.className = 'tab-name-case';
|
||||
caseSpan.textContent = _split.hidden;
|
||||
nameEl.append(document.createTextNode(_split.shown), caseSpan);
|
||||
} else {
|
||||
nameEl.textContent = name;
|
||||
}
|
||||
@@ -5675,6 +6003,8 @@ class CodemanApp {
|
||||
this._applyTabTreePositions(container);
|
||||
this._syncTabGroupHeaderAlerts(container, groupProjection);
|
||||
}
|
||||
this._syncTabTriageChrome(container, triage);
|
||||
this._syncTabArrangementClasses(container, { clusters: !!clusterLayout, groupProjection });
|
||||
} else {
|
||||
// Full rebuild needed (sessions added/removed)
|
||||
this._fullRenderSessionTabs();
|
||||
@@ -5743,6 +6073,16 @@ class CodemanApp {
|
||||
return;
|
||||
}
|
||||
|
||||
// Grouped by state, the header strip IS rows (one per state), so it always
|
||||
// wraps: the row breaks only take effect in a wrapping flex line. The ledger
|
||||
// is a grid of rows, so the same holds. Narrower screens keep the single
|
||||
// scrolling row above, where state headings read as inline dividers and the
|
||||
// ledger stays the plain strip.
|
||||
if (container.classList.contains('tabs-triage') || container.classList.contains('tabs-ledger')) {
|
||||
container.classList.add('tabs-auto-wrap');
|
||||
return;
|
||||
}
|
||||
|
||||
// Measure the natural one-row overflow, then enable wrapping only if needed.
|
||||
container.classList.remove('tabs-auto-wrap');
|
||||
const shouldWrap = window.CodemanTabOverflow?.shouldAutoWrapTabs
|
||||
@@ -5835,7 +6175,17 @@ class CodemanApp {
|
||||
// below still counts the strip, not the sorted list. Null in every other
|
||||
// layout, and the tabs then carry no inline order at all — the header
|
||||
// strip's markup is byte-identical to before.
|
||||
const railSortOrder = this._tabRailSortOrder(tabOrder.filter((id) => this.sessions.has(id)));
|
||||
const liveIds = tabOrder.filter((id) => this.sessions.has(id));
|
||||
const railSortOrder = this._tabRailSortOrder(liveIds);
|
||||
// Grouped by state (tabArrangement 'state', the default): the same `order` mechanism,
|
||||
// one band of values per state. Null in the grouped rail and with grouping
|
||||
// off, and the rows then carry exactly the inline order they did before.
|
||||
const groupProjection = this._projectTabGroups();
|
||||
const triage = this._tabTriageLayout(liveIds, groupProjection, railSortOrder);
|
||||
const listOrder = triage ? triage.order : railSortOrder;
|
||||
// Clustered by case: rows are wrapped in one box per case below, and a tab
|
||||
// in a cluster with company drops the `-<case>` from its name.
|
||||
const clusterLayout = this._tabClusterLayout(liveIds, groupProjection);
|
||||
// One row per session, in tab order. The flat strip emits them as-is; the
|
||||
// grouped rail places the SAME markup into its sections, so a row never
|
||||
// differs between the two (badge = Alt+N slot in sessionOrder either way).
|
||||
@@ -5844,7 +6194,7 @@ class CodemanApp {
|
||||
for (const id of tabOrder) {
|
||||
const session = this.sessions.get(id);
|
||||
if (!session) continue; // Skip if session was removed
|
||||
const railOrderStyle = railSortOrder?.has(id) ? ` style="order:${railSortOrder.get(id)}"` : '';
|
||||
const railOrderStyle = listOrder?.has(id) ? ` style="order:${listOrder.get(id)}"` : '';
|
||||
|
||||
// See the note in the incremental path: a web tab owns the active highlight
|
||||
// while one is open, even though activeSessionId stays set.
|
||||
@@ -5877,9 +6227,7 @@ class CodemanApp {
|
||||
// JUST the description on the tab; the generated w<n>-<case> id moves to the
|
||||
// tooltip and stays visible in the session settings modal.
|
||||
const parsedName = parseSessionPrefix(name);
|
||||
const tabLabel = parsedName && parsedName.suffix
|
||||
? `<span class="tab-name-prefix">${escapeHtml(parsedName.prefix)}: </span>${escapeHtml(parsedName.suffix)}`
|
||||
: escapeHtml(name);
|
||||
const tabLabel = this._tabNameHtml(name, clusterLayout?.labelFor.get(id));
|
||||
const tabTooltip = parsedName && parsedName.suffix
|
||||
? (session.workingDir ? `${parsedName.prefix} (${session.workingDir})` : parsedName.prefix)
|
||||
: (session.workingDir || '');
|
||||
@@ -5926,8 +6274,12 @@ class CodemanApp {
|
||||
_tabIdx++;
|
||||
}
|
||||
|
||||
const groupProjection = this._projectTabGroups();
|
||||
if (groupProjection) {
|
||||
if (clusterLayout) {
|
||||
// Clustered by case. Web tabs keep their flat-strip Alt+N slot (after
|
||||
// every session), each in a box of its own.
|
||||
parts.push(this._renderTabClusters(clusterLayout, rowHtml, _tabIdx));
|
||||
this._hiddenTabGroupByRef = new Map();
|
||||
} else if (groupProjection) {
|
||||
// Grouped vertical rail. Web tabs keep their flat-strip Alt+N slot (after
|
||||
// every session), wherever their group puts them.
|
||||
const webviewSlots = new Map(
|
||||
@@ -5953,6 +6305,7 @@ class CodemanApp {
|
||||
this._hiddenTabGroupByRef = new Map();
|
||||
}
|
||||
this._lastTabGroupStructureKey = this._tabGroupStructureKey(groupProjection);
|
||||
this._lastTabClusterKey = clusterLayout ? clusterLayout.key : null;
|
||||
|
||||
container.innerHTML = parts.join('');
|
||||
container.classList.toggle('session-tabs--grouped', !!groupProjection);
|
||||
@@ -5961,6 +6314,8 @@ class CodemanApp {
|
||||
this._applyTabTreeSemantics(container, { identity: focusIdentity, refocus: focusWasInside });
|
||||
this._syncTabGroupHeaderAlerts(container, groupProjection);
|
||||
}
|
||||
this._syncTabTriageChrome(container, triage);
|
||||
this._syncTabArrangementClasses(container, { clusters: !!clusterLayout, groupProjection });
|
||||
|
||||
// Put the strip back where the user left it, then reveal the active tab
|
||||
// only when it CHANGED (or on the first paint). Restoring unconditionally
|
||||
@@ -6035,9 +6390,13 @@ class CodemanApp {
|
||||
// the inline one, or web tabs (pinned past the cards by a CSS `order: 9999`
|
||||
// rather than an inline style) read as 0 and the walk starts on them. Array
|
||||
// sort is stable, so equal orders keep DOM order, which is the unsorted case.
|
||||
if (this.isTabRailSorted()) {
|
||||
if (this.isTabRailSorted() || container.classList.contains('tabs-triage')) {
|
||||
const orderOf = (el) => Number(getComputedStyle(el).order) || 0;
|
||||
tabs.sort((a, b) => orderOf(a) - orderOf(b));
|
||||
// Case clusters are boxes in DOM order and a sorted rail orders rows
|
||||
// INSIDE each one, so the box goes first in the key.
|
||||
const boxes = [...container.querySelectorAll(':scope > .tab-cluster')];
|
||||
const boxOf = (el) => boxes.indexOf(el.closest('.tab-cluster'));
|
||||
tabs.sort((a, b) => boxOf(a) - boxOf(b) || orderOf(a) - orderOf(b));
|
||||
}
|
||||
const currentIndex = tabs.indexOf(document.activeElement);
|
||||
|
||||
@@ -7236,6 +7595,9 @@ class CodemanApp {
|
||||
});
|
||||
|
||||
tab.addEventListener('dragover', (e) => {
|
||||
// Grouped by state: a tab in another group is not a drop target, and
|
||||
// leaving the event alone (no preventDefault) is what shows "no drop".
|
||||
if (this._isTabDropAcrossGroups(tab)) return;
|
||||
e.preventDefault();
|
||||
if (!this.draggedTabId || this.draggedTabId === tab.dataset.id) return;
|
||||
|
||||
@@ -7265,6 +7627,7 @@ class CodemanApp {
|
||||
tab.classList.remove('drag-over-left', 'drag-over-right');
|
||||
|
||||
if (!this.draggedTabId || this.draggedTabId === tab.dataset.id) return;
|
||||
if (this._isTabDropAcrossGroups(tab)) return;
|
||||
|
||||
const targetId = tab.dataset.id;
|
||||
const draggedId = this.draggedTabId;
|
||||
@@ -9141,9 +9504,6 @@ class CodemanApp {
|
||||
const fmtBindings = (s) => {
|
||||
if (s.displayBindings) return s.displayBindings.map((b) => `<kbd>${escapeHtml(b)}</kbd>`).join(' / ');
|
||||
if (!s.bindings) return '';
|
||||
// An action with no key (Close Session by default) is still listed, so the
|
||||
// overlay says so instead of showing an empty key column.
|
||||
if (s.bindings.length === 0) return '<span class="shortcut-overlay-unbound">not bound</span>';
|
||||
return s.bindings.map((b) => {
|
||||
const parts = [...(b.modifiers || []).map((m) => m.charAt(0).toUpperCase() + m.slice(1)), b.key || b.code || ''];
|
||||
return `<kbd>${escapeHtml(parts.join('+'))}</kbd>`;
|
||||
|
||||
+202
-2
@@ -658,6 +658,194 @@ function sortSessionsByActivity(rows) {
|
||||
return (Array.isArray(rows) ? rows.slice() : []).sort(compareSessionActivity);
|
||||
}
|
||||
|
||||
// Tab grouping by state (`tabArrangement: 'state'`, Discussion #426 option C).
|
||||
//
|
||||
// The tab list answers "who wants me?" the way the home screens do: a row (the
|
||||
// header strip) or a section (the flat side rail, the sidebar) per state, most
|
||||
// urgent on top. The states are the home screens' own, from
|
||||
// `_mobileOverviewState()` (mobile-overview.js); this only folds the six into
|
||||
// four groups a strip can hold:
|
||||
//
|
||||
// needs red: a permission or question dialog is blocking the agent. A
|
||||
// failed session joins it, since it also needs a human and the home
|
||||
// screens rank it right below.
|
||||
// waiting yellow: the agent finished its turn and is waiting on you.
|
||||
// working a turn is running.
|
||||
// idle everything quiet: idle, ended, and an agent that exited inside a
|
||||
// live pane (#446), which may still read as working on screen but is
|
||||
// running nothing. Web tabs close the group.
|
||||
//
|
||||
// Applied as the flex `order` property, never by reordering the DOM, the same
|
||||
// design as the sorted rail (`_tabRailSortOrder`, app.js): `#sessionTabs` stays
|
||||
// in `sessionOrder`, so Alt+N, drag-and-drop and the keyboard walk keep reading
|
||||
// the list they always read, and a state change moves one inline style instead
|
||||
// of rebuilding the strip. Each group owns a band of `TAB_TRIAGE_STRIDE` order
|
||||
// values: its heading at the start of the band, its rows after it, its web tabs
|
||||
// after those and the line break that ends the header row at the very end.
|
||||
//
|
||||
// Pure: no DOM, no `this`. Unit-tested in test/tab-triage.test.ts.
|
||||
// `quiet` groups keep their heading element (it anchors the row and holds the
|
||||
// row's place beside the brand) but draw no text: everything quiet is the
|
||||
// default state of a tab, so naming it only adds noise.
|
||||
const TAB_TRIAGE_GROUPS = [
|
||||
{ key: 'needs', label: 'Needs you' },
|
||||
{ key: 'waiting', label: 'Waiting' },
|
||||
{ key: 'working', label: 'Working' },
|
||||
{ key: 'idle', label: 'Idle', quiet: true },
|
||||
];
|
||||
|
||||
const TAB_TRIAGE_GROUP_OF_STATE = {
|
||||
needs: 'needs',
|
||||
error: 'needs',
|
||||
waiting: 'waiting',
|
||||
working: 'working',
|
||||
idle: 'idle',
|
||||
done: 'idle',
|
||||
};
|
||||
|
||||
const TAB_TRIAGE_STRIDE = 10000;
|
||||
/** Offset of a group's web tabs inside its band, past any plausible session count. */
|
||||
const TAB_TRIAGE_WEB_OFFSET = 5000;
|
||||
|
||||
/**
|
||||
* Which group a session belongs to.
|
||||
* @param {string} state a `_mobileOverviewState()` value
|
||||
* @param {boolean} exited the agent inside the pane has exited (`_mobileOverviewExit()` non-null)
|
||||
* @returns {'needs'|'waiting'|'working'|'idle'}
|
||||
*/
|
||||
function tabTriageGroupFor(state, exited) {
|
||||
const group = TAB_TRIAGE_GROUP_OF_STATE[state] || 'idle';
|
||||
return exited && group === 'working' ? 'idle' : group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Order values and visible groups for one pass.
|
||||
*
|
||||
* @param {Array<{id: string, state: string, exited?: boolean, pos?: number}>} rows
|
||||
* live sessions; `pos` ranks a row inside its group (tab order on the header
|
||||
* strip, the activity sort's position on a sorted rail). Rows without one keep
|
||||
* the order they were passed in.
|
||||
* @param {Array<string>} webviewIds open web tabs, in their own tab order
|
||||
* @param {{reverse?: boolean}} [options] `reverse` puts the groups the other
|
||||
* way up (`tabStateOrder: 'urgent-last'`): idle first, needs you last, for a
|
||||
* strip read from the bottom. Rows inside a group keep their order.
|
||||
* @returns {{
|
||||
* order: Map<string, number>,
|
||||
* webOrder: Map<string, number>,
|
||||
* groups: Array<{key: string, label: string, quiet: boolean, count: number, headOrder: number, breakOrder: number}>
|
||||
* }} `groups` lists only the non-empty groups, in display order (most urgent
|
||||
* first, or last with `reverse`).
|
||||
*/
|
||||
function computeTabTriageLayout(rows, webviewIds, options) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
const webs = Array.isArray(webviewIds) ? webviewIds : [];
|
||||
const sequence = options && options.reverse ? TAB_TRIAGE_GROUPS.slice().reverse() : TAB_TRIAGE_GROUPS;
|
||||
const baseOf = {};
|
||||
const counts = {};
|
||||
sequence.forEach((group, i) => {
|
||||
baseOf[group.key] = (i + 1) * TAB_TRIAGE_STRIDE;
|
||||
counts[group.key] = 0;
|
||||
});
|
||||
|
||||
const placed = list
|
||||
.filter((row) => row && typeof row.id === 'string')
|
||||
.map((row, i) => ({
|
||||
id: row.id,
|
||||
group: tabTriageGroupFor(row.state, !!row.exited),
|
||||
pos: Number.isFinite(row.pos) ? row.pos : i,
|
||||
index: i,
|
||||
}));
|
||||
const byGroup = {};
|
||||
for (const row of placed) (byGroup[row.group] = byGroup[row.group] || []).push(row);
|
||||
|
||||
const order = new Map();
|
||||
for (const key of Object.keys(byGroup)) {
|
||||
// Stable: equal positions keep the order the caller passed.
|
||||
byGroup[key].sort((a, b) => a.pos - b.pos || a.index - b.index);
|
||||
byGroup[key].forEach((row, i) => order.set(row.id, baseOf[key] + 1 + i));
|
||||
counts[key] = byGroup[key].length;
|
||||
}
|
||||
|
||||
const webOrder = new Map();
|
||||
webs.forEach((id, i) => {
|
||||
if (typeof id === 'string' && id) webOrder.set(id, baseOf.idle + TAB_TRIAGE_WEB_OFFSET + i);
|
||||
});
|
||||
counts.idle += webOrder.size;
|
||||
|
||||
const groups = sequence.filter((group) => counts[group.key] > 0).map((group) => ({
|
||||
key: group.key,
|
||||
label: group.label,
|
||||
quiet: !!group.quiet,
|
||||
count: counts[group.key],
|
||||
headOrder: baseOf[group.key],
|
||||
breakOrder: baseOf[group.key] + TAB_TRIAGE_STRIDE - 1,
|
||||
}));
|
||||
|
||||
return { order, webOrder, groups };
|
||||
}
|
||||
|
||||
// Tab clusters by case (`tabArrangement: 'case'`, Discussion #426 option A).
|
||||
//
|
||||
// One cluster per case, in the order the case first appears in the tab order,
|
||||
// so the strip keeps the user's arrangement at the case level. Inside a cluster
|
||||
// with two or more tabs the `-<case>` part of a generated `w<n>-<case>` name is
|
||||
// redundant and is hidden (`tabClusterNameSplit()`), which is what lets 18 tabs
|
||||
// read as 7 things. A case with one tab is still its own (unlabelled) box.
|
||||
//
|
||||
// Cluster colours come from the session palette (`--session-<colour>`) by a
|
||||
// stable hash of the case key, so a case keeps its colour across reloads and
|
||||
// devices without anything being stored.
|
||||
//
|
||||
// Pure: no DOM, no `this`. Unit-tested in test/tab-clusters.test.ts.
|
||||
const TAB_CLUSTER_COLORS = ['blue', 'green', 'purple', 'orange', 'pink', 'yellow', 'red'];
|
||||
|
||||
/** Palette colour for a cluster key: a djb2 hash, so the same key always gets the same colour. */
|
||||
function tabClusterColorFor(key) {
|
||||
const text = String(key || '');
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < text.length; i++) hash = ((hash << 5) + hash + text.charCodeAt(i)) | 0;
|
||||
return TAB_CLUSTER_COLORS[Math.abs(hash) % TAB_CLUSTER_COLORS.length];
|
||||
}
|
||||
|
||||
/**
|
||||
* Group tabs by case.
|
||||
* @param {Array<{id: string, key: string, label: string}>} rows live sessions in
|
||||
* tab order; `key` identifies the case (its path), `label` names it
|
||||
* @returns {Array<{key: string, label: string, color: string, ids: string[]}>}
|
||||
* clusters in first-appearance order, members in tab order
|
||||
*/
|
||||
function computeTabClusters(rows) {
|
||||
const clusters = [];
|
||||
const byKey = new Map();
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
if (!row || typeof row.id !== 'string') continue;
|
||||
const key = typeof row.key === 'string' && row.key ? row.key : `session:${row.id}`;
|
||||
let cluster = byKey.get(key);
|
||||
if (!cluster) {
|
||||
cluster = { key, label: typeof row.label === 'string' ? row.label : '', color: tabClusterColorFor(key), ids: [] };
|
||||
byKey.set(key, cluster);
|
||||
clusters.push(cluster);
|
||||
}
|
||||
cluster.ids.push(row.id);
|
||||
}
|
||||
return clusters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a generated `w<n>-<case>` / `s<n>-<case>` name into the part a cluster
|
||||
* shows and the case suffix it hides, or null when the name is anything else
|
||||
* (a custom name, a described `w3-x: fix login`, another case's name). Case is
|
||||
* compared case-insensitively; the hidden part keeps its original spelling so
|
||||
* the full name is still in the DOM.
|
||||
* @returns {{shown: string, hidden: string}|null}
|
||||
*/
|
||||
function tabClusterNameSplit(name, label) {
|
||||
if (typeof name !== 'string' || typeof label !== 'string' || !label) return null;
|
||||
const match = name.match(/^([ws]\d+)(-.+)$/);
|
||||
if (!match) return null;
|
||||
return match[2].slice(1).toLowerCase() === label.toLowerCase() ? { shown: match[1], hidden: match[2] } : null;
|
||||
}
|
||||
|
||||
// Terminal font stack — the single source for every xterm surface (the main
|
||||
// terminal in terminal-ui.js, the log-viewer terminal in panels-ui.js).
|
||||
// "Symbols Nerd Font Mono" is a bundled icons-only webfont (fonts/ +
|
||||
@@ -983,6 +1171,18 @@ if (typeof window !== 'undefined') {
|
||||
compare: compareSessionActivity,
|
||||
sort: sortSessionsByActivity,
|
||||
};
|
||||
window.CodemanTabClusters = {
|
||||
COLORS: TAB_CLUSTER_COLORS,
|
||||
colorFor: tabClusterColorFor,
|
||||
compute: computeTabClusters,
|
||||
nameSplit: tabClusterNameSplit,
|
||||
};
|
||||
window.CodemanTabTriage = {
|
||||
GROUPS: TAB_TRIAGE_GROUPS,
|
||||
STRIDE: TAB_TRIAGE_STRIDE,
|
||||
groupFor: tabTriageGroupFor,
|
||||
layout: computeTabTriageLayout,
|
||||
};
|
||||
window.CodemanInputLimit = {
|
||||
FRAME_MAX_CHARS: INPUT_FRAME_MAX_CHARS,
|
||||
PASTE_MAX_CHARS: INPUT_PASTE_MAX_CHARS,
|
||||
@@ -1614,7 +1814,7 @@ function buildSplitPickerSessions(sessions, sessionOrder, excludeId, detachedIds
|
||||
if (id === excludeId) continue;
|
||||
// A detached (popped-out) session's own window already yields its PTY
|
||||
// size (see sendResize's detachedElsewhere guard in terminal-ui.js) —
|
||||
// Pane B's TerminalTile._sendResize() has no such check, so letting
|
||||
// Pane B's SplitTerminalPane._sendResize() has no such check, so letting
|
||||
// one into the picker put its detached window and Pane B in a fight over
|
||||
// the same PTY's dimensions.
|
||||
if (detachedIds?.has?.(id)) continue;
|
||||
@@ -1622,7 +1822,7 @@ function buildSplitPickerSessions(sessions, sessionOrder, excludeId, detachedIds
|
||||
if (!session) continue;
|
||||
// A session with no PTY attached (exited CLI, a crash-looped session
|
||||
// whose breaker tripped, a restore that failed to re-attach) has nothing
|
||||
// reading its tmux pane. TerminalTile never does selectSession()'s
|
||||
// reading its tmux pane. SplitTerminalPane never does selectSession()'s
|
||||
// re-attach POST, so its socket would open onto a pane nothing feeds:
|
||||
// no terminal events, and Session.write() silently drops every keystroke
|
||||
// with no ack either way (Pane B sends no `seq`), so the loss is
|
||||
|
||||
@@ -221,6 +221,7 @@
|
||||
Running: '运行中',
|
||||
Idle: '空闲',
|
||||
Working: '工作中',
|
||||
Waiting: '等待中',
|
||||
Today: '今天',
|
||||
Home: '主页',
|
||||
Local: '本地',
|
||||
|
||||
@@ -50,13 +50,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Called from customKeyEventHandler in terminal-ui.js on Ctrl+V keydown.
|
||||
// Creates a hidden paste trap, lets the browser paste into it, then inspects
|
||||
// the result for images. Works on plain HTTP (no Clipboard API needed).
|
||||
// `target` names the terminal the Ctrl+V came from and its session; both
|
||||
// default to the primary pane. A second terminal (the split pane) passes its
|
||||
// own, so text pastes into THAT xterm and images upload to THAT session.
|
||||
_handleImagePaste(target = {}) {
|
||||
_handleImagePaste() {
|
||||
const self = this;
|
||||
const terminal = target.terminal || this.terminal;
|
||||
const sessionId = target.sessionId || this.activeSessionId;
|
||||
|
||||
// Create a hidden contenteditable div to receive the paste
|
||||
const trap = document.createElement('div');
|
||||
@@ -98,11 +93,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
setTimeout(function() {
|
||||
if (trap.parentNode) trap.parentNode.removeChild(trap);
|
||||
// Refocus the terminal
|
||||
if (terminal) terminal.focus();
|
||||
if (self.terminal) self.terminal.focus();
|
||||
}, 0);
|
||||
|
||||
if (imageFiles.length > 0) {
|
||||
self._uploadAndInsertImages(imageFiles, { sessionId: sessionId });
|
||||
self._uploadAndInsertImages(imageFiles);
|
||||
} else {
|
||||
// No image -- route text through xterm's paste() so bracketed-paste
|
||||
// markers (CSI 200~ ... CSI 201~) survive when the inner application
|
||||
@@ -111,7 +106,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// indistinguishable from typed input, weakening the CLI's
|
||||
// prompt-injection defenses.
|
||||
var text = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
|
||||
if (text && terminal) terminal.paste(text);
|
||||
if (text && self.terminal) self.terminal.paste(text);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -131,10 +126,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
/** Upload a batch and normally insert its paths into the active terminal.
|
||||
* The prompt composer passes `{ insert: false }` so it can put those paths
|
||||
* into its textarea instead. `options.sessionId` names the session to upload
|
||||
* to (default: the active one). Returns successful paths in selection order. */
|
||||
* into its textarea instead. Returns successful paths in selection order. */
|
||||
async _uploadAndInsertImages(fileList, options = {}) {
|
||||
const sessionId = options.sessionId || this.activeSessionId;
|
||||
const sessionId = this.activeSessionId;
|
||||
if (!sessionId) return [];
|
||||
|
||||
let files = Array.from(fileList || []);
|
||||
@@ -185,12 +179,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
const paths = results.filter(Boolean);
|
||||
if (paths.length > 0 && options.insert !== false) {
|
||||
// Insert all paths in one shot, space-separated, in selection order, into
|
||||
// the session the batch was uploaded TO. Not sendInput(): it re-reads
|
||||
// activeSessionId, and after the awaits above that is whatever tab the
|
||||
// user switched to mid-upload, so the paths landed in the wrong session.
|
||||
// Same delivery sendInput() uses (durable queue, useMux for the POST path).
|
||||
this._sendInputAsync(sessionId, paths.join(' '), { useMux: true });
|
||||
// Insert all paths in one shot, space-separated, in selection order.
|
||||
await this.sendInput(paths.join(' '));
|
||||
}
|
||||
|
||||
// Final status: successes, plus any failures / cap so nothing is silent.
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
app.js, NOT the handheld storage-key test `m`. Use a different predicate
|
||||
here and boot will contradict this value, animating the drawer open by
|
||||
itself on every load between 768 and 1023px. -->
|
||||
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var A=JSON.parse(localStorage.getItem(k)||'{}');var L=A.sessionListLayout;var F=Number(A.sessionSidebarFontSize);var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';var V=A.tabOrientation==='vertical'&&!S&&!solo&&window.innerWidth>=768;document.documentElement.dataset.tabOrientation=V?'vertical':'horizontal';document.documentElement.dataset.tabRailDetail=(A.tabRailDetail==='simple')?'simple':'rich';document.documentElement.dataset.tabRailSort=(A.tabRailSort==='manual')?'manual':'activity';var W=Number(A.tabRailWidth);if(V){if(Number.isInteger(W)&&W>=208&&W<=360)document.documentElement.style.setProperty('--tab-rail-width',W+'px');else if(document.documentElement.dataset.tabRailDetail!=='simple')document.documentElement.style.setProperty('--tab-rail-width','320px');}if(Number.isInteger(F)&&F>=11&&F<=18)document.documentElement.style.setProperty('--session-sidebar-name-font-size',F+'px');}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';document.documentElement.dataset.tabOrientation='horizontal';document.documentElement.dataset.tabRailDetail='rich';document.documentElement.dataset.tabRailSort='activity';}</script>
|
||||
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var A=JSON.parse(localStorage.getItem(k)||'{}');var L=A.sessionListLayout;var F=Number(A.sessionSidebarFontSize);var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';var V=A.tabOrientation==='vertical'&&!S&&!solo&&window.innerWidth>=768;document.documentElement.dataset.tabOrientation=V?'vertical':'horizontal';document.documentElement.dataset.tabRailDetail=(A.tabRailDetail==='simple')?'simple':'rich';document.documentElement.dataset.tabRailSort=(A.tabRailSort==='manual')?'manual':'activity';var T=A.tabArrangement;document.documentElement.dataset.tabArrangement=(T==='case'||T==='ledger'||T==='classic')?T:'state';document.documentElement.dataset.tabStateOrder=(A.tabStateOrder==='urgent-last')?'urgent-last':'urgent-first';var H=A.headerStatsStyle;document.documentElement.dataset.headerStats=(window.innerWidth<768||solo)?'classic':(H==='classic'||H==='compact')?H:'tiles';var W=Number(A.tabRailWidth);if(V){if(Number.isInteger(W)&&W>=208&&W<=360)document.documentElement.style.setProperty('--tab-rail-width',W+'px');else if(document.documentElement.dataset.tabRailDetail!=='simple')document.documentElement.style.setProperty('--tab-rail-width','320px');}if(Number.isInteger(F)&&F>=11&&F<=18)document.documentElement.style.setProperty('--session-sidebar-name-font-size',F+'px');}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';document.documentElement.dataset.tabOrientation='horizontal';document.documentElement.dataset.tabRailDetail='rich';document.documentElement.dataset.tabRailSort='activity';document.documentElement.dataset.tabArrangement='state';document.documentElement.dataset.tabStateOrder='urgent-first';document.documentElement.dataset.headerStats='classic';}</script>
|
||||
<!-- Inline critical CSS for instant skeleton paint (before styles.css loads) -->
|
||||
<style>
|
||||
.loading-skeleton{display:flex;flex-direction:column;height:100vh;height:100dvh;background:var(--bg-dark,#11151c)}
|
||||
@@ -154,6 +154,7 @@
|
||||
<div class="connection-indicator" id="connectionIndicator" style="display: none;">
|
||||
<span class="connection-dot" id="connectionDot"></span>
|
||||
<span class="connection-text" id="connectionText"></span>
|
||||
<span class="connection-tile"><span class="connection-tile-label" id="connectionTileLabel"></span><span class="connection-tile-value" id="connectionTileValue"></span></span>
|
||||
</div>
|
||||
<div class="header-font-controls">
|
||||
<button class="btn-icon-header btn-sm" onclick="app.decreaseFontSize()" title="Decrease font (Ctrl+-)" aria-label="Decrease font size">A-</button>
|
||||
@@ -162,6 +163,7 @@
|
||||
</div>
|
||||
<div class="header-system-stats" id="headerSystemStats" title="System resource usage">
|
||||
<div class="stat-item">
|
||||
<span class="stat-ring" id="statCpuRing" aria-hidden="true"></span>
|
||||
<span class="stat-label">CPU</span>
|
||||
<div class="stat-bar">
|
||||
<div class="stat-bar-fill stat-bar-cpu" id="statCpuBar"></div>
|
||||
@@ -169,6 +171,7 @@
|
||||
<span class="stat-value" id="statCpu">--%</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-ring" id="statMemRing" aria-hidden="true"></span>
|
||||
<span class="stat-label">MEM</span>
|
||||
<div class="stat-bar">
|
||||
<div class="stat-bar-fill stat-bar-mem" id="statMemBar"></div>
|
||||
@@ -807,6 +810,7 @@
|
||||
<section class="shortcut-section">
|
||||
<h4>Session</h4>
|
||||
<div class="shortcuts-grid">
|
||||
<div><kbd>Ctrl</kbd>+<kbd>W</kbd></div><div>Close Session</div>
|
||||
<div><kbd>Ctrl/Cmd/Option</kbd>+<kbd>K</kbd></div><div>Find Open Session</div>
|
||||
<div><kbd>Ctrl</kbd>+<kbd>Tab</kbd></div><div>Next Session</div>
|
||||
<div><kbd>Alt/Option</kbd>+<kbd>[</kbd> / <kbd>Alt/Option</kbd>+<kbd>]</kbd></div><div>Previous / Next Session</div>
|
||||
@@ -1917,6 +1921,17 @@
|
||||
<label class="set-chip" data-preview="header" data-preview-order="13" data-preview-text="42%"><input type="checkbox" id="appSettingsShowPlanUsageLimits"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 18a8 8 0 1 1 16 0"/><path d="M12 18l4.5-5"/></svg><span>Plan Usage</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="14"><input type="checkbox" id="appSettingsShowLifecycleLog"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg><span>Lifecycle Log</span></label>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="header stats style system cpu mem ws plan usage tiles compact rings">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Header Stats Style <span class="set-tag">desktop</span></span>
|
||||
<span class="set-row-desc">How WS, CPU, MEM and the plan-usage windows are drawn. Compact puts a ring beside each value in two pills; Tiles put each label over its value with a bar underneath.</span>
|
||||
</div>
|
||||
<select id="appSettingsHeaderStatsStyle" class="set-select">
|
||||
<option value="classic">As before (bars)</option>
|
||||
<option value="compact">Compact (pill + rings)</option>
|
||||
<option value="tiles">Tiles (default)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2069,6 +2084,28 @@
|
||||
<div class="set-group">
|
||||
<div class="set-group-head"><h4>Tabs</h4><span class="set-scope">device</span></div>
|
||||
<div class="set-group-body">
|
||||
<div class="set-row has-field" data-search="tab layout grouping group by state triage needs you waiting working idle case clusters ledger columns classic old new">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Tab Layout</span>
|
||||
<span class="set-row-desc">By state: a row each for needs you, waiting, working and idle. By case: one box per case. Ledger: an aligned column grid. Classic: the single list, as before. By state and By case group the side rail and sidebar too. Alt+1..9 keeps the tab order.</span>
|
||||
</div>
|
||||
<select id="appSettingsTabArrangement" class="set-select">
|
||||
<option value="state">By state (default)</option>
|
||||
<option value="case">By case (clusters)</option>
|
||||
<option value="ledger">Ledger (aligned columns)</option>
|
||||
<option value="classic">Classic (as before)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="state order reverse needs you bottom top rows sections">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">State Order</span>
|
||||
<span class="set-row-desc">For Tab Layout by state. At the bottom flips the rows, so needs you sits right above the terminal.</span>
|
||||
</div>
|
||||
<select id="appSettingsTabStateOrder" class="set-select">
|
||||
<option value="urgent-first">Needs you on top (default)</option>
|
||||
<option value="urgent-last">Needs you at the bottom</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="tab orientation horizontal vertical side rail">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Tab Orientation</span>
|
||||
@@ -2092,7 +2129,7 @@
|
||||
<div class="set-row has-field" data-search="tab rail sort order activity manual drag reorder">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Vertical Rail Order</span>
|
||||
<span class="set-row-desc">By activity uses the home screen's order: blocked on you first, then whatever has been running longest, then the most recently quiet. Manual keeps your tab order and is the only mode you can drag rows in. Alt+1..9 always follows the tab order either way.</span>
|
||||
<span class="set-row-desc">By activity uses the home screen's order: blocked on you first, then whatever has been running longest, then the most recently quiet. Manual keeps your tab order and is the only mode you can drag rows in. With Tab Layout by state or by case it orders the rows inside each section. Alt+1..9 always follows the tab order either way.</span>
|
||||
</div>
|
||||
<select id="appSettingsTabRailSort" class="set-select">
|
||||
<option value="activity">By activity (home screen order)</option>
|
||||
@@ -3918,7 +3955,6 @@
|
||||
<script defer src="app.js"></script>
|
||||
<script defer src="tab-rail-resize.js"></script>
|
||||
<script defer src="terminal-ui.js"></script>
|
||||
<script defer src="terminal-tile.js"></script>
|
||||
<script defer src="terminal-split.js"></script>
|
||||
<script defer src="respawn-ui.js"></script>
|
||||
<script defer src="ralph-panel.js"></script>
|
||||
|
||||
@@ -755,6 +755,25 @@ html.mobile-init .file-browser-panel {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Grouped by state (tabArrangement 'state'), the phone strip keeps its one scrolling
|
||||
row: the tabs still come in state order, most urgent first, but the
|
||||
headings would cost chips and the dots already say which state is which.
|
||||
The phone overview is where the labelled sections live. */
|
||||
:where(.header) .tab-triage-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Clustered by case, the same holds: the boxes dissolve into the one chip
|
||||
row (in cluster order) and the labels go, since every chip still names
|
||||
its session. */
|
||||
:where(.header) .session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
:where(.header) .tab-cluster-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Only the active tab shows its action icons on a phone (see below), so on
|
||||
every other tab the container is empty but still a flex item, and its gap
|
||||
made the chip visibly wider on the right than on the left. */
|
||||
|
||||
@@ -6028,6 +6028,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
}
|
||||
|
||||
// Rings for the Compact header style, kept current in every style (two
|
||||
// style writes a poll) so switching styles never shows an empty ring.
|
||||
this._setStatRing('statCpuRing', stats.cpu);
|
||||
this._setStatRing('statMemRing', stats.memory?.percent);
|
||||
|
||||
if (memEl && memBar) {
|
||||
const memGB = (stats.memory.usedMB / 1024).toFixed(1);
|
||||
memEl.textContent = `${memGB}G`;
|
||||
@@ -6045,6 +6050,20 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Fill one stat ring (Compact header style) to `percent`, clamped to 0-100,
|
||||
* and flag it `high` above 80%, the same threshold at which the value next
|
||||
* to it turns red.
|
||||
*/
|
||||
_setStatRing(id, percent) {
|
||||
const ring = this.$(id);
|
||||
if (!ring) return;
|
||||
const value = Number(percent);
|
||||
const fill = Number.isFinite(value) ? Math.round(Math.min(100, Math.max(0, value))) : 0;
|
||||
ring.style.setProperty('--pu', String(fill));
|
||||
ring.classList.toggle('high', fill > 80);
|
||||
},
|
||||
|
||||
// ─── Clipboard ──────────────────────────────────────────────────────────────
|
||||
|
||||
async _onClipboardWrite(data) {
|
||||
|
||||
@@ -382,6 +382,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Header visibility settings
|
||||
document.getElementById('appSettingsShowFontControls').checked = settings.showFontControls ?? defaults.showFontControls ?? false;
|
||||
document.getElementById('appSettingsShowSystemStats').checked = settings.showSystemStats ?? defaults.showSystemStats ?? true;
|
||||
document.getElementById('appSettingsHeaderStatsStyle').value = this.resolveHeaderStatsStyle(settings);
|
||||
document.getElementById('appSettingsShowLifecycleLog').checked = settings.showLifecycleLog ?? defaults.showLifecycleLog ?? false;
|
||||
document.getElementById('appSettingsShowResponseViewer').checked = settings.showResponseViewer ?? defaults.showResponseViewer ?? false;
|
||||
document.getElementById('appSettingsShowFileViewerButton').checked = settings.showFileViewerButton ?? defaults.showFileViewerButton ?? true;
|
||||
@@ -500,6 +501,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
settings.tabRailDetail ?? defaults.tabRailDetail ?? 'rich';
|
||||
document.getElementById('appSettingsTabRailSort').value =
|
||||
settings.tabRailSort ?? defaults.tabRailSort ?? 'activity';
|
||||
document.getElementById('appSettingsTabArrangement').value = this.resolveTabArrangement(settings);
|
||||
document.getElementById('appSettingsTabStateOrder').value = this.resolveTabStateOrder(settings);
|
||||
document.getElementById('appSettingsShowTabDetachButton').checked = settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false;
|
||||
document.getElementById('appSettingsSessionListLayout').value =
|
||||
settings.sessionListLayout ?? defaults.sessionListLayout ?? 'header';
|
||||
@@ -2475,6 +2478,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Header visibility settings
|
||||
showFontControls: document.getElementById('appSettingsShowFontControls').checked,
|
||||
showSystemStats: document.getElementById('appSettingsShowSystemStats').checked,
|
||||
headerStatsStyle: document.getElementById('appSettingsHeaderStatsStyle').value,
|
||||
showLifecycleLog: document.getElementById('appSettingsShowLifecycleLog').checked,
|
||||
showResponseViewer: document.getElementById('appSettingsShowResponseViewer').checked,
|
||||
showFileViewerButton: document.getElementById('appSettingsShowFileViewerButton').checked,
|
||||
@@ -2524,6 +2528,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
tabRailWidth: this.readTabRailWidthSetting?.() ?? 256,
|
||||
tabRailDetail: document.getElementById('appSettingsTabRailDetail').value,
|
||||
tabRailSort: document.getElementById('appSettingsTabRailSort').value,
|
||||
tabArrangement: document.getElementById('appSettingsTabArrangement').value,
|
||||
tabStateOrder: document.getElementById('appSettingsTabStateOrder').value,
|
||||
showTabDetachButton: document.getElementById('appSettingsShowTabDetachButton').checked,
|
||||
sessionListLayout: document.getElementById('appSettingsSessionListLayout').value,
|
||||
sessionSidebarFontSize: this.resolveSessionSidebarFontSize(
|
||||
@@ -3448,6 +3454,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
tabRailWidth: 256,
|
||||
tabRailDetail: 'rich',
|
||||
tabRailSort: 'activity',
|
||||
tabArrangement: 'state',
|
||||
tabStateOrder: 'urgent-first',
|
||||
sessionListLayout: 'header',
|
||||
sessionSidebarFontSize: 12,
|
||||
cjkInputEnabled: false,
|
||||
@@ -3549,6 +3557,79 @@ Object.assign(CodemanApp.prototype, {
|
||||
return now === before ? undefined : now;
|
||||
},
|
||||
|
||||
/**
|
||||
* The stored tab layout, or the default. Anything but the four known values
|
||||
* (an absent key, a value from a newer build) reads as 'state', the default
|
||||
* (Discussion #426, option C).
|
||||
*/
|
||||
resolveTabArrangement(settings) {
|
||||
const value = settings?.tabArrangement ?? this.getDefaultSettings().tabArrangement;
|
||||
return value === 'case' || value === 'ledger' || value === 'classic' ? value : 'state';
|
||||
},
|
||||
|
||||
/** The stored state-group order: 'urgent-last' only when chosen, else 'urgent-first'. */
|
||||
resolveTabStateOrder(settings) {
|
||||
const value = settings?.tabStateOrder ?? this.getDefaultSettings().tabStateOrder;
|
||||
return value === 'urgent-last' ? 'urgent-last' : 'urgent-first';
|
||||
},
|
||||
|
||||
/**
|
||||
* The stored header-stats style, or the default. Anything but the three
|
||||
* known values (an absent key, a value from a newer build) reads as 'tiles',
|
||||
* the default (the tile variant of Discussion #426's option G).
|
||||
*/
|
||||
resolveHeaderStatsStyle(settings) {
|
||||
const value = settings?.headerStatsStyle ?? this.getDefaultSettings().headerStatsStyle;
|
||||
return value === 'classic' || value === 'compact' ? value : 'tiles';
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply a header-stats style: the `data-header-stats` attribute every rule in
|
||||
* the "Header stats styles" block of styles.css keys on, plus the two DOM
|
||||
* moves the clustered styles need.
|
||||
*
|
||||
* The template keeps the classic order, where the connection indicator sits
|
||||
* before the font controls and the plan-usage chip near the end of the header.
|
||||
* Compact and Tiles draw them as ONE cluster (WS · CPU · MEM, then the plan
|
||||
* windows), so the indicator moves into #headerSystemStats as its first child
|
||||
* and the chip moves right after it. Comment anchors left at the template
|
||||
* positions are what 'classic' moves them back to, so switching back restores
|
||||
* the header exactly.
|
||||
*
|
||||
* ⚠️ The indicator only joins the pill while System Stats is shown: the pill
|
||||
* is hidden with `display: none`, and the WS readout must not disappear with
|
||||
* it. Both elements keep their ids, so every writer (setConnectionStatus,
|
||||
* updatePlanUsageChip) finds them wherever they sit.
|
||||
*
|
||||
* @param {{style: 'classic'|'compact'|'tiles', showSystemStats: boolean}} opts
|
||||
*/
|
||||
applyHeaderStatsStyle({ style, showSystemStats }) {
|
||||
document.documentElement.dataset.headerStats = style;
|
||||
const stats = document.getElementById('headerSystemStats');
|
||||
const conn = document.getElementById('connectionIndicator');
|
||||
const plan = document.getElementById('planUsageChip');
|
||||
if (!stats || !conn || !plan) return;
|
||||
if (!this._headerStatsAnchors) {
|
||||
const connAnchor = document.createComment(' connection indicator (classic position) ');
|
||||
const planAnchor = document.createComment(' plan usage chip (classic position) ');
|
||||
conn.before(connAnchor);
|
||||
plan.before(planAnchor);
|
||||
this._headerStatsAnchors = { conn: connAnchor, plan: planAnchor };
|
||||
}
|
||||
const anchors = this._headerStatsAnchors;
|
||||
const clustered = style !== 'classic';
|
||||
if (clustered && showSystemStats) {
|
||||
if (stats.firstElementChild !== conn) stats.prepend(conn);
|
||||
} else if (anchors.conn.nextSibling !== conn) {
|
||||
anchors.conn.after(conn);
|
||||
}
|
||||
if (clustered) {
|
||||
if (stats.nextElementSibling !== plan) stats.after(plan);
|
||||
} else if (anchors.plan.nextSibling !== plan) {
|
||||
anchors.plan.after(plan);
|
||||
}
|
||||
},
|
||||
|
||||
applyHeaderVisibilitySettings() {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
@@ -3579,6 +3660,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (tokenCountEl) {
|
||||
tokenCountEl.style.display = showTokenCount ? '' : 'none';
|
||||
}
|
||||
// After the System Stats visibility above: whether WS joins the stats pill
|
||||
// depends on the pill being shown.
|
||||
this.applyHeaderStatsStyle({
|
||||
style: compactHeader || this.isSoloWindow ? 'classic' : this.resolveHeaderStatsStyle(settings),
|
||||
showSystemStats,
|
||||
});
|
||||
|
||||
// Hide lifecycle log button when setting is disabled
|
||||
// Default OFF: the lifecycle-log document icon is opt-in; the default header
|
||||
@@ -3746,6 +3833,19 @@ Object.assign(CodemanApp.prototype, {
|
||||
const sort = (settings.tabRailSort ?? defaults.tabRailSort ?? 'activity') === 'manual' ? 'manual' : 'activity';
|
||||
root.dataset.tabRailSort = sort;
|
||||
|
||||
// The tab layout rides on a fourth attribute, for the same reason: it is
|
||||
// applied by the render paths (inline `order` plus headings, or cluster
|
||||
// boxes), so a flip has to re-render, and the gates in app.js
|
||||
// (`isTabTriage()`, `isTabClusters()`, `isTabLedger()`) read one attribute
|
||||
// per pass instead of re-parsing localStorage.
|
||||
const previousArrangement = root.dataset.tabArrangement || 'state';
|
||||
const arrangement = this.resolveTabArrangement(settings);
|
||||
root.dataset.tabArrangement = arrangement;
|
||||
// Which end the state groups start from; read by _tabTriageLayout().
|
||||
const previousStateOrder = root.dataset.tabStateOrder || 'urgent-first';
|
||||
const stateOrder = this.resolveTabStateOrder(settings);
|
||||
root.dataset.tabStateOrder = stateOrder;
|
||||
|
||||
const tabsEl = document.getElementById('sessionTabs');
|
||||
const rail = document.getElementById('tabRail');
|
||||
const headerHost = document.getElementById('sessionTabsHost');
|
||||
@@ -3769,7 +3869,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// the row template, not toggled by CSS — same reasoning as the sidebar's
|
||||
// detail half in applySessionListLayout(). Taller rows also move every
|
||||
// connector anchored to a tab rect.
|
||||
const changed = orientationChanged || previousDetail !== detail || previousSort !== sort;
|
||||
const changed = orientationChanged || previousDetail !== detail || previousSort !== sort || previousArrangement !== arrangement || previousStateOrder !== stateOrder;
|
||||
if (orientationChanged) {
|
||||
this.updateTabOverflowMode?.();
|
||||
if (!settleRailWidth) this.syncTerminalGeometry?.();
|
||||
@@ -4039,10 +4139,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
// NOTE: Feature toggles (subagentTrackingEnabled, imageWatcherEnabled, ralphTrackerEnabled)
|
||||
// are NOT display keys — they control server-side behavior and must sync from server.
|
||||
const displayKeys = new Set([
|
||||
'showFontControls', 'showSystemStats', 'showTokenCount', 'showCost',
|
||||
'showFontControls', 'showSystemStats', 'headerStatsStyle', 'showTokenCount', 'showCost',
|
||||
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
|
||||
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
|
||||
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
|
||||
'language',
|
||||
|
||||
+665
-6
@@ -8520,12 +8520,6 @@ kbd {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
/* An action with no key bound (Close Session by default): say so, quietly. */
|
||||
.shortcut-overlay-unbound {
|
||||
font-size: 0.75rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.shortcut-overlay-footer {
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
@@ -19794,3 +19788,668 @@ html .toolbar .btn-git-status[aria-expanded='true'] {
|
||||
padding-left: 0.4rem;
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Tab grouping by state (tabArrangement: 'state', the default;
|
||||
Discussion #426 option C)
|
||||
============================================================
|
||||
app.js writes a flex `order` per tab plus one heading and one row break per
|
||||
non-empty state, all direct children of #sessionTabs (_syncTabTriageChrome).
|
||||
The DOM stays in tab order; computeTabTriageLayout() in constants.js owns the
|
||||
bands. With grouping off none of this matches anything. */
|
||||
.tab-triage-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-self: stretch;
|
||||
gap: 5px;
|
||||
flex: 0 0 auto;
|
||||
box-sizing: border-box;
|
||||
padding: 0 6px 0 2px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
color: var(--text-muted);
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.tab-triage-count {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
color: var(--text-muted);
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.tab-triage-head--needs .tab-triage-label {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.tab-triage-head--waiting .tab-triage-label {
|
||||
color: var(--yellow);
|
||||
}
|
||||
|
||||
.tab-triage-head--working .tab-triage-label {
|
||||
color: var(--green);
|
||||
}
|
||||
|
||||
.tab-triage-break {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Counts describe the whole group, so they step aside while the sidebar
|
||||
filter narrows the rows under them. */
|
||||
.session-tabs.tabs-filtering > .tab-triage-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Header strip, wrapping (desktop): one row per state. Each heading sits in a
|
||||
left gutter, so a group too long for one line continues under its own tabs
|
||||
rather than under its heading, and each row ends with a full-width break. */
|
||||
/* The label column is as wide as the widest label on screen (app.js measures
|
||||
it into --tab-triage-gutter whenever the labels change; 92px is only the
|
||||
first-paint fallback) and the labels are left-aligned in it.
|
||||
|
||||
The brand leaves the flow and sits over the strip's top-left corner, so the
|
||||
strip starts at the header's left edge: the first row's heading (the lead)
|
||||
is pushed past the brand by --tab-triage-brand, and every later row starts
|
||||
at the edge, under "Codeman", instead of leaving that corner empty. The
|
||||
rows under the first one line up with each other in the label column. */
|
||||
.header:has(> .session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows)) > .header-brand {
|
||||
position: absolute;
|
||||
top: 0.35rem;
|
||||
left: 0.75rem;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows) {
|
||||
padding-left: var(--tab-triage-gutter, 92px);
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows) > .tab-triage-head {
|
||||
justify-content: flex-start;
|
||||
width: var(--tab-triage-gutter, 92px);
|
||||
margin-left: calc(-1 * var(--tab-triage-gutter, 92px));
|
||||
padding: 0 8px 0 0;
|
||||
}
|
||||
|
||||
/* The first row starts beside the brand and lines up with nothing else, so its
|
||||
label takes its own width and its tabs follow it directly. */
|
||||
.session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows) > .tab-triage-head--lead {
|
||||
width: auto;
|
||||
margin-left: calc(var(--tab-triage-brand, 100px) - var(--tab-triage-gutter, 92px));
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows) > .tab-triage-break {
|
||||
display: block;
|
||||
flex: 0 0 100%;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
/* Side rail and sidebar: each heading is a section row above its rows. */
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tabs.tabs-triage > .tab-triage-head,
|
||||
html[data-session-list='sidebar'] .session-sidebar .session-tabs.tabs-triage > .tab-triage-head {
|
||||
align-self: auto;
|
||||
width: 100%;
|
||||
padding: 8px 6px 3px;
|
||||
}
|
||||
|
||||
/* The collapsed sidebar is a 44px icon rail with no room for a label. */
|
||||
html[data-session-list='sidebar'][data-sidebar='collapsed'] .session-sidebar .tab-triage-head {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Tab clusters by case (tabArrangement: 'case'; Discussion #426 option A)
|
||||
============================================================
|
||||
app.js wraps each case's tabs in a .tab-cluster box (_renderTabClusters):
|
||||
a labelled box per case with two or more tabs, an unlabelled box with a
|
||||
colour swatch per case with one, and a box per web tab. --cluster-color is
|
||||
the case's colour from the session palette. Tabs inside keep their own
|
||||
markup; only the `-<case>` part of a generated name (.tab-name-case) is
|
||||
hidden, and only here. */
|
||||
.session-tabs.tabs-clusters .tab-name-case {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-cluster-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: none;
|
||||
padding: 0 6px 0 2px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
color: var(--text-dim);
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.tab-cluster-count {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.tab-cluster-swatch {
|
||||
flex: none;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 2px;
|
||||
background: var(--cluster-color, var(--text-muted));
|
||||
}
|
||||
|
||||
/* Header strip: each cluster is an inline box that wraps inside itself when a
|
||||
case has more tabs than fit on a line. */
|
||||
.session-tabs-host > .session-tabs.tabs-clusters {
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
padding: 1px 3px 1px 8px;
|
||||
border: 1px solid var(--control-border);
|
||||
border-left: 3px solid var(--cluster-color, var(--control-border));
|
||||
border-radius: 8px;
|
||||
background: var(--control-bg);
|
||||
}
|
||||
|
||||
/* A case with one tab and a web tab are boxed but not labelled: the single
|
||||
case keeps its swatch, a web tab has no case at all. */
|
||||
.session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster--single {
|
||||
border-left-width: 1px;
|
||||
padding-left: 6px;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster--single .tab-cluster-name,
|
||||
.session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster--single .tab-cluster-count {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster--single .tab-cluster-label {
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-clusters > .tab-cluster--web {
|
||||
padding-left: 3px;
|
||||
}
|
||||
|
||||
/* Side rail and sidebar: every case is a section with its label on top
|
||||
(vertical space is cheap there, so a one-tab case is labelled too). The
|
||||
label goes first by `order`, because a sorted rail orders the rows inside
|
||||
each cluster. */
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tabs.tabs-clusters > .tab-cluster,
|
||||
html[data-session-list='sidebar'] .session-sidebar .session-tabs.tabs-clusters > .tab-cluster {
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tabs.tabs-clusters > .tab-cluster + .tab-cluster,
|
||||
html[data-session-list='sidebar'] .session-sidebar .session-tabs.tabs-clusters > .tab-cluster + .tab-cluster {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'] .tab-rail .session-tabs.tabs-clusters .tab-cluster-label,
|
||||
html[data-session-list='sidebar'] .session-sidebar .session-tabs.tabs-clusters .tab-cluster-label {
|
||||
order: -1;
|
||||
padding: 6px 6px 3px;
|
||||
}
|
||||
|
||||
/* The collapsed sidebar is a 44px icon rail with no room for a label. */
|
||||
html[data-session-list='sidebar'][data-sidebar='collapsed'] .session-sidebar .tab-cluster-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Ledger (tabArrangement: 'ledger'; Discussion #426 option B)
|
||||
============================================================
|
||||
The flat list, in tab order, on an aligned column grid: equal cells, mono
|
||||
type, a 3px status bar on the left instead of the dot. Desktop header strip
|
||||
only (updateTabOverflowMode() keeps it wrapping); narrower strips, the rail
|
||||
and the sidebar keep the plain list. Nothing here touches the markup. */
|
||||
@media (min-width: 768px) {
|
||||
.session-tabs-host > .session-tabs.tabs-ledger {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(176px, 1fr));
|
||||
align-content: start;
|
||||
/* The strip's own align-items: flex-start applies to grid items too; a
|
||||
cell must stretch, or the active cell (taller with its actions) breaks
|
||||
its row. */
|
||||
align-items: stretch;
|
||||
gap: 4px 6px;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab {
|
||||
--ledger-bar: var(--green);
|
||||
min-width: 0;
|
||||
/* Tall enough for the active cell's actions, so every row is one height. */
|
||||
min-height: 30px;
|
||||
box-sizing: border-box;
|
||||
gap: 7px;
|
||||
padding: 4px 8px 4px 11px;
|
||||
border: 1px solid var(--control-border);
|
||||
border-radius: 4px;
|
||||
background: var(--control-bg);
|
||||
box-shadow: inset 3px 0 0 var(--ledger-bar);
|
||||
font-family: 'JetBrains Mono', var(--font-mono, monospace);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab .tab-info {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab .tab-number {
|
||||
width: auto;
|
||||
min-width: 1ch;
|
||||
height: auto;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--text-muted);
|
||||
font-family: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab .tab-status {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab.tab-alert-idle {
|
||||
--ledger-bar: var(--yellow);
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab:is(.tab-alert-action, :has(> .tab-status.error)) {
|
||||
--ledger-bar: var(--red);
|
||||
}
|
||||
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab:is(.tab-agent-exited, .session-tab--web, :has(> .tab-status.stopped)) {
|
||||
--ledger-bar: var(--text-muted);
|
||||
}
|
||||
|
||||
/* The active cell has to win against a grid of look-alike cells. The skin's
|
||||
active rule (1px accent border, no shadow, both !important) is too quiet
|
||||
here, so an inset second pixel doubles the border without resizing the
|
||||
cell, and the status bar turns accent. */
|
||||
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab.active {
|
||||
background: rgba(var(--accent-rgb), 0.2) !important;
|
||||
box-shadow: inset 0 0 0 1px var(--accent), inset 4px 0 0 var(--accent) !important;
|
||||
color: var(--text) !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Header stats styles (headerStatsStyle; Discussion #426 option G)
|
||||
============================================================
|
||||
html[data-header-stats] picks how the WS / CPU / MEM / plan-usage cluster
|
||||
is drawn. 'classic' matches nothing below except the hidden parts, so the
|
||||
header looks exactly as before. 'compact' and 'tiles' are desktop only
|
||||
(settings-ui.js resolves anything narrower, and a solo window, to
|
||||
'classic'), and applyHeaderStatsStyle() has already moved
|
||||
#connectionIndicator into #headerSystemStats and #planUsageChip right after
|
||||
it, so the cluster is contiguous. */
|
||||
|
||||
/* Parts only the two new styles draw. */
|
||||
.stat-ring,
|
||||
.connection-tile,
|
||||
.header-plan-usage .pu-ring,
|
||||
.header-plan-usage .pu-meter {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* --- Compact: two pills, a ring beside every value ------------------------ */
|
||||
/* One system pill (WS, CPU, MEM) and one plan pill (5h, 7d). Every reading is
|
||||
the same shape, ring then label then value, so the two pills read as one
|
||||
set; CPU and MEM rings are the accent colour (red past 80%, like their
|
||||
value), the plan rings green, yellow or red by how much is used. */
|
||||
html[data-header-stats='compact'] .header-system-stats,
|
||||
html[data-header-stats='compact'] .header-plan-usage {
|
||||
align-items: center;
|
||||
height: 24px;
|
||||
min-height: 24px;
|
||||
padding: 0 11px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 12px;
|
||||
background: var(--control-bg);
|
||||
border: 1px solid var(--control-border);
|
||||
font-family: 'JetBrains Mono', var(--font-mono, monospace);
|
||||
font-size: 0.68rem;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats {
|
||||
gap: 13px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats > .connection-indicator {
|
||||
font-size: inherit;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats > .connection-indicator > .connection-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats .stat-item {
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats .stat-bar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* One label style and one value style across both pills. */
|
||||
html[data-header-stats='compact'] .header-system-stats .stat-label,
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-label {
|
||||
min-width: 0;
|
||||
font-size: 0.6rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats .stat-value,
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-val {
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-system-stats .stat-value:not(.high) {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-plan-usage {
|
||||
flex-direction: row;
|
||||
gap: 13px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-row {
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-provider {
|
||||
width: auto;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-windows {
|
||||
align-items: center;
|
||||
gap: 13px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-sep {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-win {
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
/* A ring: a conic fill masked down to a 2px stroke. Its colour is currentColor,
|
||||
so a plan ring takes the pu-green/-yellow/-red class it shares with its
|
||||
value, and a stat ring the accent (red when .high). */
|
||||
html[data-header-stats='compact'] .stat-ring,
|
||||
html[data-header-stats='compact'] .header-plan-usage .pu-ring {
|
||||
display: inline-block;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
flex: none;
|
||||
border-radius: 50%;
|
||||
background: conic-gradient(currentColor calc(var(--pu, 0) * 1%), var(--control-border-hover, var(--control-border)) 0);
|
||||
-webkit-mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2px));
|
||||
mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2px));
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .stat-ring {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .stat-ring.high {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
/* --- Tiles: label over value, a bar underneath, no icons ----------------- */
|
||||
/* Each tile is a three-row grid (label, value, bar) with pixel line-heights,
|
||||
so its height comes from the layout, not from whichever monospace face the
|
||||
machine falls back to. The bar is a real row, never laid over the bottom
|
||||
edge: an absolutely placed bar under a fixed-height tile is what put the
|
||||
value on top of it with a taller system font (SF Mono). The bundled
|
||||
JetBrains Mono comes first so every machine draws the same tile. */
|
||||
html[data-header-stats='tiles'] .header-system-stats {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-system-stats > .stat-item,
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-win,
|
||||
html[data-header-stats='tiles'] .header-system-stats > .connection-indicator > .connection-tile {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: 9px 14px 2px;
|
||||
row-gap: 2px;
|
||||
align-content: center;
|
||||
justify-items: start;
|
||||
min-width: 54px;
|
||||
/* 2 + 9 + 2 + 14 + 2 + 2 + 3 plus the 1px borders: 36px, the header's own
|
||||
height, so the tiles never make the header grow. */
|
||||
padding: 2px 10px 3px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 7px;
|
||||
background: var(--control-bg);
|
||||
border: 1px solid var(--control-border);
|
||||
font-family: 'JetBrains Mono', var(--font-mono, monospace);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The tile label and value: the stat items already carry a label and a value,
|
||||
the connection indicator gets its own pair (its text line keeps the classic
|
||||
wording, queued bytes included, and stays the accessible name via title). */
|
||||
html[data-header-stats='tiles'] .header-system-stats .stat-label,
|
||||
html[data-header-stats='tiles'] .connection-tile-label,
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-label {
|
||||
display: block;
|
||||
grid-row: 1;
|
||||
min-width: 0;
|
||||
font-size: 9px;
|
||||
line-height: 9px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-muted);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-system-stats .stat-value,
|
||||
html[data-header-stats='tiles'] .connection-tile-value,
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-val {
|
||||
display: block;
|
||||
grid-row: 2;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
font-size: 12px;
|
||||
line-height: 14px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* Plan values keep their green/yellow/red; the stat values read as plain text
|
||||
unless they are running high. */
|
||||
html[data-header-stats='tiles'] .header-system-stats .stat-value:not(.high),
|
||||
html[data-header-stats='tiles'] .connection-tile-value {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* The WS tile: JS sets the indicator's `display` inline (flex, or none when
|
||||
there is nothing to report), so the grid lives on the .connection-tile span
|
||||
inside it and the indicator itself only keeps the flex box it already has. */
|
||||
html[data-header-stats='tiles'] .header-system-stats > .connection-indicator {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-system-stats > .connection-indicator > .connection-dot,
|
||||
html[data-header-stats='tiles'] .header-system-stats > .connection-indicator > .connection-text {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .connection-tile-value.connected {
|
||||
color: var(--green);
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .connection-tile-value.fallback,
|
||||
html[data-header-stats='tiles'] .connection-tile-value.reconnecting,
|
||||
html[data-header-stats='tiles'] .connection-tile-value.draining {
|
||||
color: var(--yellow);
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .connection-tile-value.offline {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
/* The bar is the third row, full tile width. The WS tile has no bar, and its
|
||||
empty third row keeps it the same height as its neighbours. */
|
||||
html[data-header-stats='tiles'] .header-system-stats .stat-bar,
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-meter {
|
||||
display: block;
|
||||
grid-row: 3;
|
||||
justify-self: stretch;
|
||||
width: auto;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
background: rgba(127, 127, 127, 0.18);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-meter > i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: 1px;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-plan-usage {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
background: none;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-row {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-provider {
|
||||
width: auto;
|
||||
flex: none;
|
||||
font-size: 0.55rem;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-windows {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-sep {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* An idle window keeps its tile and dims the whole thing. */
|
||||
html[data-header-stats='tiles'] .header-plan-usage .pu-win-idle {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
/* --- Header buttons next to the clustered stats ------------------------ */
|
||||
/* Bare 16px glyphs beside 36px tiles read as a different design. In Tiles the
|
||||
header's icon buttons take the tile box (same height, border and fill, a
|
||||
larger icon); in Compact they become round chips the height of the pills.
|
||||
Only the box changes: the marker classes still hide them, and the gear
|
||||
keeps its quarter turn on hover, on the glyph rather than the whole box. */
|
||||
html[data-header-stats='tiles'] .header-right > .btn-icon-header,
|
||||
html[data-header-stats='compact'] .header-right > .btn-icon-header {
|
||||
box-sizing: border-box;
|
||||
background: var(--control-bg);
|
||||
border: 1px solid var(--control-border);
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-right > .btn-icon-header {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 7px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-right > .btn-icon-header {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 13px;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-right > .btn-icon-header > svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
html[data-header-stats='compact'] .header-right > .btn-icon-header > svg {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-right > .btn-icon-header:hover,
|
||||
html[data-header-stats='compact'] .header-right > .btn-icon-header:hover {
|
||||
background: var(--control-bg-hover);
|
||||
border-color: var(--control-border-hover);
|
||||
color: var(--text);
|
||||
transform: none;
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-right > .btn-icon-header > svg,
|
||||
html[data-header-stats='compact'] .header-right > .btn-icon-header > svg {
|
||||
transition: transform var(--transition-smooth);
|
||||
}
|
||||
|
||||
html[data-header-stats='tiles'] .header-right > .btn-settings:hover > svg,
|
||||
html[data-header-stats='compact'] .header-right > .btn-settings:hover > svg {
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
/* Before the first plan reading the chip holds a bare em dash; give it a tile
|
||||
of its own so it does not read as a stray mark between the tiles. */
|
||||
html[data-header-stats='tiles'] .header-plan-usage:not(:has(.pu-row)) {
|
||||
justify-content: center;
|
||||
min-width: 54px;
|
||||
height: 36px;
|
||||
padding: 0 10px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 7px;
|
||||
background: var(--control-bg);
|
||||
border: 1px solid var(--control-border);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,640 @@
|
||||
// src/web/public/terminal-split.js
|
||||
|
||||
/**
|
||||
* @fileoverview Split-pane orchestration: opens a second live session
|
||||
* ("Pane B") beside the active one, in a TerminalTile (terminal-tile.js), with
|
||||
* a draggable divider, a session picker, and auto-collapse when either
|
||||
* session ends. Desktop-only; see docs/split-pane-sessions-plan.md.
|
||||
* @fileoverview SplitTerminalPane — a second, independent live terminal pane
|
||||
* ("Pane B") for split-view sessions. Deliberately plainer than the primary
|
||||
* pane (this.terminal/this._ws in terminal-ui.js): no local-echo overlay, no
|
||||
* CJK IME, no touch/mobile handlers, no keyboard accessory bar. Desktop-only
|
||||
* feature by nature — see docs/split-pane-sessions-plan.md.
|
||||
*
|
||||
* @dependency terminal-tile.js (window.TerminalTile)
|
||||
* @dependency constants.js (window.CodemanSplitPane, SPLIT_PANE_MIN_WIDTH)
|
||||
* @loadorder 7.5 of 16, loaded after terminal-tile.js and before respawn-ui.js
|
||||
* @dependency vendor/xterm.js, vendor/xterm-addon-fit.js
|
||||
* @dependency constants.js (window.CodemanTerminalFont, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE)
|
||||
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight)
|
||||
* @loadorder 7.5 of 16 — loaded after terminal-ui.js, before respawn-ui.js
|
||||
*/
|
||||
|
||||
(function (global) {
|
||||
// How long a scroll-to-top history pull may hold Pane B's live output.
|
||||
const HISTORY_PULL_TIMEOUT_MS = 10000;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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.
|
||||
return new Promise((resolve) => {
|
||||
let offset = 0;
|
||||
const writeNext = () => {
|
||||
if (isDestroyed() || !terminal) {
|
||||
resolve();
|
||||
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();
|
||||
}
|
||||
};
|
||||
writeNext();
|
||||
});
|
||||
}
|
||||
|
||||
class SplitTerminalPane {
|
||||
constructor(sessionId, mountEl, opts = {}) {
|
||||
this.sessionId = sessionId;
|
||||
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.
|
||||
this.detachedSessions = opts.detachedSessions;
|
||||
this.terminal = null;
|
||||
this.fitAddon = null;
|
||||
this.ws = null;
|
||||
this._wsReady = false;
|
||||
this._wsClosed = false;
|
||||
this._destroyed = false;
|
||||
// Single-flight state for _loadBuffer()/_refreshBuffer() below.
|
||||
this._bufferLoading = false;
|
||||
this._bufferRefreshPending = false;
|
||||
// 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
|
||||
// written under the replay. `_markerOwed` is the "disconnected" marker a
|
||||
// load still has to write (see _onSocketClosed()/_stampMarkerIfOwed()).
|
||||
this._historyPullAt = 0;
|
||||
this._historyPullUseless = false;
|
||||
this._liveQueue = null;
|
||||
this._markerOwed = false;
|
||||
this._onWheel = null;
|
||||
}
|
||||
|
||||
async connect() {
|
||||
const savedFontSize = parseInt(localStorage.getItem('codeman-font-size'), 10);
|
||||
this.terminal = new Terminal({
|
||||
theme: { ...global.codemanCurrentXtermTheme() },
|
||||
fontFamily: global.CodemanTerminalFont.resolve(this.fontSettings.terminalFontFamily),
|
||||
...global.CodemanTerminalFont.resolveWeights(this.fontSettings),
|
||||
fontSize: Number.isFinite(savedFontSize) ? savedFontSize : 14,
|
||||
lineHeight: 1.2,
|
||||
cursorBlink: false,
|
||||
cursorStyle: 'block',
|
||||
minimumContrastRatio: global.codemanCurrentSkinIsLight() ? 4.5 : 1,
|
||||
scrollback: DEFAULT_SCROLLBACK,
|
||||
allowTransparency: true,
|
||||
allowProposedApi: true,
|
||||
});
|
||||
|
||||
this.fitAddon = new FitAddon.FitAddon();
|
||||
this.terminal.loadAddon(this.fitAddon);
|
||||
this.terminal.open(this.mountEl);
|
||||
this.fitAddon.fit();
|
||||
|
||||
this._installWheelListener();
|
||||
|
||||
this.terminal.onData((data) => {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify({ t: 'i', d: 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 is deliberately left on xterm's own
|
||||
// default (plain-text paste): Pane B has no image-paste trap to route it
|
||||
// to, so intercepting it here would only break paste.
|
||||
this.terminal.attachCustomKeyEventHandler((ev) => {
|
||||
if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return true;
|
||||
if (
|
||||
ev.altKey &&
|
||||
!ev.ctrlKey &&
|
||||
!ev.shiftKey &&
|
||||
/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(ev.code || '')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (ev.type === 'keydown' && global.app?.shouldOpenCommandPaletteFromShortcut?.(ev)) {
|
||||
return false;
|
||||
}
|
||||
if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(ev)) {
|
||||
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.
|
||||
if (
|
||||
ev.type === 'keydown' &&
|
||||
ev.key.toLowerCase() === 'z' &&
|
||||
ev.ctrlKey &&
|
||||
!ev.altKey &&
|
||||
!ev.metaKey &&
|
||||
!ev.shiftKey &&
|
||||
this.sessionMode !== 'shell'
|
||||
) {
|
||||
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
|
||||
// activeSessionId, and has no local-echo overlay of its own to flush
|
||||
// first (Pane B 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') {
|
||||
fetch(`/api/sessions/${this.sessionId}/send-key`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: ev.ctrlKey ? 'C-Enter' : 'S-Enter' }),
|
||||
}).catch(() => {
|
||||
/* Best-effort, matching this pane's tolerance elsewhere. */
|
||||
});
|
||||
}
|
||||
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.
|
||||
if (ev.type === 'keydown' && global.app?.shouldCopyTerminalSelectionFromShortcut?.(ev)) {
|
||||
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()) {
|
||||
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');
|
||||
});
|
||||
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).
|
||||
if (this.terminal?.hasSelection?.()) {
|
||||
this.terminal.clearSelection?.();
|
||||
global.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;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// 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.
|
||||
await this._loadBuffer();
|
||||
if (this._destroyed) return;
|
||||
|
||||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const url = `${proto}//${location.host}${window.CodemanBase.base}/ws/sessions/${this.sessionId}/terminal`;
|
||||
this.ws = new WebSocket(url);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
this._wsReady = true;
|
||||
this._sendResize();
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.t === 'o') {
|
||||
this._onLiveOutput(msg.d);
|
||||
} else if (msg.t === 'c') {
|
||||
this._onLiveClear();
|
||||
} else if (msg.t === 'r') {
|
||||
// Server-triggered refresh (SSE backpressure cleared, terminal
|
||||
// data was dropped). The primary pane routes this to
|
||||
// _onSessionNeedsRefresh (app.js:2990) — Pane B has its own
|
||||
// buffer loader for the same reason connect() does.
|
||||
this._refreshBuffer();
|
||||
}
|
||||
} catch {
|
||||
/* Malformed frame — ignore, matches primary pane's tolerance. */
|
||||
}
|
||||
};
|
||||
|
||||
// Mirror app.js's onclose/onerror pattern (app.js:2905-2964): _wsReady
|
||||
// must go false on a drop or fit()/_sendResize() silently no-ops on a
|
||||
// closed socket per the WebSocket spec (no exception, no log). No
|
||||
// reconnect logic here — Pane B is deliberately plainer than the
|
||||
// primary pane (see the fileoverview above); a drop just stops
|
||||
// resizing until the parent recreates the pane. But onData already
|
||||
// silently drops keystrokes while _wsReady is false (below), so
|
||||
// without a visible marker a dropped socket left Pane B looking
|
||||
// normal while it quietly ate everything typed into it. v1 scope is
|
||||
// "say so", not reconnect — collapsing the split would lose the
|
||||
// user's place in Pane B's scrollback for a transient blip.
|
||||
this.ws.onclose = () => this._onSocketClosed();
|
||||
|
||||
this.ws.onerror = () => {
|
||||
// onclose fires after onerror — cleanup happens there.
|
||||
};
|
||||
}
|
||||
|
||||
// The socket's close, split out of connect() so the tests can drive it.
|
||||
// While any load runs (a history pull or a `{t:'r'}` refresh) the marker is
|
||||
// only owed, and that load's finally block settles it (_stampMarkerIfOwed()):
|
||||
// written now, it would sit above the output a pull is still holding (flushed
|
||||
// after it on a skip, a downgrade or a failed fetch), above a refresh's
|
||||
// replay, or in the middle of a chunked replay. A pull still waiting for its
|
||||
// response holds the marker too, for as long as the request takes (up to its
|
||||
// budget, see _pullHistory()).
|
||||
_onSocketClosed() {
|
||||
this._wsReady = false;
|
||||
this._wsClosed = true;
|
||||
if (this._bufferLoading) this._markerOwed = true;
|
||||
else this._writeDisconnectedMarker();
|
||||
}
|
||||
|
||||
// Settles a marker the pane owes: set when a close lands during a load (the
|
||||
// replay would otherwise sit below it) or when a load wipes the terminal on
|
||||
// a closed socket. Called from each load's own finally, just before
|
||||
// _endBufferLoad() starts any trailing refresh.
|
||||
_stampMarkerIfOwed() {
|
||||
// A trailing refresh is about to clear() synchronously, while xterm parses
|
||||
// a write() on a later tick: a marker written here would land in the
|
||||
// freshly cleared buffer ABOVE that refresh's replay, a second, stale copy.
|
||||
// The refresh re-owes the marker on a closed socket and stamps it itself.
|
||||
if (this._bufferRefreshPending && !this._destroyed) return;
|
||||
const owed = this._markerOwed;
|
||||
this._markerOwed = false;
|
||||
if (owed && this._wsClosed && !this._destroyed) this._writeDisconnectedMarker();
|
||||
}
|
||||
|
||||
// Extracted so both _onSocketClosed() and a load that ends owing it on a
|
||||
// closed socket can write it (see _stampMarkerIfOwed()).
|
||||
_writeDisconnectedMarker() {
|
||||
this.terminal?.write('\r\n\x1b[2m[Pane B disconnected — close and reopen the split to reconnect]\x1b[0m\r\n');
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
//
|
||||
// Mirrors the primary pane's own mode check (app.js's selectSession /
|
||||
// _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.
|
||||
//
|
||||
// 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() {
|
||||
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);
|
||||
}
|
||||
} catch {
|
||||
/* Best-effort — live output still arrives once the socket connects. */
|
||||
} finally {
|
||||
this._stampMarkerIfOwed();
|
||||
this._endBufferLoad();
|
||||
}
|
||||
}
|
||||
|
||||
// Ends a single-flight load (initial, refresh or history pull): clears the
|
||||
// flag, then runs the ONE trailing refresh that arrived while it was busy.
|
||||
_endBufferLoad() {
|
||||
this._bufferLoading = false;
|
||||
if (this._bufferRefreshPending && !this._destroyed) {
|
||||
this._bufferRefreshPending = false;
|
||||
this._refreshBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
// Live terminal output. Written straight through, except while a history
|
||||
// pull is replaying: a capture is current only up to the instant tmux took
|
||||
// it, so a frame arriving mid-replay is held with its arrival time and
|
||||
// replayed behind the snapshot by _pullHistory() (the primary pane's
|
||||
// _finishBufferLoad `since` rule), never written underneath it.
|
||||
_onLiveOutput(data) {
|
||||
if (this._liveQueue) this._liveQueue.push({ at: performance.now(), data });
|
||||
else this.terminal?.write(data);
|
||||
}
|
||||
|
||||
// The server's `{t:'c'}` clear frame takes the same route as output, for the
|
||||
// same reason: clearing straight away, mid-replay, would wipe the half-written
|
||||
// snapshot and leave _pullHistory() measuring a buffer that is no longer the
|
||||
// one it is restoring. Queued, it lands in order with the frames around it.
|
||||
_onLiveClear() {
|
||||
if (this._liveQueue) this._liveQueue.push({ at: performance.now(), clear: true });
|
||||
else this.terminal?.clear();
|
||||
}
|
||||
|
||||
// Capture phase, because xterm's own wheel handler stopPropagation()s every
|
||||
// event it consumes, so a bubbling listener here would never see the wheel
|
||||
// while the pane still has scrollback to scroll. Passive: this only observes,
|
||||
// xterm keeps doing the scrolling.
|
||||
_installWheelListener() {
|
||||
this._onWheel = (ev) => {
|
||||
if (ev.deltaY < 0) this._maybeLoadMoreHistory();
|
||||
};
|
||||
this.mountEl.addEventListener('wheel', this._onWheel, { capture: true, passive: true });
|
||||
}
|
||||
|
||||
// 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.
|
||||
_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.
|
||||
if (this.detachedSessions?.has(this.sessionId)) return;
|
||||
const active = this.terminal.buffer.active;
|
||||
if (active.type !== 'normal' || active.viewportY !== 0) return;
|
||||
// Momentum scrolling fires this dozens of times per flick, so cooldown
|
||||
// rather than latch; a pull that could only have downgraded the pane
|
||||
// waits far longer.
|
||||
const cooldown = this._historyPullUseless ? 60000 : 4000;
|
||||
const now = Date.now();
|
||||
if (now - this._historyPullAt < cooldown) return;
|
||||
this._historyPullAt = now;
|
||||
void this._pullHistory();
|
||||
}
|
||||
|
||||
// Pulls a BOUNDED window of tmux's full history (the same TERMINAL_TAIL_SIZE
|
||||
// a tab switch loads, so a multi-megabyte capture never lands on xterm's
|
||||
// main thread) and replays it under the reader's current place. Holds the
|
||||
// single-flight flag across the fetch AND the replay, like _loadBuffer().
|
||||
async _pullHistory() {
|
||||
this._bufferLoading = true;
|
||||
let replayed = false;
|
||||
let capturedAt = 0;
|
||||
// Two budgets on one signal. The request itself gets the primary pane's
|
||||
// (CodemanFetchDeadline, constants.js): live output is not held while it
|
||||
// runs, but the single-flight flag is, so a coalesced `{t:'r'}` refresh and
|
||||
// the marker owed by a close (_onSocketClosed()) both wait for it, at worst
|
||||
// for that whole budget. Once the headers land live output IS held, so the
|
||||
// body read gets the short one instead: a body that hangs would otherwise
|
||||
// freeze the pane for the long budget. Aborting lands in the catch below,
|
||||
// which releases the flag and the queue. AbortSignal.timeout() alone cannot
|
||||
// be re-armed, hence the controller; without AbortController the pull
|
||||
// simply has no deadline.
|
||||
const controller = global.AbortController ? new global.AbortController() : null;
|
||||
let abortTimer = null;
|
||||
const armDeadline = (ms) => {
|
||||
if (!controller) return;
|
||||
clearTimeout(abortTimer);
|
||||
abortTimer = setTimeout(() => controller.abort(), ms);
|
||||
};
|
||||
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,
|
||||
});
|
||||
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
|
||||
// for the instant tmux took the capture, which lies somewhere in the
|
||||
// round trip, so a frame in that window can be lost or doubled. Bounded
|
||||
// by one round trip and not closable without a server-side capture time.
|
||||
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.
|
||||
this._liveQueue = [];
|
||||
const payload = (await res.json())?.data;
|
||||
clearTimeout(abortTimer);
|
||||
const buffer = payload?.terminalBuffer;
|
||||
const term = this.terminal;
|
||||
if (!buffer || !term || this._destroyed) return;
|
||||
const rowsBefore = term.buffer.active.length;
|
||||
const rowsIncoming = global.app?._estimateReplayRows?.(buffer, term.cols) ?? buffer.split('\n').length;
|
||||
// xterm keeps at most `scrollback + rows` rows while tmux keeps far more
|
||||
// lines, so a window of short lines can carry more rows than this pane
|
||||
// can ever hold, and `rowsIncoming <= rowsBefore` would never come true.
|
||||
const scrollbackCap = term.options?.scrollback || 0;
|
||||
const paneFull = scrollbackCap > 0 && rowsBefore >= scrollbackCap + term.rows;
|
||||
// Nothing to gain (this also covers a downgrade, which would delete
|
||||
// history mid-scroll), and a reset+rewrite would jump the viewport. An
|
||||
// untruncated window IS all of tmux's history and the next burst can add
|
||||
// more, so keep the 4 s cooldown. A truncated window can never reach past
|
||||
// what the pane shows, and every ask costs the server a capture-pane of
|
||||
// the whole history (`tail` is cut after it): back off to 60 s, as the
|
||||
// primary pane does (app.js _maybeRefetchFullHistory). A full pane backs
|
||||
// off too, since no window can ever fit in it.
|
||||
if (rowsIncoming <= rowsBefore || paneFull) {
|
||||
if (payload.truncated || paneFull) this._historyPullUseless = true;
|
||||
return;
|
||||
}
|
||||
this._historyPullUseless = false;
|
||||
term.write('\x1bc');
|
||||
replayed = true;
|
||||
if (this._wsClosed) this._markerOwed = true;
|
||||
await writeChunked(term, buffer, () => this._destroyed);
|
||||
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.
|
||||
await new Promise((resolve) => this.terminal.write('', resolve));
|
||||
if (this._destroyed || !this.terminal) return;
|
||||
// The replay grew the buffer UPWARD, so what was row 0 is now `delta`
|
||||
// rows down; land there and the recovered history sits above it.
|
||||
const delta = this.terminal.buffer.active.length - rowsBefore;
|
||||
if (delta > 0) this.terminal.scrollToLine(delta);
|
||||
else this.terminal.scrollToTop();
|
||||
} catch {
|
||||
/* Best-effort — live output keeps arriving whatever happens here. */
|
||||
} finally {
|
||||
clearTimeout(abortTimer);
|
||||
const queued = this._liveQueue ?? [];
|
||||
this._liveQueue = null;
|
||||
// After a replay, only frames that arrived after the capture are news;
|
||||
// earlier ones are already in it. With no replay, every held frame is.
|
||||
const cutoff = replayed ? capturedAt : 0;
|
||||
for (const entry of queued) {
|
||||
if (entry.at < cutoff) continue;
|
||||
if (entry.clear) this.terminal?.clear();
|
||||
else this.terminal?.write(entry.data);
|
||||
}
|
||||
// Settled after the queue flush so the marker is the last thing on
|
||||
// screen: a close during the pull wrote nothing (_onSocketClosed() defers
|
||||
// it while a load runs), and a replay's own `\x1bc` (flagged above) wipes
|
||||
// one written before it, which would paint a fresh, current-looking
|
||||
// history while onData keeps silently dropping every keystroke on the
|
||||
// dead socket. With a trailing refresh pending (_endBufferLoad) the marker
|
||||
// is left to that refresh, which writes it below its own replay.
|
||||
this._stampMarkerIfOwed();
|
||||
this._endBufferLoad();
|
||||
}
|
||||
}
|
||||
|
||||
// The `{t:'r'}` server-refresh path: clear, then replay. Two refresh
|
||||
// frames in a row used to 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,
|
||||
// and no further frame is coming to correct stale content.
|
||||
_refreshBuffer() {
|
||||
if (this._bufferLoading) {
|
||||
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();
|
||||
}
|
||||
|
||||
// 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
|
||||
// the actual `{t:'z'}` resize once, at drag end, matching the primary
|
||||
// pane's own convention (throttledResize in terminal-ui.js).
|
||||
localFit() {
|
||||
if (!this.fitAddon) return;
|
||||
this.fitAddon.fit();
|
||||
}
|
||||
|
||||
fit() {
|
||||
this.localFit();
|
||||
this._sendResize();
|
||||
}
|
||||
|
||||
_sendResize() {
|
||||
if (!this._wsReady || !this.fitAddon) 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.
|
||||
if (this.detachedSessions?.has(this.sessionId)) return;
|
||||
const dims = this.fitAddon.proposeDimensions();
|
||||
if (!dims) return;
|
||||
// Send the real proposed dimensions unclamped, matching the primary
|
||||
// pane's convention (terminal-ui.js's getTerminalDimensions()) — the
|
||||
// server enforces its own valid range ([1,500]/[1,200] in ws-routes.ts).
|
||||
// A 40/10 floor here misreported Pane B's real width to the PTY at the
|
||||
// divider's own reachable 20% floor position, causing real
|
||||
// output-wrapping bugs.
|
||||
this.ws.send(JSON.stringify({ t: 'z', c: dims.cols, r: dims.rows, v: 'desktop' }));
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this._destroyed = true;
|
||||
if (this._onWheel) {
|
||||
this.mountEl?.removeEventListener('wheel', this._onWheel, { capture: true });
|
||||
this._onWheel = null;
|
||||
}
|
||||
if (this.ws) {
|
||||
this.ws.onopen = null;
|
||||
this.ws.onmessage = null;
|
||||
// onclose fires asynchronously AFTER close(); without this it ran
|
||||
// its "disconnected" write against a pane already torn down.
|
||||
this.ws.onclose = null;
|
||||
this.ws.onerror = null;
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
if (this.terminal) {
|
||||
this.terminal.dispose();
|
||||
this.terminal = null;
|
||||
}
|
||||
this.fitAddon = null;
|
||||
}
|
||||
}
|
||||
|
||||
global.SplitTerminalPane = SplitTerminalPane;
|
||||
})(window);
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
/**
|
||||
* Desktop-only gate, same shape as home-sessions.js's shouldShowHomeSessions
|
||||
@@ -153,7 +777,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// B's own session tab while split can otherwise land here with
|
||||
// sessionId === activeSessionId: two live WebSockets to the same
|
||||
// session, each independently claiming PTY dimensions via its own `{t:'z',...}`
|
||||
// resize frame. Refuse before creating any DOM or TerminalTile.
|
||||
// resize frame. Refuse before creating any DOM or SplitTerminalPane.
|
||||
if (sessionId === this.activeSessionId) return;
|
||||
// The picker's own exclusions (buildSplitPickerSessions in constants.js),
|
||||
// re-applied here: the menu can sit open while a listed session's CLI
|
||||
@@ -194,7 +818,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
container.appendChild(paneB);
|
||||
paneB.style.flexBasis = '50%';
|
||||
|
||||
this._splitPane = new window.TerminalTile(sessionId, paneB.querySelector('.terminal-pane-b-container'), {
|
||||
this._splitPane = new window.SplitTerminalPane(sessionId, paneB.querySelector('.terminal-pane-b-container'), {
|
||||
mode: session?.mode,
|
||||
fontSettings: this.loadAppSettingsFromStorage?.() || {},
|
||||
detachedSessions: this.detachedSessions,
|
||||
@@ -276,7 +900,7 @@ 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
|
||||
// panes AND sent Pane B a `{t:'z'}` resize frame (SplitTerminalPane 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.
|
||||
|
||||
@@ -1,887 +0,0 @@
|
||||
// src/web/public/terminal-tile.js
|
||||
|
||||
/**
|
||||
* @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.
|
||||
*
|
||||
* Deliberately plainer than the primary pane (this.terminal/this._ws in
|
||||
* terminal-ui.js): no local-echo overlay, no CJK IME, no touch/mobile
|
||||
* handlers, no keyboard accessory bar. Desktop-only by nature; see
|
||||
* 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 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.
|
||||
const HISTORY_PULL_TIMEOUT_MS = 10000;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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.
|
||||
return new Promise((resolve) => {
|
||||
let offset = 0;
|
||||
const writeNext = () => {
|
||||
if (isDestroyed() || !terminal) {
|
||||
resolve();
|
||||
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();
|
||||
}
|
||||
};
|
||||
writeNext();
|
||||
});
|
||||
}
|
||||
|
||||
class TerminalTile {
|
||||
constructor(sessionId, mountEl, opts = {}) {
|
||||
this.sessionId = sessionId;
|
||||
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.
|
||||
this.detachedSessions = opts.detachedSessions;
|
||||
this.terminal = null;
|
||||
this.fitAddon = null;
|
||||
this.ws = null;
|
||||
this._wsReady = false;
|
||||
this._wsClosed = false;
|
||||
this._destroyed = false;
|
||||
// Single-flight state for _loadBuffer()/_refreshBuffer() below.
|
||||
this._bufferLoading = false;
|
||||
this._bufferRefreshPending = false;
|
||||
// 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
|
||||
// written under the replay. `_markerOwed` is the "disconnected" marker a
|
||||
// load still has to write (see _onSocketClosed()/_stampMarkerIfOwed()).
|
||||
this._historyPullAt = 0;
|
||||
this._historyPullUseless = false;
|
||||
this._liveQueue = null;
|
||||
this._markerOwed = false;
|
||||
this._onWheel = null;
|
||||
// `{ ws, lastRecvAt }`, registered with the app's input-socket map while
|
||||
// this pane's socket is open, so the exactly-once input queue delivers this
|
||||
// session's keystrokes over it (app.js _inputSocketFor). Null otherwise.
|
||||
this._inputHandle = null;
|
||||
// Reconnect state. `_socketUrl` is set once connect() opens the first
|
||||
// socket: a pane that never connected has nothing to reconnect to.
|
||||
// `_reconnectAttempts` counts consecutive failed opens and is reset ONLY by
|
||||
// a successful open (resetting it per attempt is the tight-loop bug the
|
||||
// primary pane's _disconnectWs documents). `_stoppedCode` is the close code
|
||||
// that ended the pane for good; `onExit(code)` tells the owner once.
|
||||
this._socketUrl = null;
|
||||
this._reconnectAttempts = 0;
|
||||
this._reconnectTimer = null;
|
||||
this._stoppedCode = null;
|
||||
this._markerText = TerminalTile.MARKER_RECONNECTING;
|
||||
this.onExit = typeof opts.onExit === 'function' ? opts.onExit : null;
|
||||
// The `{ cols, rows }` last sent in a `{t:'z'}` frame, so an unchanged size
|
||||
// is not resent (each one costs a `tmux resize-window` and a SIGWINCH).
|
||||
// Cleared on every open: a fresh socket must announce its size, which is
|
||||
// also what registers it as a desktop viewer server-side.
|
||||
this._lastSentDims = null;
|
||||
// Whether the pointer is over a link in THIS pane (the primary pane's own
|
||||
// flag, app._linkHovered, belongs to its terminal alone).
|
||||
this._linkHovered = false;
|
||||
this._onFocusIn = null;
|
||||
}
|
||||
|
||||
async connect() {
|
||||
const savedFontSize = parseInt(localStorage.getItem('codeman-font-size'), 10);
|
||||
this.terminal = new Terminal({
|
||||
theme: { ...global.codemanCurrentXtermTheme() },
|
||||
fontFamily: global.CodemanTerminalFont.resolve(this.fontSettings.terminalFontFamily),
|
||||
...global.CodemanTerminalFont.resolveWeights(this.fontSettings),
|
||||
fontSize: Number.isFinite(savedFontSize) ? savedFontSize : 14,
|
||||
lineHeight: 1.2,
|
||||
cursorBlink: false,
|
||||
cursorStyle: 'block',
|
||||
minimumContrastRatio: global.codemanCurrentSkinIsLight() ? 4.5 : 1,
|
||||
scrollback: DEFAULT_SCROLLBACK,
|
||||
allowTransparency: true,
|
||||
allowProposedApi: true,
|
||||
});
|
||||
|
||||
this.fitAddon = new FitAddon.FitAddon();
|
||||
this.terminal.loadAddon(this.fitAddon);
|
||||
this.terminal.open(this.mountEl);
|
||||
this.fitAddon.fit();
|
||||
|
||||
// File paths and URLs printed here are clickable, through the SAME
|
||||
// provider as the primary pane (registerFilePathLinkProvider,
|
||||
// terminal-ui.js), and open against THIS pane's session.
|
||||
global.app?.registerFilePathLinkProvider?.({
|
||||
terminal: this.terminal,
|
||||
getSessionId: () => this.sessionId,
|
||||
setHovered: (hovered) => {
|
||||
this._linkHovered = hovered;
|
||||
},
|
||||
});
|
||||
|
||||
this._installWheelListener();
|
||||
|
||||
// Focusing this terminal makes it the pane the keyboard is in, so the
|
||||
// app-level shortcuts, voice and paste act on it (app._focusedPane).
|
||||
this._onFocusIn = () => global.app?._noteFocusedTile?.(this);
|
||||
this.terminal.textarea?.addEventListener('focus', this._onFocusIn);
|
||||
|
||||
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).
|
||||
this.terminal.attachCustomKeyEventHandler((ev) => {
|
||||
if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return true;
|
||||
if (
|
||||
ev.altKey &&
|
||||
!ev.ctrlKey &&
|
||||
!ev.shiftKey &&
|
||||
/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(ev.code || '')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (ev.type === 'keydown' && global.app?.shouldOpenCommandPaletteFromShortcut?.(ev)) {
|
||||
return false;
|
||||
}
|
||||
if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(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
|
||||
// markers intact. Mirrors terminal-ui.js's own Ctrl+V gate; without it
|
||||
// xterm's default only ever pasted text.
|
||||
if ((ev.ctrlKey || ev.metaKey) && ev.key === 'v' && ev.type === 'keydown') {
|
||||
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.
|
||||
if (
|
||||
ev.type === 'keydown' &&
|
||||
ev.key.toLowerCase() === 'z' &&
|
||||
ev.ctrlKey &&
|
||||
!ev.altKey &&
|
||||
!ev.metaKey &&
|
||||
!ev.shiftKey &&
|
||||
this.sessionMode !== 'shell'
|
||||
) {
|
||||
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
|
||||
// activeSessionId, and has no local-echo overlay of its own to flush
|
||||
// first (Pane B 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') {
|
||||
fetch(`/api/sessions/${this.sessionId}/send-key`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: ev.ctrlKey ? 'C-Enter' : 'S-Enter' }),
|
||||
}).catch(() => {
|
||||
/* Best-effort, matching this pane's tolerance elsewhere. */
|
||||
});
|
||||
}
|
||||
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.
|
||||
if (ev.type === 'keydown' && global.app?.shouldCopyTerminalSelectionFromShortcut?.(ev)) {
|
||||
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()) {
|
||||
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');
|
||||
});
|
||||
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).
|
||||
if (this.terminal?.hasSelection?.()) {
|
||||
this.terminal.clearSelection?.();
|
||||
global.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;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// 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.
|
||||
await this._loadBuffer();
|
||||
if (this._destroyed) return;
|
||||
|
||||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
// The tab's own connection identity plus a `:tile` suffix. The server
|
||||
// supersedes a socket that reuses a cid on the same session (4010), so a
|
||||
// pane must never share the primary pane's exact cid: were both ever on
|
||||
// one session they would evict each other in a loop. Input frames still
|
||||
// carry the BARE clientId, which is what the server dedups on.
|
||||
const app = global.app;
|
||||
const cid = app?._clientId ? `${app._clientId}:${app._wsTabNonce}:tile` : '';
|
||||
const cidQuery = cid ? `?cid=${encodeURIComponent(cid)}` : '';
|
||||
this._socketUrl = `${proto}//${location.host}${window.CodemanBase.base}/ws/sessions/${this.sessionId}/terminal${cidQuery}`;
|
||||
this._openSocket();
|
||||
}
|
||||
|
||||
// Opens a socket and makes it THE socket. A previous one is detached first
|
||||
// (handlers nulled, then closed), and every handler below checks it still
|
||||
// belongs to the current socket: a replacement opened while the old socket
|
||||
// still looked alive (a half-open connection whose close has not landed)
|
||||
// makes the server supersede the old one with a 4010, and that late close
|
||||
// must not stop a pane that is already running on its successor.
|
||||
_openSocket() {
|
||||
if (this._destroyed || !this._socketUrl) return;
|
||||
this._detachSocket();
|
||||
const ws = new WebSocket(this._socketUrl);
|
||||
this.ws = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
if (ws !== this.ws) return;
|
||||
this._onSocketOpen();
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
if (ws !== this.ws) return;
|
||||
if (this._inputHandle) this._inputHandle.lastRecvAt = Date.now();
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.t === 'o') {
|
||||
this._onLiveOutput(msg.d);
|
||||
} else if (msg.t === 'c') {
|
||||
this._onLiveClear();
|
||||
} 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.
|
||||
this._refreshBuffer();
|
||||
} else if (msg.t === 'ia') {
|
||||
// Input ACK. The frame names no session, so it is this pane's.
|
||||
global.app?._onWsInputAck?.(msg.seq, msg, this.sessionId);
|
||||
} else if (msg.t === 'zc') {
|
||||
this._onPtyGeometryReport(msg.c, msg.r);
|
||||
}
|
||||
} catch {
|
||||
/* Malformed frame — ignore, matches primary pane's tolerance. */
|
||||
}
|
||||
};
|
||||
|
||||
// _wsReady must go false on a drop or fit()/_sendResize() silently
|
||||
// no-op on a closed socket per the WebSocket spec (no exception, no log).
|
||||
// Input is not lost meanwhile: it waits in the app's durable queue and
|
||||
// goes out over HTTP or the next socket. The "disconnected" marker says
|
||||
// so on screen, and a transient close reconnects (_onSocketClosed).
|
||||
ws.onclose = (event) => {
|
||||
if (ws !== this.ws) return;
|
||||
this._onSocketClosed(event);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
// onclose fires after onerror — cleanup happens there.
|
||||
};
|
||||
}
|
||||
|
||||
// Lets go of the current socket without running its close handling.
|
||||
_detachSocket() {
|
||||
const ws = this.ws;
|
||||
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.
|
||||
ws.onclose = null;
|
||||
ws.onerror = null;
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* Already closed. */
|
||||
}
|
||||
this.ws = null;
|
||||
this._wsReady = false;
|
||||
this._unregisterInputSocket();
|
||||
}
|
||||
|
||||
// A socket came up. After a drop this is a reconnect: the gap left nothing
|
||||
// to replay (output frames carry no sequence number), so the buffer is
|
||||
// refreshed. The closed state is reset FIRST, or the refresh would re-owe
|
||||
// the "disconnected" marker (_refreshBuffer does on a closed socket) and
|
||||
// stamp it under a healthy pane.
|
||||
_onSocketOpen() {
|
||||
const reconnected = this._wsClosed;
|
||||
this._wsReady = true;
|
||||
this._wsClosed = false;
|
||||
this._markerOwed = false;
|
||||
this._reconnectAttempts = 0;
|
||||
this._lastSentDims = null;
|
||||
this._registerInputSocket();
|
||||
this._sendResize();
|
||||
if (reconnected) this._refreshBuffer();
|
||||
}
|
||||
|
||||
// Opens a replacement socket now instead of waiting out the backoff (for an
|
||||
// owner that just learned the server is back). No-op while the current
|
||||
// socket is open, after a permanent stop, or once destroyed.
|
||||
reconnectNow() {
|
||||
if (this._destroyed || this._stoppedCode !== null || !this._socketUrl) return;
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
this._openSocket();
|
||||
}
|
||||
|
||||
// The socket's close, split out of connect() so the tests can drive it.
|
||||
// While any load runs (a history pull or a `{t:'r'}` refresh) the marker is
|
||||
// only owed, and that load's finally block settles it (_stampMarkerIfOwed()):
|
||||
// written now, it would sit above the output a pull is still holding (flushed
|
||||
// after it on a skip, a downgrade or a failed fetch), above a refresh's
|
||||
// replay, or in the middle of a chunked replay. A pull still waiting for its
|
||||
// response holds the marker too, for as long as the request takes (up to its
|
||||
// budget, see _pullHistory()).
|
||||
//
|
||||
// Then decides what comes next. Codes that cannot get better stop the pane
|
||||
// for good and report once through `onExit(code)`: 4004/4009 (the session
|
||||
// is gone), 4003 (refused: Host/Origin/owner, a retry gets the same answer)
|
||||
// and 4010 (another socket with this pane's cid took over; only ever
|
||||
// reaches here for the CURRENT socket, see _openSocket). Everything else,
|
||||
// including the redelivery sweep force-closing a silent socket (1005), is
|
||||
// transient and reconnects on the primary pane's backoff ladder
|
||||
// (CodemanWsReconnect, constants.js) plus jitter.
|
||||
_onSocketClosed(event) {
|
||||
this._wsReady = false;
|
||||
this._wsClosed = true;
|
||||
this._unregisterInputSocket();
|
||||
const code = event?.code;
|
||||
const permanent = TerminalTile.STOP_MARKERS[code];
|
||||
this._markerText = permanent || TerminalTile.MARKER_RECONNECTING;
|
||||
if (this._bufferLoading) this._markerOwed = true;
|
||||
else this._writeDisconnectedMarker();
|
||||
if (this._destroyed) return;
|
||||
if (permanent) {
|
||||
this._stop(code);
|
||||
return;
|
||||
}
|
||||
this._scheduleReconnect(code);
|
||||
}
|
||||
|
||||
_scheduleReconnect(code) {
|
||||
if (this._destroyed || !this._socketUrl || this._reconnectTimer) return;
|
||||
const plan = global.CodemanWsReconnect?.plan?.(code ?? 1006, this._reconnectAttempts) || {
|
||||
action: 'reconnect',
|
||||
delayMs: 1000,
|
||||
};
|
||||
if (plan.action === 'give-up') {
|
||||
this._stop(code);
|
||||
return;
|
||||
}
|
||||
this._reconnectAttempts++;
|
||||
const delay = plan.delayMs + Math.floor(Math.random() * 250); // jitter: tiles must not reconnect in lockstep
|
||||
this._reconnectTimer = setTimeout(() => {
|
||||
this._reconnectTimer = null;
|
||||
this._openSocket();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
_stop(code) {
|
||||
if (this._stoppedCode !== null) return;
|
||||
this._stoppedCode = code ?? null;
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
if (!this._destroyed) this.onExit?.(code);
|
||||
}
|
||||
|
||||
// Keystrokes and pastes go through the app's exactly-once input queue (seq,
|
||||
// ACK, persisted until delivered, redelivered after a drop), over this
|
||||
// pane's own socket while it is open and the HTTP fallback while it is not.
|
||||
// What xterm GENERATES must not be queued: a query reply (DA/CPR/OSC) is
|
||||
// dropped, as the primary pane drops it, because forwarding it types
|
||||
// "0;276;0c" into the CLI, and replaying one after a reload would do so
|
||||
// again into a later screen. A focus or mouse report is real input the
|
||||
// program asked for, but nobody typed it: it goes out once, never
|
||||
// persisted. Same predicates as the primary pane (terminal-ui.js onData).
|
||||
_onTerminalData(data) {
|
||||
const input = global.CodemanTerminalInput;
|
||||
if (input?.shouldSuppressTerminalQueryResponse?.(data)) return;
|
||||
const app = global.app;
|
||||
if (input?.isTerminalFocusOrMouseReport?.(data)) {
|
||||
app?._sendInputEphemeral?.(this.sessionId, data);
|
||||
return;
|
||||
}
|
||||
app?._sendInputAsync?.(this.sessionId, data);
|
||||
}
|
||||
|
||||
// Joins the app's input-socket map for this session and flushes anything
|
||||
// already queued for it (typed while the socket was down, or left over from
|
||||
// a reload) over the fresh socket. Called from onopen.
|
||||
_registerInputSocket() {
|
||||
const app = global.app;
|
||||
if (!this.ws || !app?._registerInputSocket) return;
|
||||
this._unregisterInputSocket();
|
||||
this._inputHandle = { ws: this.ws, lastRecvAt: 0 };
|
||||
app._registerInputSocket(this.sessionId, this._inputHandle);
|
||||
app._onWsReady?.(this.sessionId);
|
||||
}
|
||||
|
||||
// Leaves the map; only this pane's own handle is removed (a replacement
|
||||
// socket's registration survives a late close of the old one).
|
||||
_unregisterInputSocket() {
|
||||
if (!this._inputHandle) return;
|
||||
global.app?._unregisterInputSocket?.(this.sessionId, this._inputHandle);
|
||||
this._inputHandle = null;
|
||||
}
|
||||
|
||||
// Settles a marker the pane owes: set when a close lands during a load (the
|
||||
// replay would otherwise sit below it) or when a load wipes the terminal on
|
||||
// a closed socket. Called from each load's own finally, just before
|
||||
// _endBufferLoad() starts any trailing refresh.
|
||||
_stampMarkerIfOwed() {
|
||||
// A trailing refresh is about to clear() synchronously, while xterm parses
|
||||
// a write() on a later tick: a marker written here would land in the
|
||||
// freshly cleared buffer ABOVE that refresh's replay, a second, stale copy.
|
||||
// The refresh re-owes the marker on a closed socket and stamps it itself.
|
||||
if (this._bufferRefreshPending && !this._destroyed) return;
|
||||
const owed = this._markerOwed;
|
||||
this._markerOwed = false;
|
||||
if (owed && this._wsClosed && !this._destroyed) this._writeDisconnectedMarker();
|
||||
}
|
||||
|
||||
// Extracted so both _onSocketClosed() and a load that ends owing it on a
|
||||
// closed socket can write it (see _stampMarkerIfOwed()).
|
||||
_writeDisconnectedMarker() {
|
||||
this.terminal?.write(`\r\n\x1b[2m${this._markerText}\x1b[0m\r\n`);
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
//
|
||||
// Mirrors the primary pane's own mode check (app.js's selectSession /
|
||||
// _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.
|
||||
//
|
||||
// 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() {
|
||||
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);
|
||||
}
|
||||
} catch {
|
||||
/* Best-effort — live output still arrives once the socket connects. */
|
||||
} finally {
|
||||
this._stampMarkerIfOwed();
|
||||
this._endBufferLoad();
|
||||
}
|
||||
}
|
||||
|
||||
// Ends a single-flight load (initial, refresh or history pull): clears the
|
||||
// flag, then runs the ONE trailing refresh that arrived while it was busy.
|
||||
_endBufferLoad() {
|
||||
this._bufferLoading = false;
|
||||
if (this._bufferRefreshPending && !this._destroyed) {
|
||||
this._bufferRefreshPending = false;
|
||||
this._refreshBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
// Live terminal output. Written straight through, except while a history
|
||||
// pull is replaying: a capture is current only up to the instant tmux took
|
||||
// it, so a frame arriving mid-replay is held with its arrival time and
|
||||
// replayed behind the snapshot by _pullHistory() (the primary pane's
|
||||
// _finishBufferLoad `since` rule), never written underneath it.
|
||||
_onLiveOutput(data) {
|
||||
if (this._liveQueue) this._liveQueue.push({ at: performance.now(), data });
|
||||
else this.terminal?.write(data);
|
||||
}
|
||||
|
||||
// The server's `{t:'c'}` clear frame takes the same route as output, for the
|
||||
// same reason: clearing straight away, mid-replay, would wipe the half-written
|
||||
// snapshot and leave _pullHistory() measuring a buffer that is no longer the
|
||||
// one it is restoring. Queued, it lands in order with the frames around it.
|
||||
_onLiveClear() {
|
||||
if (this._liveQueue) this._liveQueue.push({ at: performance.now(), clear: true });
|
||||
else this.terminal?.clear();
|
||||
}
|
||||
|
||||
// Capture phase, because xterm's own wheel handler stopPropagation()s every
|
||||
// event it consumes, so a bubbling listener here would never see the wheel
|
||||
// while the pane still has scrollback to scroll. Passive: this only observes,
|
||||
// xterm keeps doing the scrolling.
|
||||
_installWheelListener() {
|
||||
this._onWheel = (ev) => {
|
||||
if (ev.deltaY < 0) this._maybeLoadMoreHistory();
|
||||
};
|
||||
this.mountEl.addEventListener('wheel', this._onWheel, { capture: true, passive: true });
|
||||
}
|
||||
|
||||
// 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.
|
||||
_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.
|
||||
if (this.detachedSessions?.has(this.sessionId)) return;
|
||||
const active = this.terminal.buffer.active;
|
||||
if (active.type !== 'normal' || active.viewportY !== 0) return;
|
||||
// Momentum scrolling fires this dozens of times per flick, so cooldown
|
||||
// rather than latch; a pull that could only have downgraded the pane
|
||||
// waits far longer.
|
||||
const cooldown = this._historyPullUseless ? 60000 : 4000;
|
||||
const now = Date.now();
|
||||
if (now - this._historyPullAt < cooldown) return;
|
||||
this._historyPullAt = now;
|
||||
void this._pullHistory();
|
||||
}
|
||||
|
||||
// Pulls a BOUNDED window of tmux's full history (the same TERMINAL_TAIL_SIZE
|
||||
// a tab switch loads, so a multi-megabyte capture never lands on xterm's
|
||||
// main thread) and replays it under the reader's current place. Holds the
|
||||
// single-flight flag across the fetch AND the replay, like _loadBuffer().
|
||||
async _pullHistory() {
|
||||
this._bufferLoading = true;
|
||||
let replayed = false;
|
||||
let capturedAt = 0;
|
||||
// Two budgets on one signal. The request itself gets the primary pane's
|
||||
// (CodemanFetchDeadline, constants.js): live output is not held while it
|
||||
// runs, but the single-flight flag is, so a coalesced `{t:'r'}` refresh and
|
||||
// the marker owed by a close (_onSocketClosed()) both wait for it, at worst
|
||||
// for that whole budget. Once the headers land live output IS held, so the
|
||||
// body read gets the short one instead: a body that hangs would otherwise
|
||||
// freeze the pane for the long budget. Aborting lands in the catch below,
|
||||
// which releases the flag and the queue. AbortSignal.timeout() alone cannot
|
||||
// be re-armed, hence the controller; without AbortController the pull
|
||||
// simply has no deadline.
|
||||
const controller = global.AbortController ? new global.AbortController() : null;
|
||||
let abortTimer = null;
|
||||
const armDeadline = (ms) => {
|
||||
if (!controller) return;
|
||||
clearTimeout(abortTimer);
|
||||
abortTimer = setTimeout(() => controller.abort(), ms);
|
||||
};
|
||||
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,
|
||||
});
|
||||
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
|
||||
// for the instant tmux took the capture, which lies somewhere in the
|
||||
// round trip, so a frame in that window can be lost or doubled. Bounded
|
||||
// by one round trip and not closable without a server-side capture time.
|
||||
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.
|
||||
this._liveQueue = [];
|
||||
const payload = (await res.json())?.data;
|
||||
clearTimeout(abortTimer);
|
||||
const buffer = payload?.terminalBuffer;
|
||||
const term = this.terminal;
|
||||
if (!buffer || !term || this._destroyed) return;
|
||||
const rowsBefore = term.buffer.active.length;
|
||||
const rowsIncoming = global.app?._estimateReplayRows?.(buffer, term.cols) ?? buffer.split('\n').length;
|
||||
// xterm keeps at most `scrollback + rows` rows while tmux keeps far more
|
||||
// lines, so a window of short lines can carry more rows than this pane
|
||||
// can ever hold, and `rowsIncoming <= rowsBefore` would never come true.
|
||||
const scrollbackCap = term.options?.scrollback || 0;
|
||||
const paneFull = scrollbackCap > 0 && rowsBefore >= scrollbackCap + term.rows;
|
||||
// Nothing to gain (this also covers a downgrade, which would delete
|
||||
// history mid-scroll), and a reset+rewrite would jump the viewport. An
|
||||
// untruncated window IS all of tmux's history and the next burst can add
|
||||
// more, so keep the 4 s cooldown. A truncated window can never reach past
|
||||
// what the pane shows, and every ask costs the server a capture-pane of
|
||||
// the whole history (`tail` is cut after it): back off to 60 s, as the
|
||||
// primary pane does (app.js _maybeRefetchFullHistory). A full pane backs
|
||||
// off too, since no window can ever fit in it.
|
||||
if (rowsIncoming <= rowsBefore || paneFull) {
|
||||
if (payload.truncated || paneFull) this._historyPullUseless = true;
|
||||
return;
|
||||
}
|
||||
this._historyPullUseless = false;
|
||||
term.write('\x1bc');
|
||||
replayed = true;
|
||||
if (this._wsClosed) this._markerOwed = true;
|
||||
await writeChunked(term, buffer, () => this._destroyed);
|
||||
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.
|
||||
await new Promise((resolve) => this.terminal.write('', resolve));
|
||||
if (this._destroyed || !this.terminal) return;
|
||||
// The replay grew the buffer UPWARD, so what was row 0 is now `delta`
|
||||
// rows down; land there and the recovered history sits above it.
|
||||
const delta = this.terminal.buffer.active.length - rowsBefore;
|
||||
if (delta > 0) this.terminal.scrollToLine(delta);
|
||||
else this.terminal.scrollToTop();
|
||||
} catch {
|
||||
/* Best-effort — live output keeps arriving whatever happens here. */
|
||||
} finally {
|
||||
clearTimeout(abortTimer);
|
||||
const queued = this._liveQueue ?? [];
|
||||
this._liveQueue = null;
|
||||
// After a replay, only frames that arrived after the capture are news;
|
||||
// earlier ones are already in it. With no replay, every held frame is.
|
||||
const cutoff = replayed ? capturedAt : 0;
|
||||
for (const entry of queued) {
|
||||
if (entry.at < cutoff) continue;
|
||||
if (entry.clear) this.terminal?.clear();
|
||||
else this.terminal?.write(entry.data);
|
||||
}
|
||||
// Settled after the queue flush so the marker is the last thing on
|
||||
// screen: a close during the pull wrote nothing (_onSocketClosed() defers
|
||||
// it while a load runs), and a replay's own `\x1bc` (flagged above) wipes
|
||||
// one written before it, which would paint a fresh, current-looking
|
||||
// history while onData keeps silently dropping every keystroke on the
|
||||
// dead socket. With a trailing refresh pending (_endBufferLoad) the marker
|
||||
// is left to that refresh, which writes it below its own replay.
|
||||
this._stampMarkerIfOwed();
|
||||
this._endBufferLoad();
|
||||
}
|
||||
}
|
||||
|
||||
// The `{t:'r'}` server-refresh path: clear, then replay. Two refresh
|
||||
// frames in a row used to 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,
|
||||
// and no further frame is coming to correct stale content.
|
||||
_refreshBuffer() {
|
||||
if (this._bufferLoading) {
|
||||
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();
|
||||
}
|
||||
|
||||
// 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
|
||||
// the actual `{t:'z'}` resize once, at drag end, matching the primary
|
||||
// pane's own convention (throttledResize in terminal-ui.js).
|
||||
localFit() {
|
||||
if (!this.fitAddon) return;
|
||||
this.fitAddon.fit();
|
||||
}
|
||||
|
||||
// Reflow to the container and tell the PTY, as one step: the xterm and the
|
||||
// PTY must never disagree about size (#464), and a font change is a size
|
||||
// change too, so the font setters call this rather than localFit().
|
||||
// `force` resends an unchanged size.
|
||||
fit({ force = false } = {}) {
|
||||
this.localFit();
|
||||
this._sendResize({ force });
|
||||
}
|
||||
|
||||
_sendResize({ force = false } = {}) {
|
||||
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.
|
||||
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.
|
||||
const dims = this.fitAddon.proposeDimensions();
|
||||
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
|
||||
// its own valid range ([1,500]/[1,200] in ws-routes.ts).
|
||||
const cols = this.terminal.cols;
|
||||
const rows = this.terminal.rows;
|
||||
const last = this._lastSentDims;
|
||||
if (!force && last && last.cols === cols && last.rows === rows) return;
|
||||
this._lastSentDims = { cols, rows };
|
||||
this.ws.send(JSON.stringify({ t: 'z', c: cols, r: rows, v: 'desktop' }));
|
||||
}
|
||||
|
||||
// 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
|
||||
// the primary pane (_onPtyGeometryReport in terminal-ui.js, #464). The
|
||||
// pure verdict is the primary's too (reconcilePtyGeometry, constants.js).
|
||||
_onPtyGeometryReport(cols, rows) {
|
||||
const terminal = this.terminal;
|
||||
if (!terminal) return;
|
||||
const verdict = global.CodemanTerminalGeometry?.reconcilePtyGeometry?.(
|
||||
{ cols: terminal.cols, rows: terminal.rows },
|
||||
{ cols, rows }
|
||||
);
|
||||
if (!verdict?.adopt) return;
|
||||
terminal.resize(verdict.cols, terminal.rows);
|
||||
this._lastSentDims = { cols: verdict.cols, rows: terminal.rows };
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this._destroyed = true;
|
||||
// Anything still queued for this session stays in the app's queue and is
|
||||
// delivered over HTTP by the redelivery sweep, so closing the pane mid-
|
||||
// keystroke loses nothing.
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
if (this._onWheel) {
|
||||
this.mountEl?.removeEventListener('wheel', this._onWheel, { capture: true });
|
||||
this._onWheel = null;
|
||||
}
|
||||
this._detachSocket();
|
||||
if (this._onFocusIn) {
|
||||
this.terminal?.textarea?.removeEventListener('focus', this._onFocusIn);
|
||||
this._onFocusIn = null;
|
||||
}
|
||||
// A destroyed pane cannot hold the keyboard: shortcuts fall back to the
|
||||
// primary terminal (_focusedPane also skips a destroyed tile on its own).
|
||||
if (global.app?._focusedTile === this) global.app._noteFocusedTile?.(null);
|
||||
if (this.terminal) {
|
||||
this.terminal.dispose();
|
||||
this.terminal = null;
|
||||
}
|
||||
this.fitAddon = null;
|
||||
}
|
||||
}
|
||||
|
||||
// The marker a pane writes when its socket drops: a transient drop says it is
|
||||
// reconnecting; a permanent stop says why, keyed by close code. All start
|
||||
// with `[disconnected` so a reader (and a test) can tell any of them apart
|
||||
// from session output.
|
||||
TerminalTile.MARKER_RECONNECTING = '[disconnected, reconnecting…]';
|
||||
TerminalTile.STOP_MARKERS = {
|
||||
4003: '[disconnected: the server refused this connection]',
|
||||
4004: '[disconnected: the session ended]',
|
||||
4009: '[disconnected: the session ended]',
|
||||
4010: '[disconnected: another connection took over this pane]',
|
||||
};
|
||||
|
||||
global.TerminalTile = TerminalTile;
|
||||
})(window);
|
||||
+42
-113
@@ -544,9 +544,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._installMobileTapMouseGuard();
|
||||
this._installShiftDragSelection();
|
||||
this._installTouchSelectionFocusGuard();
|
||||
// Focus coming back to the primary terminal ends a second pane's claim on
|
||||
// the keyboard (see _focusedPane).
|
||||
this.terminal.textarea?.addEventListener('focus', () => this._noteFocusedTile(null));
|
||||
|
||||
// Let xterm's CompositionHelper own IME key events. In particular, a
|
||||
// non-composing keyCode 229 is how an active IME commits numbers and
|
||||
@@ -1419,7 +1416,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// 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());
|
||||
this._splitPane?.fit();
|
||||
}, 300); // Trailing-edge: only fire after 300ms of no resize events
|
||||
};
|
||||
|
||||
@@ -1830,24 +1827,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
* Register a custom link provider for xterm.js that detects file paths
|
||||
* in terminal output and makes them clickable.
|
||||
* When clicked, opens a floating log viewer window with live streaming.
|
||||
*
|
||||
* `target` defaults to the primary terminal and the active session. A second
|
||||
* terminal (the split pane) passes its own `{ terminal, getSessionId,
|
||||
* setHovered }`, so a path printed there opens against THAT pane's session and
|
||||
* hovering it never flips the primary pane's `_linkHovered`. Only the primary
|
||||
* registration is kept on `_terminalLinkProvider`, which the touch path reads.
|
||||
* Returns the provider.
|
||||
*/
|
||||
registerFilePathLinkProvider(target = {}) {
|
||||
registerFilePathLinkProvider() {
|
||||
const self = this;
|
||||
const terminal = target.terminal || this.terminal;
|
||||
const getSessionId = target.getSessionId || (() => this.activeSessionId);
|
||||
const setHovered =
|
||||
target.setHovered ||
|
||||
((hovered) => {
|
||||
this._linkHovered = hovered;
|
||||
});
|
||||
const isPrimary = terminal === this.terminal;
|
||||
|
||||
// Debug: Track if provider is being invoked
|
||||
let lastInvokedLine = -1;
|
||||
@@ -1860,7 +1842,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
console.debug('[LinkProvider] Checking line:', bufferLineNumber);
|
||||
}
|
||||
|
||||
const buffer = terminal.buffer.active;
|
||||
const buffer = self.terminal.buffer.active;
|
||||
// provideLinks passes 1-based line number, getLine expects 0-based
|
||||
const line = buffer.getLine(bufferLineNumber - 1);
|
||||
|
||||
@@ -1884,7 +1866,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const logical = window.CodemanTerminalLines?.terminalLogicalLine(
|
||||
buffer,
|
||||
bufferLineNumber - 1,
|
||||
terminal.cols,
|
||||
self.terminal.cols,
|
||||
MAX_STITCHED_ROWS
|
||||
);
|
||||
if (!logical) {
|
||||
@@ -1937,10 +1919,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
window.open(text, '_blank', 'noopener,noreferrer');
|
||||
},
|
||||
hover() {
|
||||
setHovered(true);
|
||||
self._linkHovered = true;
|
||||
},
|
||||
leave() {
|
||||
setHovered(false);
|
||||
self._linkHovered = false;
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -1996,18 +1978,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
// path clicked in the response viewer previewed fine. The preview
|
||||
// reads those through the guarded attachment routes, so external
|
||||
// paths route there and the two surfaces agree.
|
||||
const sessionId = getSessionId();
|
||||
if (previewsInFileViewer(text) || self._isExternalPreviewPath(text, sessionId)) {
|
||||
self.openFilePreview(text, sessionId);
|
||||
if (previewsInFileViewer(text) || self._isExternalPreviewPath(text, self.activeSessionId)) {
|
||||
self.openFilePreview(text, self.activeSessionId);
|
||||
return;
|
||||
}
|
||||
self.openLogViewerWindow(text, sessionId);
|
||||
self.openLogViewerWindow(text, self.activeSessionId);
|
||||
},
|
||||
hover() {
|
||||
setHovered(true);
|
||||
self._linkHovered = true;
|
||||
},
|
||||
leave() {
|
||||
setHovered(false);
|
||||
self._linkHovered = false;
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -2050,11 +2031,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
// produce), so the tap path asks this SAME provider what is under the finger
|
||||
// rather than growing a second, driftable copy of the patterns.
|
||||
// See _terminalLinkAtPoint.
|
||||
if (isPrimary) this._terminalLinkProvider = provider;
|
||||
terminal.registerLinkProvider(provider);
|
||||
this._terminalLinkProvider = provider;
|
||||
this.terminal.registerLinkProvider(provider);
|
||||
|
||||
console.log('[LinkProvider] File path link provider registered');
|
||||
return provider;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -4500,45 +4480,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Terminal Controls
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* The terminal the keyboard is in, as `{ terminal, sessionId, isPrimary, tile }`.
|
||||
*
|
||||
* The ONE place a shortcut, voice or paste should ask "which pane?", rather
|
||||
* than reading `this.terminal` / `this.activeSessionId`, which always mean the
|
||||
* primary pane. It answers with the pane whose terminal was focused LAST, not
|
||||
* with `document.activeElement`: clicking the mic or a header button moves
|
||||
* DOM focus to that button, and the dictation it starts still belongs to the
|
||||
* pane the user was typing in. A second pane (the split pane's Pane B) claims
|
||||
* it from its own terminal's focus; the primary terminal's focus gives it back.
|
||||
*/
|
||||
_focusedPane() {
|
||||
const tile = this._focusedTile;
|
||||
if (tile && !tile._destroyed && tile.terminal) {
|
||||
return { terminal: tile.terminal, sessionId: tile.sessionId, isPrimary: false, tile };
|
||||
}
|
||||
return { terminal: this.terminal, sessionId: this.activeSessionId, isPrimary: true, tile: null };
|
||||
},
|
||||
|
||||
/** Record which second pane holds the keyboard (null: the primary terminal). */
|
||||
_noteFocusedTile(tile) {
|
||||
this._focusedTile = tile || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
_forEachTile(fn) {
|
||||
if (this._splitPane?.terminal) fn(this._splitPane);
|
||||
},
|
||||
|
||||
// Clears the pane the keyboard is in. The chord itself also reaches that
|
||||
// pane's xterm (the capture handler only preventDefault()s), so the ^L lands
|
||||
// in the same pane whose display is cleared, never a different one.
|
||||
clearTerminal() {
|
||||
this._focusedPane().terminal?.clear();
|
||||
this.terminal.clear();
|
||||
},
|
||||
|
||||
/** Insert editable text at the active prompt without pressing Enter. */
|
||||
@@ -4602,14 +4545,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
* Ctrl+L is NOT sent here (Claude Code 2.x treats it as "clear conversation").
|
||||
*/
|
||||
async restoreTerminalSize() {
|
||||
// A second pane owns its own geometry: refit it and force its PTY to the
|
||||
// size it renders at (TerminalTile.fit), whatever another device set.
|
||||
const pane = this._focusedPane();
|
||||
if (!pane.isPrimary) {
|
||||
pane.tile.fit({ force: true });
|
||||
this.showToast(`Terminal restored to ${pane.terminal.cols}x${pane.terminal.rows}`, 'success');
|
||||
return;
|
||||
}
|
||||
if (!this.activeSessionId) {
|
||||
this.showToast('No active session', 'warning');
|
||||
return;
|
||||
@@ -4704,18 +4639,15 @@ Object.assign(CodemanApp.prototype, {
|
||||
* terminal._core for cell dimensions, and falls back to cleaning normally if
|
||||
* a future xterm renames it. SelectionMode.COLUMN is 3.
|
||||
*/
|
||||
cleanedTerminalSelection(text, target = {}) {
|
||||
// `target` names a second terminal (the split pane) and its session; both
|
||||
// default to the primary pane, whose `this.terminal` this file otherwise reads.
|
||||
const terminal = target.terminal || this.terminal;
|
||||
const raw = text ?? (terminal?.hasSelection?.() ? terminal.getSelection() : '');
|
||||
cleanedTerminalSelection(text) {
|
||||
const raw = text ?? (this.terminal?.hasSelection?.() ? this.terminal.getSelection() : '');
|
||||
if (!raw) return '';
|
||||
if (terminal?._core?._selectionService?._activeSelectionMode === 3) return raw;
|
||||
if (this.terminal?._core?._selectionService?._activeSelectionMode === 3) return raw;
|
||||
const clean = window.CodemanCopySelection?.clean;
|
||||
if (!clean) return raw;
|
||||
const range = this._normalisedSelectionRange(terminal);
|
||||
const range = this._normalisedSelectionRange();
|
||||
return clean(raw, {
|
||||
margin: this._cliGutterColumns(target.sessionId),
|
||||
margin: this._cliGutterColumns(),
|
||||
firstLinePartial: !!range && range.start.x > 0,
|
||||
});
|
||||
},
|
||||
@@ -4785,11 +4717,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Copy the current terminal selection. Goes through _copyText (Clipboard API,
|
||||
// then a hidden-textarea + execCommand fallback) because install.sh's LAN
|
||||
// option serves plain HTTP, where navigator.clipboard is undefined.
|
||||
async copyTerminalSelection(text, target = {}) {
|
||||
// Every terminal touched below is the TARGET one: clearing or refocusing the
|
||||
// primary after copying from the split pane would hit the wrong pane.
|
||||
const terminal = target.terminal || this.terminal;
|
||||
const selection = this.cleanedTerminalSelection(text, target);
|
||||
async copyTerminalSelection(text) {
|
||||
const selection = this.cleanedTerminalSelection(text);
|
||||
// trim(), not emptiness: a multi-row drag across padding cleans to newlines
|
||||
// alone, which are truthy, and a bare newline pasted into a chat composer
|
||||
// or a shell submits the line. decideAutoCopy applies the same rule.
|
||||
@@ -4798,7 +4727,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// selection, so a padding-only selection left set can no longer swallow a
|
||||
// later interrupt; it cleans to '' and the press reaches the PTY. What the
|
||||
// clear avoids is a highlight that sits there having copied nothing.
|
||||
terminal?.clearSelection?.();
|
||||
this.terminal?.clearSelection?.();
|
||||
this.showToast('Nothing to copy', 'warning');
|
||||
return false;
|
||||
}
|
||||
@@ -4806,14 +4735,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (ok) {
|
||||
// Clearing is what makes a second Ctrl+C an interrupt (and xterm already
|
||||
// drops the selection on any keypress, so this matches existing feel).
|
||||
terminal.clearSelection?.();
|
||||
this.terminal.clearSelection?.();
|
||||
this.showToast('Copied to clipboard', 'success');
|
||||
} else {
|
||||
this.showToast('Failed to copy', 'error');
|
||||
}
|
||||
// The execCommand fallback focuses a temp textarea, so hand focus back. This
|
||||
// is the CJK-aware focus router, not xterm's raw focus().
|
||||
terminal.focus();
|
||||
this.terminal.focus();
|
||||
return ok;
|
||||
},
|
||||
|
||||
@@ -5759,10 +5688,10 @@ 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)
|
||||
});
|
||||
if (this._splitPane?.terminal) {
|
||||
this._splitPane.terminal.options.fontSize = size;
|
||||
this._splitPane.fitAddon?.fit();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -5788,10 +5717,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._refitAfterCellSizeChange();
|
||||
this._localEchoOverlay?.refreshFont();
|
||||
this._predictiveEcho?.refreshFont();
|
||||
this._forEachTile?.((tile) => {
|
||||
tile.terminal.options.fontFamily = resolved;
|
||||
tile.fit(); // a font change is a size change: tell its PTY too (#464)
|
||||
});
|
||||
if (this._splitPane?.terminal) {
|
||||
this._splitPane.terminal.options.fontFamily = resolved;
|
||||
this._splitPane.fitAddon?.fit();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -5843,11 +5772,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
/* pane not laid out yet — its own resize observer refits it */
|
||||
}
|
||||
}
|
||||
this._forEachTile?.((tile) => {
|
||||
tile.terminal.options.fontWeight = fontWeight;
|
||||
tile.terminal.options.fontWeightBold = fontWeightBold;
|
||||
tile.fit(); // a font change is a size change: tell its PTY too (#464)
|
||||
});
|
||||
if (this._splitPane?.terminal) {
|
||||
this._splitPane.terminal.options.fontWeight = fontWeight;
|
||||
this._splitPane.terminal.options.fontWeightBold = fontWeightBold;
|
||||
this._splitPane.fitAddon?.fit();
|
||||
}
|
||||
},
|
||||
|
||||
loadFontSize() {
|
||||
@@ -6316,13 +6245,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
}
|
||||
}
|
||||
this._forEachTile?.((tile) => {
|
||||
tile.terminal.options.minimumContrastRatio = minimumContrastRatio;
|
||||
tile.terminal.options.theme = { ...theme };
|
||||
if (this._splitPane?.terminal) {
|
||||
this._splitPane.terminal.options.minimumContrastRatio = minimumContrastRatio;
|
||||
this._splitPane.terminal.options.theme = { ...theme };
|
||||
try {
|
||||
tile.terminal.refresh(0, tile.terminal.rows - 1);
|
||||
this._splitPane.terminal.refresh(0, this._splitPane.terminal.rows - 1);
|
||||
} catch {}
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -554,11 +554,6 @@ const VoiceInput = {
|
||||
_analyserSource: null, // MediaStreamSource for level meter
|
||||
_audioContext: null, // AudioContext for level meter
|
||||
_levelAnimFrame: null, // rAF handle for level meter
|
||||
// The session dictation was started FOR, captured in start(). Transcripts
|
||||
// arrive seconds later and the green send button / compose overlay can be
|
||||
// used later still; reading app.activeSessionId at that point sent the text
|
||||
// to whatever tab the user had switched to in the meantime.
|
||||
_targetSessionId: null,
|
||||
|
||||
init() {
|
||||
this._initRecognition();
|
||||
@@ -668,12 +663,10 @@ const VoiceInput = {
|
||||
|
||||
start() {
|
||||
if (this.isRecording) return;
|
||||
const target = app._focusedPane?.()?.sessionId || app.activeSessionId;
|
||||
if (!target) {
|
||||
if (!app.activeSessionId) {
|
||||
app.showToast('No active session', 'warning');
|
||||
return;
|
||||
}
|
||||
this._targetSessionId = target;
|
||||
this._retryCount = 0;
|
||||
|
||||
const provider = this._resolveProvider();
|
||||
@@ -966,31 +959,8 @@ const VoiceInput = {
|
||||
this.stop();
|
||||
},
|
||||
|
||||
/** The session this dictation belongs to (see _targetSessionId). */
|
||||
_targetSession() {
|
||||
return this._targetSessionId || app.activeSessionId;
|
||||
},
|
||||
|
||||
/**
|
||||
* Send text to the dictation's own session. The active session keeps going
|
||||
* through app.sendInput() exactly as before; any other session goes straight
|
||||
* to the durable queue with the same useMux flag sendInput() passes.
|
||||
*/
|
||||
_sendToTarget(target, text) {
|
||||
if (target === app.activeSessionId) return app.sendInput(text);
|
||||
// Closed while dictating: say so instead of queueing text for a session
|
||||
// that will only answer 404 (and never typing it into some other tab).
|
||||
if (app.sessions && !app.sessions.has(target)) {
|
||||
app.showToast?.('That session has closed; dictation not sent', 'warning');
|
||||
return Promise.resolve();
|
||||
}
|
||||
app._sendInputAsync(target, text, { useMux: true });
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
_insertText(text) {
|
||||
const target = this._targetSession();
|
||||
if (!target || !text.trim()) return;
|
||||
if (!app.activeSessionId || !text.trim()) return;
|
||||
const trimmed = text.trim();
|
||||
const mode = this._getDeepgramConfig().insertMode || 'direct';
|
||||
|
||||
@@ -1005,17 +975,14 @@ const VoiceInput = {
|
||||
this._showComposeOverlay(trimmed);
|
||||
}
|
||||
} else {
|
||||
// Direct mode: inject into local echo overlay if available, else send to PTY.
|
||||
// The overlay belongs to the ACTIVE session's terminal, so text dictated
|
||||
// for any other session must not be typed into it.
|
||||
const isActive = target === app.activeSessionId;
|
||||
if (isActive && app._localEchoEnabled && app._localEchoOverlay) {
|
||||
// Direct mode: inject into local echo overlay if available, else send to PTY
|
||||
if (app._localEchoEnabled && app._localEchoOverlay) {
|
||||
app._localEchoOverlay.appendText(trimmed);
|
||||
} else {
|
||||
this._sendToTarget(target, trimmed).catch(() => {});
|
||||
app.sendInput(trimmed).catch(() => {});
|
||||
}
|
||||
this._showVoiceSendBtn();
|
||||
setTimeout(() => { if (isActive && app.terminal) app.terminal.focus(); }, 150);
|
||||
setTimeout(() => { if (app.terminal) app.terminal.focus(); }, 150);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1041,15 +1008,10 @@ const VoiceInput = {
|
||||
|
||||
// Click handler
|
||||
this._voiceSendHandler = () => {
|
||||
const target = this._targetSession();
|
||||
if (!target) return;
|
||||
if (!app.activeSessionId) return;
|
||||
// Simulate Enter key: if local echo is active, flush its buffer + send \r;
|
||||
// otherwise just send \r directly to the PTY. Both the overlay and the
|
||||
// predictions belong to the ACTIVE session's terminal, so a dictation
|
||||
// for another session just sends its Enter there.
|
||||
if (target !== app.activeSessionId) {
|
||||
this._sendToTarget(target, '\r').catch(() => {});
|
||||
} else if (app._localEchoEnabled && app._localEchoOverlay) {
|
||||
// otherwise just send \r directly to the PTY
|
||||
if (app._localEchoEnabled && app._localEchoOverlay) {
|
||||
const text = app._localEchoOverlay.pendingText || '';
|
||||
app._localEchoOverlay.clear();
|
||||
app._localEchoOverlay.suppressBufferDetection();
|
||||
@@ -1103,7 +1065,7 @@ const VoiceInput = {
|
||||
const send = () => {
|
||||
const val = textarea.value.trim();
|
||||
overlay.remove();
|
||||
if (val) this._sendToTarget(this._targetSession(), val + '\r').catch(() => {});
|
||||
if (val) app.sendInput(val + '\r').catch(() => {});
|
||||
};
|
||||
const cancel = () => overlay.remove();
|
||||
const newInput = () => {
|
||||
|
||||
@@ -1403,6 +1403,25 @@ export const SettingsUpdateSchema = z
|
||||
* rail drag-reorderable.
|
||||
*/
|
||||
tabRailSort: z.enum(['activity', 'manual']).optional(),
|
||||
/**
|
||||
* Tab layout, the arrangement of the tab list (Discussion #426). Display key
|
||||
* (per-device).
|
||||
* 'state' = a row per state in the header strip (needs you, waiting,
|
||||
* working, idle; option C), sections in the flat side rail and
|
||||
* the sidebar. The default.
|
||||
* 'case' = one cluster per case (option A): a labelled box in the strip,
|
||||
* a section in the side rail and the sidebar.
|
||||
* 'ledger' = the flat list on an aligned column grid with a status bar
|
||||
* per cell (option B). Header strip on desktop only.
|
||||
* 'classic' = one flat list in tab order, as before.
|
||||
*/
|
||||
tabArrangement: z.enum(['state', 'case', 'ledger', 'classic']).optional(),
|
||||
/**
|
||||
* Which end the state groups start from when `tabArrangement` is 'state'.
|
||||
* Display key (per-device). 'urgent-first' = needs you on top (the
|
||||
* default); 'urgent-last' = the other way up, needs you in the bottom row.
|
||||
*/
|
||||
tabStateOrder: z.enum(['urgent-first', 'urgent-last']).optional(),
|
||||
/**
|
||||
* Session list layout. Display key (per-device).
|
||||
* 'header' = horizontal tab strip
|
||||
@@ -1434,6 +1453,14 @@ export const SettingsUpdateSchema = z
|
||||
// UI visibility
|
||||
showFontControls: z.boolean().optional(),
|
||||
showSystemStats: z.boolean().optional(),
|
||||
/**
|
||||
* How the header draws its WS / CPU / MEM / plan-usage cluster. Display key
|
||||
* (per-device), desktop only (the cluster is hidden below 768px).
|
||||
* 'classic' = the bars and the 5H · 7D chip, as before
|
||||
* 'compact' = two pills (WS/CPU/MEM, the plan windows), a ring beside every value
|
||||
* 'tiles' = label over value with a bar underneath, no icons. The default.
|
||||
*/
|
||||
headerStatsStyle: z.enum(['classic', 'compact', 'tiles']).optional(),
|
||||
showTokenCount: z.boolean().optional(),
|
||||
showCost: z.boolean().optional(),
|
||||
showLifecycleLog: z.boolean().optional(),
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Ctrl+W never closes a session; it reaches the terminal.
|
||||
*
|
||||
* "Close Session" used to be bound to Ctrl+W by default. Ctrl+W is "delete the
|
||||
* previous word" in every shell, readline prompt and agent CLI, so muscle memory
|
||||
* killed the session (its tmux pane and CLI, with no confirm) in the middle of a
|
||||
* sentence; with the split pane open it was not even the pane being typed in.
|
||||
* The action now has NO default key: the capture-phase shortcut handler lets
|
||||
* Ctrl+W through, and xterm sends ^W to the CLI like any other key. The action
|
||||
* stays in the registry so a user can still bind a key to it in App Settings →
|
||||
* Shortcuts.
|
||||
*
|
||||
* Real code under test: constants.js + app.js (DEFAULT_SHORTCUTS,
|
||||
* getShortcutRegistry, matchesShortcutEvent) in a `vm` context.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../src/web/public/${f}`), 'utf8');
|
||||
|
||||
type Shortcut = { id: string; action?: string; bindings?: unknown[]; disabled?: boolean };
|
||||
type App = {
|
||||
getShortcutRegistry(): Shortcut[];
|
||||
matchesShortcutEvent(e: Record<string, unknown>, s: Shortcut): boolean;
|
||||
loadAppSettingsFromStorage: () => Record<string, unknown>;
|
||||
};
|
||||
|
||||
function makeApp(settings: Record<string, unknown> = {}): App {
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
performance,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: { OPEN: 1 },
|
||||
fetch: vi.fn(),
|
||||
document: { addEventListener: vi.fn() },
|
||||
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
MobileDetection: {},
|
||||
});
|
||||
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
|
||||
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
|
||||
const app = Object.create(CodemanApp.prototype) as App;
|
||||
app.loadAppSettingsFromStorage = () => settings;
|
||||
return app;
|
||||
}
|
||||
|
||||
const keydown = (overrides: Record<string, unknown>) => ({
|
||||
type: 'keydown',
|
||||
key: 'w',
|
||||
code: 'KeyW',
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('Ctrl+W is left to the terminal', () => {
|
||||
it('Close Session is still in the registry, with no default key', () => {
|
||||
const close = makeApp()
|
||||
.getShortcutRegistry()
|
||||
.find((s) => s.id === 'close-session');
|
||||
|
||||
expect(close?.action).toBe('killActiveSession');
|
||||
expect(close?.bindings).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Ctrl+W', { ctrlKey: true }],
|
||||
['Cmd+W', { metaKey: true }],
|
||||
])('no default shortcut answers %s, so the capture handler lets it reach xterm', (_name, mods) => {
|
||||
const app = makeApp();
|
||||
const event = keydown(mods);
|
||||
|
||||
const matched = app.getShortcutRegistry().filter((s) => !s.disabled && s.action && app.matchesShortcutEvent(event, s));
|
||||
|
||||
expect(matched.map((s) => s.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('a user can still bind a key to Close Session', () => {
|
||||
const app = makeApp({
|
||||
shortcutOverrides: { 'close-session': { bindings: [{ modifiers: ['ctrl', 'shift'], key: 'w' }] } },
|
||||
});
|
||||
const close = app.getShortcutRegistry().find((s) => s.id === 'close-session')!;
|
||||
|
||||
expect(app.matchesShortcutEvent(keydown({ ctrlKey: true, shiftKey: true, key: 'W' }), close)).toBe(true);
|
||||
expect(app.matchesShortcutEvent(keydown({ ctrlKey: true }), close)).toBe(false);
|
||||
});
|
||||
|
||||
it('the shortcut overlay says an unbound action is not bound', () => {
|
||||
const appSource = read('app.js');
|
||||
const overlay = appSource.slice(appSource.indexOf('renderShortcutOverlay() {'), appSource.indexOf('closeShortcutOverlay() {'));
|
||||
|
||||
expect(overlay).toContain("if (s.bindings.length === 0) return '<span class=\"shortcut-overlay-unbound\">not bound</span>';");
|
||||
});
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
/**
|
||||
* @fileoverview App-level terminal shortcuts act on the pane the keyboard is in.
|
||||
*
|
||||
* With the split pane open, the global shortcut handler (app.js, capture phase)
|
||||
* used to resolve every terminal action against the PRIMARY pane: Ctrl+L typed
|
||||
* into Pane B cleared Pane A's display while xterm sent the ^L into Pane B's
|
||||
* PTY, and Ctrl+Shift+R restored Pane A's size. `_focusedPane()` (terminal-ui.js)
|
||||
* now answers with the pane whose terminal was focused last, and the actions
|
||||
* that are about a TERMINAL (clear, restore size) go through it.
|
||||
*
|
||||
* Close Session is not one of them: it has no default key any more (Ctrl+W is
|
||||
* left to the terminal as delete-word, see ctrl-w-never-closes.test.ts), and a
|
||||
* key a user binds to it closes the active session, as it always did.
|
||||
*
|
||||
* Real code under test: constants.js + terminal-ui.js in a `vm` context.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../src/web/public/${f}`), 'utf8');
|
||||
|
||||
function loadApp() {
|
||||
const CodemanApp = function CodemanApp(this: unknown) {};
|
||||
const context = vm.createContext({
|
||||
window: {},
|
||||
document: {
|
||||
body: { classList: { contains: () => false } },
|
||||
activeElement: null,
|
||||
addEventListener: vi.fn(),
|
||||
getElementById: () => null,
|
||||
},
|
||||
CodemanApp,
|
||||
console: { warn: vi.fn(), log: vi.fn(), debug: vi.fn(), error: vi.fn() },
|
||||
_crashDiag: { log: vi.fn() },
|
||||
performance: { now: () => 0 },
|
||||
requestAnimationFrame: () => 1,
|
||||
setTimeout: () => 1,
|
||||
MobileDetection: { isTouchDevice: () => false },
|
||||
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
|
||||
TERMINAL_CHUNK_SIZE: 32 * 1024,
|
||||
});
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
vm.runInContext(read('terminal-ui.js'), context, { filename: 'terminal-ui.js' });
|
||||
const app = new (CodemanApp as unknown as new () => Record<string, any>)();
|
||||
app.activeSessionId = 'session-a';
|
||||
app.terminal = { clear: vi.fn(), cols: 120, rows: 40 };
|
||||
app.showToast = vi.fn();
|
||||
app.sendResize = vi.fn(async () => true);
|
||||
app.getTerminalDimensions = () => ({ cols: 120, rows: 40 });
|
||||
return app;
|
||||
}
|
||||
|
||||
function paneB(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
sessionId: 'session-b',
|
||||
terminal: { clear: vi.fn(), cols: 60, rows: 30 },
|
||||
fit: vi.fn(),
|
||||
_destroyed: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('_focusedPane()', () => {
|
||||
it('is the primary pane until another pane claims the keyboard', () => {
|
||||
const app = loadApp();
|
||||
|
||||
const pane = app._focusedPane();
|
||||
|
||||
expect(pane.isPrimary).toBe(true);
|
||||
expect(pane.terminal).toBe(app.terminal);
|
||||
expect(pane.sessionId).toBe('session-a');
|
||||
});
|
||||
|
||||
it('is the second pane after its terminal was focused, and the primary again after the primary was', () => {
|
||||
const app = loadApp();
|
||||
const tile = paneB();
|
||||
|
||||
app._noteFocusedTile(tile);
|
||||
expect(app._focusedPane()).toMatchObject({ isPrimary: false, sessionId: 'session-b', terminal: tile.terminal });
|
||||
|
||||
app._noteFocusedTile(null);
|
||||
expect(app._focusedPane().isPrimary).toBe(true);
|
||||
});
|
||||
|
||||
it('never answers with a destroyed pane', () => {
|
||||
const app = loadApp();
|
||||
const tile = paneB();
|
||||
app._noteFocusedTile(tile);
|
||||
|
||||
tile._destroyed = true;
|
||||
|
||||
expect(app._focusedPane().isPrimary).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('terminal shortcuts follow the focused pane', () => {
|
||||
it('Ctrl+L clears the focused second pane, not the primary', () => {
|
||||
const app = loadApp();
|
||||
const tile = paneB();
|
||||
app._noteFocusedTile(tile);
|
||||
|
||||
app.clearTerminal();
|
||||
|
||||
expect(tile.terminal.clear).toHaveBeenCalledTimes(1);
|
||||
expect(app.terminal.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('Ctrl+L still clears the primary when it holds the keyboard', () => {
|
||||
const app = loadApp();
|
||||
|
||||
app.clearTerminal();
|
||||
|
||||
expect(app.terminal.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("Ctrl+Shift+R forces the focused second pane's size onto its own PTY", async () => {
|
||||
const app = loadApp();
|
||||
const tile = paneB();
|
||||
app._noteFocusedTile(tile);
|
||||
|
||||
await app.restoreTerminalSize();
|
||||
|
||||
expect(tile.fit).toHaveBeenCalledWith({ force: true });
|
||||
expect(app.sendResize).not.toHaveBeenCalled();
|
||||
expect(app.showToast).toHaveBeenCalledWith('Terminal restored to 60x30', 'success');
|
||||
});
|
||||
|
||||
it('Ctrl+Shift+R keeps restoring the primary when it holds the keyboard', async () => {
|
||||
const app = loadApp();
|
||||
|
||||
await app.restoreTerminalSize();
|
||||
|
||||
expect(app.sendResize).toHaveBeenCalledWith('session-a', { force: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Close Session (user-bound key only) stays on the active session', () => {
|
||||
it('killActiveSession closes activeSessionId and never consults the focused pane', () => {
|
||||
const appSource = read('app.js');
|
||||
const body = appSource.slice(
|
||||
appSource.indexOf('async killActiveSession() {'),
|
||||
appSource.indexOf('async killAllSessions() {')
|
||||
);
|
||||
|
||||
expect(body).toContain('await this.closeSession(this.activeSessionId);');
|
||||
expect(body).not.toContain('_focusedPane');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* @fileoverview The header-stats styles (`headerStatsStyle`, Discussion #426
|
||||
* option G): 'classic' (as before), 'compact' (one system pill with rings
|
||||
* plus a plan-ring pill) and 'tiles' (label over value, bar underneath; the
|
||||
* default).
|
||||
*
|
||||
* Pinned here:
|
||||
* - The default is 'tiles', and only the three known values are honoured.
|
||||
* - The two clustered styles move the connection indicator INTO the system
|
||||
* stats pill and the plan chip right after it, on the REAL header markup
|
||||
* from index.html, and 'classic' puts both back exactly where the template
|
||||
* had them.
|
||||
* - The WS readout never disappears with a hidden System Stats pill.
|
||||
* - The parts only the new styles draw (stat rings, plan rings, meters, tile words)
|
||||
* are rendered with sane values and hidden by default in CSS, which is what
|
||||
* keeps 'classic' looking exactly as before.
|
||||
*
|
||||
* The real modules run INSIDE a JSDOM window (runScripts: 'outside-only').
|
||||
*
|
||||
* Port: none.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = join(process.cwd(), 'src/web/public');
|
||||
const read = (name: string) => readFileSync(join(PUBLIC, name), 'utf8');
|
||||
const INDEX = read('index.html');
|
||||
const HEADER = INDEX.slice(INDEX.indexOf('<header class="header">'), INDEX.indexOf('</header>') + '</header>'.length);
|
||||
|
||||
let CodemanApp: { prototype: Record<string, any> };
|
||||
let window: any;
|
||||
let document: Document;
|
||||
|
||||
beforeAll(async () => {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
|
||||
url: 'https://localhost/',
|
||||
runScripts: 'outside-only',
|
||||
});
|
||||
if (dom.window.document.readyState !== 'complete') {
|
||||
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
|
||||
}
|
||||
window = dom.window;
|
||||
document = window.document;
|
||||
window.setInterval = () => 0;
|
||||
window.requestAnimationFrame = () => 0;
|
||||
window.eval(
|
||||
'var MobileDetection = { isTouchDevice: () => false, isHandheldDevice: () => false, getDeviceType: () => "desktop" }, ' +
|
||||
'KeyboardHandler = {}, SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
|
||||
read('constants.js') +
|
||||
'\n' +
|
||||
read('app.js') +
|
||||
'\n' +
|
||||
read('settings-ui.js') +
|
||||
'\n' +
|
||||
read('panels-ui.js') +
|
||||
'\n;window.__HeaderStatsCodemanApp = CodemanApp;'
|
||||
);
|
||||
CodemanApp = window.__HeaderStatsCodemanApp;
|
||||
});
|
||||
|
||||
function makeApp() {
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
|
||||
app.$ = (id: string) => document.getElementById(id);
|
||||
return app;
|
||||
}
|
||||
|
||||
/** Element children of the header's right side, by id (or first class). */
|
||||
const rightSide = () =>
|
||||
[...document.getElementById('headerRight')!.children].map((el) => el.id || el.classList[0]);
|
||||
const statsChildren = () =>
|
||||
[...document.getElementById('headerSystemStats')!.children].map((el) => el.id || el.classList[0]);
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = HEADER;
|
||||
delete document.documentElement.dataset.headerStats;
|
||||
});
|
||||
|
||||
describe('resolveHeaderStatsStyle', () => {
|
||||
it("defaults to 'tiles' and honours only the three known styles", () => {
|
||||
const app = makeApp();
|
||||
expect(app.resolveHeaderStatsStyle({})).toBe('tiles');
|
||||
expect(app.resolveHeaderStatsStyle(undefined)).toBe('tiles');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'classic' })).toBe('classic');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'compact' })).toBe('compact');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'tiles' })).toBe('tiles');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'neon' })).toBe('tiles');
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyHeaderStatsStyle', () => {
|
||||
it('clusters WS, the system stats and the plan chip for tiles and compact', () => {
|
||||
for (const style of ['tiles', 'compact']) {
|
||||
document.body.innerHTML = HEADER;
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style, showSystemStats: true });
|
||||
expect(document.documentElement.dataset.headerStats).toBe(style);
|
||||
expect(statsChildren()[0]).toBe('connectionIndicator');
|
||||
const right = rightSide();
|
||||
expect(right[right.indexOf('headerSystemStats') + 1]).toBe('planUsageChip');
|
||||
expect(right).not.toContain('connectionIndicator');
|
||||
}
|
||||
});
|
||||
|
||||
it("'classic' puts both back exactly where the template had them", () => {
|
||||
const template = rightSide();
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
app.applyHeaderStatsStyle({ style: 'compact', showSystemStats: true });
|
||||
app.applyHeaderStatsStyle({ style: 'classic', showSystemStats: true });
|
||||
expect(rightSide()).toEqual(template);
|
||||
expect(statsChildren()).not.toContain('connectionIndicator');
|
||||
expect(document.documentElement.dataset.headerStats).toBe('classic');
|
||||
});
|
||||
|
||||
it('keeps WS out of a hidden System Stats pill', () => {
|
||||
const template = rightSide();
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: false });
|
||||
expect(statsChildren()).not.toContain('connectionIndicator');
|
||||
expect(rightSide().indexOf('connectionIndicator')).toBe(template.indexOf('connectionIndicator'));
|
||||
});
|
||||
|
||||
it('is idempotent: re-applying the same style moves nothing', () => {
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
const once = document.getElementById('headerRight')!.innerHTML;
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
expect(document.getElementById('headerRight')!.innerHTML).toBe(once);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the parts the new styles draw', () => {
|
||||
it('gives every plan window a ring and a meter with a clamped fill, the label the real number', () => {
|
||||
const app = makeApp();
|
||||
app.updatePlanUsageChip({ fiveHour: { usedPercentage: 28 }, sevenDay: { usedPercentage: 104 } });
|
||||
const wins = [...document.querySelectorAll<HTMLElement>('#planUsageChip .pu-win')];
|
||||
expect(wins).toHaveLength(2);
|
||||
expect(wins[0].querySelector<HTMLElement>('.pu-ring')!.style.getPropertyValue('--pu')).toBe('28');
|
||||
expect(wins[0].querySelector<HTMLElement>('.pu-meter > i')!.style.width).toBe('28%');
|
||||
expect(wins[0].querySelector('.pu-ring')!.classList.contains('pu-green')).toBe(true);
|
||||
expect(wins[1].querySelector('.pu-val')!.textContent).toBe('104%');
|
||||
expect(wins[1].querySelector<HTMLElement>('.pu-meter > i')!.style.width).toBe('100%');
|
||||
expect(wins[1].querySelector('.pu-meter')!.classList.contains('pu-red')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps an idle Claude window as a dimmed slot with an empty ring and meter', () => {
|
||||
const app = makeApp();
|
||||
app.updatePlanUsageChip({ sevenDay: { usedPercentage: 35 } });
|
||||
const idle = document.querySelector<HTMLElement>('#planUsageChip .pu-win-idle')!;
|
||||
expect(idle.querySelector('.pu-val')!.textContent).toBe('—');
|
||||
expect(idle.querySelector<HTMLElement>('.pu-ring')!.style.getPropertyValue('--pu')).toBe('0');
|
||||
expect(idle.querySelector<HTMLElement>('.pu-meter > i')!.style.width).toBe('0%');
|
||||
});
|
||||
|
||||
it('names the connection state in two short words per dot state', () => {
|
||||
const app = makeApp();
|
||||
const words = (dotClass: string, text = '') => app._connectionTileWords({ dotClass, text });
|
||||
expect(words('connection-dot connected', 'WS')).toMatchObject({ label: 'WS', value: 'live', state: 'connected' });
|
||||
expect(words('connection-dot fallback', 'HTTP')).toMatchObject({ label: 'HTTP', value: 'fallback' });
|
||||
expect(words('connection-dot offline', 'Offline')).toMatchObject({ label: 'NET', value: 'offline' });
|
||||
expect(words('connection-dot draining', 'Sending...')).toMatchObject({ label: 'SEND', value: 'queued' });
|
||||
expect(words('connection-dot reconnecting', 'WS…')).toMatchObject({ label: 'WS', value: 'retry' });
|
||||
expect(words('connection-dot reconnecting', 'Reconnecting...')).toMatchObject({ label: 'SSE', value: 'retry' });
|
||||
});
|
||||
|
||||
it('writes the tile words beside the classic text, which stays as it was', () => {
|
||||
const app = makeApp();
|
||||
app._computeConnectionDescriptor = () => ({
|
||||
display: 'flex',
|
||||
dotClass: 'connection-dot connected',
|
||||
text: 'WS · 2.0KB queued',
|
||||
title: 'Terminal connected over WebSocket',
|
||||
});
|
||||
app._updateConnectionIndicator();
|
||||
expect(document.getElementById('connectionText')!.textContent).toBe('WS · 2.0KB queued');
|
||||
expect(document.getElementById('connectionTileLabel')!.textContent).toBe('WS');
|
||||
expect(document.getElementById('connectionTileValue')!.textContent).toBe('live');
|
||||
expect(document.getElementById('connectionTileValue')!.className).toBe('connection-tile-value connected');
|
||||
});
|
||||
|
||||
it('fills the CPU and MEM rings from the stats poll, clamped, red past 80%', () => {
|
||||
const app = makeApp();
|
||||
const ring = (id: string) => {
|
||||
const el = document.getElementById(id)!;
|
||||
return [el.style.getPropertyValue('--pu'), el.classList.contains('high')];
|
||||
};
|
||||
app.updateSystemStatsDisplay({ cpu: 22, memory: { usedMB: 14.4 * 1024, percent: 45.6 } });
|
||||
expect(ring('statCpuRing')).toEqual(['22', false]);
|
||||
expect(ring('statMemRing')).toEqual(['46', false]);
|
||||
app.updateSystemStatsDisplay({ cpu: 140, memory: { usedMB: 30 * 1024, percent: 81 } });
|
||||
expect(ring('statCpuRing')).toEqual(['100', true]);
|
||||
expect(ring('statMemRing')).toEqual(['81', true]);
|
||||
// A ring comes first in its stat, before the label, like the plan rings.
|
||||
expect(document.getElementById('statCpuRing')!.nextElementSibling!.className).toBe('stat-label');
|
||||
});
|
||||
});
|
||||
|
||||
describe('header stats wiring (static)', () => {
|
||||
const css = read('styles.css');
|
||||
|
||||
it('hides the new-style parts by default, so classic looks exactly as before', () => {
|
||||
expect(css).toMatch(
|
||||
/\.stat-ring,\s*\.connection-tile,\s*\.header-plan-usage \.pu-ring,\s*\.header-plan-usage \.pu-meter \{\s*display: none;/
|
||||
);
|
||||
});
|
||||
|
||||
it('lays a tile out as three rows, so its height never depends on the font', () => {
|
||||
// A bar laid over the bottom of a fixed-height tile is what let a taller
|
||||
// system mono (SF Mono) push the value into it.
|
||||
expect(css).toMatch(/grid-template-rows: 9px 14px 2px;\s*row-gap: 2px;/);
|
||||
const tiles = css.slice(css.indexOf('/* --- Tiles: label over value'));
|
||||
const bar = tiles.slice(tiles.indexOf("html[data-header-stats='tiles'] .header-system-stats .stat-bar,"));
|
||||
expect(bar.slice(0, bar.indexOf('}'))).not.toContain('position: absolute');
|
||||
expect(bar.slice(0, bar.indexOf('}'))).toContain('grid-row: 3;');
|
||||
});
|
||||
|
||||
it('gives the header buttons the tile box beside the tiles', () => {
|
||||
expect(css).toMatch(
|
||||
/html\[data-header-stats='tiles'\] \.header-right > \.btn-icon-header \{\s*width: 36px;\s*height: 36px;/
|
||||
);
|
||||
expect(css).toMatch(/html\[data-header-stats='tiles'\] \.header-right > \.btn-icon-header > svg \{\s*width: 18px;/);
|
||||
});
|
||||
|
||||
it('stamps data-header-stats before first paint, tiles by default and classic on narrow screens', () => {
|
||||
expect(INDEX).toContain(
|
||||
"dataset.headerStats=(window.innerWidth<768||solo)?'classic':(H==='classic'||H==='compact')?H:'tiles'"
|
||||
);
|
||||
});
|
||||
|
||||
it('offers the three styles with tiles marked as the default', () => {
|
||||
expect(INDEX).toMatch(
|
||||
/<select id="appSettingsHeaderStatsStyle"[^>]*>\s*<option value="classic">[^<]+<\/option>\s*<option value="compact">[^<]+<\/option>\s*<option value="tiles">Tiles \(default\)<\/option>/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -38,9 +38,7 @@ describe('help modal shortcuts', () => {
|
||||
const helpModal = normalizedHtml(extractElementById(INDEX_HTML, 'helpModal'));
|
||||
|
||||
it('documents implemented global and tab shortcuts', () => {
|
||||
// Ctrl+W is NOT an app shortcut: it is delete-word in the terminal, and as
|
||||
// Close Session it killed sessions with no confirm (ctrl-w-never-closes.test.ts).
|
||||
expect(helpModal).not.toMatch(/<kbd>Ctrl<\/kbd>\s*\+\s*<kbd>W<\/kbd>/i);
|
||||
expectShortcut(helpModal, ['Ctrl', 'W'], 'Close Session');
|
||||
expectShortcut(helpModal, ['Ctrl', 'Tab'], 'Next Session');
|
||||
expectShortcut(helpModal, ['Alt/Option', '['], 'Previous / Next Session');
|
||||
expectShortcut(helpModal, ['Alt/Option', ']'], 'Previous / Next Session');
|
||||
|
||||
@@ -143,7 +143,6 @@ function loadImageInputApp() {
|
||||
app.activeSessionId = 'session-1';
|
||||
app.showToast = vi.fn();
|
||||
app.sendInput = vi.fn(async () => {});
|
||||
app._sendInputAsync = vi.fn();
|
||||
app._normalizeImageForUpload = vi.fn(async (file) => file);
|
||||
app._uploadPasteImage = vi.fn(async (_sessionId, file: { path: string }) => file.path);
|
||||
return app as Record<string, any>;
|
||||
@@ -200,7 +199,6 @@ describe('image upload insertion policy', () => {
|
||||
|
||||
expect(Array.from(paths)).toEqual(['/tmp/first.png', '/tmp/second.png']);
|
||||
expect(app.sendInput).not.toHaveBeenCalled();
|
||||
expect(app._sendInputAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves terminal insertion by default', async () => {
|
||||
@@ -209,33 +207,6 @@ describe('image upload insertion policy', () => {
|
||||
const paths = await app._uploadAndInsertImages([{ path: '/tmp/legacy.png' }]);
|
||||
|
||||
expect(Array.from(paths)).toEqual(['/tmp/legacy.png']);
|
||||
// The same delivery sendInput() uses (durable queue, useMux for the POST
|
||||
// fallback), but addressed to the session the batch was uploaded to.
|
||||
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/tmp/legacy.png', { useMux: true });
|
||||
});
|
||||
|
||||
it('inserts into the session the upload started in, even after a tab switch mid-upload', async () => {
|
||||
const app = loadImageInputApp();
|
||||
// The user switches tabs while the upload is in flight. sendInput() re-read
|
||||
// activeSessionId after the awaits, so the paths used to land in session-2.
|
||||
app._uploadPasteImage = vi.fn(async (_sessionId, file: { path: string }) => {
|
||||
app.activeSessionId = 'session-2';
|
||||
return file.path;
|
||||
});
|
||||
|
||||
await app._uploadAndInsertImages([{ path: '/tmp/shot.png' }]);
|
||||
|
||||
expect(app._uploadPasteImage).toHaveBeenCalledWith('session-1', { path: '/tmp/shot.png' });
|
||||
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/tmp/shot.png', { useMux: true });
|
||||
expect(app.sendInput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads to and inserts into an explicitly named session', async () => {
|
||||
const app = loadImageInputApp();
|
||||
|
||||
await app._uploadAndInsertImages([{ path: '/tmp/pane-b.png' }], { sessionId: 'session-b' });
|
||||
|
||||
expect(app._uploadPasteImage).toHaveBeenCalledWith('session-b', { path: '/tmp/pane-b.png' });
|
||||
expect(app._sendInputAsync).toHaveBeenCalledWith('session-b', '/tmp/pane-b.png', { useMux: true });
|
||||
expect(app.sendInput).toHaveBeenCalledWith('/tmp/legacy.png');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,7 +97,7 @@ describe('the client never queues or keeps an undeliverable frame', () => {
|
||||
});
|
||||
|
||||
it('drops a frame the WebSocket refused with an error ACK', () => {
|
||||
const handler = appSource.slice(appSource.indexOf('_onWsInputAck(seq, msg, sessionId = this._wsSessionId) {'));
|
||||
const handler = appSource.slice(appSource.indexOf('_onWsInputAck(seq, msg) {'));
|
||||
expect(handler.slice(0, 600)).toMatch(/if \(msg && msg\.err\)/);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,281 +0,0 @@
|
||||
/**
|
||||
* @fileoverview The durable input layer delivers over ANY registered terminal
|
||||
* socket, not only the primary one (`_inputSocketFor`, app.js).
|
||||
*
|
||||
* The exactly-once queue (`_sendInputAsync` → `_reliableSend` → `_drainSession`,
|
||||
* ACKed by `{t:'ia'}`, swept by `_redeliverSweep`) used to read the single
|
||||
* primary socket (`this._ws` / `this._wsSessionId`) directly. A second terminal
|
||||
* bound to another session (the split pane's Pane B, later a grid tile) had no
|
||||
* way in, so its keystrokes went out as seq-less frames with no ACK, no retry
|
||||
* and no idle-alert acknowledgement. These tests pin the seam: a registered
|
||||
* socket gets seq frames, its ACK lands on ITS session's queue, a stale
|
||||
* registration can never evict the socket that replaced it, and the sweep
|
||||
* judges a socket's silence by that socket's own last frame.
|
||||
*
|
||||
* Loaded via `vm` with a stubbed context (no jsdom), like input-send-order.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
function loadCodemanAppClass() {
|
||||
const constants = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
performance,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: { OPEN: 1 },
|
||||
fetch: (...args: Parameters<typeof fetch>) => global.fetch(...args),
|
||||
document: { addEventListener: vi.fn() },
|
||||
localStorage: {
|
||||
length: 0,
|
||||
key: vi.fn(),
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
MobileDetection: {},
|
||||
});
|
||||
vm.runInContext(`${constants}\n${source}\nglobalThis.__CodemanApp = CodemanApp;`, context);
|
||||
return (context as { __CodemanApp: new () => unknown }).__CodemanApp;
|
||||
}
|
||||
|
||||
const CodemanApp = loadCodemanAppClass();
|
||||
|
||||
type Frame = { t: string; d: string; seq?: number; cid?: string };
|
||||
type FakeSocket = { readyState: number; send: (data: string) => void; close: ReturnType<typeof vi.fn> };
|
||||
type Handle = { ws: FakeSocket; lastRecvAt: number };
|
||||
type Rec = { seq: number; data: string; sentAt: number; tries: number };
|
||||
|
||||
type App = {
|
||||
_sendInputAsync: (sessionId: string, input: string, opts?: { useMux?: boolean }) => void;
|
||||
_sendInputEphemeral: (sessionId: string, input: string) => void;
|
||||
_inputSocketFor: (sessionId: string) => { ws: FakeSocket; lastRecvAt: number } | null;
|
||||
_registerInputSocket: (sessionId: string, handle: Handle) => void;
|
||||
_unregisterInputSocket: (sessionId: string, handle: Handle) => void;
|
||||
_onWsInputAck: (seq: number, msg: Record<string, unknown>, sessionId?: string) => void;
|
||||
_onWsReady: (sessionId: string) => void;
|
||||
_redeliverSweep: () => void;
|
||||
_pendingDeliveries: Map<string, Rec[]>;
|
||||
_seqCounters: Map<string, number>;
|
||||
_ws: FakeSocket | null;
|
||||
_wsSessionId: string | null;
|
||||
_wsLastRecvAt: number;
|
||||
_reliableAckTimeoutMs: number;
|
||||
markIdleAlertSeen: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function makeApp(): App {
|
||||
const app = Object.create((CodemanApp as { prototype: object }).prototype) as App & Record<string, unknown>;
|
||||
app._clientId = 'c-test';
|
||||
app._seqCounters = new Map();
|
||||
app._pendingDeliveries = new Map();
|
||||
app._postDraining = new Set();
|
||||
app._persistReliableState = vi.fn();
|
||||
app._persistReliableNow = vi.fn();
|
||||
app._updateConnectionIndicator = vi.fn();
|
||||
app.markIdleAlertSeen = vi.fn();
|
||||
app.activeSessionId = 'primary';
|
||||
app._ws = null;
|
||||
app._wsSessionId = null;
|
||||
app._wsLastRecvAt = 0;
|
||||
app._reliableAckTimeoutMs = 4000;
|
||||
return app as unknown as App;
|
||||
}
|
||||
|
||||
function fakeSocket(frames: Frame[]): FakeSocket {
|
||||
return { readyState: 1, send: (d: string) => frames.push(JSON.parse(d) as Frame), close: vi.fn() };
|
||||
}
|
||||
|
||||
describe('a registered second socket joins the exactly-once queue', () => {
|
||||
it('delivers seq-tagged frames over the registered socket for its session', () => {
|
||||
const app = makeApp();
|
||||
const primaryFrames: Frame[] = [];
|
||||
const tileFrames: Frame[] = [];
|
||||
app._ws = fakeSocket(primaryFrames);
|
||||
app._wsSessionId = 'primary';
|
||||
app._registerInputSocket('other', { ws: fakeSocket(tileFrames), lastRecvAt: 0 });
|
||||
|
||||
app._sendInputAsync('other', 'x');
|
||||
app._sendInputAsync('other', 'y');
|
||||
|
||||
expect(tileFrames.map((f) => [f.d, f.seq, f.cid])).toEqual([
|
||||
['x', 1, 'c-test'],
|
||||
['y', 2, 'c-test'],
|
||||
]);
|
||||
// Nothing for the other session leaks onto the primary socket.
|
||||
expect(primaryFrames).toEqual([]);
|
||||
});
|
||||
|
||||
it('still prefers the primary socket for the primary session', () => {
|
||||
const app = makeApp();
|
||||
const primaryFrames: Frame[] = [];
|
||||
app._ws = fakeSocket(primaryFrames);
|
||||
app._wsSessionId = 'primary';
|
||||
|
||||
app._sendInputAsync('primary', 'a');
|
||||
|
||||
expect(primaryFrames.map((f) => f.d)).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('ignores a registered socket that is not OPEN (falls back to POST)', async () => {
|
||||
const app = makeApp();
|
||||
const posts: Array<{ input: string; seq: number }> = [];
|
||||
global.fetch = vi.fn(async (_url, init) => {
|
||||
posts.push(JSON.parse(String(init?.body)));
|
||||
return new Response('{}', { status: 200 });
|
||||
});
|
||||
const closing = { ...fakeSocket([]), readyState: 3 };
|
||||
app._registerInputSocket('other', { ws: closing, lastRecvAt: 0 });
|
||||
|
||||
expect(app._inputSocketFor('other')).toBeNull();
|
||||
app._sendInputAsync('other', 'z');
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
expect(posts.map((p) => [p.input, p.seq])).toEqual([['z', 1]]);
|
||||
});
|
||||
|
||||
it('routes ephemeral input over the registered socket too', () => {
|
||||
const app = makeApp();
|
||||
const tileFrames: Frame[] = [];
|
||||
app._registerInputSocket('other', { ws: fakeSocket(tileFrames), lastRecvAt: 0 });
|
||||
|
||||
app._sendInputEphemeral('other', '\x1b[<64;1;1M');
|
||||
|
||||
expect(tileFrames).toEqual([{ t: 'i', d: '\x1b[<64;1;1M' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ACK routing', () => {
|
||||
it('drops the record from the queue of the session the ACK arrived for', () => {
|
||||
const app = makeApp();
|
||||
app._ws = fakeSocket([]);
|
||||
app._wsSessionId = 'primary';
|
||||
app._registerInputSocket('other', { ws: fakeSocket([]), lastRecvAt: 0 });
|
||||
app._sendInputAsync('primary', 'p');
|
||||
app._sendInputAsync('other', 'o');
|
||||
|
||||
// Both sessions issued seq 1. The ACK names no session, so the socket's own
|
||||
// session decides which queue it drains; the primary's must be untouched.
|
||||
app._onWsInputAck(1, { t: 'ia', seq: 1 }, 'other');
|
||||
|
||||
expect(app._pendingDeliveries.get('other')).toBeUndefined();
|
||||
expect(app._pendingDeliveries.get('primary')?.map((r) => r.data)).toEqual(['p']);
|
||||
expect(app.markIdleAlertSeen).toHaveBeenCalledWith('other');
|
||||
});
|
||||
|
||||
it('defaults to the primary socket session when no session is passed', () => {
|
||||
const app = makeApp();
|
||||
app._ws = fakeSocket([]);
|
||||
app._wsSessionId = 'primary';
|
||||
app._sendInputAsync('primary', 'p');
|
||||
|
||||
app._onWsInputAck(1, { t: 'ia', seq: 1 });
|
||||
|
||||
expect(app._pendingDeliveries.get('primary')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('re-sends everything pending over a freshly registered socket on ready', () => {
|
||||
const app = makeApp();
|
||||
const first: Frame[] = [];
|
||||
const firstHandle = { ws: fakeSocket(first), lastRecvAt: 0 };
|
||||
app._registerInputSocket('other', firstHandle);
|
||||
app._sendInputAsync('other', 'a');
|
||||
expect(first.map((f) => f.d)).toEqual(['a']);
|
||||
|
||||
// The socket dies without an ACK; a replacement opens and asks for a flush.
|
||||
firstHandle.ws.readyState = 3;
|
||||
const second: Frame[] = [];
|
||||
app._registerInputSocket('other', { ws: fakeSocket(second), lastRecvAt: 0 });
|
||||
app._onWsReady('other');
|
||||
|
||||
expect(second.map((f) => [f.d, f.seq])).toEqual([['a', 1]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('registration ownership', () => {
|
||||
it('a stale handle cannot unregister the socket that replaced it', () => {
|
||||
const app = makeApp();
|
||||
const oldHandle = { ws: fakeSocket([]), lastRecvAt: 0 };
|
||||
const newFrames: Frame[] = [];
|
||||
const newHandle = { ws: fakeSocket(newFrames), lastRecvAt: 0 };
|
||||
app._registerInputSocket('other', oldHandle);
|
||||
app._registerInputSocket('other', newHandle);
|
||||
|
||||
// The old socket's close lands late and tries to clean up after itself.
|
||||
app._unregisterInputSocket('other', oldHandle);
|
||||
|
||||
app._sendInputAsync('other', 'still-here');
|
||||
expect(newFrames.map((f) => f.d)).toEqual(['still-here']);
|
||||
});
|
||||
|
||||
it('the owning handle does unregister', () => {
|
||||
const app = makeApp();
|
||||
const handle = { ws: fakeSocket([]), lastRecvAt: 0 };
|
||||
app._registerInputSocket('other', handle);
|
||||
app._unregisterInputSocket('other', handle);
|
||||
|
||||
expect(app._inputSocketFor('other')).toBeNull();
|
||||
});
|
||||
|
||||
it('stamps lastRecvAt at registration so a fresh socket never looks silent', () => {
|
||||
const app = makeApp();
|
||||
const handle = { ws: fakeSocket([]), lastRecvAt: 0 };
|
||||
const before = Date.now();
|
||||
app._registerInputSocket('other', handle);
|
||||
|
||||
expect(handle.lastRecvAt).toBeGreaterThanOrEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the redelivery sweep judges each socket by its own last frame', () => {
|
||||
function staleRecord(app: App, sessionId: string) {
|
||||
const rec = app._pendingDeliveries.get(sessionId)![0];
|
||||
rec.sentAt = Date.now() - (app._reliableAckTimeoutMs + 1000);
|
||||
}
|
||||
|
||||
it('force-closes a silent registered socket with a stale record', () => {
|
||||
const app = makeApp();
|
||||
const handle = { ws: fakeSocket([]), lastRecvAt: 0 };
|
||||
app._registerInputSocket('other', handle);
|
||||
app._sendInputAsync('other', 'a');
|
||||
staleRecord(app, 'other');
|
||||
handle.lastRecvAt = Date.now() - (app._reliableAckTimeoutMs + 1000);
|
||||
// The primary socket is chatty; that must not vouch for the other one.
|
||||
app._ws = fakeSocket([]);
|
||||
app._wsSessionId = 'primary';
|
||||
app._wsLastRecvAt = Date.now();
|
||||
|
||||
app._redeliverSweep();
|
||||
|
||||
expect(handle.ws.close).toHaveBeenCalledTimes(1);
|
||||
expect(app._ws.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-drives (does not close) a registered socket that is still receiving', () => {
|
||||
const app = makeApp();
|
||||
const frames: Frame[] = [];
|
||||
const handle = { ws: fakeSocket(frames), lastRecvAt: 0 };
|
||||
app._registerInputSocket('other', handle);
|
||||
app._sendInputAsync('other', 'a');
|
||||
staleRecord(app, 'other');
|
||||
handle.lastRecvAt = Date.now();
|
||||
// A SILENT primary must not condemn the live registered socket either.
|
||||
app._wsLastRecvAt = 0;
|
||||
|
||||
app._redeliverSweep();
|
||||
|
||||
expect(handle.ws.close).not.toHaveBeenCalled();
|
||||
expect(frames.map((f) => f.d)).toEqual(['a', 'a']);
|
||||
});
|
||||
});
|
||||
@@ -42,7 +42,7 @@ describe('the duplicate ACK carries what the client needs', () => {
|
||||
|
||||
describe('the client lifts itself over the watermark', () => {
|
||||
const handler = appSource.slice(
|
||||
appSource.indexOf('_onWsInputAck(seq, msg, sessionId'),
|
||||
appSource.indexOf('_onWsInputAck(seq, msg)'),
|
||||
appSource.indexOf('/** Called from ws.onopen')
|
||||
);
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = join(new URL('.', import.meta.url).pathname, '../src/web/public');
|
||||
|
||||
describe.each(['terminal-ui.js', 'terminal-tile.js'])('%s Shift/Ctrl+Enter handler', (file) => {
|
||||
describe.each(['terminal-ui.js', 'terminal-split.js'])('%s Shift/Ctrl+Enter handler', (file) => {
|
||||
const src = readFileSync(join(PUBLIC, file), 'utf8');
|
||||
|
||||
it('swallows every event type for Shift/Ctrl+Enter', () => {
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
* worked all along because Chromium fires no keypress for it.
|
||||
*
|
||||
* The page is the real app served by a real WebServer, so the handlers under test are the ones
|
||||
* terminal-ui.js (the main pane, `app.terminal`) and terminal-tile.js (Pane B, a real
|
||||
* `TerminalTile`) attach. Nothing restates their predicate. What stands in for the server is
|
||||
* terminal-ui.js (the main pane, `app.terminal`) and terminal-split.js (Pane B, a real
|
||||
* `SplitTerminalPane`) attach. Nothing restates their predicate. What stands in for the server is
|
||||
* only the edge: a fetch wrapper records the send-key POSTs instead of letting them reach tmux, and
|
||||
* no session exists behind the ids, so nothing is ever typed into a real pane.
|
||||
*
|
||||
@@ -74,7 +74,7 @@ describe('Shift/Ctrl+Enter through the shipped key handlers (keypress must be sw
|
||||
const mount = document.createElement('div');
|
||||
mount.style.cssText = 'position:fixed;left:0;top:0;width:400px;height:300px;';
|
||||
document.body.appendChild(mount);
|
||||
const pane = new w.TerminalTile(paneBId, mount, { mode: 'claude' });
|
||||
const pane = new w.SplitTerminalPane(paneBId, mount, { mode: 'claude' });
|
||||
void pane.connect().catch(() => {});
|
||||
// What xterm emits here is exactly what Pane B's own onData forwards to its WebSocket.
|
||||
w.__paneBData = [] as string[];
|
||||
@@ -200,7 +200,7 @@ describe('Shift/Ctrl+Enter through the shipped key handlers (keypress must be sw
|
||||
expect(shift.sendKeys).toEqual([]);
|
||||
});
|
||||
|
||||
it("Pane B (terminal-tile.js): Shift+Enter and Ctrl+Enter write nothing and POST send-key once for Pane B's own session", async () => {
|
||||
it("Pane B (terminal-split.js): Shift+Enter and Ctrl+Enter write nothing and POST send-key once for Pane B's own session", async () => {
|
||||
const shift = await pressIn('paneB', 'Shift+Enter');
|
||||
expect(shift.focused).toBe(true);
|
||||
expect(shift.data).toEqual([]);
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
// test/terminal-tile-unit.test.ts
|
||||
// Port: N/A (no server/browser; TerminalTile is loaded via `vm`, like
|
||||
// test/split-pane-terminal-unit.test.ts
|
||||
// Port: N/A (no server/browser; SplitTerminalPane is loaded via `vm`, like
|
||||
// split-pane-auto-collapse-unit.test.ts loads the CodemanApp patches).
|
||||
//
|
||||
// Unit coverage for the two TerminalTile (terminal-tile.js, the split pane's
|
||||
// Pane B until it moved out of terminal-split.js) fixes from
|
||||
// Unit coverage for the two SplitTerminalPane (terminal-split.js) fixes from
|
||||
// the final review of #453 that need no browser: destroy() nulling EVERY socket
|
||||
// handler (onclose used to survive it and fire its "disconnected" write into a
|
||||
// pane already torn down), and the `{t:'r'}` server-refresh path being
|
||||
@@ -16,7 +15,7 @@
|
||||
// The last block covers the scroll-to-top history pull: a burst of output leaves
|
||||
// a shell pane's xterm with about one screen of scrollback while tmux holds every
|
||||
// line, and Pane B (a separate xterm from the primary pane) never went back to
|
||||
// ask. See _maybeLoadMoreHistory / _pullHistory in terminal-tile.js.
|
||||
// ask. See _maybeLoadMoreHistory / _pullHistory in terminal-split.js.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
@@ -74,9 +73,9 @@ const fetchMock = vi.fn();
|
||||
const rafQueue: Array<() => void> = [];
|
||||
/** Recorded deadline timers (see the context's setTimeout); `fn` aborts the request. */
|
||||
const deadlines: Array<{ fn: () => void; ms: number; cleared: boolean }> = [];
|
||||
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-tile.js'), 'utf8');
|
||||
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-split.js'), 'utf8');
|
||||
|
||||
function loadTerminalTile() {
|
||||
function loadSplitTerminalPane() {
|
||||
const context = vm.createContext({
|
||||
console: { ...console, log: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
// The primary pane's row estimator, reduced to a line count: the pull only
|
||||
@@ -112,18 +111,18 @@ function loadTerminalTile() {
|
||||
});
|
||||
// The module's tail patches CodemanApp.prototype; nothing on it runs here.
|
||||
vm.runInContext(`class CodemanApp { _onSessionDeleted() {} selectSession() {} }\n${SOURCE}`, context);
|
||||
return (context.window as { TerminalTile: new (id: string, mount: unknown, opts?: object) => PaneUnderTest })
|
||||
.TerminalTile;
|
||||
return (context.window as { SplitTerminalPane: new (id: string, mount: unknown, opts?: object) => PaneUnderTest })
|
||||
.SplitTerminalPane;
|
||||
}
|
||||
|
||||
const TerminalTile = loadTerminalTile();
|
||||
const SplitTerminalPane = loadSplitTerminalPane();
|
||||
|
||||
function makePane(
|
||||
mode = 'claude',
|
||||
mount: unknown = {},
|
||||
opts: { detachedSessions?: Set<string> } = {}
|
||||
): PaneUnderTest & { terminal: FakeTerminal } {
|
||||
const pane = new TerminalTile('s1', mount, { mode, ...opts });
|
||||
const pane = new SplitTerminalPane('s1', mount, { mode, ...opts });
|
||||
pane.terminal = {
|
||||
// xterm invokes a write's callback once everything before it is parsed.
|
||||
write: vi.fn((_data: string, done?: () => void) => done?.()),
|
||||
@@ -176,8 +175,7 @@ function deferred<T>() {
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
// Every marker variant (reconnecting, session ended, refused, taken over) starts the same way.
|
||||
const isMarker = (data: unknown) => typeof data === 'string' && data.includes('[disconnected');
|
||||
const isMarker = (data: unknown) => typeof data === 'string' && data.includes('Pane B disconnected');
|
||||
|
||||
/** Lets every microtask the vm-side promise chain queued run. */
|
||||
const settle = () => new Promise((r) => setTimeout(r, 0));
|
||||
@@ -189,7 +187,7 @@ beforeEach(() => {
|
||||
clock = 0;
|
||||
});
|
||||
|
||||
describe('TerminalTile.destroy()', () => {
|
||||
describe('SplitTerminalPane.destroy()', () => {
|
||||
it('nulls every WebSocket handler, onclose included, before closing the socket', () => {
|
||||
const pane = makePane();
|
||||
const terminal = pane.terminal;
|
||||
@@ -212,7 +210,7 @@ describe('TerminalTile.destroy()', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile server-refresh single-flight', () => {
|
||||
describe('SplitTerminalPane server-refresh single-flight', () => {
|
||||
it('a refresh with nothing in flight clears and fetches straight away', async () => {
|
||||
const pane = makePane();
|
||||
fetchMock.mockResolvedValueOnce(jsonResponse('one'));
|
||||
@@ -331,7 +329,7 @@ describe('TerminalTile server-refresh single-flight', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile scroll-to-top history pull', () => {
|
||||
describe('SplitTerminalPane scroll-to-top history pull', () => {
|
||||
it('a shell pane at the top pulls a bounded window of full history and replays it', async () => {
|
||||
const pane = makePane('shell');
|
||||
const term = pane.terminal;
|
||||
@@ -723,11 +721,8 @@ describe('TerminalTile scroll-to-top history pull', () => {
|
||||
expect(connect).toContain('this._installWheelListener();');
|
||||
expect(connect).toContain('this._onLiveClear();');
|
||||
expect(connect).not.toContain('this.terminal.clear();');
|
||||
// The tests below drive the close through _onSocketClosed() directly; the
|
||||
// socket's own handler forwards the close event (and its code) there, and
|
||||
// only for the current socket (_openSocket).
|
||||
expect(connect).toContain('this._onSocketClosed(event);');
|
||||
expect(connect).toMatch(/ws\.onclose = \(event\) => \{\s*if \(ws !== this\.ws\) return;/);
|
||||
// The tests below drive the close through _onSocketClosed() directly.
|
||||
expect(connect).toContain('this.ws.onclose = () => this._onSocketClosed();');
|
||||
});
|
||||
|
||||
it('a close with no pull running writes the marker straight away', () => {
|
||||
@@ -751,9 +746,9 @@ describe('TerminalTile scroll-to-top history pull', () => {
|
||||
void pane._pullHistory();
|
||||
await settle();
|
||||
|
||||
const marker = expect.stringContaining('[disconnected');
|
||||
const marker = expect.stringContaining('Pane B disconnected');
|
||||
const writes = pane.terminal.write.mock.calls.map((c) => c[0]);
|
||||
expect(writes.at(-1)).toEqual(expect.stringMatching(/\[disconnected/));
|
||||
expect(writes.at(-1)).toEqual(expect.stringMatching(/Pane B disconnected/));
|
||||
expect(pane.terminal.write).toHaveBeenCalledWith(marker);
|
||||
});
|
||||
|
||||
@@ -1008,7 +1003,7 @@ describe('TerminalTile scroll-to-top history pull', () => {
|
||||
await settle();
|
||||
|
||||
for (const call of pane.terminal.write.mock.calls) {
|
||||
expect(call[0]).toEqual(expect.not.stringMatching(/\[disconnected/));
|
||||
expect(call[0]).toEqual(expect.not.stringMatching(/Pane B disconnected/));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** @fileoverview Real Chromium + real WebSocket coverage for TerminalTile (Task 4 of the split-pane-sessions plan). */
|
||||
/** @fileoverview Real Chromium + real WebSocket coverage for SplitTerminalPane (Task 4 of the split-pane-sessions plan). */
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { chromium, type Browser, type Page } from 'playwright';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
@@ -6,7 +6,7 @@ import { WebServer } from '../src/web/server.js';
|
||||
const PORT = 3175;
|
||||
const BASE_URL = `http://localhost:${PORT}`;
|
||||
|
||||
describe('TerminalTile in a real browser', () => {
|
||||
describe('SplitTerminalPane in a real browser', () => {
|
||||
let server: WebServer;
|
||||
let browser: Browser;
|
||||
let page: Page;
|
||||
@@ -37,7 +37,7 @@ describe('TerminalTile in a real browser', () => {
|
||||
// Testing section) — the shell PTY only spawns once this is called, and
|
||||
// without it the WS opens but no bytes ever flow, and the echo assertion
|
||||
// below would hang until its own timeout for reasons unrelated to
|
||||
// TerminalTile.
|
||||
// SplitTerminalPane.
|
||||
await fetch(`/api/sessions/${id}/shell`, { method: 'POST' });
|
||||
return id;
|
||||
});
|
||||
@@ -48,7 +48,7 @@ describe('TerminalTile in a real browser', () => {
|
||||
mount.style.height = '300px';
|
||||
document.body.appendChild(mount);
|
||||
|
||||
const pane = new (window as any).TerminalTile(id, mount);
|
||||
const pane = new (window as any).SplitTerminalPane(id, mount);
|
||||
pane.connect();
|
||||
|
||||
// Wait for the WS to open, then send a real input frame — testMode's
|
||||
@@ -107,7 +107,7 @@ describe('TerminalTile in a real browser', () => {
|
||||
});
|
||||
const id = (await res.json()).data.session.id;
|
||||
await fetch(`/api/sessions/${id}/shell`, { method: 'POST' });
|
||||
// Write directly to the session (not through TerminalTile, which
|
||||
// Write directly to the session (not through SplitTerminalPane, which
|
||||
// does not exist yet). Poll the real ?full=1 capture (same endpoint
|
||||
// connect() below will use) rather than a fixed delay — the shell's
|
||||
// own startup can race an early write and, on this box, a startup
|
||||
@@ -135,7 +135,7 @@ describe('TerminalTile in a real browser', () => {
|
||||
mount.style.height = '300px';
|
||||
document.body.appendChild(mount);
|
||||
|
||||
const pane = new (window as any).TerminalTile(id, mount);
|
||||
const pane = new (window as any).SplitTerminalPane(id, mount);
|
||||
await pane.connect();
|
||||
|
||||
// xterm's write() parses asynchronously (it queues data and processes it
|
||||
@@ -191,7 +191,7 @@ describe('TerminalTile in a real browser', () => {
|
||||
mount.style.height = '300px';
|
||||
document.body.appendChild(mount);
|
||||
|
||||
const pane = new (window as any).TerminalTile(id, mount);
|
||||
const pane = new (window as any).SplitTerminalPane(id, mount);
|
||||
await pane.connect();
|
||||
await new Promise((resolve) => {
|
||||
const check = () => (pane._wsReady ? resolve(undefined) : setTimeout(check, 100));
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
/**
|
||||
* @fileoverview Tab layouts by case and ledger (`tabArrangement: 'case'` and
|
||||
* `'ledger'`, Discussion #426 options A and B).
|
||||
*
|
||||
* What is pinned, and why it matters:
|
||||
* - By case, each case's tabs sit in ONE box, in the order the case first
|
||||
* appears in the tab order, with a colour that is a pure function of the
|
||||
* case (no storage, the same on every device).
|
||||
* - Inside a box with company, a generated `w75-api-gateway` reads `w75`, but
|
||||
* the full name stays in the DOM and in the accessible name; a custom or
|
||||
* described name is never touched.
|
||||
* - The Alt+N badges keep counting the tab order, and an incremental pass
|
||||
* patches tabs in place unless the cluster structure changed.
|
||||
* - Drag only reorders inside a box. Named groups in the vertical rail win.
|
||||
* - The ledger changes no markup at all: it is a class on #sessionTabs and
|
||||
* CSS scoped to the desktop header strip.
|
||||
*
|
||||
* The real modules run INSIDE a JSDOM window (runScripts: 'outside-only').
|
||||
*
|
||||
* Port: none.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = join(process.cwd(), 'src/web/public');
|
||||
const read = (name: string) => readFileSync(join(PUBLIC, name), 'utf8');
|
||||
|
||||
type Cluster = { key: string; label: string; color: string; ids: string[] };
|
||||
type Clusters = {
|
||||
COLORS: string[];
|
||||
colorFor: (key: string) => string;
|
||||
compute: (rows: Array<{ id: string; key: string; label: string }>) => Cluster[];
|
||||
nameSplit: (name: string, label: string) => { shown: string; hidden: string } | null;
|
||||
};
|
||||
|
||||
function loadClusters(): Clusters {
|
||||
const context = vm.createContext({ window: {}, globalThis: {} });
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
return (context.window as { CodemanTabClusters: Clusters }).CodemanTabClusters;
|
||||
}
|
||||
|
||||
describe('CodemanTabClusters (pure)', () => {
|
||||
const C = loadClusters();
|
||||
|
||||
it('groups by case in first-appearance order, members in tab order', () => {
|
||||
const out = C.compute([
|
||||
{ id: 'a', key: '/c/web', label: 'web' },
|
||||
{ id: 'b', key: '/c/api', label: 'api' },
|
||||
{ id: 'c', key: '/c/web', label: 'web' },
|
||||
]);
|
||||
expect(out.map((c) => [c.key, c.ids])).toEqual([
|
||||
['/c/web', ['a', 'c']],
|
||||
['/c/api', ['b']],
|
||||
]);
|
||||
});
|
||||
|
||||
it('gives a session with no case a cluster of its own', () => {
|
||||
const out = C.compute([
|
||||
{ id: 'a', key: '', label: '' },
|
||||
{ id: 'b', key: '', label: '' },
|
||||
]);
|
||||
expect(out.map((c) => c.ids)).toEqual([['a'], ['b']]);
|
||||
});
|
||||
|
||||
it('colours a case from the session palette, the same way every time', () => {
|
||||
for (const key of ['/c/web', '/c/api', '/home/x/codeman-cases/long-name', '']) {
|
||||
expect(C.COLORS).toContain(C.colorFor(key));
|
||||
expect(C.colorFor(key)).toBe(C.colorFor(key));
|
||||
}
|
||||
});
|
||||
|
||||
it('only shortens a generated name that carries this case', () => {
|
||||
expect(C.nameSplit('w75-api-gateway', 'api-gateway')).toEqual({ shown: 'w75', hidden: '-api-gateway' });
|
||||
expect(C.nameSplit('s2-API-Gateway', 'api-gateway')).toEqual({ shown: 's2', hidden: '-API-Gateway' });
|
||||
expect(C.nameSplit('w75-api-gateway', 'webshop')).toBeNull();
|
||||
expect(C.nameSplit('w3-x: fix login', 'x')).toBeNull();
|
||||
expect(C.nameSplit('DocsBot', 'docsbot')).toBeNull();
|
||||
expect(C.nameSplit('w1-webshop', '')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('tab layouts by case and ledger (app.js)', () => {
|
||||
let CodemanApp: { prototype: Record<string, any> };
|
||||
let window: any;
|
||||
let document: Document;
|
||||
|
||||
beforeAll(async () => {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
|
||||
url: 'https://localhost/',
|
||||
runScripts: 'outside-only',
|
||||
});
|
||||
if (dom.window.document.readyState !== 'complete') {
|
||||
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
|
||||
}
|
||||
window = dom.window;
|
||||
document = window.document;
|
||||
window.setInterval = () => 0;
|
||||
window.requestAnimationFrame = () => 0;
|
||||
window.CSS = { escape: (value: string) => value };
|
||||
window.eval(
|
||||
'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' +
|
||||
'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
|
||||
read('constants.js') +
|
||||
'\n' +
|
||||
read('tab-layout-browser.js') +
|
||||
'\n' +
|
||||
read('app.js') +
|
||||
'\n' +
|
||||
read('mobile-overview.js') +
|
||||
'\n' +
|
||||
read('webview-tabs.js') +
|
||||
'\n;window.__ClusterCodemanApp = CodemanApp;'
|
||||
);
|
||||
CodemanApp = window.__ClusterCodemanApp;
|
||||
});
|
||||
|
||||
function makeApp(arrangement: 'state' | 'case' | 'ledger' | 'classic' = 'case') {
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
|
||||
const root = document.documentElement;
|
||||
root.setAttribute('data-tab-orientation', 'horizontal');
|
||||
root.dataset.tabRailSort = 'activity';
|
||||
root.dataset.tabArrangement = arrangement;
|
||||
document.body.innerHTML = '<div class="session-tabs-host"><div id="sessionTabs" class="session-tabs"></div></div>';
|
||||
app.$ = (id: string) => document.getElementById(id);
|
||||
app.cases = [
|
||||
{ name: 'webshop', path: '/c/webshop' },
|
||||
{ name: 'api-gateway', path: '/c/api-gateway' },
|
||||
];
|
||||
app.sessions = new Map([
|
||||
['s1', { id: 's1', name: 'w1-webshop', status: 'idle', workingDir: '/c/webshop' }],
|
||||
['s2', { id: 's2', name: 'w75-api-gateway', status: 'busy', workingDir: '/c/api-gateway' }],
|
||||
['s3', { id: 's3', name: 'w3-webshop', status: 'idle', workingDir: '/c/webshop/sub' }],
|
||||
['s4', { id: 's4', name: 'landing', status: 'idle', workingDir: '/srv/landing/' }],
|
||||
['s5', { id: 's5', name: 'w4-webshop: fix login', status: 'busy', workingDir: '/c/webshop' }],
|
||||
]);
|
||||
app.sessionOrder = ['s1', 's2', 's3', 's4', 's5'];
|
||||
app.pendingHooks = new Map();
|
||||
app.webviews = new Map([['w1', { id: 'w1', name: 'Dashboard', url: 'https://example.test' }]]);
|
||||
app.webviewOrder = ['w1'];
|
||||
app.activeSessionId = 's2';
|
||||
app.activeWebviewId = null;
|
||||
app.tabLayout = null;
|
||||
app.collapsedTabGroupIds = new Set();
|
||||
app._hiddenTabGroupByRef = new Map();
|
||||
app._lastTabGroupStructureKey = null;
|
||||
app._inlineRenameActive = false;
|
||||
app.tabAlerts = new Map();
|
||||
app.terminalLoadStates = new Map();
|
||||
app.minimizedSubagents = new Map();
|
||||
app.hasTabDetachOverride = () => false;
|
||||
app.renderSubagentTabBadge = () => '';
|
||||
app.cancelHideSubagentDropdown = () => {};
|
||||
app.updateTabOverflowMode = () => {};
|
||||
app.updateConnectionLines = vi.fn();
|
||||
app._applyTabEntrances = () => {};
|
||||
app._scrollActiveTabIntoView = () => {};
|
||||
app._refreshMobileOverviewIfVisible = () => {};
|
||||
app._refreshHomeSessionsIfVisible = () => {};
|
||||
app.applySidebarFilter = () => {};
|
||||
return app;
|
||||
}
|
||||
|
||||
const container = () => document.getElementById('sessionTabs')!;
|
||||
const tab = (id: string) => container().querySelector<HTMLElement>(`.session-tab[data-id="${id}"]`)!;
|
||||
const boxes = () =>
|
||||
[...container().querySelectorAll<HTMLElement>(':scope > .tab-cluster')].map((box) => ({
|
||||
name: box.querySelector('.tab-cluster-name')?.textContent ?? null,
|
||||
count: box.querySelector('.tab-cluster-count')?.textContent ?? null,
|
||||
single: box.classList.contains('tab-cluster--single'),
|
||||
rows: [...box.querySelectorAll<HTMLElement>('.session-tab')].map((t) => t.dataset.id || `web:${t.dataset.webviewId}`),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('puts each case in one box, in first-appearance order, a web tab in its own', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('tabs-clusters')).toBe(true);
|
||||
expect(boxes()).toEqual([
|
||||
// s3 sits in a subdirectory of the case and still joins it.
|
||||
{ name: 'webshop', count: '3', single: false, rows: ['s1', 's3', 's5'] },
|
||||
{ name: 'api-gateway', count: '1', single: true, rows: ['s2'] },
|
||||
// No case matches: the directory names the cluster, trailing slash and all.
|
||||
{ name: 'landing', count: '1', single: true, rows: ['s4'] },
|
||||
{ name: null, count: null, single: true, rows: ['web:w1'] },
|
||||
]);
|
||||
for (const box of container().querySelectorAll<HTMLElement>(':scope > .tab-cluster:not(.tab-cluster--web)')) {
|
||||
expect(box.getAttribute('style')).toMatch(/^--cluster-color: var\(--session-(blue|green|purple|orange|pink|yellow|red)\)$/);
|
||||
expect(box.getAttribute('role')).toBe('presentation');
|
||||
}
|
||||
});
|
||||
|
||||
it('drops the case from a generated name inside a box with company, and only there', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
const nameOf = (id: string) => tab(id).querySelector('.tab-name')!;
|
||||
expect(nameOf('s1').innerHTML).toBe('w1<span class="tab-name-case">-webshop</span>');
|
||||
expect(nameOf('s1').textContent).toBe('w1-webshop');
|
||||
expect(tab('s1').getAttribute('aria-label')).toContain('w1-webshop');
|
||||
// A described name keeps its #232 treatment.
|
||||
expect(nameOf('s5').querySelector('.tab-name-prefix')?.textContent).toBe('w4-webshop: ');
|
||||
// Alone in its box, nothing is redundant, so nothing is hidden.
|
||||
expect(nameOf('s2').innerHTML).toBe('w75-api-gateway');
|
||||
});
|
||||
|
||||
it('keeps the Alt+N badges on the tab order', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
expect(tab('s3').querySelector('.tab-number')?.textContent).toBe('3');
|
||||
expect(tab('s2').querySelector('.tab-number')?.textContent).toBe('2');
|
||||
expect(container().querySelector('.session-tab[data-webview-id="w1"] .tab-number')?.textContent).toBe('6');
|
||||
});
|
||||
|
||||
it('patches in place while the clusters stay the same, and rebuilds when they change', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
const s1 = tab('s1');
|
||||
const full = vi.spyOn(app, '_fullRenderSessionTabs');
|
||||
app.sessions.get('s1').status = 'busy';
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(full).not.toHaveBeenCalled();
|
||||
expect(tab('s1')).toBe(s1);
|
||||
// s4 moves into the webshop case: a different box, so a full rebuild.
|
||||
app.sessions.get('s4').workingDir = '/c/webshop';
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(full).toHaveBeenCalledTimes(1);
|
||||
expect(boxes()[0].rows).toEqual(['s1', 's3', 's4', 's5']);
|
||||
});
|
||||
|
||||
it('only accepts a drop inside the same box', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
app.draggedTabId = 's1';
|
||||
expect(app._isTabDropAcrossGroups(tab('s3'))).toBe(false);
|
||||
expect(app._isTabDropAcrossGroups(tab('s2'))).toBe(true);
|
||||
});
|
||||
|
||||
it('lets named groups in the vertical rail win', () => {
|
||||
const app = makeApp();
|
||||
document.documentElement.setAttribute('data-tab-orientation', 'vertical');
|
||||
app.tabLayout = {
|
||||
version: 1,
|
||||
groups: [{ id: 'g1', name: 'Core', refs: [{ kind: 'session', id: 's1' }] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
app._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('session-tabs--grouped')).toBe(true);
|
||||
expect(container().classList.contains('tabs-clusters')).toBe(false);
|
||||
expect(container().querySelector('.tab-cluster, .tab-name-case')).toBeNull();
|
||||
});
|
||||
|
||||
it('switching back to classic leaves no boxes and no name splits', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
document.documentElement.dataset.tabArrangement = 'classic';
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(container().querySelector('.tab-cluster, .tab-name-case')).toBeNull();
|
||||
expect(container().classList.contains('tabs-clusters')).toBe(false);
|
||||
});
|
||||
|
||||
it('draws the ledger with the classic markup and one class', () => {
|
||||
makeApp('classic')._fullRenderSessionTabs();
|
||||
const classic = container().innerHTML;
|
||||
makeApp('ledger')._fullRenderSessionTabs();
|
||||
expect(container().innerHTML).toBe(classic);
|
||||
expect(container().classList.contains('tabs-ledger')).toBe(true);
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tab layouts by case and ledger (static)', () => {
|
||||
const css = read('styles.css');
|
||||
const mobileCss = read('mobile.css');
|
||||
|
||||
it('hides the case part of a name only in the clustered strip', () => {
|
||||
expect(css).toMatch(/\.session-tabs\.tabs-clusters \.tab-name-case \{\s*display: none;/);
|
||||
});
|
||||
|
||||
it('keeps the ledger to the desktop header strip', () => {
|
||||
const media = css.indexOf('@media (min-width: 768px) {\n .session-tabs-host > .session-tabs.tabs-ledger {');
|
||||
expect(media).toBeGreaterThan(-1);
|
||||
// Every ledger rule lives inside that block.
|
||||
const before = css.slice(0, media);
|
||||
expect(before).not.toContain('.tabs-ledger');
|
||||
});
|
||||
|
||||
it('keeps every ledger row one height and makes the active cell stand out', () => {
|
||||
const ledger = css.slice(css.indexOf('@media (min-width: 768px) {\n .session-tabs-host > .session-tabs.tabs-ledger {'));
|
||||
expect(ledger).toContain('align-items: stretch;');
|
||||
expect(ledger).toContain('min-height: 30px;');
|
||||
expect(ledger).toMatch(
|
||||
/\.tabs-ledger > \.session-tab\.active \{[^}]*box-shadow: inset 0 0 0 1px var\(--accent\), inset 4px 0 0 var\(--accent\) !important;/
|
||||
);
|
||||
});
|
||||
|
||||
it('dissolves the boxes into the one chip row on phones', () => {
|
||||
expect(mobileCss).toMatch(
|
||||
/:where\(\.header\) \.session-tabs-host > \.session-tabs\.tabs-clusters > \.tab-cluster \{\s*display: contents;/
|
||||
);
|
||||
expect(mobileCss).toMatch(/:where\(\.header\) \.tab-cluster-label \{\s*display: none;/);
|
||||
});
|
||||
});
|
||||
+11
-10
@@ -205,10 +205,11 @@ describe('vertical tab rail row order', () => {
|
||||
it('keeps the Alt+N badge on the tab index while the cards are sorted', () => {
|
||||
// `_tabIdx` counts the loop over sessionOrder, and only `style="order:…"`
|
||||
// moves the card — so the badge names a shortcut, not a row position.
|
||||
expect(appJs).toContain(
|
||||
'const railSortOrder = this._tabRailSortOrder(tabOrder.filter((id) => this.sessions.has(id)));'
|
||||
);
|
||||
expect(appJs).toContain('` style="order:${railSortOrder.get(id)}"`');
|
||||
// `listOrder` is the rail sort's map, or the state grouping's when that is
|
||||
// on (test/tab-triage.test.ts); either way it only sets the inline order.
|
||||
expect(appJs).toContain('const liveIds = tabOrder.filter((id) => this.sessions.has(id));');
|
||||
expect(appJs).toContain('const railSortOrder = this._tabRailSortOrder(liveIds);');
|
||||
expect(appJs).toContain('` style="order:${listOrder.get(id)}"`');
|
||||
expect(appJs).toMatch(/_tabIdx < 9 \? '<span class="tab-number">' \+ \(_tabIdx \+ 1\)/);
|
||||
// The loop itself still walks the user's order, which is what makes the
|
||||
// badge, drag-and-drop and the arrow-key walk agree with each other.
|
||||
@@ -219,12 +220,11 @@ describe('vertical tab rail row order', () => {
|
||||
// A session going working→idle never adds or removes a tab, so the full
|
||||
// rebuild is not reached — and a rebuild here would restart every card's
|
||||
// animation on every SSE tick anyway.
|
||||
expect(appJs).toContain(
|
||||
'const railSortOrder = this._tabRailSortOrder(this.sessionOrder.filter((sid) => this.sessions.has(sid)));'
|
||||
);
|
||||
expect(appJs).toContain('const liveIds = this.sessionOrder.filter((sid) => this.sessions.has(sid));');
|
||||
expect(appJs).toContain('const railSortOrder = this._tabRailSortOrder(liveIds);');
|
||||
expect(appJs).toContain('if (tab.style.order !== railOrder) tab.style.order = railOrder;');
|
||||
// An empty string is what clears the property when the rail stops sorting.
|
||||
expect(appJs).toContain("const railOrder = railSortOrder?.has(id) ? String(railSortOrder.get(id)) : '';");
|
||||
expect(appJs).toContain("const railOrder = listOrder?.has(id) ? String(listOrder.get(id)) : '';");
|
||||
});
|
||||
|
||||
it('drops the drag affordance while sorting, so a card cannot snap back', () => {
|
||||
@@ -280,9 +280,10 @@ describe('vertical tab rail sort setting', () => {
|
||||
expect(html).toContain("document.documentElement.dataset.tabRailSort='activity';");
|
||||
expect(settingsUi).toContain('root.dataset.tabRailSort = sort;');
|
||||
// A sort flip leaves orientation on 'vertical' both times, so it has to
|
||||
// count as a change of its own or nothing re-renders.
|
||||
// count as a change of its own or nothing re-renders. The same holds for a
|
||||
// tab layout or state order flip (test/tab-triage.test.ts).
|
||||
expect(settingsUi).toContain(
|
||||
'const changed = orientationChanged || previousDetail !== detail || previousSort !== sort;'
|
||||
'const changed = orientationChanged || previousDetail !== detail || previousSort !== sort || previousArrangement !== arrangement || previousStateOrder !== stateOrder;'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
/**
|
||||
* @fileoverview Tab grouping by state (`tabArrangement: 'state'`, Discussion #426
|
||||
* option C): the pure layout in constants.js and the render paths in app.js.
|
||||
*
|
||||
* What is pinned, and why it matters:
|
||||
* - The four groups and their order (needs you, waiting, working, idle) and
|
||||
* which home-screen state lands in which, including the two folds that are
|
||||
* easy to get wrong: a failed session joins "needs you", and an agent that
|
||||
* exited inside a live pane (#446) is idle even while its status says busy.
|
||||
* - It is applied as flex `order` only. The DOM stays in tab order, so Alt+N
|
||||
* badges, drag and the keyboard walk keep reading the list they always read.
|
||||
* - A state change is an INCREMENTAL pass: the tab element survives, only its
|
||||
* `order` and the heading counts move, and a group that empties loses its
|
||||
* heading.
|
||||
* - `tabArrangement: 'classic'` leaves no trace (no headings, no inline order, no
|
||||
* class), and named groups in the vertical rail win over it.
|
||||
*
|
||||
* The real modules run INSIDE a JSDOM window (runScripts: 'outside-only'), so
|
||||
* `document` below is that window's.
|
||||
*
|
||||
* Port: none.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = join(process.cwd(), 'src/web/public');
|
||||
const read = (name: string) => readFileSync(join(PUBLIC, name), 'utf8');
|
||||
|
||||
type Row = { id: string; state: string; exited?: boolean; pos?: number };
|
||||
type Layout = {
|
||||
order: Map<string, number>;
|
||||
webOrder: Map<string, number>;
|
||||
groups: Array<{ key: string; label: string; count: number; headOrder: number; breakOrder: number }>;
|
||||
};
|
||||
type Triage = {
|
||||
GROUPS: Array<{ key: string; label: string }>;
|
||||
STRIDE: number;
|
||||
groupFor: (state: string, exited: boolean) => string;
|
||||
layout: (rows: Row[], webviewIds?: string[]) => Layout;
|
||||
};
|
||||
|
||||
function loadTriage(): Triage {
|
||||
const context = vm.createContext({ window: {}, globalThis: {} });
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
return (context.window as { CodemanTabTriage: Triage }).CodemanTabTriage;
|
||||
}
|
||||
|
||||
describe('CodemanTabTriage (pure)', () => {
|
||||
const triage = loadTriage();
|
||||
|
||||
it('has four groups, most urgent first', () => {
|
||||
expect(triage.GROUPS.map((g) => g.key)).toEqual(['needs', 'waiting', 'working', 'idle']);
|
||||
expect(triage.GROUPS.map((g) => g.label)).toEqual(['Needs you', 'Waiting', 'Working', 'Idle']);
|
||||
// Only idle is quiet: it keeps a heading element but draws no label.
|
||||
expect(triage.GROUPS.filter((g) => (g as { quiet?: boolean }).quiet).map((g) => g.key)).toEqual(['idle']);
|
||||
});
|
||||
|
||||
it('folds the six home-screen states into the four groups', () => {
|
||||
expect(triage.groupFor('needs', false)).toBe('needs');
|
||||
expect(triage.groupFor('error', false)).toBe('needs');
|
||||
expect(triage.groupFor('waiting', false)).toBe('waiting');
|
||||
expect(triage.groupFor('working', false)).toBe('working');
|
||||
expect(triage.groupFor('idle', false)).toBe('idle');
|
||||
expect(triage.groupFor('done', false)).toBe('idle');
|
||||
expect(triage.groupFor('something-new', false)).toBe('idle');
|
||||
});
|
||||
|
||||
it('puts an exited agent with idle, never with working', () => {
|
||||
expect(triage.groupFor('working', true)).toBe('idle');
|
||||
expect(triage.groupFor('idle', true)).toBe('idle');
|
||||
// A human being blocked still outranks the agent having exited.
|
||||
expect(triage.groupFor('needs', true)).toBe('needs');
|
||||
expect(triage.groupFor('waiting', true)).toBe('waiting');
|
||||
});
|
||||
|
||||
it('gives each group a band of order values and lists only non-empty groups', () => {
|
||||
const out = triage.layout([
|
||||
{ id: 'a', state: 'idle', pos: 0 },
|
||||
{ id: 'b', state: 'needs', pos: 1 },
|
||||
{ id: 'c', state: 'idle', pos: 2 },
|
||||
]);
|
||||
expect(out.groups.map((g) => [g.key, g.count])).toEqual([
|
||||
['needs', 1],
|
||||
['idle', 2],
|
||||
]);
|
||||
const needs = out.groups[0];
|
||||
const idle = out.groups[1];
|
||||
expect(out.order.get('b')).toBeGreaterThan(needs.headOrder);
|
||||
expect(out.order.get('b')).toBeLessThan(needs.breakOrder);
|
||||
// Rows keep their relative position inside a group.
|
||||
expect(out.order.get('a')).toBeLessThan(out.order.get('c')!);
|
||||
expect(out.order.get('a')).toBeGreaterThan(idle.headOrder);
|
||||
// A heading opens its band, the break closes it, and bands never overlap.
|
||||
expect(needs.breakOrder).toBeLessThan(idle.headOrder);
|
||||
expect(Math.floor(out.order.get('b')! / triage.STRIDE)).toBe(Math.floor(needs.headOrder / triage.STRIDE));
|
||||
});
|
||||
|
||||
it('ranks rows inside a group by `pos`, stably', () => {
|
||||
const out = triage.layout([
|
||||
{ id: 'x', state: 'working', pos: 5 },
|
||||
{ id: 'y', state: 'working', pos: 1 },
|
||||
{ id: 'z', state: 'working', pos: 1 },
|
||||
]);
|
||||
const sorted = [...out.order.entries()].sort((p, q) => p[1] - q[1]).map(([id]) => id);
|
||||
expect(sorted).toEqual(['y', 'z', 'x']);
|
||||
});
|
||||
|
||||
it('closes the idle group with the web tabs and counts them', () => {
|
||||
const out = triage.layout([{ id: 's', state: 'idle', pos: 0 }], ['w1', 'w2']);
|
||||
expect(out.groups).toHaveLength(1);
|
||||
expect(out.groups[0]).toMatchObject({ key: 'idle', count: 3 });
|
||||
expect(out.webOrder.get('w1')).toBeGreaterThan(out.order.get('s')!);
|
||||
expect(out.webOrder.get('w2')).toBeGreaterThan(out.webOrder.get('w1')!);
|
||||
expect(out.webOrder.get('w2')).toBeLessThan(out.groups[0].breakOrder);
|
||||
});
|
||||
|
||||
it('turns the groups the other way up with reverse, rows unchanged inside them', () => {
|
||||
const rows = [
|
||||
{ id: 'a', state: 'idle', pos: 0 },
|
||||
{ id: 'b', state: 'needs', pos: 1 },
|
||||
{ id: 'c', state: 'working', pos: 2 },
|
||||
{ id: 'd', state: 'working', pos: 3 },
|
||||
];
|
||||
const out = triage.layout(rows, ['w1'], { reverse: true });
|
||||
expect(out.groups.map((g) => g.key)).toEqual(['idle', 'working', 'needs']);
|
||||
const sorted = [...out.order.entries()].sort((p, q) => p[1] - q[1]).map(([id]) => id);
|
||||
expect(sorted).toEqual(['a', 'c', 'd', 'b']);
|
||||
// Web tabs still close the idle group, which now comes first.
|
||||
expect(out.webOrder.get('w1')).toBeLessThan(out.order.get('c')!);
|
||||
for (let i = 1; i < out.groups.length; i++) {
|
||||
expect(out.groups[i].headOrder).toBeGreaterThan(out.groups[i - 1].breakOrder);
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the idle group for web tabs alone, and nothing for nothing', () => {
|
||||
expect(triage.layout([], ['w1']).groups.map((g) => g.key)).toEqual(['idle']);
|
||||
expect(triage.layout([], []).groups).toEqual([]);
|
||||
expect(triage.layout(undefined as unknown as Row[], undefined).groups).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tab grouping in the render paths (app.js)', () => {
|
||||
let CodemanApp: { prototype: Record<string, any> };
|
||||
let window: any;
|
||||
let document: Document;
|
||||
|
||||
beforeAll(async () => {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
|
||||
url: 'https://localhost/',
|
||||
runScripts: 'outside-only',
|
||||
});
|
||||
if (dom.window.document.readyState !== 'complete') {
|
||||
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
|
||||
}
|
||||
window = dom.window;
|
||||
document = window.document;
|
||||
window.setInterval = () => 0;
|
||||
window.requestAnimationFrame = () => 0;
|
||||
window.CSS = { escape: (value: string) => value };
|
||||
window.eval(
|
||||
'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' +
|
||||
'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
|
||||
read('constants.js') +
|
||||
'\n' +
|
||||
read('tab-layout-browser.js') +
|
||||
'\n' +
|
||||
read('app.js') +
|
||||
'\n' +
|
||||
read('mobile-overview.js') +
|
||||
'\n' +
|
||||
read('webview-tabs.js') +
|
||||
'\n;window.__TriageCodemanApp = CodemanApp;'
|
||||
);
|
||||
CodemanApp = window.__TriageCodemanApp;
|
||||
});
|
||||
|
||||
function makeApp(arrangement: 'state' | 'case' | 'ledger' | 'classic' = 'state') {
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
|
||||
const root = document.documentElement;
|
||||
root.setAttribute('data-tab-orientation', 'horizontal');
|
||||
root.dataset.tabRailSort = 'activity';
|
||||
root.dataset.tabArrangement = arrangement;
|
||||
delete root.dataset.tabStateOrder;
|
||||
document.body.innerHTML = '<div class="session-tabs-host"><div id="sessionTabs" class="session-tabs"></div></div>';
|
||||
app.$ = (id: string) => document.getElementById(id);
|
||||
app.sessions = new Map([
|
||||
['s1', { id: 's1', name: 'w1-alpha', status: 'idle' }],
|
||||
['s2', { id: 's2', name: 'w2-beta', status: 'busy' }],
|
||||
['s3', { id: 's3', name: 'w3-gamma', status: 'idle' }],
|
||||
['s4', { id: 's4', name: 'w4-delta', status: 'busy' }],
|
||||
]);
|
||||
app.sessionOrder = ['s1', 's2', 's3', 's4'];
|
||||
app.pendingHooks = new Map([
|
||||
['s3', new Set(['permission_prompt'])],
|
||||
['s1', new Set(['idle_prompt'])],
|
||||
]);
|
||||
app.webviews = new Map([['w1', { id: 'w1', name: 'Dashboard', url: 'https://example.test' }]]);
|
||||
app.webviewOrder = ['w1'];
|
||||
app.activeSessionId = 's2';
|
||||
app.activeWebviewId = null;
|
||||
app.tabLayout = null;
|
||||
app.collapsedTabGroupIds = new Set();
|
||||
app._hiddenTabGroupByRef = new Map();
|
||||
app._lastTabGroupStructureKey = null;
|
||||
app._inlineRenameActive = false;
|
||||
app.tabAlerts = new Map();
|
||||
app.terminalLoadStates = new Map();
|
||||
app.minimizedSubagents = new Map();
|
||||
app.hasTabDetachOverride = () => false;
|
||||
app.renderSubagentTabBadge = () => '';
|
||||
app.cancelHideSubagentDropdown = () => {};
|
||||
app.updateTabOverflowMode = () => {};
|
||||
app.updateConnectionLines = vi.fn();
|
||||
app._applyTabEntrances = () => {};
|
||||
app._scrollActiveTabIntoView = () => {};
|
||||
app._refreshMobileOverviewIfVisible = () => {};
|
||||
app._refreshHomeSessionsIfVisible = () => {};
|
||||
app.applySidebarFilter = () => {};
|
||||
return app;
|
||||
}
|
||||
|
||||
const container = () => document.getElementById('sessionTabs')!;
|
||||
const tab = (id: string) => container().querySelector<HTMLElement>(`.session-tab[data-id="${id}"]`)!;
|
||||
const orderOf = (el: HTMLElement) => Number(el.style.order);
|
||||
/** What the eye sees: every ordered child, by `order`, as `head:<key>` / `<id>`. */
|
||||
const visual = () =>
|
||||
[...container().children]
|
||||
.filter((el) => !(el as HTMLElement).classList.contains('tab-triage-break'))
|
||||
.sort((a, b) => orderOf(a as HTMLElement) - orderOf(b as HTMLElement))
|
||||
.map((el) => {
|
||||
const h = el as HTMLElement;
|
||||
if (h.classList.contains('tab-triage-head')) return `head:${h.dataset.triageGroup}`;
|
||||
return h.dataset.webviewId ? `web:${h.dataset.webviewId}` : h.dataset.id!;
|
||||
});
|
||||
const heads = () =>
|
||||
[...container().querySelectorAll<HTMLElement>(':scope > .tab-triage-head')]
|
||||
.sort((a, b) => orderOf(a) - orderOf(b))
|
||||
.map((h) =>
|
||||
h.classList.contains('tab-triage-head--quiet')
|
||||
? `${h.dataset.triageGroup}:quiet`
|
||||
: `${h.querySelector('.tab-triage-label')!.textContent}:${h.querySelector('.tab-triage-count')!.textContent}`
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('draws a heading per non-empty state and places every tab in its group', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('tabs-triage')).toBe(true);
|
||||
expect(heads()).toEqual(['Needs you:1', 'Waiting:1', 'Working:2', 'idle:quiet']);
|
||||
// The idle row keeps its heading as an anchor, with nothing drawn in it.
|
||||
expect(container().querySelector('.tab-triage-head[data-triage-group="idle"]')!.textContent).toBe('');
|
||||
expect(visual()).toEqual([
|
||||
'head:needs',
|
||||
's3',
|
||||
'head:waiting',
|
||||
's1',
|
||||
'head:working',
|
||||
's2',
|
||||
's4',
|
||||
'head:idle',
|
||||
'web:w1',
|
||||
]);
|
||||
// One row break per heading; headings and breaks stay out of the tablist.
|
||||
expect(container().querySelectorAll(':scope > .tab-triage-break')).toHaveLength(4);
|
||||
for (const el of container().querySelectorAll(':scope > .tab-triage-head, :scope > .tab-triage-break')) {
|
||||
expect(el.getAttribute('aria-hidden')).toBe('true');
|
||||
}
|
||||
});
|
||||
|
||||
it("puts needs you in the bottom row with tabStateOrder 'urgent-last'", () => {
|
||||
const app = makeApp();
|
||||
document.documentElement.dataset.tabStateOrder = 'urgent-last';
|
||||
app._fullRenderSessionTabs();
|
||||
expect(heads()).toEqual(['idle:quiet', 'Working:2', 'Waiting:1', 'Needs you:1']);
|
||||
expect(visual()).toEqual([
|
||||
'head:idle',
|
||||
'web:w1',
|
||||
'head:working',
|
||||
's2',
|
||||
's4',
|
||||
'head:waiting',
|
||||
's1',
|
||||
'head:needs',
|
||||
's3',
|
||||
]);
|
||||
});
|
||||
|
||||
it('marks the first row heading as the lead, in either state order', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
const lead = () =>
|
||||
[...container().querySelectorAll<HTMLElement>(':scope > .tab-triage-head--lead')].map((h) => h.dataset.triageGroup);
|
||||
expect(lead()).toEqual(['needs']);
|
||||
document.documentElement.dataset.tabStateOrder = 'urgent-last';
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(lead()).toEqual(['idle']);
|
||||
});
|
||||
|
||||
it('keeps the DOM, and with it the Alt+N badges, in tab order', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
const domOrder = [...container().querySelectorAll<HTMLElement>('.session-tab[data-id]')].map((t) => t.dataset.id);
|
||||
expect(domOrder).toEqual(['s1', 's2', 's3', 's4']);
|
||||
expect(tab('s3').querySelector('.tab-number')?.textContent).toBe('3');
|
||||
});
|
||||
|
||||
it('moves a tab between groups on an incremental pass, without rebuilding it', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
const s2 = tab('s2');
|
||||
const fullRender = vi.spyOn(app, '_fullRenderSessionTabs');
|
||||
// s2 finishes its turn; the dialog on s3 is answered.
|
||||
app.sessions.get('s2').status = 'idle';
|
||||
app.pendingHooks.delete('s3');
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(fullRender).not.toHaveBeenCalled();
|
||||
expect(tab('s2')).toBe(s2);
|
||||
expect(heads()).toEqual(['Waiting:1', 'Working:1', 'idle:quiet']);
|
||||
expect(container().querySelector('.tab-triage-head[data-triage-group="needs"]')).toBeNull();
|
||||
expect(container().querySelector('.tab-triage-break[data-triage-group="needs"]')).toBeNull();
|
||||
expect(visual()).toEqual(['head:waiting', 's1', 'head:working', 's4', 'head:idle', 's2', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it('reconciles headings in place: an unchanged pass rewrites nothing', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
app._renderSessionTabsImmediate();
|
||||
const head = container().querySelector('.tab-triage-head[data-triage-group="working"]');
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(container().querySelector('.tab-triage-head[data-triage-group="working"]')).toBe(head);
|
||||
expect(container().querySelectorAll(':scope > .tab-triage-head')).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('files an agent that exited in a live pane under idle, a failed session under needs you', () => {
|
||||
const app = makeApp();
|
||||
app.pendingHooks = new Map();
|
||||
app.sessions.get('s2').paneExit = { at: 1, status: 0 };
|
||||
app.sessions.get('s1').status = 'error';
|
||||
app._fullRenderSessionTabs();
|
||||
expect(visual()).toEqual(['head:needs', 's1', 'head:working', 's4', 'head:idle', 's2', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it("leaves no trace with tabArrangement 'classic'", () => {
|
||||
makeApp('classic')._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
expect(container().querySelector('.tab-triage-head, .tab-triage-break')).toBeNull();
|
||||
expect(container().innerHTML).not.toContain('order:');
|
||||
expect(container().querySelector<HTMLElement>('.session-tab[data-webview-id]')!.style.order).toBe('');
|
||||
});
|
||||
|
||||
it('switching off removes the headings and every inline order it wrote', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
document.documentElement.dataset.tabArrangement = 'classic';
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(container().querySelector('.tab-triage-head, .tab-triage-break')).toBeNull();
|
||||
for (const el of container().querySelectorAll<HTMLElement>('.session-tab')) expect(el.style.order).toBe('');
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
});
|
||||
|
||||
it('ranks rows inside each section by the activity sort on a sorted rail', () => {
|
||||
const app = makeApp();
|
||||
document.documentElement.setAttribute('data-tab-orientation', 'vertical');
|
||||
app.pendingHooks = new Map();
|
||||
// Both working; s4 has been running longer, so the activity sort puts it first.
|
||||
app.sessions.get('s2').lastSubmitAt = 2_000;
|
||||
app.sessions.get('s4').lastSubmitAt = 1_000;
|
||||
app._fullRenderSessionTabs();
|
||||
expect(visual()).toEqual(['head:working', 's4', 's2', 'head:idle', 's1', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it('keeps tab order inside each row on the header strip', () => {
|
||||
const app = makeApp();
|
||||
app.pendingHooks = new Map();
|
||||
app.sessions.get('s2').lastSubmitAt = 2_000;
|
||||
app.sessions.get('s4').lastSubmitAt = 1_000;
|
||||
app._fullRenderSessionTabs();
|
||||
expect(visual()).toEqual(['head:working', 's2', 's4', 'head:idle', 's1', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it('lets named groups in the vertical rail win', () => {
|
||||
const app = makeApp();
|
||||
document.documentElement.setAttribute('data-tab-orientation', 'vertical');
|
||||
app.tabLayout = {
|
||||
version: 1,
|
||||
groups: [{ id: 'g1', name: 'Core', refs: [{ kind: 'session', id: 's1' }] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
app._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('session-tabs--grouped')).toBe(true);
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
expect(container().querySelector('.tab-triage-head')).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses a drop into another group and allows one inside the same group', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
app.draggedTabId = 's2';
|
||||
expect(app._isTabDropAcrossGroups(tab('s4'))).toBe(false);
|
||||
expect(app._isTabDropAcrossGroups(tab('s1'))).toBe(true);
|
||||
expect(app._isTabDropAcrossGroups(tab('s3'))).toBe(true);
|
||||
document.documentElement.dataset.tabArrangement = 'classic';
|
||||
app._fullRenderSessionTabs();
|
||||
expect(app._isTabDropAcrossGroups(tab('s1'))).toBe(false);
|
||||
});
|
||||
|
||||
it('degrades to the flat strip when mobile-overview.js is stale or missing', () => {
|
||||
const app = makeApp();
|
||||
app._mobileOverviewState = undefined;
|
||||
app._fullRenderSessionTabs();
|
||||
expect(container().querySelector('.tab-triage-head')).toBeNull();
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tab grouping wiring (static)', () => {
|
||||
const html = read('index.html');
|
||||
const css = read('styles.css');
|
||||
const mobileCss = read('mobile.css');
|
||||
|
||||
it('stamps data-tab-arrangement and data-tab-state-order before first paint', () => {
|
||||
expect(html).toContain(
|
||||
"dataset.tabArrangement=(T==='case'||T==='ledger'||T==='classic')?T:'state'"
|
||||
);
|
||||
expect(html).toContain("dataset.tabStateOrder=(A.tabStateOrder==='urgent-last')?'urgent-last':'urgent-first'");
|
||||
// The catch branch (localStorage threw) must set both too.
|
||||
expect(html).toContain(
|
||||
"document.documentElement.dataset.tabArrangement='state';document.documentElement.dataset.tabStateOrder='urgent-first';"
|
||||
);
|
||||
});
|
||||
|
||||
it('offers the four layouts with "By state" as the default, and the state order', () => {
|
||||
expect(html).toMatch(
|
||||
/<select id="appSettingsTabArrangement"[^>]*>\s*<option value="state">By state \(default\)<\/option>\s*<option value="case">[^<]+<\/option>\s*<option value="ledger">[^<]+<\/option>\s*<option value="classic">Classic \(as before\)<\/option>/
|
||||
);
|
||||
expect(html).toMatch(
|
||||
/<select id="appSettingsTabStateOrder"[^>]*>\s*<option value="urgent-first">Needs you on top \(default\)<\/option>\s*<option value="urgent-last">/
|
||||
);
|
||||
});
|
||||
|
||||
it('only shows row breaks in a wrapping header strip', () => {
|
||||
expect(css).toMatch(/\.tab-triage-break \{\s*display: none;/);
|
||||
expect(css).toContain(
|
||||
'.session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows) > .tab-triage-break'
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the rows after the first start under the brand, labels left-aligned', () => {
|
||||
expect(css).toMatch(
|
||||
/\.header:has\(> \.session-tabs-host > \.session-tabs\.tabs-triage:is\(\.tabs-auto-wrap, \.tabs-two-rows\)\) > \.header-brand \{\s*position: absolute;/
|
||||
);
|
||||
expect(css).toMatch(/> \.tab-triage-head \{\s*justify-content: flex-start;/);
|
||||
expect(css).toMatch(
|
||||
/> \.tab-triage-head--lead \{\s*width: auto;\s*margin-left: calc\(var\(--tab-triage-brand, 100px\) - var\(--tab-triage-gutter, 92px\)\);/
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the headings on phones, whose strip stays one scrolling row', () => {
|
||||
expect(mobileCss).toMatch(/:where\(\.header\) \.tab-triage-head \{\s*display: none;/);
|
||||
});
|
||||
});
|
||||
@@ -63,13 +63,7 @@ function fakeTerminal(options: Record<string, unknown> = {}) {
|
||||
return { options: { fontFamily: '"JetBrains Mono"', fontSize: 14, ...options } };
|
||||
}
|
||||
|
||||
function makeApp(
|
||||
opts: {
|
||||
teammates?: number;
|
||||
terminal?: ReturnType<typeof fakeTerminal> | null;
|
||||
splitPane?: { terminal: ReturnType<typeof fakeTerminal>; fit: () => void } | null;
|
||||
} = {}
|
||||
) {
|
||||
function makeApp(opts: { teammates?: number; terminal?: ReturnType<typeof fakeTerminal> | null } = {}) {
|
||||
const fit = vi.fn();
|
||||
const teammateFits: ReturnType<typeof vi.fn>[] = [];
|
||||
const teammateTerminals = new Map<string, { terminal: ReturnType<typeof fakeTerminal>; fitAddon: unknown }>();
|
||||
@@ -80,10 +74,6 @@ function makeApp(
|
||||
}
|
||||
const app = {
|
||||
applyTerminalFontWeights: mixin.applyTerminalFontWeights,
|
||||
// Secondary panes (the split pane's second terminal) are reached through
|
||||
// this helper, so it is wired for real like the geometry chain below.
|
||||
_forEachTile: mixin._forEachTile,
|
||||
_splitPane: opts.splitPane ?? null,
|
||||
// The REAL geometry chain, not stubs. A font change moves the cell size, so
|
||||
// it moves cols/rows, and `applyTerminalFontWeights` now routes its refit
|
||||
// through the one function that floors the result and reports it (#464).
|
||||
@@ -108,23 +98,6 @@ function makeApp(
|
||||
}
|
||||
|
||||
describe('applyTerminalFontWeights', () => {
|
||||
it('reaches an open split pane: same weights, refit AND reported to its PTY', () => {
|
||||
const splitTerminal = fakeTerminal();
|
||||
// fit(), not localFit(): a weight change can move the cell size, and the
|
||||
// split pane's PTY must hear about the new geometry like the primary's does.
|
||||
const fit = vi.fn();
|
||||
const { app } = makeApp({ splitPane: { terminal: splitTerminal, fit } });
|
||||
|
||||
(app as unknown as { applyTerminalFontWeights: (s: unknown) => void }).applyTerminalFontWeights({
|
||||
terminalFontWeight: '300',
|
||||
terminalFontWeightBold: '700',
|
||||
});
|
||||
|
||||
expect(splitTerminal.options.fontWeight).toBe(300);
|
||||
expect(splitTerminal.options.fontWeightBold).toBe(700);
|
||||
expect(fit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('writes both slots to the live terminal', () => {
|
||||
const { app, fit } = makeApp();
|
||||
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
/**
|
||||
* @fileoverview The file-path / URL link provider can serve a second terminal.
|
||||
*
|
||||
* `registerFilePathLinkProvider()` (terminal-ui.js) was hardwired to the
|
||||
* primary terminal and the ACTIVE session: a path clicked anywhere opened
|
||||
* against `activeSessionId`. It now takes an optional target `{ terminal,
|
||||
* getSessionId, setHovered }`, so the split pane's second terminal (and later a
|
||||
* grid tile) gets clickable paths that open against ITS session. With no target
|
||||
* it behaves exactly as before, and only the primary registration is kept on
|
||||
* `_terminalLinkProvider`, which the touch-tap path reads.
|
||||
*
|
||||
* Real code under test: constants.js + terminal-ui.js in a `vm` context.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type Link = { text: string; activate: (ev: unknown, text: string) => void; hover: () => void; leave: () => void };
|
||||
type Provider = { provideLinks: (line: number, cb: (links: Link[] | undefined) => void) => void };
|
||||
|
||||
function loadHarness() {
|
||||
const CodemanApp = function CodemanApp(this: unknown) {};
|
||||
const windowRef: Record<string, unknown> = {};
|
||||
const context = vm.createContext({
|
||||
window: windowRef,
|
||||
document: {
|
||||
body: { classList: { contains: () => false } },
|
||||
activeElement: null,
|
||||
addEventListener: vi.fn(),
|
||||
getElementById: () => null,
|
||||
},
|
||||
CodemanApp,
|
||||
console: { warn: vi.fn(), log: vi.fn(), debug: vi.fn() },
|
||||
_crashDiag: { log: vi.fn() },
|
||||
performance: { now: () => 0 },
|
||||
requestAnimationFrame: () => 1,
|
||||
setTimeout: () => 1,
|
||||
MobileDetection: { isTouchDevice: () => false },
|
||||
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
|
||||
TERMINAL_CHUNK_SIZE: 32 * 1024,
|
||||
});
|
||||
const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../src/web/public/${f}`), 'utf8');
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
vm.runInContext(read('terminal-ui.js'), context, { filename: 'terminal-ui.js' });
|
||||
return new (CodemanApp as unknown as new () => Record<string, any>)();
|
||||
}
|
||||
|
||||
/** A one-screen xterm stand-in holding `lines`, recording every provider registered on it. */
|
||||
function fakeTerminal(lines: string[]) {
|
||||
const providers: Provider[] = [];
|
||||
return {
|
||||
cols: 80,
|
||||
providers,
|
||||
registerLinkProvider: (p: Provider) => providers.push(p),
|
||||
buffer: {
|
||||
active: {
|
||||
length: lines.length,
|
||||
getLine: (row: number) =>
|
||||
row >= 0 && row < lines.length
|
||||
? {
|
||||
isWrapped: false,
|
||||
translateToString: (trim?: boolean) => (trim === false ? lines[row].padEnd(80) : lines[row]),
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function linksOn(provider: Provider, line: number): Link[] {
|
||||
let out: Link[] = [];
|
||||
provider.provideLinks(line, (links) => {
|
||||
out = links || [];
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeApp() {
|
||||
const app = loadHarness();
|
||||
app.activeSessionId = 'primary-session';
|
||||
app.openFilePreview = vi.fn();
|
||||
app.openLogViewerWindow = vi.fn();
|
||||
app._isExternalPreviewPath = () => false;
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('registerFilePathLinkProvider with no target (the primary pane)', () => {
|
||||
it('registers on the primary terminal, keeps the provider for the tap path, opens against the active session', () => {
|
||||
const app = makeApp();
|
||||
app.terminal = fakeTerminal(['wrote /tmp/shot.png']);
|
||||
|
||||
const provider = app.registerFilePathLinkProvider();
|
||||
|
||||
expect(app.terminal.providers).toEqual([provider]);
|
||||
expect(app._terminalLinkProvider).toBe(provider);
|
||||
const [link] = linksOn(provider, 1);
|
||||
link.activate({}, link.text);
|
||||
expect(app.openFilePreview).toHaveBeenCalledWith('/tmp/shot.png', 'primary-session');
|
||||
link.hover();
|
||||
expect(app._linkHovered).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('registerFilePathLinkProvider with a target (a second pane)', () => {
|
||||
it("registers on the target terminal and opens against the target's session, not the active one", () => {
|
||||
const app = makeApp();
|
||||
app.terminal = fakeTerminal([]);
|
||||
const primaryProvider = app.registerFilePathLinkProvider();
|
||||
const paneTerminal = fakeTerminal(['tail -f /var/log/app.log']);
|
||||
const setHovered = vi.fn();
|
||||
|
||||
const provider = app.registerFilePathLinkProvider({
|
||||
terminal: paneTerminal,
|
||||
getSessionId: () => 'pane-session',
|
||||
setHovered,
|
||||
});
|
||||
|
||||
expect(paneTerminal.providers).toEqual([provider]);
|
||||
expect(app.terminal.providers).toEqual([primaryProvider]);
|
||||
// The tap path's provider is still the primary one.
|
||||
expect(app._terminalLinkProvider).toBe(primaryProvider);
|
||||
|
||||
const [link] = linksOn(provider, 1);
|
||||
link.activate({}, link.text);
|
||||
expect(app.openLogViewerWindow).toHaveBeenCalledWith('/var/log/app.log', 'pane-session');
|
||||
|
||||
link.hover();
|
||||
link.leave();
|
||||
expect(setHovered.mock.calls).toEqual([[true], [false]]);
|
||||
expect(app._linkHovered).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reads the session at click time, so a pane rebound to another session follows it', () => {
|
||||
const app = makeApp();
|
||||
let sessionId = 'first';
|
||||
const paneTerminal = fakeTerminal(['see /tmp/a.pdf']);
|
||||
const provider = app.registerFilePathLinkProvider({ terminal: paneTerminal, getSessionId: () => sessionId });
|
||||
|
||||
sessionId = 'second';
|
||||
const [link] = linksOn(provider, 1);
|
||||
link.activate({}, link.text);
|
||||
|
||||
expect(app.openFilePreview).toHaveBeenCalledWith('/tmp/a.pdf', 'second');
|
||||
});
|
||||
});
|
||||
@@ -1,691 +0,0 @@
|
||||
/**
|
||||
* @fileoverview TerminalTile input rides the app's exactly-once queue, and only
|
||||
* what a human typed is queued.
|
||||
*
|
||||
* Before, the split pane's second terminal sent every xterm `onData` chunk as a
|
||||
* bare `{t:'i', d}` frame: no seq, no ACK, dropped while the socket was down,
|
||||
* never acknowledged an idle alert. It now goes through `app._sendInputAsync`,
|
||||
* over the pane's own socket registered in the app's input-socket map. That
|
||||
* queue PERSISTS and REDELIVERS, so it must never hold what xterm generates on
|
||||
* its own: a query reply (DA/CPR/OSC) is dropped, exactly as the primary pane
|
||||
* drops it, and a focus or mouse report goes out once, ephemeral.
|
||||
*
|
||||
* The socket's lifecycle is pinned here too: a transient drop reconnects on the
|
||||
* primary pane's backoff and refreshes the buffer without leaving a stale
|
||||
* "disconnected" marker under a healthy pane; codes that cannot get better stop
|
||||
* the pane once (`onExit`); a late close from a REPLACED socket is ignored; and
|
||||
* destroy() cancels a pending reconnect.
|
||||
*
|
||||
* Real code under test: constants.js + app.js (the queue) + terminal-ui.js (the
|
||||
* shared input predicates) + terminal-tile.js, in one `vm` context. xterm, the
|
||||
* fit addon and WebSocket are fakes; `connect()` runs for real.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type Frame = { t: string; d?: string; seq?: number; cid?: string; c?: number; r?: number };
|
||||
|
||||
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 fit addon: proposes `FakeFit.proposed` and, like the real one, resizes to it (NaN = hidden pane). */
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
class FakeTerminal {
|
||||
static last: FakeTerminal | null = null;
|
||||
options: Record<string, unknown>;
|
||||
cols = 80;
|
||||
rows = 24;
|
||||
dataCb: ((data: string) => void) | null = null;
|
||||
buffer = { active: { type: 'normal', viewportY: 0, length: 24 } };
|
||||
constructor(options: Record<string, unknown>) {
|
||||
this.options = { ...options };
|
||||
FakeTerminal.last = this;
|
||||
}
|
||||
loadAddon(addon: FakeFit) {
|
||||
addon.term = this;
|
||||
}
|
||||
open() {}
|
||||
onData(cb: (data: string) => void) {
|
||||
this.dataCb = cb;
|
||||
}
|
||||
keyHandler: ((ev: Record<string, unknown>) => 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<string, unknown>) => boolean) {
|
||||
this.keyHandler = fn;
|
||||
}
|
||||
registerLinkProvider() {}
|
||||
writes: string[] = [];
|
||||
write(data: string, cb?: () => void) {
|
||||
this.writes.push(data);
|
||||
cb?.();
|
||||
}
|
||||
clear() {
|
||||
this.writes.push('<CLEAR>');
|
||||
}
|
||||
resizes: Array<[number, number]> = [];
|
||||
resize(cols: number, rows: number) {
|
||||
this.resizes.push([cols, rows]);
|
||||
this.cols = cols;
|
||||
this.rows = rows;
|
||||
}
|
||||
dispose() {}
|
||||
type(data: string) {
|
||||
this.dataCb?.(data);
|
||||
}
|
||||
}
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
|
||||
function loadContext() {
|
||||
const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../src/web/public/${f}`), 'utf8');
|
||||
const windowStub: Record<string, unknown> = {
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
CodemanBase: { base: '' },
|
||||
};
|
||||
const context = vm.createContext({
|
||||
console: { ...console, log: vi.fn(), debug: vi.fn() },
|
||||
performance,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
// Late-bound, so vi.useFakeTimers() (which swaps the globals) reaches code
|
||||
// running inside this context.
|
||||
setTimeout: (fn: () => void, ms?: number) => globalThis.setTimeout(fn, ms),
|
||||
clearTimeout: (id: ReturnType<typeof setTimeout>) => globalThis.clearTimeout(id),
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: FakeSocket,
|
||||
Terminal: FakeTerminal,
|
||||
FitAddon: { FitAddon: FakeFit },
|
||||
fetch: (...args: unknown[]) => fetchMock(...args),
|
||||
location: { protocol: 'http:', host: 'codeman.test' },
|
||||
document: { addEventListener: vi.fn(), documentElement: { dataset: {} } },
|
||||
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
window: windowStub,
|
||||
MobileDetection: {
|
||||
isTouchDevice: () => false,
|
||||
isHandheldDevice: () => false,
|
||||
getDeviceType: () => 'desktop',
|
||||
},
|
||||
});
|
||||
vm.runInContext(
|
||||
`${read('constants.js')}\n${read('app.js')}\n${read('terminal-ui.js')}\n${read('terminal-tile.js')}\n` +
|
||||
'globalThis.__CodemanApp = CodemanApp;',
|
||||
context
|
||||
);
|
||||
return {
|
||||
CodemanApp: (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp,
|
||||
windowStub,
|
||||
};
|
||||
}
|
||||
|
||||
const { CodemanApp, windowStub } = loadContext();
|
||||
|
||||
type App = Record<string, unknown> & {
|
||||
_pendingDeliveries: Map<string, Array<{ seq: number; data: string }>>;
|
||||
markIdleAlertSeen: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function makeApp(): App {
|
||||
const app = Object.create(CodemanApp.prototype) as App;
|
||||
app._clientId = 'c-test';
|
||||
app._wsTabNonce = 'nonce-1';
|
||||
app._seqCounters = new Map();
|
||||
app._pendingDeliveries = new Map();
|
||||
app._postDraining = new Set();
|
||||
app._extraInputSockets = new Map();
|
||||
app._persistReliableState = vi.fn();
|
||||
app._persistReliableNow = vi.fn();
|
||||
app._updateConnectionIndicator = vi.fn();
|
||||
app.markIdleAlertSeen = vi.fn();
|
||||
app.showToast = vi.fn();
|
||||
// The key handler's chord gates read the shortcut registry, which reads these.
|
||||
app.loadAppSettingsFromStorage = () => ({});
|
||||
app._ws = null;
|
||||
app._wsSessionId = null;
|
||||
app._estimateReplayRows = (text: string) => text.split('\n').length;
|
||||
return app;
|
||||
}
|
||||
|
||||
type Tile = {
|
||||
connect(): Promise<void>;
|
||||
destroy(): void;
|
||||
reconnectNow(): void;
|
||||
fit(opts?: { force?: boolean }): void;
|
||||
detachedSessions?: Set<string>;
|
||||
ws: FakeSocket | null;
|
||||
_reconnectAttempts: number;
|
||||
};
|
||||
const TerminalTile = windowStub.TerminalTile as new (id: string, mount: unknown, opts?: object) => Tile;
|
||||
|
||||
/**
|
||||
* Every tile a test creates, destroyed after it. A tile closed with real timers
|
||||
* schedules a real reconnect, and one firing during a LATER test opens a socket
|
||||
* there (FakeSocket.instances is shared), which flaked under full-suite load.
|
||||
*/
|
||||
const liveTiles: Tile[] = [];
|
||||
|
||||
async function connectTile(app: App, opts: Record<string, unknown> = {}) {
|
||||
windowStub.app = app;
|
||||
const tile = new TerminalTile(
|
||||
's-tile',
|
||||
{ addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
{ mode: 'claude', ...opts }
|
||||
);
|
||||
liveTiles.push(tile);
|
||||
await tile.connect();
|
||||
const ws = FakeSocket.instances.at(-1)!;
|
||||
return { tile, ws, term: FakeTerminal.last! };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const tile of liveTiles.splice(0)) tile.destroy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
FakeFit.proposed = { cols: 80, rows: 24 };
|
||||
FakeSocket.instances = [];
|
||||
fetchMock.mockReset();
|
||||
fetchMock.mockImplementation(async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { terminalBuffer: '' } }),
|
||||
}));
|
||||
});
|
||||
|
||||
describe('TerminalTile socket identity', () => {
|
||||
it('connects with the tab identity plus a :tile suffix, never the primary pane cid', async () => {
|
||||
const { ws } = await connectTile(makeApp());
|
||||
|
||||
const cid = new URL(ws.url).searchParams.get('cid');
|
||||
expect(cid).toBe('c-test:nonce-1:tile');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile input through the exactly-once queue', () => {
|
||||
it('sends typed input as seq-tagged frames with the bare clientId once the socket opens', async () => {
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
|
||||
term.type('h');
|
||||
term.type('i');
|
||||
|
||||
expect(ws.inputFrames().map((f) => [f.d, f.seq, f.cid])).toEqual([
|
||||
['h', 1, 'c-test'],
|
||||
['i', 2, 'c-test'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops a record on its ACK and acknowledges the session idle alert', async () => {
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
term.type('x');
|
||||
expect(app._pendingDeliveries.get('s-tile')).toHaveLength(1);
|
||||
|
||||
ws.receive({ t: 'ia', seq: 1 });
|
||||
|
||||
expect(app._pendingDeliveries.get('s-tile')).toBeUndefined();
|
||||
expect(app.markIdleAlertSeen).toHaveBeenCalledWith('s-tile');
|
||||
});
|
||||
|
||||
it('flushes input typed before the socket opened, in order, once it does', async () => {
|
||||
const app = makeApp();
|
||||
// POSTs fail, as they would while the server restarts, so the input waits.
|
||||
const { ws, term } = await connectTile(app);
|
||||
fetchMock.mockImplementation(async () => ({ ok: false, status: 503, json: async () => ({}) }));
|
||||
term.type('a');
|
||||
term.type('b');
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(ws.inputFrames()).toEqual([]);
|
||||
|
||||
ws.open();
|
||||
|
||||
expect(ws.inputFrames().map((f) => [f.d, f.seq])).toEqual([
|
||||
['a', 1],
|
||||
['b', 2],
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps queuing after the socket closes (HTTP fallback), instead of dropping keystrokes', async () => {
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
ws.readyState = 3;
|
||||
ws.onclose?.({ code: 1006 });
|
||||
const posts: Array<{ input: string; seq: number }> = [];
|
||||
fetchMock.mockImplementation(async (_url: string, init?: { body?: string }) => {
|
||||
if (init?.body) posts.push(JSON.parse(init.body));
|
||||
return { ok: true, status: 200, json: async () => ({}) };
|
||||
});
|
||||
|
||||
term.type('z');
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
expect(posts.map((p) => [p.input, p.seq])).toEqual([['z', 1]]);
|
||||
expect(ws.inputFrames()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what xterm generates never enters the durable queue', () => {
|
||||
it('drops a DA query reply entirely', async () => {
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
|
||||
term.type('\x1b[?1;2c');
|
||||
|
||||
expect(ws.inputFrames()).toEqual([]);
|
||||
expect(app._pendingDeliveries.get('s-tile')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends a mouse report once, without a seq, and never persists it', async () => {
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
|
||||
term.type('\x1b[<0;10;5M');
|
||||
|
||||
expect(ws.inputFrames()).toEqual([{ t: 'i', d: '\x1b[<0;10;5M' }]);
|
||||
expect(app._pendingDeliveries.get('s-tile')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends a focus report once, without a seq', async () => {
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
|
||||
term.type('\x1b[I');
|
||||
|
||||
expect(ws.inputFrames()).toEqual([{ t: 'i', d: '\x1b[I' }]);
|
||||
expect(app._pendingDeliveries.get('s-tile')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile leaves the input-socket map', () => {
|
||||
it('on close, so a later keystroke cannot be written into a dead socket', async () => {
|
||||
const app = makeApp();
|
||||
const { ws } = await connectTile(app);
|
||||
ws.open();
|
||||
expect((app._extraInputSockets as Map<string, unknown>).has('s-tile')).toBe(true);
|
||||
|
||||
ws.onclose?.({ code: 1006 });
|
||||
|
||||
expect((app._extraInputSockets as Map<string, unknown>).has('s-tile')).toBe(false);
|
||||
});
|
||||
|
||||
it('on destroy, while pending input stays queued for the HTTP sweep', async () => {
|
||||
const app = makeApp();
|
||||
const { tile, ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
term.type('q');
|
||||
|
||||
tile.destroy();
|
||||
|
||||
expect((app._extraInputSockets as Map<string, unknown>).has('s-tile')).toBe(false);
|
||||
expect(app._pendingDeliveries.get('s-tile')?.map((r) => r.data)).toEqual(['q']);
|
||||
});
|
||||
});
|
||||
|
||||
const isMarker = (data: string) => data.includes('[disconnected');
|
||||
|
||||
/**
|
||||
* Lets the async buffer refresh settle: the fetch, the body read, the chunked
|
||||
* write AND the load's finally block, which is where a stale marker would be
|
||||
* stamped. Too few turns here and that assertion passes vacuously.
|
||||
*/
|
||||
async function settle() {
|
||||
for (let i = 0; i < 50; i++) await Promise.resolve();
|
||||
}
|
||||
|
||||
describe('TerminalTile reconnects after a transient drop', () => {
|
||||
it('reopens on the backoff, refreshes the buffer, and leaves no stale marker', async () => {
|
||||
vi.useFakeTimers();
|
||||
const app = makeApp();
|
||||
const { tile, ws, term } = await connectTile(app);
|
||||
ws.open();
|
||||
fetchMock.mockImplementation(async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { terminalBuffer: 'fresh screen' } }),
|
||||
}));
|
||||
|
||||
ws.readyState = 3;
|
||||
ws.onclose?.({ code: 1006 });
|
||||
expect(term.writes.filter(isMarker)).toEqual([expect.stringContaining('[disconnected, reconnecting')]);
|
||||
expect(FakeSocket.instances).toHaveLength(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
const ws2 = FakeSocket.instances[1];
|
||||
expect(ws2.url).toBe(ws.url);
|
||||
|
||||
ws2.open();
|
||||
await settle();
|
||||
|
||||
// The refresh cleared the pane and replayed the current screen, and nothing
|
||||
// after that clear is a marker: the pane is healthy again.
|
||||
const lastClear = term.writes.lastIndexOf('<CLEAR>');
|
||||
expect(lastClear).toBeGreaterThan(-1);
|
||||
expect(term.writes.slice(lastClear)).toContain('fresh screen');
|
||||
expect(term.writes.slice(lastClear).some(isMarker)).toBe(false);
|
||||
expect(tile._reconnectAttempts).toBe(0);
|
||||
expect(tile.ws).toBe(ws2);
|
||||
});
|
||||
|
||||
it('counts failed attempts and resets the count only on a successful open', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { tile, ws } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
ws.onclose?.({ code: 1006 });
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
FakeSocket.instances[1].onclose?.({ code: 1006 }); // the retry fails too
|
||||
expect(tile._reconnectAttempts).toBe(2);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
FakeSocket.instances[2].open();
|
||||
expect(tile._reconnectAttempts).toBe(0);
|
||||
});
|
||||
|
||||
it('reconnects after the redelivery sweep force-closes a silent socket (1005)', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { ws } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
ws.onclose?.({ code: 1005 });
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('reconnectNow() skips the backoff, but never replaces an open socket', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { tile, ws } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
tile.reconnectNow();
|
||||
expect(FakeSocket.instances).toHaveLength(1);
|
||||
|
||||
ws.readyState = 3;
|
||||
ws.onclose?.({ code: 1006 });
|
||||
tile.reconnectNow();
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
// The backoff timer it pre-empted must not open a third socket later.
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile stops for good on codes that cannot get better', () => {
|
||||
it.each([
|
||||
[4004, 'the session ended'],
|
||||
[4009, 'the session ended'],
|
||||
[4003, 'the server refused this connection'],
|
||||
[4010, 'another connection took over this pane'],
|
||||
])('close %i: no reconnect, onExit once, marker says why', async (code, reason) => {
|
||||
vi.useFakeTimers();
|
||||
const onExit = vi.fn();
|
||||
const { tile, ws, term } = await connectTile(makeApp(), { onExit });
|
||||
ws.open();
|
||||
|
||||
ws.onclose?.({ code });
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
tile.reconnectNow();
|
||||
|
||||
expect(FakeSocket.instances).toHaveLength(1);
|
||||
expect(onExit).toHaveBeenCalledTimes(1);
|
||||
expect(onExit).toHaveBeenCalledWith(code);
|
||||
expect(term.writes.filter(isMarker)).toEqual([expect.stringContaining(reason)]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile ignores a socket it already replaced', () => {
|
||||
it('a late close (4010) from the old socket neither stops the pane nor unregisters its successor', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onExit = vi.fn();
|
||||
const app = makeApp();
|
||||
const { ws, term } = await connectTile(app, { onExit });
|
||||
ws.open();
|
||||
const lateClose = ws.onclose!;
|
||||
|
||||
ws.onclose?.({ code: 1006 });
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const ws2 = FakeSocket.instances[1];
|
||||
ws2.open();
|
||||
|
||||
// The server supersedes the old socket by cid; its close arrives late.
|
||||
lateClose({ code: 4010 });
|
||||
|
||||
expect(onExit).not.toHaveBeenCalled();
|
||||
term.type('still typing');
|
||||
expect(ws2.inputFrames().map((f) => f.d)).toEqual(['still typing']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile destroy()', () => {
|
||||
it('cancels a pending reconnect and never reports an exit afterwards', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onExit = vi.fn();
|
||||
const { tile, ws } = await connectTile(makeApp(), { onExit });
|
||||
ws.open();
|
||||
|
||||
ws.onclose?.({ code: 1006 });
|
||||
tile.destroy();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
|
||||
expect(FakeSocket.instances).toHaveLength(1);
|
||||
expect(onExit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile geometry (#464: the pane and its PTY never disagree)', () => {
|
||||
const resizeFrames = (ws: FakeSocket) => ws.sent.filter((f) => f.t === 'z');
|
||||
|
||||
it('announces its size as a desktop viewer when the socket opens', async () => {
|
||||
const { ws } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
expect(resizeFrames(ws)).toEqual([{ t: 'z', c: 80, r: 24, v: 'desktop' }]);
|
||||
});
|
||||
|
||||
it('does not resend an unchanged size, sends a changed one, and force resends', async () => {
|
||||
const { tile, ws } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
tile.fit();
|
||||
expect(resizeFrames(ws)).toHaveLength(1);
|
||||
|
||||
FakeFit.proposed = { cols: 100, rows: 30 };
|
||||
tile.fit();
|
||||
expect(resizeFrames(ws).at(-1)).toEqual({ t: 'z', c: 100, r: 30, v: 'desktop' });
|
||||
|
||||
tile.fit({ force: true });
|
||||
expect(resizeFrames(ws)).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('re-announces an unchanged size on a reconnected socket', async () => {
|
||||
vi.useFakeTimers();
|
||||
const { ws } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
ws.onclose?.({ code: 1006 });
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const ws2 = FakeSocket.instances[1];
|
||||
|
||||
ws2.open();
|
||||
|
||||
expect(resizeFrames(ws2)).toEqual([{ t: 'z', c: 80, r: 24, v: 'desktop' }]);
|
||||
});
|
||||
|
||||
it('applies no 40-column floor: a pane at the divider clamp gets its real width on both sides', async () => {
|
||||
const { tile, ws, term } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
FakeFit.proposed = { cols: 28, rows: 30 };
|
||||
tile.fit();
|
||||
|
||||
expect(term.cols).toBe(28);
|
||||
expect(resizeFrames(ws).at(-1)).toEqual({ t: 'z', c: 28, r: 30, v: 'desktop' });
|
||||
});
|
||||
|
||||
it('reports nothing while hidden (the fit addon measures NaN)', async () => {
|
||||
const { tile, ws, term } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
FakeFit.proposed = { cols: NaN, rows: NaN };
|
||||
tile.fit();
|
||||
|
||||
expect(resizeFrames(ws)).toHaveLength(1);
|
||||
expect([term.cols, term.rows]).toEqual([80, 24]);
|
||||
});
|
||||
|
||||
it('stands aside for a session detached into its own window', async () => {
|
||||
const { tile, ws } = await connectTile(makeApp(), { detachedSessions: new Set(['s-tile']) });
|
||||
ws.open();
|
||||
FakeFit.proposed = { cols: 120, rows: 40 };
|
||||
|
||||
tile.fit();
|
||||
|
||||
expect(resizeFrames(ws)).toEqual([]);
|
||||
});
|
||||
|
||||
it('adopts the column count the PTY reports, keeping its own rows', async () => {
|
||||
const { ws, term } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
|
||||
ws.receive({ t: 'zc', c: 132, r: 50 });
|
||||
|
||||
expect([term.cols, term.rows]).toEqual([132, 24]);
|
||||
});
|
||||
|
||||
it('leaves the pane alone when the PTY agrees on width', async () => {
|
||||
const { ws, term } = await connectTile(makeApp());
|
||||
ws.open();
|
||||
const before = term.resizes.length;
|
||||
|
||||
ws.receive({ t: 'zc', c: 80, r: 60 });
|
||||
|
||||
expect(term.resizes.length).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile links and paste follow THIS pane', () => {
|
||||
it('registers the shared link provider on its own terminal, resolving its own session', async () => {
|
||||
const app = makeApp();
|
||||
const register = vi.fn();
|
||||
app.registerFilePathLinkProvider = register;
|
||||
|
||||
const { term } = await connectTile(app);
|
||||
|
||||
expect(register).toHaveBeenCalledTimes(1);
|
||||
const target = register.mock.calls[0][0] as { terminal: unknown; getSessionId: () => string };
|
||||
expect(target.terminal).toBe(term);
|
||||
expect(target.getSessionId()).toBe('s-tile');
|
||||
});
|
||||
|
||||
it("routes Ctrl+V into the paste trap with this pane's terminal and session", async () => {
|
||||
const app = makeApp();
|
||||
const paste = vi.fn();
|
||||
app._handleImagePaste = paste;
|
||||
const { term } = await connectTile(app);
|
||||
|
||||
const handled = term.keyHandler!({ type: 'keydown', key: 'v', ctrlKey: true, code: 'KeyV' });
|
||||
|
||||
expect(handled).toBe(false);
|
||||
expect(paste).toHaveBeenCalledWith({ terminal: term, sessionId: 's-tile' });
|
||||
});
|
||||
|
||||
it('leaves Ctrl+Shift+V (voice input) out of the paste trap', async () => {
|
||||
const app = makeApp();
|
||||
const paste = vi.fn();
|
||||
app._handleImagePaste = paste;
|
||||
const { term } = await connectTile(app);
|
||||
|
||||
term.keyHandler!({ type: 'keydown', key: 'V', ctrlKey: true, shiftKey: true, code: 'KeyV' });
|
||||
|
||||
expect(paste).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalTile claims the keyboard for the app-level shortcuts', () => {
|
||||
it('focusing its terminal makes it the focused pane; destroy() hands the keyboard back', async () => {
|
||||
const app = makeApp();
|
||||
const { tile, term } = await connectTile(app);
|
||||
expect(app._focusedTile ?? null).toBeNull();
|
||||
|
||||
term.focusTextarea();
|
||||
expect(app._focusedTile).toBe(tile);
|
||||
|
||||
tile.destroy();
|
||||
expect(app._focusedTile).toBeNull();
|
||||
expect(term.focusListeners).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the server coming back kicks Pane B', () => {
|
||||
it("handleInit's reconnect branch asks the split pane's tile to reconnect without waiting out its backoff", () => {
|
||||
// handleInit needs a whole app to run, so the wiring is pinned by source;
|
||||
// reconnectNow() itself is exercised above.
|
||||
const appSource = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
|
||||
const start = appSource.indexOf('if (keepTerminal && restoreId === previousActiveId');
|
||||
const branch = appSource.slice(start, appSource.indexOf('} else {', start));
|
||||
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
expect(branch).toContain('this._splitPane?.reconnectNow?.();');
|
||||
});
|
||||
});
|
||||
@@ -1,175 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Dictation lands in the session it was started for.
|
||||
*
|
||||
* `VoiceInput` (voice-input.js) used to read `app.activeSessionId` when the
|
||||
* transcript ARRIVED, and again when the green send button or the compose
|
||||
* overlay's Send was pressed. Both happen seconds after recording started, so a
|
||||
* user who switched tabs in between had their dictation typed into the other
|
||||
* session. The target is now captured in `start()` (through `_focusedPane()`,
|
||||
* so a second terminal pane can claim it later) and every send path uses it.
|
||||
*
|
||||
* Loaded via `vm` with a stubbed `app` (no jsdom).
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const voiceSource = readFileSync(resolve(import.meta.dirname, '../src/web/public/voice-input.js'), 'utf8');
|
||||
|
||||
type Voice = {
|
||||
start: () => void;
|
||||
_insertText: (text: string) => void;
|
||||
_resolveProvider: () => string;
|
||||
_startWebSpeech: () => void;
|
||||
_showComposeOverlay: (text: string) => void;
|
||||
_voiceSendHandler: (() => void) | null;
|
||||
_targetSessionId: string | null;
|
||||
};
|
||||
|
||||
function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string } = {}) {
|
||||
const sendInput = vi.fn(async () => {});
|
||||
const sendInputAsync = vi.fn();
|
||||
const appendText = vi.fn();
|
||||
const showToast = vi.fn();
|
||||
const gear = {
|
||||
classList: { contains: () => false, add: vi.fn(), remove: vi.fn() },
|
||||
innerHTML: '',
|
||||
title: '',
|
||||
getAttribute: () => null,
|
||||
setAttribute: vi.fn(),
|
||||
removeAttribute: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
};
|
||||
const app: Record<string, unknown> = {
|
||||
activeSessionId: 'session-a',
|
||||
sessions: new Map([
|
||||
['session-a', {}],
|
||||
['session-b', {}],
|
||||
]),
|
||||
sendInput,
|
||||
_sendInputAsync: sendInputAsync,
|
||||
showToast,
|
||||
terminal: { focus: vi.fn() },
|
||||
_localEchoEnabled: !!opts.localEcho,
|
||||
_localEchoOverlay: opts.localEcho ? { appendText, pendingText: '', clear: vi.fn() } : null,
|
||||
};
|
||||
if (opts.focused) app._focusedPane = () => ({ sessionId: opts.focused });
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
setTimeout: (fn: () => void) => fn(),
|
||||
clearTimeout: () => {},
|
||||
setInterval: () => 0,
|
||||
clearInterval: () => {},
|
||||
app,
|
||||
localStorage: {
|
||||
getItem: (key: string) =>
|
||||
key === 'codeman-voice-settings' ? JSON.stringify({ insertMode: opts.insertMode || 'direct' }) : null,
|
||||
setItem: () => {},
|
||||
},
|
||||
document: {
|
||||
querySelector: (sel: string) => (sel === '.btn-settings' ? gear : null),
|
||||
createElement: () => ({}),
|
||||
body: { appendChild: () => {} },
|
||||
},
|
||||
window: {},
|
||||
navigator: {},
|
||||
});
|
||||
vm.runInContext(`${voiceSource}\nglobalThis.__VoiceInput = VoiceInput;`, context);
|
||||
const voice = (context as unknown as { __VoiceInput: Voice }).__VoiceInput;
|
||||
// Recording itself is out of scope: start() only has to pick the target.
|
||||
voice._resolveProvider = () => 'webspeech';
|
||||
voice._startWebSpeech = vi.fn();
|
||||
return { voice, app, sendInput, sendInputAsync, appendText, showToast, gear };
|
||||
}
|
||||
|
||||
describe('dictation target', () => {
|
||||
it('sends to the session recording started in, even after a tab switch', () => {
|
||||
const { voice, app, sendInput, sendInputAsync } = load();
|
||||
voice.start();
|
||||
app.activeSessionId = 'session-b'; // user switched tabs while speaking
|
||||
|
||||
voice._insertText('fix the login bug');
|
||||
|
||||
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'fix the login bug', { useMux: true });
|
||||
expect(sendInput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the existing path when the target is still the active session', () => {
|
||||
const { voice, sendInput, sendInputAsync } = load();
|
||||
voice.start();
|
||||
|
||||
voice._insertText('hello');
|
||||
|
||||
expect(sendInput).toHaveBeenCalledWith('hello');
|
||||
expect(sendInputAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never types another session dictation into the active local-echo overlay', () => {
|
||||
const { voice, app, appendText, sendInputAsync } = load({ localEcho: true });
|
||||
voice.start();
|
||||
app.activeSessionId = 'session-b';
|
||||
|
||||
voice._insertText('for session a');
|
||||
|
||||
expect(appendText).not.toHaveBeenCalled();
|
||||
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'for session a', { useMux: true });
|
||||
});
|
||||
|
||||
it('still uses the local-echo overlay for the active session', () => {
|
||||
const { voice, appendText, sendInput } = load({ localEcho: true });
|
||||
voice.start();
|
||||
|
||||
voice._insertText('typed locally');
|
||||
|
||||
expect(appendText).toHaveBeenCalledWith('typed locally');
|
||||
expect(sendInput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('takes its target from the focused pane when one is reported', () => {
|
||||
const { voice, sendInputAsync } = load({ focused: 'session-b' });
|
||||
voice.start();
|
||||
|
||||
voice._insertText('into pane b');
|
||||
|
||||
expect(sendInputAsync).toHaveBeenCalledWith('session-b', 'into pane b', { useMux: true });
|
||||
});
|
||||
|
||||
it('the green send button sends Enter to the dictation target', () => {
|
||||
const { voice, app, gear, sendInput, sendInputAsync } = load();
|
||||
voice.start();
|
||||
voice._insertText('ship it');
|
||||
app.activeSessionId = 'session-b';
|
||||
const handler = gear.addEventListener.mock.calls.find((c: unknown[]) => c[0] === 'click')?.[1] as () => void;
|
||||
|
||||
handler();
|
||||
|
||||
expect(sendInputAsync).toHaveBeenLastCalledWith('session-a', '\r', { useMux: true });
|
||||
// Only the original insert went through sendInput (target was active then).
|
||||
expect(sendInput).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('drops dictation for a session that closed meanwhile, with a toast', () => {
|
||||
const { voice, app, sendInput, sendInputAsync, showToast } = load();
|
||||
voice.start();
|
||||
app.activeSessionId = 'session-b';
|
||||
(app.sessions as Map<string, unknown>).delete('session-a');
|
||||
|
||||
voice._insertText('too late');
|
||||
|
||||
expect(sendInput).not.toHaveBeenCalled();
|
||||
expect(sendInputAsync).not.toHaveBeenCalled();
|
||||
expect(showToast).toHaveBeenCalledWith('That session has closed; dictation not sent', 'warning');
|
||||
});
|
||||
|
||||
it('refuses to start with no session at all', () => {
|
||||
const { voice, app, showToast } = load();
|
||||
app.activeSessionId = null;
|
||||
|
||||
voice.start();
|
||||
|
||||
expect(showToast).toHaveBeenCalledWith('No active session', 'warning');
|
||||
expect(voice._targetSessionId).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user