Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53f61ca539 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'aicodeman': patch
|
||||
---
|
||||
|
||||
The "Showing the most recent 1.0 MB of this session" notice no longer appears on every tab switch. It shows up only when you scroll to the top of a terminal, leaves when you scroll back down, and stays closed for that tab once you dismiss it. Sessions with nothing more to load (fullscreen Claude, whose history lives in Claude itself) never show it, and when there is more, it states the scrollback line count instead of an inflated byte figure. `GET /api/v1/sessions/:id/terminal` reports the new `paneHistoryLines` field.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'aicodeman': minor
|
||||
---
|
||||
|
||||
Notifications stay as long as you want. Settings → Notifications has a "Toast display time" and a "Browser notification display time" (seconds, per device; the defaults stay 3s and 8s).
|
||||
@@ -248,7 +248,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**MCP server sync** (opt-in, `mcpSyncEnabled`, SYNCED, default OFF; `src/mcp-sync.ts`, `GET`/`POST /api/mcp-sync`): copies each installed, enabled CLI's user-level MCP servers into the others. It is the ONE subsystem that writes another CLI's REAL user config (`~/.claude.json`, `~/.codex/config.toml`, `~/.gemini/*`, opencode's), which is why it is opt-in and admin-only in multi-user mode (both verbs 403 for a non-admin, and the Settings group is hidden for them). Where each CLI keeps the file is registry data, `capabilities.mcpConfig` (`{ path, format, relocation? }`), never a branch on the id. ⚠️ ADDITIVE only: a name already defined, in any shape, is never edited or removed (a different same-name definition is a reported conflict), and a server switched off in its own CLI is never copied. ⚠️ Never write a file that did not parse; re-parse the NEW text and require every added server to read back before the tmp+rename (written through a symlink, previous file kept as `<file>.codeman-bak`, one apply at a time, else 409). ⚠️ A file that receives copied `env`/`headers` (secrets) is left `0600`, and so is the backup. ⚠️ Responses carry server NAMES only, never env values, headers or file text: a parse failure is reported by line and column (`describeMcpSyncError`), never the parser's own message (smol-toml and V8 both quote source). ⚠️ `mcpConfig.relocation` names the env var the CLI reads to move its file (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_CONFIG_HOME`, `GEMINI_CLI_HOME`), resolved from the SERVER env at call time; a relative value reports the target `skipped`, never a guessed write, and a per-session `envOverrides` relocation is not followed. Tests must pass `home` (which drops the `process.env` default) or clear those vars first. → `docs/cli-registry.md` (MCP server sync), `docs/api-reference.md`, `docs/wiki/Settings-Reference.md`
|
||||
|
||||
**Run launch synchronization**: the Run entrypoint holds an in-flight lock and disables `#runBtn` for the whole launch (≥500ms) so a double click cannot create duplicate `w<n>-<case>` sessions; `_ensureCreatedSessionVisible()` runs before `selectSession()` and `_onSessionCreated()` stays an idempotent upsert, so POST-first and SSE-first both render exactly one tab. ⚠️ **Closing has the mirror-image race**: `closeSession()` must read `wasActive` BEFORE its `await` and announce the delete via `_closingSessions`, and `_onSessionDeleted` skips the active-session handoff for ids in that set; never read `activeSessionId` after the fact. The fallback picks the first `sessionOrder` entry still in `sessions`. ⚠️ The close is OPTIMISTIC: the tab goes and the next one is selected BEFORE the DELETE is sent (upserts skip ids in `_closingSessions`), and only a delete the server refused (checked with a GET) puts the row back; never await the server before hiding the tab. Tests: `test/session-close-fallback.test.ts`. → [architecture-invariants#run-launch-synchronization](docs/architecture-invariants.md#run-launch-synchronization)
|
||||
**Run launch synchronization**: the Run entrypoint holds an in-flight lock and disables `#runBtn` for the whole launch (≥500ms) so a double click cannot create duplicate `w<n>-<case>` sessions; `_ensureCreatedSessionVisible()` runs before `selectSession()` and `_onSessionCreated()` stays an idempotent upsert, so POST-first and SSE-first both render exactly one tab. ⚠️ **Closing has the mirror-image race**: `closeSession()` must read `wasActive` BEFORE its `await` and announce the delete via `_closingSessions`, and `_onSessionDeleted` skips the active-session handoff for ids in that set; never read `activeSessionId` after the fact. The fallback picks the first `sessionOrder` entry still in `sessions`. Tests: `test/session-close-fallback.test.ts`. → [architecture-invariants#run-launch-synchronization](docs/architecture-invariants.md#run-launch-synchronization)
|
||||
|
||||
**Session lineage lines** (tab → tab it spawned, `sessionLineageLines`, per-device, desktop default ON): a create request may name its spawner via a `parentSessionId` body field or the `X-Codeman-Parent-Session` header; `resolveParentSessionId()` (route-helpers.ts) resolves it (exact id or unique ≥8-char prefix, live, visible, same owner) and ⚠️ anything unresolvable is DROPPED, never a 400. Rides `toState()`, no new SSE event. ⚠️ Rendering is a LAYER on the existing SVG pass (`_appendLineageConnectionLines` at the tail of `_updateConnectionLinesImmediate()`) and draws EVERY family, emphasizing the selected tab's (what it spawned, and the family it was spawned into: `lineage-family--focus`, thicker, opaque, drawn last; lanes stay in strip order), so a selection change must redraw (`_updateActiveTabImmediate`, gated on `_lineageTotalEdges`), and again on the strip's size `transitionend` (the active tab widens for ~150ms after the redraw). Geometry is pure in `computeLineageTree()`: one rounded orthogonal tree per spawning tab, every route starting at the PARENT (siblings share the trunk exactly), routed ONLY through the gaps between tab rows plus a spine left of every row, so it never crosses a tab or the terminal. ⚠️ That room is reserved in CSS by `.session-tabs.lineage-tree` (`_syncLineageGutter()`, called before the wrap is measured), keyed on whether ANY family exists, never on the selection, or every tab switch would resize the header and the PTY. Colors are keyed on the SPAWNING tab, claimed in strip order for every family, and memoized (never by draw index or selection order). ⚠️ Desktop only (z-index vs the fixed mobile header). ⚠️ Paths must keep `data-agent-id="lineage:<childId>"` (the entrance animation queries it); skip endpoints scrolled out of the strip. → [architecture-invariants#session-lineage-lines-tab--tab-it-spawned](docs/architecture-invariants.md#session-lineage-lines-tab--tab-it-spawned)
|
||||
|
||||
@@ -286,7 +286,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Ctrl+V paste trap** (`image-input.js`): `Ctrl+V` routes through `_handleImagePaste()`, which focuses a hidden `contenteditable` trap and reads the clipboard from the paste event landing there; images upload and their paths are typed in, text goes through `terminal.paste()` so bracketed-paste markers survive. ⚠️ **The trap must consume exactly ONE paste event** (Firefox delivers two per keypress: the `execCommand('paste')` event and the keydown's default action); the one-shot flag lives on the trap, never on a browser check. ⚠️ Do not remove the `execCommand('paste')` call: on some mobile engines it is the only route into the trap, and the trap is the only place image blobs are read. Tests: `test/image-paste-trap.test.ts`. → [architecture-invariants#terminal-paste-ctrlv](docs/architecture-invariants.md#terminal-paste-ctrlv)
|
||||
|
||||
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode gets the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/pi/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward to the CLI for **claude ≥ 2.1.187 ONLY, and only while it has mouse tracking on** (`cliMouseTracking`: fullscreen claude sets it, its default inline renderer does not and scrolls locally like codex); ⚠️ never re-add codex without a fresh measurement (it ignores SGR wheel reports). ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) pages the wheel and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`); never copy the mode lists into terminal-tile.js. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
|
||||
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode gets the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/pi/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward to the CLI for **claude ≥ 2.1.187 ONLY, and only while it has mouse tracking on** (`cliMouseTracking`: fullscreen claude sets it, its default inline renderer does not and scrolls locally like codex); ⚠️ never re-add codex without a fresh measurement (it ignores SGR wheel reports). ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
|
||||
**Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install)
|
||||
|
||||
**Self-update** (App Settings → System → Updates): in-app updater for git-clone installs under a supervisor (`systemd`, `launchd`, `launchd-daemon`, `docker-compose`, else `none`). The work runs in a DETACHED `scripts/self-update.sh` writing `update-status.json`, polled across the restart; pure helpers in `src/web/self-update.ts`. ⚠️ Compose: the restart kills the script, so nothing may be appended after the `restarting` marker; the repo must stay a host bind mount over `/opt/codeman` and the image must keep devDependencies + toolchain. ⚠️ `evaluateEnvironmentGate()` refuses releases that change `server.Dockerfile`/`docker-compose.yaml` or add `.env.example` keys, re-evaluated on `POST /api/system/update`; unknowns fail OPEN, but the exit-to-restart needs `--restart-by-exit 1` (`CODEMAN_RESTART_BY_EXIT=1` only in the Compose file). ⚠️ Keep the agent CLIs in `server.Dockerfile` pinned. → [docs/docker-self-update.md](docs/docker-self-update.md), [architecture-invariants#self-update](docs/architecture-invariants.md#self-update)
|
||||
|
||||
@@ -19,12 +19,16 @@
|
||||
<a href="https://github.com/Ark0N/Codeman/commits/master"><img src="https://img.shields.io/github/commit-activity/t/Ark0N/Codeman?style=flat-square&color=1e3a5f" alt="Total commits"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
⭐ <strong>Like Codeman? <a href="https://github.com/Ark0N/Codeman">Give it a star on GitHub!</a></strong> It takes one click and helps more people find the project. ⭐
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> • <a href="README.zh-CN.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/tiles-crt-stats-20261010.gif" alt="Codeman tile grid: six live agents (DeepSeek Harness, Claude Code, Pi, Codex, OpenCode and a shell) powering on and off with the CRT animation, with the live header strip showing CPU, memory and Claude plan usage" width="800">
|
||||
<img src="docs/images/subagent-demo-20260724.gif" alt="Codeman — parallel subagent visualization" width="900">
|
||||
</p>
|
||||
|
||||
**Codeman** is a self-hosted mission control for AI coding agents. It spawns Claude Code, OpenCode, Codex, Antigravity, Gemini, Pi, Grok, DeepSeek Harness, or OMP inside persistent tmux sessions, streams the real terminal to any browser, and keeps agents productive after you walk away: it re-prompts on idle, resumes when a usage limit resets, runs scheduled jobs, and shows every background agent working in real time.
|
||||
@@ -50,7 +54,7 @@ The installer asks before every system change, and re-running the same line upda
|
||||
- **Self-hosted and private** - loopback-only by default, MIT licensed, no telemetry, runs entirely on your machine
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/codeman-tour-20261010.png" alt="Codeman dashboard tour: session tabs per case, one-click Run for new agents, live plan usage in the header" width="900">
|
||||
<img src="docs/images/codeman-tour-20260724.png" alt="Codeman dashboard tour: session tabs per case, one-click Run for new agents, live plan usage in the header" width="900">
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -422,7 +426,7 @@ The title is templated into the served HTML on first byte, so it's correct from
|
||||
### Tab Alerts
|
||||
|
||||
<p align="center">
|
||||
<a href="docs/images/codeman-tab-states-20261010.png"><img src="docs/images/codeman-tab-states-20261010.gif" alt="Tab states, annotated: a working tab with a spinning green ring, a red tab blocked on the agent's question shown below it, and a yellow tab whose turn is done, both alert tabs breathing" width="900"></a>
|
||||
<img src="docs/images/tab-alerts-glow-20260815.gif" alt="Session tabs: a regular active tab beside a yellow waiting-for-input tab and a red needs-decision tab, both with a breathing glow" width="900">
|
||||
</p>
|
||||
|
||||
Every tab tells you its state at a glance. A running session keeps its green status dot. When a session stops and waits for input, its tab turns **yellow**: steady ring, tinted background, yellow dot, with a slow breathing glow on top. When a permission prompt or question is **blocking** the agent, the tab turns **red** with a faster pulse. The base tint never blinks off, so even a split-second glance (or a screenshot) reads the true state; the ring stays visible while the tab is selected, and a page reload re-arms pending alerts from the server, so a blocked session can never hide behind a fresh-looking tab.
|
||||
@@ -735,10 +739,6 @@ For AI agents and automation that control Codeman without a browser: an agent th
|
||||
|
||||
Everything in this section also ships as a **Claude Code skill** in [`skills/codeman`](skills/codeman/SKILL.md). Install it once and you never paste API docs into a prompt again. You ask for what you want in plain English, and the agent already sitting inside a Codeman session loads the recipes and drives the API itself.
|
||||
|
||||
<p align="center">
|
||||
<a href="docs/images/codeman-skill-20261010.png"><img src="docs/images/codeman-skill-20261010.gif" alt="A real codeman skill run: one plain-English request to a lead session, three Claude Code workers opening as new tabs, and lineage lines from the lead to every worker" width="900"></a>
|
||||
</p>
|
||||
|
||||
#### Step 1: install it
|
||||
|
||||
| How | Command | Scope |
|
||||
|
||||
@@ -24,7 +24,11 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/tiles-crt-stats-20261010.gif" alt="Codeman 平铺视图:六个实时智能体(DeepSeek Harness、Claude Code、Pi、Codex、OpenCode 和一个 shell)以 CRT 动画开启与关闭,顶部实时显示 CPU、内存和 Claude 套餐用量" width="800">
|
||||
⭐ <strong>喜欢 Codeman?<a href="https://github.com/Ark0N/Codeman">在 GitHub 上给它点个 Star 吧!</a></strong>只需轻点一下,就能帮助更多人发现这个项目。⭐
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/subagent-demo-20260724.gif" alt="Codeman — 并行子智能体可视化" width="900">
|
||||
</p>
|
||||
|
||||
> 本文档由英文版 [`README.md`](README.md) 翻译而来。如有出入,以英文版为准。
|
||||
|
||||
@@ -457,13 +457,8 @@ client that opens many concurrent waits against one session will still hit the c
|
||||
What a session's terminal shows, for a client to replay: `data.terminalBuffer`,
|
||||
with `source` (`mux-visible`, `mux-full-history` or `history`), `truncated`,
|
||||
`truncationReason`, `fullSize`, and `captureCols`/`captureRows` when the pane's
|
||||
geometry was read. `paneHistoryLines` (present whenever the body is a pane capture)
|
||||
is the number of scrollback rows tmux holds above the visible frame, which is the
|
||||
most a `full=1` request can add. `truncated` describes the byte stream instead: for a
|
||||
pane with `paneHistoryLines: 0` (a fullscreen CLI in the alternate screen) the bytes a
|
||||
`tail` cut dropped are earlier repaints that no request returns. The capture runs
|
||||
synchronous tmux calls on the server; the `Server-Timing` header reports `capture`,
|
||||
`prepare` and `total`.
|
||||
geometry was read. The capture runs synchronous tmux calls on the server; the
|
||||
`Server-Timing` header reports `capture`, `prepare` and `total`.
|
||||
|
||||
| Query | Meaning |
|
||||
|---|---|
|
||||
|
||||
@@ -211,8 +211,6 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
|
||||
|
||||
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded 1 MiB `?tail=` window on every selection and automatic drop recovery: a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session. Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the Line truncated
|
||||
|
||||
**The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`.
|
||||
|
||||
**A capture reports the geometry it was taken at** (#435): a visible frame repaints each row at an absolute position, counting up to the pane's height and out to the pane's width, so a terminal smaller than that pane damages it two ways at once. Too short and every address past the browser's own height clamps onto the last line, overwriting the rows underneath (measured: against a 50-row pane, a 30-row terminal rendered 28 of a 45-line command and drew the survivors twice). Too narrow and each row is painted out to the pane's width, so the browser wraps every painted row and the wrap on the last one scrolls the whole frame up by one. Nothing in the response used to say what geometry the frame was built for, so the client could not see either case. `PaneCaptureOptions.capturedGeometry` carries it out, and the terminal response publishes it as `captureCols`/`captureRows`. ⚠️ **Both fields are ABSENT unless a frame was really positioned**, and every consumer must test `Number.isFinite` rather than truthiness: `mux-visible` is necessary but not sufficient, because when the `display-message` cursor query fails `capturePaneBuffer` skips the snapshot repaint and returns the raw capture, and the route still labels that non-empty body `mux-visible`. A body that positioned nothing has no geometry to describe and nothing to repair, so a comparison that fires there buys a second capture, a reset plus chunked rewrite, a dropped and reopened WebSocket and a discarded xterm snapshot for no gain. ⚠️ **The comparison runs on `mux-visible` ONLY.** A full-history body is linear scrollback closed by a RELATIVE cursor move, which is relative precisely so the browser's row count need not match the pane's, and a byte-history body carries no row alignment at all, so a size mismatch damages neither and a replay repairs neither. That gate matters because the first select of every non-shell session per page takes the full-history path, where an ungated comparison would fire most often on the one response it cannot help, at the price of a second whole-scrollback capture. ⚠️ **The replay is capped at one attempt and latches per session when it cannot converge.** `resizeRetry` stops two competing fits trading replays forever; a pane already drawing at the size just requested is left alone, because a retry would capture the identical frame; and a pass that still does not converge joins `_geometryRetryUseless`, so the case `Session.resize` declines outright (a small viewport while a desktop viewport's size claim is live, where the retry re-sends the same declined resize and captures the same pane) costs one attempt per session per page load instead of one per select. ⚠️ **The clamp used to manufacture that equality, and no longer can** (#464). This paragraph previously explained it as the signature of a clamp: `getTerminalDimensions()` floors at 40x10 while `fitAddon.fit()` did not, so a terminal under 40 columns or 10 rows reported a pane permanently bigger than itself and would replay on every tab switch. That divergence is fixed at the source — `syncTerminalGeometry()` (terminal-ui.js) fits, floors and APPLIES in one step, so the browser terminal IS the size it reports. The only remaining reason the two can differ is a resize the server declined, which the server now reports back (`Session.ptyGeometry`, the `{"t":"zc"}` frame and the resize response) for the client to adopt by COLUMNS. The equality guard stays, for the plain case of a pane already at the requested size. ⚠️ **A retry pass must not re-arm `_fullHistoryLoaded`**: it did not consume the full-history pull, and re-arming it would spend a whole-scrollback capture on the next select. That branch is currently unreachable by construction, since reaching it needs `source === 'mux-visible'` while a `full=1` pass is answered `mux-full-history` or `history`; a static test over the source is the habit this repo uses for an invariant nothing can execute. Tests: `test/capture-geometry-retry.browser.test.ts` (eight cases, five of which fail against the merge base), `test/tmux-capture-full-history.test.ts`, `test/routes/session-routes.test.ts`.
|
||||
|
||||
⚠️ **A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery must verify itself** (`_scheduleDroppedOutputRecovery`, app.js): a hole in a TUI byte stream is a desynced cursor, which is muffled text (#464). It was a fire-and-forget 2s timer that nulled its own handle and then called `_onSessionNeedsRefresh()` — whose early returns (a buffer load in flight, a refresh already owning the session) are MOST likely to be true during exactly the burst that caused the drop, so the recovery was lost silently and the bytes were never replayed. `_onSessionNeedsRefresh` now returns whether it actually repainted, and the scheduler re-arms while it has not, bounded by `DROP_RECOVERY_MAX_ATTEMPTS` because the early returns it retries past are transient contention. A refresh that died at the capture fetch DEADLINE (it returns `'deadline'`) is a stalled link, not contention, and is NOT retried: each retry would be another `?full=1` capture waiting out a deadline of up to two minutes. The same debounce still collapses a burst into one attempt, and the `TERMINAL DROP` crash-trail line sits behind it, since one line per dropped frame evicted the whole 50-entry trail in under a second. Tests: `test/dropped-output-recovery.test.ts`, whose retry case and no-retry case only pin the fix as a pair.
|
||||
@@ -227,7 +225,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
|
||||
|
||||
**Wheel/touch forwarding is NOT gated on viewport-at-bottom** (#205, `terminal-ui.js:_shouldForwardWheelToApp`): for sessions verified to scroll their own transcript on SGR wheel reports (claude ≥ 2.1.187 while `cliMouseTracking` is true, i.e. fullscreen; version via the local/docker/remote `--version` probes), the plain wheel AND touch drags forward as coalesced SGR reports (`_forwardScrollToApp` → `_sendSyntheticSgrWheel`, 40ms batches, 5-tick cap, 512-byte queue bound). It used to gate on the viewport being at the bottom so both scrollbacks stayed reachable, but a repaint-mode CLI keeps NO terminal scrollback of its own — xterm's buffer holds only replayed repaint frames, so local scrolling drags the CLI's pinned prompt box up the screen over stale frames; and `scrollToLastNonEmptyLine()` routinely parked the viewport off-bottom, silently pinning the wheel to local. Forwarding now snaps the viewport home first (SGR coordinates address the LIVE screen — a report computed from a scrolled-up viewport would hit-test the wrong row). Local scrollback remains on Shift+wheel and the `terminalWheelLocalScrollback` opt-out (both also cover touch via the shared gate; touch has no Shift, so the setting is its only local pin). `_wheelScrollLines()` normalizes `deltaMode` (Firefox fires LINE deltas ≈3/notch — read as pixels that rounded to 0 and fell to the ±1 fallback, ~4× too slow; PAGE deltas scale by `terminal.rows`) while keeping the #154 Shift-axis trap (macOS trackpads put Shift+scroll magnitude on deltaX). Tests: `test/terminal-touch-tap.test.ts`.
|
||||
|
||||
**A false gate on a hollow pane must not mean a DEAD gesture** (#205 round 2, `_maybePageCliTranscript`): every way `_shouldForwardWheelToApp()` returns false leaves a repaint-mode pane scrolling a buffer that has nothing in it (`baseY === 0`) — the version probe came back empty, the CLI really is older than 2.1.187, the `cliMouseTracking` flag is unset (inline claude, or fullscreen right after a server restart), or the user turned on `terminalWheelLocalScrollback`. **opencode is the fifth case, and the gate is false there by design**: its TUI runs on the ALTERNATE SCREEN (1.18.31 measured: tmux `alternate_on=1`, `history_size=0`), so the buffer is hollow, and it IGNORES SGR wheel reports entirely (six `\x1b[<64;…M` reports against an idle pane left the capture byte-identical) while still paging its transcript on PageUp/PageDown (`messages_page_up/down`) — so paging is the only gesture that can reach it, and without it the wheel was silently dead in every opencode tab. The 1.12.0 retest reported exactly that shape for Claude: a wheel that did nothing at all while Fn+Up (PageUp) paged back through intact text, which is the proof that the CLI's own history and the PTY input path were both fine. So under the guard (`_localScrollbackIsHollow()` — `claude` or `opencode`, gate false, `baseY === 0`) wheel and touch travel is translated into coalesced `\x1b[5~` / `\x1b[6~` through the same 40ms queue as the SGR reports, at half a screen of travel per page key (the key jumps a whole screen; a 1:1 mapping was unusably slow with a discrete wheel). ⚠️ `shell`/`pi` own real terminal scrollback and are never paged, and codex/gemini/antigravity/grok/deepseek/omp page-key behaviour is unverified (`docs/scrollback-fix-plan.md`). ⚠️ Shift is excluded on purpose — it is the explicit "give me local scrollback" gesture and must keep that meaning. ⚠️ `terminalWheelLocalScrollback` is deliberately NOT scoped away from repaint-mode CLIs even though it is a footgun there: that would silently override an explicit user choice, so the fallback catches it instead. **Server-side counterpart**: `getClaudeCliVersion()` caches SUCCESS for the process lifetime but must never cache FAILURE — it used to, so one timed-out or PATH-starved probe at the first Claude session start disabled wheel-forwarding for every Claude session until the server restarted (a dead wheel on phone, tablet and laptop at once, the signature of a server-side cause). Failures now retry with a 1/2/4…15min backoff; the policy is the pure `resolveClaudeCliVersion()`. **Tiles** (a grid tile, the split's Pane B: `TerminalTile`) page the wheel through these same gates, called with the tile's own terminal and session (`_localScrollbackIsHollow(target)`, `_shouldForwardWheelToApp(ev, target)`) and the pure `CodemanTerminalInput.pageKeysForTravel`, so the mode list stays in terminal-ui.js alone. ⚠️ A tile's `baseY` is rarely 0 even when hollow: its first capture is taken at the PTY's previous, taller size and its row-shrinking fits push rows up, so it passes `localRows` with those rows discounted (`TerminalTile._localRows`). ⚠️ So a tile can be hollow with its viewport still up in those rows (Shift+PageUp, a scrollbar drag, a wheel during the first replay), and it pages only while `_terminalViewportAtBottom(tile.terminal)` holds: otherwise every wheel, wheel-down included, was paged and swallowed, the stale rows stayed on screen and the click report (which refuses an off-bottom viewport) went dead too. Off the bottom the wheel stays xterm's, so a wheel-down brings the viewport home. The primary pane needs no such gate: hollow there means `baseY === 0`, which is always at the bottom. Tiles have no touch path and do not forward SGR wheel (tile-grid-plan follow-up 4). Tests: `test/terminal-scroll-routing.test.ts`, `test/terminal-tile-scroll.test.ts`, `test/claude-cli-version-cache.test.ts`.
|
||||
**A false gate on a hollow pane must not mean a DEAD gesture** (#205 round 2, `_maybePageCliTranscript`): every way `_shouldForwardWheelToApp()` returns false leaves a repaint-mode pane scrolling a buffer that has nothing in it (`baseY === 0`) — the version probe came back empty, the CLI really is older than 2.1.187, the `cliMouseTracking` flag is unset (inline claude, or fullscreen right after a server restart), or the user turned on `terminalWheelLocalScrollback`. **opencode is the fifth case, and the gate is false there by design**: its TUI runs on the ALTERNATE SCREEN (1.18.31 measured: tmux `alternate_on=1`, `history_size=0`), so the buffer is hollow, and it IGNORES SGR wheel reports entirely (six `\x1b[<64;…M` reports against an idle pane left the capture byte-identical) while still paging its transcript on PageUp/PageDown (`messages_page_up/down`) — so paging is the only gesture that can reach it, and without it the wheel was silently dead in every opencode tab. The 1.12.0 retest reported exactly that shape for Claude: a wheel that did nothing at all while Fn+Up (PageUp) paged back through intact text, which is the proof that the CLI's own history and the PTY input path were both fine. So under the guard (`_localScrollbackIsHollow()` — `claude` or `opencode`, gate false, `baseY === 0`) wheel and touch travel is translated into coalesced `\x1b[5~` / `\x1b[6~` through the same 40ms queue as the SGR reports, at half a screen of travel per page key (the key jumps a whole screen; a 1:1 mapping was unusably slow with a discrete wheel). ⚠️ `shell`/`pi` own real terminal scrollback and are never paged, and codex/gemini/antigravity/grok/deepseek/omp page-key behaviour is unverified (`docs/scrollback-fix-plan.md`). ⚠️ Shift is excluded on purpose — it is the explicit "give me local scrollback" gesture and must keep that meaning. ⚠️ `terminalWheelLocalScrollback` is deliberately NOT scoped away from repaint-mode CLIs even though it is a footgun there: that would silently override an explicit user choice, so the fallback catches it instead. **Server-side counterpart**: `getClaudeCliVersion()` caches SUCCESS for the process lifetime but must never cache FAILURE — it used to, so one timed-out or PATH-starved probe at the first Claude session start disabled wheel-forwarding for every Claude session until the server restarted (a dead wheel on phone, tablet and laptop at once, the signature of a server-side cause). Failures now retry with a 1/2/4…15min backoff; the policy is the pure `resolveClaudeCliVersion()`. **Tiles** (a grid tile, the split's Pane B: `TerminalTile`) page the wheel through these same gates, called with the tile's own terminal and session (`_localScrollbackIsHollow(target)`, `_shouldForwardWheelToApp(ev, target)`) and the pure `CodemanTerminalInput.pageKeysForTravel`, so the mode list stays in terminal-ui.js alone. ⚠️ A tile's `baseY` is rarely 0 even when hollow: its first capture is taken at the PTY's previous, taller size and its row-shrinking fits push rows up, so it passes `localRows` with those rows discounted (`TerminalTile._localRows`). ⚠️ So a tile can be hollow with its viewport still up in those rows (Shift+PageUp, a scrollbar drag, a wheel during the first replay), and it pages only while `_terminalViewportAtBottom(tile.terminal)` holds: otherwise every wheel, wheel-down included, was paged and swallowed, the stale rows stayed on screen and the click report (which refuses an off-bottom viewport) went dead too. Off the bottom the wheel stays xterm's, so a wheel-down brings the viewport home. The primary pane needs no such gate: hollow there means `baseY === 0`, which is always at the bottom. Tiles also FORWARD the wheel to Claude's fullscreen renderer as SGR reports (`TerminalTile._maybeForwardWheelToCli`: the same `_shouldForwardWheelToApp(ev, target)` gate, the cell from `_clientPointToCell(x, y, tile.terminal)`, the bytes from the pure `CodemanTerminalInput.sgrWheelReports` the primary pane's `_sendSyntheticSgrWheel` also uses, flushed through the tile's own coalescer to the tile's session, never the primary queue, which flushes to `activeSessionId`); before that a fullscreen Claude tile left the wheel to xterm, which scrolled only stale replayed frames while Claude's transcript never moved. ⚠️ Shift+wheel in a tile is scrolled by the tile itself (`_maybeScrollLocalOnShift`, `scrollLines()` on the dominant axis), as in the primary pane: xterm's own scroller turns a Shift+vertical wheel into a horizontal one off macOS and Chrome on Windows sends Shift+wheel as `deltaX`, so left to xterm the gesture was dead. Tiles have no touch path. Tests: `test/terminal-scroll-routing.test.ts`, `test/terminal-tile-scroll.test.ts`, `test/claude-cli-version-cache.test.ts`.
|
||||
|
||||
**Why the wheel went where it went is LOGGED** (`_logScrollRouting`): one console line per session per distinct decision — `[scroll] <id> → forward-sgr|page-keys|local-scrollback|repull-refused-downgrade (mode=…, cliVersion=…, localScrollbackOptOut=…, mouseTracking=…, localScrollbackRows=…)`. #205 ran two rounds of remote guesswork over questions this line answers directly; keep it when touching the routing.
|
||||
|
||||
@@ -237,7 +235,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
|
||||
|
||||
**Run launch synchronization**: the main Run entrypoint in `session-ui.js` holds an in-flight lock and disables `#runBtn` for the whole launch (at least 500ms), so a double click cannot create duplicate sessions with the same `w<n>-<case>` name. A successful create/quick-start also calls `_ensureCreatedSessionVisible()` before `selectSession()`: local creates use the response's full session snapshot; quick-start modes fetch `GET /api/sessions/:id` only when `session:created` SSE has not already populated the map. The normal `_onSessionCreated()` handler remains the idempotent upsert, so POST-first and SSE-first ordering both produce one immediately-rendered tab. Tests: `test/run-mode-ui.test.ts`.
|
||||
|
||||
Further detail, closing: ⚠️ **Closing has the mirror-image race and one owner**: `closeSession()` reads `wasActive` BEFORE its `await` and announces the delete via `_closingSessions`, while `_onSessionDeleted` skips the active-session handoff for an id in that set. Both used to read `activeSessionId` after the fact, so the `session_deleted` broadcast for your own delete could null it first and closing the tab you were on landed on the welcome screen instead of the next session, on the same build, depending on timing. The fallback also picks the first order entry that is still in `sessions` (a dead id can linger in `sessionOrder`, same reason Alt+N indexes a live-filtered list). A delete from ANOTHER client still shows the welcome screen, which is the honest answer when what you were looking at was taken away. ⚠️ **The close is optimistic**: `closeSession()` runs `_onSessionDeleted({ id })` itself (the split, tile, detached-window, WebSocket and per-session teardown, idempotent so the real broadcast finds nothing left), does the follow-up selection and renders the strip with `renderSessionTabs({ immediate: true })` BEFORE sending the DELETE; the server's kill takes a few hundred ms and a tab that sat there that long read as a dead button. `_onSessionCreated`/`_onSessionUpdated` ignore ids in `_closingSessions`, so no upsert brings the row back mid-request. `_apiDelete` resolves a Response (or `null`), never throws: OK or 404 is closed; anything else is checked with `GET /api/sessions/:id` (a delete can land and lose its reply, after its broadcast was already spent) and only a session that still exists gets its row back at its old index, with the error toast. Tests: `test/session-close-fallback.test.ts`.
|
||||
Further detail, closing: ⚠️ **Closing has the mirror-image race and one owner**: `closeSession()` reads `wasActive` BEFORE its `await` and announces the delete via `_closingSessions`, while `_onSessionDeleted` skips the active-session handoff for an id in that set. Both used to read `activeSessionId` after the fact, so the `session_deleted` broadcast for your own delete could null it first and closing the tab you were on landed on the welcome screen instead of the next session, on the same build, depending on timing. The fallback also picks the first order entry that is still in `sessions` (a dead id can linger in `sessionOrder`, same reason Alt+N indexes a live-filtered list). A delete from ANOTHER client still shows the welcome screen, which is the honest answer when what you were looking at was taken away. Tests: `test/session-close-fallback.test.ts`.
|
||||
|
||||
### Circuit breakers: Ralph and PTY-exit
|
||||
|
||||
@@ -813,7 +811,7 @@ Further detail: with many sessions the horizontal strip stops being scannable, w
|
||||
|
||||
⚠️ **One load queue.** Every capture a tile fetches (initial load, refresh after a reconnect, server `{t:'r'}` refresh, server `{t:'c'}` refresh, dropped-output recovery refresh, shell history pull) goes through the grid's ONE `TileLoadQueue` (terminal-tile.js, the tile's `scheduleLoad` option): concurrency 1, a history pull first, then the focused tile, then reading order; a destroyed tile's waiting loads are dropped unrun and destroy() aborts its running fetch. A load holds the slot only while xterm parses its replay: `writeChunked` queues every 32 KB slice at once (one 1 MiB window at a time, since xterm's write queue throws past 50 MB) and settles on the callback of a write queued behind them, never one slice per animation frame (that pacing held the slot about a second per 1 MiB tile). ⚠️ destroy() settles a replay in progress (`_cancelReplay`): a disposed xterm never runs that callback, and an unsettled replay would hold the tile's flag and the grid's queue forever. Each `GET /api/sessions/:id/terminal` runs synchronous tmux calls, so N tiles loading at once (after a deploy restart all N reopen within a second) would stall every WebSocket and SSE stream on the server back to back. Grid tiles load the BOUNDED window (`full=1&tail=TERMINAL_TAIL_SIZE` for a TUI, `tail=` for a shell; the `boundedLoad` option), and every full capture of theirs (a TUI load, a shell history pull) also sends `lines=<TILE_SCROLLBACK + rows>`, so tmux reads no more history than the tile keeps instead of the whole history limit (the route's optional `lines` bound, docs/api-reference.md; the split's Pane B sends none), keep `TILE_SCROLLBACK` lines and their own per-device font (`codeman-tile-font-size`, Ctrl +/- while the grid is open). A refresh fetches at its turn, not when asked, and resets the screen with the queued in-stream `\x1bc` only once its capture is in hand, right before the replay (never xterm's `clear()` before the fetch), so a tile keeps its last frame through its wait and its own round trip; a failed, aborted or empty fetch writes nothing and resets nothing, and the tile keeps its last frame and every held live frame.
|
||||
|
||||
⚠️ **Selections.** The tile branch of `selectSession` sits right after its "already active" early return: a tiled id is FOCUSED (`_selectTiledSession`: no cleanup, replay, resize or main socket; the shared `_refreshSessionPanels`; only a user-initiated pick acknowledges the idle alert). A USER-initiated pick of a session that is not tiled leaves the grid for the single view, remembered (decision 1), and so does `leaveTiles` (a followed `#session=` link); an `auto` pick never collapses it. Whoever calls `closeTileGrid({ reselect: false })` and then selects must null `activeSessionId` first, or `_cleanupPreviousSession` saves the parked terminal's stale content as a snapshot. App-driven fallbacks pick a tile: `closeSession` captures the neighbouring tile BEFORE it tears the tile down (like `wasActive`) and focuses it with `auto` before the delete request goes out; the `_onSessionDeleted` wrapper does the same for a delete from elsewhere, and leaves a close from this tab (`_closingSessions`) to `closeSession`. Ctrl+Tab and Alt+[ ] cycle the tiles. A popped-out (detached) session leaves the grid. Moving focus off a zoomed tile restores the grid (tmux `select-pane`); an automatic zoom (window too small for the minimum tile) follows focus instead.
|
||||
⚠️ **Selections.** The tile branch of `selectSession` sits right after its "already active" early return: a tiled id is FOCUSED (`_selectTiledSession`: no cleanup, replay, resize or main socket; the shared `_refreshSessionPanels`; only a user-initiated pick acknowledges the idle alert). A USER-initiated pick of a session that is not tiled leaves the grid for the single view, remembered (decision 1), and so does `leaveTiles` (a followed `#session=` link); an `auto` pick never collapses it. Whoever calls `closeTileGrid({ reselect: false })` and then selects must null `activeSessionId` first, or `_cleanupPreviousSession` saves the parked terminal's stale content as a snapshot. App-driven fallbacks pick a tile: `closeSession` captures the neighbouring tile BEFORE its await (like `wasActive`; the delete broadcast may already have removed the tile) and focuses it with `auto`; the `_onSessionDeleted` wrapper does the same for a delete from elsewhere, and leaves a close from this tab (`_closingSessions`) to `closeSession`. Ctrl+Tab and Alt+[ ] cycle the tiles. A popped-out (detached) session leaves the grid. Moving focus off a zoomed tile restores the grid (tmux `select-pane`); an automatic zoom (window too small for the minimum tile) follows focus instead.
|
||||
|
||||
⚠️ **Chords.** `toggle-tile-grid` (Ctrl+Shift+G), `focus-tile-*` (Alt+Shift+Arrows), `move-tile-*` (Ctrl+Shift+Arrows), `zoom-tile` (Alt+Shift+Enter) and `remove-tile` (unbound) are registry entries kept OUT of `SHORTCUT_ACTIONS`: `tileShortcutFor` decides whether one applies (the toggle while the grid is open, or where one could open AND `showTileGridButton` is on, an owner decision: with the setting off the chord is inert and passes through like any unbound key; the rest only while it is open), the capture handler dispatches it, and the main terminal's and every tile's xterm key handler return false for it, for every event type and BEFORE the Shift+Enter gate (Alt+Shift+Enter would otherwise send `S-Enter`). Outside the grid the focus chords reach the terminal untouched. The move chords also apply while a tile is zoomed (a no-op, so their keys never reach the CLI). The arrow chords, focus and move, never apply in a text field other than xterm's own textarea (`isTextFieldTarget`), where shifted arrows select.
|
||||
|
||||
@@ -1073,8 +1071,6 @@ Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: termina
|
||||
|
||||
⚠️ It lives in its own module because as a private method of `tmux-manager.ts` the regression test had to keep its own COPY of the algorithm, which is a test that passes while the shipped code rots.
|
||||
|
||||
⚠️ **The kill path's waits are deadlines, not sleeps** (`waitForProcessesExit()`, `utils/process-exit-wait.ts`): `Session.stop()` (PTY client, 100 ms), and `killSession()`'s children (200 ms), process group (100 ms) and final verify (2 s) each stop waiting as soon as the processes are gone. They used to be fixed sleeps plus a 100 ms verify poll, ~0.45 s per close even for a session whose processes died in a few ms. `isProcessRunning()` counts a zombie as exited (`/proc/<pid>/stat` state `Z`/`X`), since `kill(pid, 0)` cannot tell one apart and a zombie only awaits its reaper. Claude itself takes ~0.8 s to exit on SIGTERM or SIGHUP (measured 2026-10-10), so the process-group deadline still ends in SIGKILL for a claude pane, as it always did. `tmux kill-session` and the pane-pid lookup on this path are async, never `execSync` (tens of ms of a frozen server per close). `killSubagentsForSession()` makes ONE `getClaudePids()` scan for all of the session's active/idle subagents, never one `pgrep` per agent (~85 ms each with ~100 matching processes).
|
||||
|
||||
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
|
||||
|
||||
## Local packages and build artifacts
|
||||
|
||||
|
Before Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 706 KiB |
|
Before Width: | Height: | Size: 3.6 MiB |
|
Before Width: | Height: | Size: 774 KiB |
|
Before Width: | Height: | Size: 379 KiB |
|
Before Width: | Height: | Size: 2.7 MiB |
|
Before Width: | Height: | Size: 2.7 MiB |
@@ -1008,13 +1008,17 @@ exits green. Use the browser runner for those files and read the file count.
|
||||
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. (Done since: a tile pages a
|
||||
hollow buffer's CLI transcript with PageUp/PageDown, the primary pane's
|
||||
#555 route, and hand-reports a plain click while its session has
|
||||
`cliMouseTracking` on, both through the primary pane's gates aimed at the
|
||||
tile. The SGR wheel forwarding itself is still open: a fullscreen Claude
|
||||
tile leaves the wheel to xterm.)
|
||||
4. Tile parity extras: a "Load full history" action inside a tile. (Done
|
||||
since: a tile pages a hollow buffer's CLI transcript with PageUp/PageDown,
|
||||
the primary pane's #555 route, hand-reports a plain click while its session
|
||||
has `cliMouseTracking` on, and forwards the wheel to Claude's fullscreen
|
||||
renderer as SGR wheel reports from its own cells
|
||||
(`TerminalTile._maybeForwardWheelToCli`, encoding shared with the primary
|
||||
pane via `CodemanTerminalInput.sgrWheelReports`), all through the primary
|
||||
pane's gates aimed at the tile. Before that, a fullscreen Claude tile left
|
||||
the wheel to xterm, which scrolled only stale replayed frames. Shift+wheel
|
||||
scrolls the tile's local scrollback itself (`_maybeScrollLocalOnShift`),
|
||||
since xterm turns it into a horizontal no-op off macOS.)
|
||||
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`,
|
||||
|
||||
@@ -146,11 +146,7 @@ instead of its native cloud backend. See [Custom Model Endpoints](Custom-Model-E
|
||||
|
||||
### Notifications
|
||||
|
||||
Master toggle, browser notifications, push subscription, audio alerts, how long a
|
||||
corner toast stays on screen (**Toast display time**, 1 to 300 seconds, default 3) and
|
||||
how long a desktop notification stays up before Codeman closes it (**Browser
|
||||
notification display time**, default 8; both per device, and your OS may close a
|
||||
desktop notification sooner), the idle
|
||||
Master toggle, browser notifications, push subscription, audio alerts, the idle
|
||||
threshold that decides when a quiet session counts as needing you, and the server-wide
|
||||
webhook (ntfy, Slack, Discord or generic JSON; admins only in multi-user mode). See
|
||||
[Notifications And Approvals](Notifications-And-Approvals).
|
||||
|
||||
@@ -6,7 +6,7 @@ Most of Codeman's UI is **opt-in**. A stock install shows a deliberately small h
|
||||
feature you read about here may simply not be on screen yet. Where that is the case, this
|
||||
page says so and names the setting.
|
||||
|
||||

|
||||

|
||||
|
||||
## Layout
|
||||
|
||||
@@ -212,10 +212,7 @@ Worth knowing:
|
||||
- **Scrollback.** Agent/TUI sessions pull their entire tmux scrollback on first open.
|
||||
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
|
||||
switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux
|
||||
history; press **Load full history** to pull the rest explicitly. That notice only
|
||||
appears once you scroll to the top, leaves when you scroll back down, and stays away
|
||||
for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen
|
||||
Claude) never show it, since there is nothing more to load. Automatic output
|
||||
history; press **Load full history** to pull the rest explicitly. Automatic output
|
||||
recovery stays within the bounded browser buffer.
|
||||
- **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent
|
||||
Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in
|
||||
|
||||
@@ -204,15 +204,6 @@ export interface PaneCaptureOptions {
|
||||
* rendering it needs the real height to know the frame fits.
|
||||
*/
|
||||
capturedGeometry?: { cols: number; rows: number };
|
||||
/**
|
||||
* Filled in by the implementation with the number of rows the pane holds in
|
||||
* scrollback ABOVE the visible frame (tmux `#{history_size}`), read in the
|
||||
* same query as the geometry. 0 means a full-history capture can return
|
||||
* nothing beyond the visible frame: a pane in the alternate screen (a
|
||||
* fullscreen CLI that keeps its transcript itself) never accumulates any.
|
||||
* Absent when the pane could not be queried.
|
||||
*/
|
||||
capturedHistoryLines?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -106,7 +106,6 @@ import {
|
||||
getClaudeBinaryPath,
|
||||
spawnPtyWithHelperRepair,
|
||||
resolveLocalShell,
|
||||
waitForProcessesExit,
|
||||
} from './utils/index.js';
|
||||
import {
|
||||
MAX_TERMINAL_BUFFER_SIZE,
|
||||
@@ -180,10 +179,7 @@ const WIRE_ACTIVITY_SETTLE_MS = 15_000;
|
||||
|
||||
// Note: Auto-compact/clear timing constants moved to session-auto-ops.ts
|
||||
|
||||
/**
|
||||
* Longest the PTY process gets to exit on SIGTERM before SIGKILL when stopping a
|
||||
* session. A deadline, not a sleep: stop() moves on as soon as it has exited.
|
||||
*/
|
||||
/** Graceful shutdown delay when stopping session (100ms) */
|
||||
const GRACEFUL_SHUTDOWN_DELAY_MS = 100;
|
||||
|
||||
// Conversations kept in a pane's chain. A pane that /clears repeatedly would
|
||||
@@ -4805,10 +4801,8 @@ export class Session extends EventEmitter {
|
||||
console.warn('[Session] Failed to send SIGTERM to PTY process (may already be dead):', err);
|
||||
}
|
||||
|
||||
// Give it a moment to terminate gracefully. For a tmux-backed session this
|
||||
// is the attach client, gone within a few ms of SIGTERM, and this used to be
|
||||
// a fixed 100ms sleep on every close.
|
||||
if (pid) await waitForProcessesExit([pid], { timeoutMs: GRACEFUL_SHUTDOWN_DELAY_MS });
|
||||
// Give it a moment to terminate gracefully
|
||||
await new Promise((resolve) => setTimeout(resolve, GRACEFUL_SHUTDOWN_DELAY_MS));
|
||||
|
||||
// Force kill with SIGKILL if still alive
|
||||
try {
|
||||
|
||||
@@ -761,35 +761,13 @@ export class SubagentWatcher extends EventEmitter {
|
||||
* by workingDir alone would kill subagents belonging to OTHER sessions.
|
||||
*/
|
||||
async killSubagentsForSession(workingDir: string, sessionId?: string): Promise<void> {
|
||||
const targets = this.getSubagentsForSession(workingDir).filter(
|
||||
// Only kill subagents belonging to this specific session
|
||||
(agent) => (agent.status === 'active' || agent.status === 'idle') && (!sessionId || agent.sessionId === sessionId)
|
||||
);
|
||||
if (targets.length === 0) return;
|
||||
|
||||
// ONE process scan for the lot. This used to call killSubagent() per agent, and
|
||||
// each call ran its own `pgrep -f claude` plus a /proc read per match (~85ms on a
|
||||
// box with ~100 matching processes), so closing a session right after a workflow
|
||||
// paid that once per recently active subagent. The match rules are
|
||||
// findSubagentProcess()'s: getClaudePids() skips CODEMAN_MUX=1 processes too.
|
||||
const pidMap = await this.getClaudePids();
|
||||
const signalled = new Set<number>();
|
||||
for (const agent of targets) {
|
||||
// The liveness checker may have completed it while the scan ran.
|
||||
if (agent.status !== 'active' && agent.status !== 'idle') continue;
|
||||
for (const [pid, procInfo] of pidMap) {
|
||||
if (signalled.has(pid)) continue;
|
||||
if (procInfo.environ.includes(agent.sessionId) || procInfo.cmdline.includes(agent.sessionId)) {
|
||||
signalled.add(pid);
|
||||
try {
|
||||
process.kill(pid, 'SIGTERM');
|
||||
} catch {
|
||||
// Process may have already exited
|
||||
}
|
||||
break; // one process per agent, as killSubagent() does
|
||||
}
|
||||
const subagents = this.getSubagentsForSession(workingDir);
|
||||
for (const agent of subagents) {
|
||||
if (agent.status === 'active' || agent.status === 'idle') {
|
||||
// Only kill subagents belonging to this specific session
|
||||
if (sessionId && agent.sessionId !== sessionId) continue;
|
||||
await this.killSubagent(agent.agentId);
|
||||
}
|
||||
this.markSubagentAsCompleted(agent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,13 +94,7 @@ import {
|
||||
type DockerMount,
|
||||
type DockerSeedCopy,
|
||||
} from './docker-hosts.js';
|
||||
import {
|
||||
wrapWithNice,
|
||||
SAFE_PATH_PATTERN,
|
||||
resolveLocalShell,
|
||||
loginShellArgs,
|
||||
waitForProcessesExit,
|
||||
} from './utils/index.js';
|
||||
import { wrapWithNice, SAFE_PATH_PATTERN, resolveLocalShell, loginShellArgs } from './utils/index.js';
|
||||
import type {
|
||||
TerminalMultiplexer,
|
||||
MuxSession,
|
||||
@@ -150,18 +144,12 @@ const TMUX_CREATION_WAIT_MS = 100;
|
||||
const GET_PID_MAX_RETRIES = 5;
|
||||
const GET_PID_RETRY_MS = 200;
|
||||
|
||||
/**
|
||||
* How long killSession gives a pane's children to exit on SIGTERM before it
|
||||
* re-scans and SIGKILLs. A deadline, not a sleep (see utils/process-exit-wait.ts).
|
||||
*/
|
||||
/** Delay after tmux kill command (200ms) */
|
||||
const TMUX_KILL_WAIT_MS = 200;
|
||||
|
||||
/** How long the pane's process group gets to exit on SIGTERM before SIGKILL. Also a deadline. */
|
||||
/** Delay for graceful shutdown (100ms) */
|
||||
const GRACEFUL_SHUTDOWN_WAIT_MS = 100;
|
||||
|
||||
/** How long killSession waits for every process it signalled to be gone before it warns. */
|
||||
const KILL_VERIFY_TIMEOUT_MS = 2000;
|
||||
|
||||
/** Default stats collection interval (2 seconds) */
|
||||
const DEFAULT_STATS_INTERVAL_MS = 2000;
|
||||
|
||||
@@ -700,12 +688,6 @@ interface PaneCursorGeometry {
|
||||
rows: number;
|
||||
cursorX: number;
|
||||
cursorY: number;
|
||||
/**
|
||||
* `#{history_size}`: rows tmux holds ABOVE the visible frame, i.e. what a
|
||||
* full-history capture can add. Absent when the query did not return it.
|
||||
* Optional and validated on its own, so a bad value never voids the caret.
|
||||
*/
|
||||
historyLines?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -722,7 +704,7 @@ export function queryPaneCursor(run: () => string): PaneCursorGeometry | null {
|
||||
console.error('[TmuxManager] Failed to query pane cursor after capture:', cursorErr);
|
||||
return null;
|
||||
}
|
||||
const [cursorX, cursorY, cols, rows, historyLines] = raw.split(/\s+/).map((value) => parseInt(value, 10));
|
||||
const [cursorX, cursorY, cols, rows] = raw.split(/\s+/).map((value) => parseInt(value, 10));
|
||||
if (
|
||||
!Number.isFinite(cursorX) ||
|
||||
!Number.isFinite(cursorY) ||
|
||||
@@ -735,9 +717,7 @@ export function queryPaneCursor(run: () => string): PaneCursorGeometry | null {
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const geometry: PaneCursorGeometry = { cols, rows, cursorX, cursorY };
|
||||
if (Number.isFinite(historyLines) && historyLines >= 0) geometry.historyLines = historyLines;
|
||||
return geometry;
|
||||
return { cols, rows, cursorX, cursorY };
|
||||
}
|
||||
|
||||
/** SGR attributes, which is all `capture-pane -e` emits. */
|
||||
@@ -2370,28 +2350,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link getPanePid} without blocking the event loop, for the kill path: a close
|
||||
* must not stall every other session's I/O while tmux answers.
|
||||
*/
|
||||
private async getPanePidAsync(muxName: string): Promise<number | null> {
|
||||
if (IS_TEST_MODE) return 99999;
|
||||
if (!isValidMuxName(muxName)) {
|
||||
console.error('[TmuxManager] Invalid session name in getPanePidAsync:', muxName);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execAsync(`${this.tmux()} display-message -t "${muxName}" -p '#{pane_pid}'`, {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
const pid = parseInt(stdout.trim(), 10);
|
||||
return Number.isNaN(pid) ? null : pid;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a tmux session exists.
|
||||
*/
|
||||
@@ -2646,9 +2604,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
});
|
||||
}
|
||||
|
||||
// Check if a process is still alive. Signal decisions only: an unreaped zombie
|
||||
// counts here, so its process group still gets the SIGKILL below. The WAITS use
|
||||
// waitForProcessesExit(), which counts a zombie as exited.
|
||||
// Check if a process is still alive
|
||||
private isProcessAlive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
@@ -2658,9 +2614,20 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
// Verify all PIDs are dead, returning as soon as they are
|
||||
// Verify all PIDs are dead, with retry
|
||||
private async verifyProcessesDead(pids: number[], maxWaitMs: number = 1000): Promise<boolean> {
|
||||
const stillAlive = await waitForProcessesExit(pids, { timeoutMs: maxWaitMs });
|
||||
const startTime = Date.now();
|
||||
const checkInterval = 100;
|
||||
|
||||
while (Date.now() - startTime < maxWaitMs) {
|
||||
const aliveCount = pids.filter((pid) => this.isProcessAlive(pid)).length;
|
||||
if (aliveCount === 0) {
|
||||
return true;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, checkInterval));
|
||||
}
|
||||
|
||||
const stillAlive = pids.filter((pid) => this.isProcessAlive(pid));
|
||||
if (stillAlive.length > 0) {
|
||||
console.warn(`[TmuxManager] ${stillAlive.length} processes still alive after kill: ${stillAlive.join(', ')}`);
|
||||
}
|
||||
@@ -2718,7 +2685,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
if (isValidMuxName(session.muxName)) {
|
||||
try {
|
||||
// Local socket only — detaches the remote session by killing the local ssh pane.
|
||||
await execAsync(`${this.tmux()} kill-session -t "${session.muxName}" 2>/dev/null`, {
|
||||
execSync(`${this.tmux()} kill-session -t "${session.muxName}" 2>/dev/null`, {
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
} catch {
|
||||
@@ -2735,7 +2702,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
|
||||
// Get current PID (may have changed)
|
||||
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
|
||||
const currentPid = this.getPanePid(session.muxName) || session.pid;
|
||||
|
||||
console.log(`[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`);
|
||||
|
||||
@@ -2757,9 +2724,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
// Most children are gone within a few ms; the re-scan below still runs, to
|
||||
// catch anything spawned since the first one.
|
||||
await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS });
|
||||
await new Promise((resolve) => setTimeout(resolve, TMUX_KILL_WAIT_MS));
|
||||
|
||||
childPids = await this.getChildPidsFresh(currentPid);
|
||||
for (const childPid of childPids) {
|
||||
@@ -2777,7 +2742,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
if (this.isProcessAlive(currentPid)) {
|
||||
try {
|
||||
process.kill(-currentPid, 'SIGTERM');
|
||||
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
|
||||
await new Promise((resolve) => setTimeout(resolve, GRACEFUL_SHUTDOWN_WAIT_MS));
|
||||
if (this.isProcessAlive(currentPid)) {
|
||||
process.kill(-currentPid, 'SIGKILL');
|
||||
}
|
||||
@@ -2786,12 +2751,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 3: Kill tmux session by name (guard the name before it reaches the shell).
|
||||
// Async: tmux takes tens of ms to tear a session down, and execSync held the
|
||||
// whole server for that long on every close.
|
||||
// Strategy 3: Kill tmux session by name (guard the name before it reaches the shell)
|
||||
if (isValidMuxName(session.muxName)) {
|
||||
try {
|
||||
await execAsync(`${this.tmux()} kill-session -t "${session.muxName}" 2>/dev/null`, {
|
||||
execSync(`${this.tmux()} kill-session -t "${session.muxName}" 2>/dev/null`, {
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
} catch {
|
||||
@@ -2835,7 +2798,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
|
||||
// Verify all processes are dead
|
||||
const allDead = await this.verifyProcessesDead(allPids, KILL_VERIFY_TIMEOUT_MS);
|
||||
const allDead = await this.verifyProcessesDead(allPids, 2000);
|
||||
if (!allDead) {
|
||||
console.error(`[TmuxManager] Warning: Some processes may still be alive for session ${session.muxName}`);
|
||||
}
|
||||
@@ -3898,7 +3861,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// to keep when a move follows to put the caret back above them.
|
||||
const geometry = queryPaneCursor(() =>
|
||||
execSync(
|
||||
`${this.tmux()} display-message -p -t ${shellescape(target)} '#{cursor_x} #{cursor_y} #{pane_width} #{pane_height} #{history_size}'`,
|
||||
`${this.tmux()} display-message -p -t ${shellescape(target)} '#{cursor_x} #{cursor_y} #{pane_width} #{pane_height}'`,
|
||||
{ encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }
|
||||
)
|
||||
);
|
||||
@@ -3910,10 +3873,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// geometry is reported there for diagnosis rather than for repair. Only
|
||||
// the caller can see both sizes, so hand it this one.
|
||||
if (opts && geometry) opts.capturedGeometry = { cols: geometry.cols, rows: geometry.rows };
|
||||
// Same query, no extra tmux call: how much scrollback a full-history pull
|
||||
// could return. A pane in the alternate screen (fullscreen claude) holds
|
||||
// none, and the partial-history notice must not promise it.
|
||||
if (opts && geometry?.historyLines !== undefined) opts.capturedHistoryLines = geometry.historyLines;
|
||||
|
||||
if (fullHistory) {
|
||||
// Without geometry there is no cursor move, so fall back to the old trim.
|
||||
|
||||
@@ -12,7 +12,6 @@ export { Debouncer, KeyedDebouncer } from './debouncer.js';
|
||||
export { startEventLoopMonitor } from './event-loop-monitor.js';
|
||||
export type { EventLoopMonitorHandle } from './event-loop-monitor.js';
|
||||
export { StaleExpirationMap } from './stale-expiration-map.js';
|
||||
export { isProcessRunning, waitForProcessesExit, PROCESS_EXIT_POLL_MS } from './process-exit-wait.js';
|
||||
export {
|
||||
ANSI_ESCAPE_PATTERN_FULL,
|
||||
ANSI_ESCAPE_PATTERN_SIMPLE,
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Wait for processes to exit, and return as soon as they have.
|
||||
*
|
||||
* The session kill path used to sleep a FIXED interval after each signal (100 ms
|
||||
* for the PTY client, 200 ms for the pane's children, 100 ms for the process
|
||||
* group) and then verified in 100 ms steps. A process that was gone after 3 ms
|
||||
* still cost the whole interval, so closing a tab spent most of its ~0.5 s in
|
||||
* timers. This keeps every deadline the kill path had; it only stops waiting
|
||||
* once there is nothing left to wait for.
|
||||
*
|
||||
* A zombie counts as exited. It holds nothing but its pid until the parent reaps
|
||||
* it, and on the kill path that parent is the tmux server or the service
|
||||
* manager, which is no reason to hold up a close. `kill(pid, 0)` cannot tell a
|
||||
* zombie from a running process, so on Linux the state letter in
|
||||
* `/proc/<pid>/stat` decides; without procfs `kill(pid, 0)` is the answer.
|
||||
*
|
||||
* @module utils/process-exit-wait
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
/** Poll step while waiting: an exit is noticed within about one frame. */
|
||||
export const PROCESS_EXIT_POLL_MS = 10;
|
||||
|
||||
/**
|
||||
* True while `pid` names a process that has not exited. A pid we may not signal
|
||||
* reads as not running, which is what the kill path's own check always did:
|
||||
* there is nothing it could do about such a process anyway.
|
||||
*/
|
||||
export function isProcessRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (process.platform !== 'linux') return true;
|
||||
let stat: string;
|
||||
try {
|
||||
stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
} catch (err) {
|
||||
// Gone between the two reads. Any other failure: trust kill(pid, 0).
|
||||
return (err as NodeJS.ErrnoException).code !== 'ENOENT';
|
||||
}
|
||||
// "<pid> (<comm>) <state> …": comm may hold spaces and parentheses itself,
|
||||
// so the state is the field after the LAST ')'.
|
||||
const close = stat.lastIndexOf(')');
|
||||
const state = close === -1 ? '' : stat.charAt(close + 2);
|
||||
return state !== 'Z' && state !== 'X';
|
||||
}
|
||||
|
||||
export interface WaitForExitOptions {
|
||||
/** Give up after this long; the survivors are returned, never thrown. */
|
||||
timeoutMs: number;
|
||||
/** Poll step, {@link PROCESS_EXIT_POLL_MS} by default. */
|
||||
pollMs?: number;
|
||||
/** Liveness probe, {@link isProcessRunning} by default (injectable for tests). */
|
||||
isRunning?: (pid: number) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve once every pid in `pids` has exited, or at the deadline with the ones
|
||||
* that have not. Never rejects.
|
||||
*/
|
||||
export async function waitForProcessesExit(pids: readonly number[], options: WaitForExitOptions): Promise<number[]> {
|
||||
const isRunning = options.isRunning ?? isProcessRunning;
|
||||
const pollMs = Math.max(1, options.pollMs ?? PROCESS_EXIT_POLL_MS);
|
||||
const deadline = Date.now() + options.timeoutMs;
|
||||
let running = pids.filter((pid) => isRunning(pid));
|
||||
while (running.length > 0) {
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) break;
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, remaining)));
|
||||
running = running.filter((pid) => isRunning(pid));
|
||||
}
|
||||
return running;
|
||||
}
|
||||
@@ -2286,8 +2286,6 @@ class CodemanApp {
|
||||
}
|
||||
|
||||
_onSessionCreated(data) {
|
||||
// A session this tab is closing stays closed until the server answers.
|
||||
if (this._closingSessions?.has(data.id)) return;
|
||||
this.sessions.set(data.id, data);
|
||||
// Add new session to end of tab order
|
||||
if (!this.sessionOrder.includes(data.id)) {
|
||||
@@ -2312,9 +2310,6 @@ class CodemanApp {
|
||||
|
||||
_onSessionUpdated(data) {
|
||||
const session = data.session || data;
|
||||
// A session this tab is closing stays closed until the server answers
|
||||
// (closeSession() puts it back if the delete is refused).
|
||||
if (this._closingSessions?.has(session.id)) return;
|
||||
const oldSession = this.sessions.get(session.id);
|
||||
const claudeSessionIdJustSet = session.claudeSessionId && (!oldSession || !oldSession.claudeSessionId);
|
||||
this.sessions.set(session.id, session);
|
||||
@@ -5959,19 +5954,9 @@ class CodemanApp {
|
||||
// Session Tabs
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
renderSessionTabs({ immediate = false } = {}) {
|
||||
renderSessionTabs() {
|
||||
// Don't re-render while user is typing in the inline rename input
|
||||
if (this._inlineRenameActive) return;
|
||||
if (immediate) {
|
||||
// For a change the user just made and is watching for (closing a tab). The
|
||||
// debounce restarts on every session update, so with busy sessions around a
|
||||
// debounced pass can lag well past its 100ms. A pass still pending would only
|
||||
// repeat this one, so it is dropped.
|
||||
clearTimeout(this._debounceTimers.sessionTabs);
|
||||
this._debounceTimers.sessionTabs = null;
|
||||
this._renderSessionTabsImmediate();
|
||||
return;
|
||||
}
|
||||
this._debouncedCall('sessionTabs', this._renderSessionTabsImmediate);
|
||||
}
|
||||
|
||||
@@ -8689,9 +8674,6 @@ class CodemanApp {
|
||||
// Set once a full-history pull has been refused as a downgrade: the
|
||||
// browser holds more than the server can return, so there is no more.
|
||||
exhausted: !!payload.exhausted,
|
||||
// tmux scrollback above the frame (null = not reported). 0 is a pane with
|
||||
// nothing a pull could add, which hides the notice outright.
|
||||
paneHistoryLines: payload.paneHistoryLines ?? null,
|
||||
});
|
||||
if (sessionId === this.activeSessionId) this._renderHistoryTruncationBanner();
|
||||
}
|
||||
@@ -8699,27 +8681,9 @@ class CodemanApp {
|
||||
/** Drop banner state for a session that is going away. */
|
||||
_clearHistoryTruncation(sessionId) {
|
||||
this._historyTruncation?.delete(sessionId);
|
||||
this._historyNoticeDismissed?.delete(sessionId);
|
||||
if (sessionId === this.activeSessionId) this._renderHistoryTruncationBanner();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the partial-history notice up for `sessionId`, or retire it (null).
|
||||
*
|
||||
* The notice is LAZY: a tail replay is truncated on nearly every tab switch,
|
||||
* and a bar over the top rows on every switch described history the user had
|
||||
* not reached for. It now waits for the scroll gesture that reaches the top of
|
||||
* the browser's buffer (the moment the missing part matters, and the same
|
||||
* gesture that already re-pulls history), and goes away again once the user
|
||||
* scrolls back down to live output. A tab switch retires it (selectSession).
|
||||
*/
|
||||
_setHistoryNoticeRevealed(sessionId) {
|
||||
const next = sessionId || null;
|
||||
if ((this._historyNoticeRevealedFor ?? null) === next) return;
|
||||
this._historyNoticeRevealedFor = next;
|
||||
this._renderHistoryTruncationBanner();
|
||||
}
|
||||
|
||||
/**
|
||||
* Paint the partial-history banner for the active session.
|
||||
*
|
||||
@@ -8729,22 +8693,13 @@ class CodemanApp {
|
||||
* - recoverable → offer to load the rest
|
||||
* - exhausted → say so plainly, offer nothing
|
||||
* - at the limit → the full capture ITSELF hit the byte ceiling
|
||||
*
|
||||
* Shown only while revealed (`_setHistoryNoticeRevealed`: the user scrolled
|
||||
* to the top of this tab's buffer) and never again for a session whose notice
|
||||
* the user dismissed on this page.
|
||||
*/
|
||||
_renderHistoryTruncationBanner() {
|
||||
const bar = document.getElementById('historyTruncationBar');
|
||||
if (!bar) return;
|
||||
const sessionId = this.activeSessionId;
|
||||
const state = sessionId ? this._historyTruncation?.get(sessionId) : null;
|
||||
const state = this.activeSessionId ? this._historyTruncation?.get(this.activeSessionId) : null;
|
||||
const notice = computeHistoryTruncationNotice(state || {});
|
||||
if (
|
||||
!notice.visible ||
|
||||
this._historyNoticeRevealedFor !== sessionId ||
|
||||
this._historyNoticeDismissed?.has(sessionId)
|
||||
) {
|
||||
if (!notice.visible) {
|
||||
bar.hidden = true;
|
||||
return;
|
||||
}
|
||||
@@ -8777,9 +8732,6 @@ class CodemanApp {
|
||||
dismiss.setAttribute('aria-label', 'Dismiss history notice');
|
||||
dismiss.textContent = '×';
|
||||
dismiss.onclick = () => {
|
||||
// Sticky for this session until the page reloads: a dismissed notice used
|
||||
// to come straight back on the next tab switch.
|
||||
(this._historyNoticeDismissed ||= new Set()).add(sessionId);
|
||||
bar.hidden = true;
|
||||
};
|
||||
bar.appendChild(dismiss);
|
||||
@@ -8893,9 +8845,7 @@ class CodemanApp {
|
||||
this._activateFileBrowserSession?.(sessionId);
|
||||
// Repaint the partial-history banner for the tab being switched TO. The
|
||||
// replay paths refresh it when their fetch lands; without this the previous
|
||||
// session's notice stays on screen until then (#258). The switch lands at
|
||||
// live output, so the notice waits for a scroll to the top again.
|
||||
this._historyNoticeRevealedFor = null;
|
||||
// session's notice stays on screen until then (#258).
|
||||
this._renderHistoryTruncationBanner();
|
||||
try { localStorage.setItem('codeman-active-session', sessionId); } catch {}
|
||||
// Narrow SSE filter to the active session — server stops streaming
|
||||
@@ -9689,32 +9639,27 @@ class CodemanApp {
|
||||
}
|
||||
|
||||
async closeSession(sessionId, killMux = true) {
|
||||
// Already on its way out (a repeated click, the mux panel racing the tab).
|
||||
if (this._closingSessions.has(sessionId)) return;
|
||||
// The tab goes FIRST and the server is asked after. The kill takes the server
|
||||
// a few hundred ms (SIGTERM grace, the process tree, tmux), and a tab that sat
|
||||
// there that long after "Kill" read as a click that did nothing. A refused
|
||||
// delete puts the row back below.
|
||||
//
|
||||
// ⚠️ Everything is read BEFORE the first await, and the delete is announced
|
||||
// to _onSessionDeleted through _closingSessions: the `session_deleted` SSE
|
||||
// broadcast for THIS delete arrives while the request is still in flight, and
|
||||
// that handler must leave the follow-up selection to this method (both
|
||||
// outcomes of that race were measured on one build, 2026-08-17).
|
||||
const session = this.sessions.get(sessionId);
|
||||
const orderIndex = this.sessionOrder.indexOf(sessionId);
|
||||
// ⚠️ Captured BEFORE the await, and the delete is announced to
|
||||
// _onSessionDeleted through _closingSessions. The `session_deleted` SSE
|
||||
// broadcast for THIS delete routinely lands while the request is still in
|
||||
// flight, and that handler nulls activeSessionId and shows the welcome
|
||||
// screen. Re-reading the field after the await therefore made the fallback
|
||||
// below a coin flip: closing the tab you were on either moved you to the
|
||||
// next session or dumped you on the home screen, depending on which path
|
||||
// won the race (both outcomes measured on one build, 2026-08-17).
|
||||
const wasActive = this.activeSessionId === sessionId;
|
||||
// Tile grid open: the fallback is the NEIGHBOURING TILE, never the first
|
||||
// sessionOrder entry (often not tiled, which would collapse the grid).
|
||||
// Captured here for the same reason as wasActive: the SSE delete can remove
|
||||
// the tile while the request is still in flight.
|
||||
const grid = this._tileGrid;
|
||||
const tileNeighborId = grid?.has(sessionId) ? window.CodemanTileGrid.tileNeighbor(grid.ids, sessionId) : null;
|
||||
this._closingSessions.add(sessionId);
|
||||
let res = null;
|
||||
try {
|
||||
// The same teardown the SSE event runs (split pane, tile, detached window,
|
||||
// WebSocket, per-session state), only now instead of when the server is
|
||||
// done. It is idempotent, so the real event finds nothing left to do.
|
||||
this._onSessionDeleted({ id: sessionId });
|
||||
await this._apiDelete(`/api/sessions/${sessionId}?killMux=${killMux}`);
|
||||
this._cleanupSessionData(sessionId);
|
||||
// The last tile leaving closes the grid (no reselect): the pick below runs.
|
||||
if (grid?.has(sessionId)) this.removeTile(sessionId, { refocus: false });
|
||||
|
||||
if (wasActive && grid?.open) {
|
||||
// `auto`: the app chose this tile because the previous one went away.
|
||||
@@ -9739,50 +9684,18 @@ class CodemanApp {
|
||||
}
|
||||
}
|
||||
|
||||
this.renderSessionTabs({ immediate: true });
|
||||
this.renderSessionTabs();
|
||||
|
||||
res = await this._apiDelete(`/api/sessions/${sessionId}?killMux=${killMux}`);
|
||||
} catch (err) {
|
||||
// `res` stays null: handled below like a delete that got no answer.
|
||||
console.warn('[closeSession] close failed:', err);
|
||||
} finally {
|
||||
this._closingSessions.delete(sessionId);
|
||||
}
|
||||
|
||||
// 404: already gone (closed from another tab or device), which is what was asked.
|
||||
let gone = !!res && (res.ok || res.status === 404);
|
||||
if (!gone) {
|
||||
// Refused, or no answer. Ask rather than guess: a delete can land on the
|
||||
// server and still lose its reply, and its session_deleted event has then
|
||||
// already been spent while the request was in flight.
|
||||
const check = await this._api(`/api/sessions/${sessionId}`);
|
||||
gone = check?.status === 404;
|
||||
}
|
||||
|
||||
if (gone) {
|
||||
// An SSE resync (handleInit) that landed mid-request rebuilds the list from
|
||||
// the server, which still had the session then.
|
||||
if (this.sessions.has(sessionId)) this._onSessionDeleted({ id: sessionId });
|
||||
if (killMux) {
|
||||
this.showToast('Session closed and tmux killed', 'success');
|
||||
} else {
|
||||
this.showToast('Tab hidden, tmux still running', 'info');
|
||||
}
|
||||
return;
|
||||
} catch (err) {
|
||||
this.showToast('Failed to close session', 'error');
|
||||
} finally {
|
||||
this._closingSessions.delete(sessionId);
|
||||
}
|
||||
|
||||
// Still on the server (or the server is unreachable, in which case the resync
|
||||
// on reconnect has the last word): its row comes back where it was.
|
||||
if (session && !this.sessions.has(sessionId)) {
|
||||
this.sessions.set(sessionId, session);
|
||||
if (!this.sessionOrder.includes(sessionId)) {
|
||||
const at = orderIndex === -1 ? this.sessionOrder.length : Math.min(orderIndex, this.sessionOrder.length);
|
||||
this.sessionOrder.splice(at, 0, sessionId);
|
||||
this.saveSessionOrder();
|
||||
}
|
||||
this.renderSessionTabs();
|
||||
}
|
||||
this.showToast('Failed to close session', 'error');
|
||||
}
|
||||
|
||||
// Request confirmation before closing a session
|
||||
|
||||
@@ -110,9 +110,6 @@ const TITLE_FLASH_INTERVAL_MS = 1500; // Title flash rate
|
||||
const BROWSER_NOTIF_RATE_LIMIT_MS = 3000; // Rate limit for browser notifications
|
||||
const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send while a desktop sizing claim is hot
|
||||
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
|
||||
const DEFAULT_TOAST_DURATION_MS = 3000; // How long a corner toast stays by default
|
||||
const MIN_NOTIFICATION_DURATION_MS = 1000; // Shortest configurable toast / browser-notification time
|
||||
const MAX_NOTIFICATION_DURATION_MS = 300000; // Longest configurable toast / browser-notification time
|
||||
const THROTTLE_DELAY_MS = 100; // General UI throttle delay
|
||||
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
|
||||
const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more scrollback on tab switch)
|
||||
@@ -1744,10 +1741,7 @@ function escapeHtml(text) {
|
||||
function formatHistoryBytes(bytes) {
|
||||
const n = typeof bytes === 'number' && isFinite(bytes) && bytes > 0 ? bytes : 0;
|
||||
if (n < 1024) return 'less than 1 KB';
|
||||
// Switch on the ROUNDED value: a 1 MiB tail cut back to a line boundary is
|
||||
// just under 1 MiB and used to print as "1024 KB".
|
||||
const kb = Math.round(n / 1024);
|
||||
if (kb < 1024) return `${kb} KB`;
|
||||
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
@@ -1761,27 +1755,12 @@ function formatHistoryBytes(bytes) {
|
||||
* - atCeiling: the FULL capture itself hit the byte ceiling
|
||||
* - exhausted: a full pull was refused as a downgrade, so this is all there is
|
||||
*
|
||||
* ⚠️ `truncated` measures the server's BYTE stream, not history a pull can
|
||||
* return. `paneHistoryLines` (tmux `#{history_size}`) is the latter: 0 means the
|
||||
* pane keeps no scrollback at all (a fullscreen CLI in the alternate screen,
|
||||
* whose transcript lives in the CLI and is scrolled there), so the bytes a tail
|
||||
* cut dropped are old repaint frames that `full=1` cannot bring back. Measured
|
||||
* on live fullscreen claude panes: "4.8 MB more" was ~33 copies of one frame,
|
||||
* and the button only ever ended in the downgrade refusal. Nothing to offer,
|
||||
* nothing to say. Absent means unknown and keeps the byte-based behaviour.
|
||||
*
|
||||
* @param {{truncated?: boolean, reason?: string|null, source?: string|null,
|
||||
* fullSize?: number, retainedBytes?: number, exhausted?: boolean,
|
||||
* paneHistoryLines?: number|null}} state
|
||||
* fullSize?: number, retainedBytes?: number, exhausted?: boolean}} state
|
||||
* @returns {{visible: boolean, message: string, canLoadMore: boolean}}
|
||||
*/
|
||||
function computeHistoryTruncationNotice(state = {}) {
|
||||
if (!state.truncated) return { visible: false, message: '', canLoadMore: false };
|
||||
const historyLines =
|
||||
typeof state.paneHistoryLines === 'number' && Number.isFinite(state.paneHistoryLines)
|
||||
? Math.max(0, state.paneHistoryLines)
|
||||
: null;
|
||||
if (historyLines === 0) return { visible: false, message: '', canLoadMore: false };
|
||||
|
||||
const retained = Math.max(0, state.retainedBytes || 0);
|
||||
const dropped = Math.max(0, (state.fullSize || 0) - retained);
|
||||
@@ -1804,15 +1783,9 @@ function computeHistoryTruncationNotice(state = {}) {
|
||||
canLoadMore: false,
|
||||
};
|
||||
}
|
||||
// Name what a pull can actually return when the server said: the byte gap
|
||||
// counts repaints and redraw bloat, and overstates it many times over.
|
||||
const more =
|
||||
historyLines !== null
|
||||
? `${historyLines.toLocaleString('en-US')} ${historyLines === 1 ? 'line of scrollback is' : 'lines of scrollback are'} retained.`
|
||||
: `${formatHistoryBytes(dropped)} more may still be retained.`;
|
||||
return {
|
||||
visible: true,
|
||||
message: `Showing the most recent ${shown} of this session. ${more}`,
|
||||
message: `Showing the most recent ${shown} of this session. ${formatHistoryBytes(dropped)} more may still be retained.`,
|
||||
canLoadMore: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2723,26 +2723,6 @@
|
||||
<span class="set-unit">min</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row" data-search="toast display time popup dismiss seconds notification">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Toast display time</span>
|
||||
<span class="set-row-desc">How long the corner pop-ups stay on screen.</span>
|
||||
</div>
|
||||
<div class="set-row-actions">
|
||||
<input type="number" id="appSettingsNotifToastSecs" class="set-num" value="3" min="1" max="300">
|
||||
<span class="set-unit">sec</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row" data-search="browser notification auto close dismiss seconds">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Browser notification display time</span>
|
||||
<span class="set-row-desc">How long a desktop notification stays up before Codeman closes it. Your OS may close it sooner.</span>
|
||||
</div>
|
||||
<div class="set-row-actions">
|
||||
<input type="number" id="appSettingsNotifBrowserSecs" class="set-num" value="8" min="1" max="300">
|
||||
<span class="set-unit">sec</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* The NotificationManager class implements five notification layers:
|
||||
* 1. In-app notification drawer (slide-out panel with grouped notifications)
|
||||
* 2. Tab title flash (alternating "⚠️ (N) codeman:<host>" / "codeman:<host>" when tab is hidden; uses this.originalTitle so it tracks any per-host title)
|
||||
* 3. Browser Notification API (desktop push; auto-closes after 8s by default, configurable per device in Settings → Notifications)
|
||||
* 3. Browser Notification API (desktop push with auto-close after 8s)
|
||||
* 4. Web Push via service worker (OS-level notifications when tab is closed)
|
||||
* 5. Audio alerts (Web Audio API beep, user-opt-in)
|
||||
*
|
||||
@@ -93,10 +93,6 @@ class NotificationManager {
|
||||
browserNotifications: !isMobile,
|
||||
audioAlerts: false,
|
||||
stuckThresholdMs: STUCK_THRESHOLD_DEFAULT_MS,
|
||||
// How long a corner toast stays on screen, and how long a browser notification
|
||||
// stays up before Codeman closes it (ms; per-device like the rest of these)
|
||||
toastDurationMs: DEFAULT_TOAST_DURATION_MS,
|
||||
browserAutoCloseMs: AUTO_CLOSE_NOTIFICATION_MS,
|
||||
// Legacy urgency muting (keep for backwards compat)
|
||||
muteCritical: false,
|
||||
muteWarning: false,
|
||||
@@ -171,24 +167,11 @@ class NotificationManager {
|
||||
return {
|
||||
...defaults,
|
||||
...prefs,
|
||||
toastDurationMs: this.clampDuration(prefs.toastDurationMs, defaults.toastDurationMs),
|
||||
browserAutoCloseMs: this.clampDuration(prefs.browserAutoCloseMs, defaults.browserAutoCloseMs),
|
||||
eventTypes: { ...defaults.eventTypes, ...prefs.eventTypes },
|
||||
_version: 5,
|
||||
};
|
||||
}
|
||||
|
||||
/** A display time in ms kept within [1s, 5min]; anything unusable falls back to the default. */
|
||||
clampDuration(value, fallback) {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;
|
||||
return Math.min(MAX_NOTIFICATION_DURATION_MS, Math.max(MIN_NOTIFICATION_DURATION_MS, Math.round(value)));
|
||||
}
|
||||
|
||||
/** Display time for corner toasts that do not set their own `duration`. */
|
||||
getToastDurationMs() {
|
||||
return this.clampDuration(this.preferences?.toastDurationMs, DEFAULT_TOAST_DURATION_MS);
|
||||
}
|
||||
|
||||
loadPreferences() {
|
||||
try {
|
||||
const storageKey = this.getStorageKey();
|
||||
@@ -420,7 +403,7 @@ class NotificationManager {
|
||||
};
|
||||
|
||||
// Auto-close
|
||||
setTimeout(() => notif.close(), this.clampDuration(this.preferences.browserAutoCloseMs, AUTO_CLOSE_NOTIFICATION_MS));
|
||||
setTimeout(() => notif.close(), AUTO_CLOSE_NOTIFICATION_MS);
|
||||
}
|
||||
|
||||
async requestPermission() {
|
||||
@@ -483,7 +466,7 @@ class NotificationManager {
|
||||
notif.read = true;
|
||||
this.unreadCount = Math.max(0, this.unreadCount - 1);
|
||||
this.updateBadge();
|
||||
}
|
||||
}
|
||||
|
||||
// Switch to session if available
|
||||
if (notif.sessionId && this.app.sessions.has(notif.sessionId)) {
|
||||
|
||||
@@ -5862,8 +5862,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
/**
|
||||
* `duration` defaults to the "Toast display time" preference (3000ms unless changed in
|
||||
* Settings → Notifications) for every toast type. A message worth
|
||||
* `duration` defaults to 3000ms for every toast type. A message worth
|
||||
* reading rather than glancing at (e.g. "Session started on the native
|
||||
* backend — could not apply the custom endpoint: <the actual reason>")
|
||||
* passes an explicit `opts.duration: 0` at its own call site instead of
|
||||
@@ -5875,7 +5874,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
* regardless of duration.
|
||||
*/
|
||||
showToast(message, type = 'info', opts = {}) {
|
||||
const { duration = this.notificationManager?.getToastDurationMs?.() ?? 3000, action } = opts;
|
||||
const { duration = 3000, action } = opts;
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast-${type}`;
|
||||
|
||||
|
||||
@@ -563,12 +563,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsNotifBrowser').checked = notifPrefs.browserNotifications ?? false;
|
||||
document.getElementById('appSettingsNotifAudio').checked = notifPrefs.audioAlerts ?? false;
|
||||
document.getElementById('appSettingsNotifStuckMins').value = Math.round((notifPrefs.stuckThresholdMs || 600000) / 60000);
|
||||
document.getElementById('appSettingsNotifToastSecs').value = Math.round(
|
||||
(this.notificationManager?.getToastDurationMs?.() ?? DEFAULT_TOAST_DURATION_MS) / 1000
|
||||
);
|
||||
document.getElementById('appSettingsNotifBrowserSecs').value = Math.round(
|
||||
(notifPrefs.browserAutoCloseMs ?? AUTO_CLOSE_NOTIFICATION_MS) / 1000
|
||||
);
|
||||
document.getElementById('appSettingsNotifCritical').checked = !notifPrefs.muteCritical;
|
||||
document.getElementById('appSettingsNotifWarning').checked = !notifPrefs.muteWarning;
|
||||
document.getElementById('appSettingsNotifInfo').checked = !notifPrefs.muteInfo;
|
||||
@@ -2673,8 +2667,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
browserNotifications: document.getElementById('appSettingsNotifBrowser').checked,
|
||||
audioAlerts: document.getElementById('appSettingsNotifAudio').checked,
|
||||
stuckThresholdMs: (parseInt(document.getElementById('appSettingsNotifStuckMins').value) || 10) * 60000,
|
||||
toastDurationMs: (parseInt(document.getElementById('appSettingsNotifToastSecs').value) || 3) * 1000,
|
||||
browserAutoCloseMs: (parseInt(document.getElementById('appSettingsNotifBrowserSecs').value) || 8) * 1000,
|
||||
muteCritical: !document.getElementById('appSettingsNotifCritical').checked,
|
||||
muteWarning: !document.getElementById('appSettingsNotifWarning').checked,
|
||||
muteInfo: !document.getElementById('appSettingsNotifInfo').checked,
|
||||
@@ -2744,7 +2736,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
_version: 5,
|
||||
};
|
||||
if (this.notificationManager) {
|
||||
this.notificationManager.preferences = this.notificationManager.normalizePreferences(notifPrefsToSave);
|
||||
this.notificationManager.preferences = notifPrefsToSave;
|
||||
this.notificationManager.savePreferences();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,14 +11,20 @@
|
||||
*
|
||||
* Deliberately plainer than the primary pane (this.terminal/this._ws in
|
||||
* terminal-ui.js): no local-echo overlay, no CJK IME textarea, no touch/mobile
|
||||
* handlers (a swipe on a touch screen pages nothing), no keyboard accessory
|
||||
* bar, and no SGR wheel forwarding to Claude's fullscreen renderer
|
||||
* (docs/tile-grid-plan.md follow-up 4). Built for wide screens; see
|
||||
* docs/split-pane-sessions-plan.md and docs/tile-grid-plan.md.
|
||||
* handlers (a swipe on a touch screen pages nothing), and no keyboard
|
||||
* accessory bar. Built for wide screens; see docs/split-pane-sessions-plan.md
|
||||
* and docs/tile-grid-plan.md.
|
||||
*
|
||||
* What it does carry over from the primary pane, through the primary pane's
|
||||
* own code aimed at THIS pane (its terminal, its session, never the active
|
||||
* one):
|
||||
* - SGR wheel forwarding (_maybeForwardWheelToCli): Claude's fullscreen
|
||||
* renderer scrolls its own transcript on SGR wheel reports, while this
|
||||
* xterm holds only replayed repaint frames, so the wheel goes to the CLI
|
||||
* as reports at the pointer's cell in this pane, through the primary
|
||||
* pane's forwarding gate and its encoding (sgrWheelReports). Shift+wheel
|
||||
* scrolls the local scrollback itself (_maybeScrollLocalOnShift), as the
|
||||
* primary pane does, since xterm turns it into a horizontal no-op.
|
||||
* - Hollow-buffer paging (#555): a CLI that draws in place (opencode on the
|
||||
* alternate screen, Claude's repaint mode) leaves the xterm no scrollback,
|
||||
* so the wheel pages the CLI's own transcript with PageUp/PageDown
|
||||
@@ -43,7 +49,7 @@
|
||||
*
|
||||
* @dependency vendor/xterm.js, vendor/xterm-addon-fit.js
|
||||
* @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE)
|
||||
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/pageKeysForTravel, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_handleDesktopTerminalClick)
|
||||
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/wheelDeltaWholeLines/sgrWheelReports/pageKeysForTravel, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_clientPointToCell/_handleDesktopTerminalClick)
|
||||
* @dependency terminal-keycode229-recovery.js (window.CodemanKeyCode229Recovery, optional: absent, xterm's own textarea handling stands)
|
||||
* @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js
|
||||
*/
|
||||
@@ -201,6 +207,9 @@
|
||||
// Hollow-buffer paging (_maybePageCliTranscript): wheel travel short of a
|
||||
// whole page, carried to the next wheel event.
|
||||
this._pageKeyPending = 0;
|
||||
// Shift+wheel travel short of a whole line, carried to the next wheel
|
||||
// event (_maybeScrollLocalOnShift).
|
||||
this._shiftScrollPending = 0;
|
||||
// Page keys waiting for the 40 ms flush, and its timer (_queueScrollBytes).
|
||||
this._scrollBytes = '';
|
||||
this._scrollFlushTimer = null;
|
||||
@@ -1027,16 +1036,18 @@
|
||||
|
||||
// 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. Not passive: the one route
|
||||
// this pane takes over, paging a hollow buffer's CLI transcript
|
||||
// (_maybePageCliTranscript), is consumed right here (preventDefault plus
|
||||
// while the pane still has scrollback to scroll. Not passive: the three
|
||||
// routes this pane takes over, forwarding the wheel to Claude's fullscreen
|
||||
// renderer (_maybeForwardWheelToCli), paging a hollow buffer's CLI
|
||||
// transcript (_maybePageCliTranscript) and Shift+wheel's local scrollback
|
||||
// (_maybeScrollLocalOnShift), are consumed right here (preventDefault plus
|
||||
// stopPropagation in the capture phase, the primary pane's technique), so
|
||||
// xterm's viewport, a descendant, never sees it. Every other wheel is left
|
||||
// xterm's viewport, a descendant, never sees them. Every other wheel is left
|
||||
// to xterm, which keeps doing the scrolling, and only observed for the
|
||||
// shell history pull.
|
||||
_installWheelListener() {
|
||||
this._onWheel = (ev) => {
|
||||
if (this._maybePageCliTranscript(ev)) {
|
||||
if (this._maybeForwardWheelToCli(ev) || this._maybePageCliTranscript(ev) || this._maybeScrollLocalOnShift(ev)) {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
return;
|
||||
@@ -1046,6 +1057,71 @@
|
||||
this.mountEl.addEventListener('wheel', this._onWheel, { capture: true, passive: false });
|
||||
}
|
||||
|
||||
// SGR wheel forwarding, the twin of the primary pane's capture-phase wheel
|
||||
// handler and _forwardScrollToApp (terminal-ui.js; keep them in step).
|
||||
// Claude's fullscreen renderer (claude 2.1.187+ while its mouse tracking is
|
||||
// on, cliMouseTracking) scrolls its own transcript on SGR wheel reports,
|
||||
// while this xterm holds only Codeman's replayed repaint frames (tmux keeps
|
||||
// no history for such a pane). Left to xterm, the wheel dragged those stale
|
||||
// frames, Claude's pinned input box with them, up the tile, or scrolled
|
||||
// nothing at all. The gate is the primary pane's own, asked for THIS pane
|
||||
// (its terminal, its session, never the active one), so the CLI rules stay
|
||||
// in terminal-ui.js and this file names no CLI; the reports go to this
|
||||
// pane's session through its own coalescer. Returns true when the wheel
|
||||
// belongs to the CLI: a gesture with no whole line or no measurable cell is
|
||||
// consumed too, as in the primary pane, so xterm never scrolls the stale
|
||||
// frames under a forwarding session. Shift fails the gate, so Shift+wheel
|
||||
// still scrolls the local scrollback (_maybeScrollLocalOnShift).
|
||||
_maybeForwardWheelToCli(ev) {
|
||||
if (this._destroyed || !this.terminal || !ev) return false;
|
||||
const app = global.app;
|
||||
const input = global.CodemanTerminalInput;
|
||||
if (!app?._shouldForwardWheelToApp || !input?.sgrWheelReports || !input.wheelDeltaWholeLines) return false;
|
||||
// xterm's own encoder forwards the wheel while the CLI's tracking reaches
|
||||
// it, and its alt-scroll owns the alternate buffer, as in the primary pane.
|
||||
const tracking = this.terminal.modes?.mouseTrackingMode;
|
||||
if (tracking && tracking !== 'none') return false;
|
||||
if (this.terminal.buffer?.active?.type === 'alternate') return false;
|
||||
if (!app._shouldForwardWheelToApp(ev, { terminal: this.terminal, sessionId: this.sessionId })) return false;
|
||||
// SGR coordinates address the live screen, so a report from a scrolled-up
|
||||
// viewport would hit-test another row: snap home first (_forwardScrollToApp).
|
||||
if (!app._terminalViewportAtBottom?.(this.terminal)) this.terminal.scrollToBottom?.();
|
||||
const lines = input.wheelDeltaWholeLines(ev, this.terminal.rows);
|
||||
const pos = app._clientPointToCell?.(ev.clientX, ev.clientY, this.terminal);
|
||||
const bytes = input.sgrWheelReports(lines, pos);
|
||||
if (bytes) this._queueScrollBytes(bytes);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Shift+wheel scrolls this xterm's local scrollback, the explicit "local
|
||||
// history" gesture, here as in the primary pane (whose capture-phase wheel
|
||||
// handler scrolls with terminal.scrollLines() for the same reason). Left to
|
||||
// xterm it was dead off macOS: Chrome on Windows sends Shift+wheel as a
|
||||
// HORIZONTAL wheel (deltaX), and xterm's own scroller turns a Shift+vertical
|
||||
// wheel into a horizontal one, so the viewport never moved. Reads the
|
||||
// dominant axis under Shift (wheelDeltaLines), keeps the sub-line remainder
|
||||
// for the next event (a trackpad's small deltas), and on the way up still
|
||||
// asks a shell pane for more history. Returns true when the wheel was
|
||||
// consumed here.
|
||||
_maybeScrollLocalOnShift(ev) {
|
||||
if (this._destroyed || !this.terminal || !ev?.shiftKey) return false;
|
||||
const input = global.CodemanTerminalInput;
|
||||
if (!input?.wheelDeltaLines) return false;
|
||||
// xterm's own encoder forwards the wheel while the CLI's tracking reaches
|
||||
// it, and its alt-scroll owns the alternate buffer, as in the primary pane.
|
||||
const tracking = this.terminal.modes?.mouseTrackingMode;
|
||||
if (tracking && tracking !== 'none') return false;
|
||||
if (this.terminal.buffer?.active?.type === 'alternate') return false;
|
||||
const total = this._shiftScrollPending + input.wheelDeltaLines(ev, this.terminal.rows);
|
||||
const lines = Math.trunc(total);
|
||||
this._shiftScrollPending = total - lines;
|
||||
if (lines) {
|
||||
this.terminal.scrollLines(lines);
|
||||
if (lines < 0) this._maybeLoadMoreHistory();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// A plain left-click reported to the CLI, the primary pane's desktop click
|
||||
// (terminal-ui.js _handleDesktopTerminalClick) aimed at this pane. The
|
||||
// server strips the mouse DECSETs of some modes (opencode's since #555, so a
|
||||
@@ -1087,9 +1163,9 @@
|
||||
const tracking = this.terminal.modes?.mouseTrackingMode;
|
||||
if (tracking && tracking !== 'none') return false;
|
||||
const target = { terminal: this.terminal, sessionId: this.sessionId };
|
||||
// The primary pane would forward this wheel to Claude's fullscreen
|
||||
// renderer as SGR reports. Tiles do not do that yet (docs/tile-grid-plan.md
|
||||
// follow-up 4), so the wheel stays with xterm, as before.
|
||||
// A wheel for Claude's fullscreen renderer was forwarded as SGR reports
|
||||
// before this ran (_maybeForwardWheelToCli); the gate is repeated so a
|
||||
// forwarding session is never paged.
|
||||
if (app._shouldForwardWheelToApp?.(ev, target)) return false;
|
||||
if (!app._localScrollbackIsHollow?.({ ...target, localRows: this._localRows() })) return false;
|
||||
// Only from the live screen. The one gate the primary pane never needs: a
|
||||
@@ -1111,8 +1187,9 @@
|
||||
return true;
|
||||
}
|
||||
|
||||
// Coalesces the page keys into one send per 40 ms, bounded at 512 bytes so a
|
||||
// fling cannot build a backlog that keeps paging after it stops. A narrow
|
||||
// Coalesces the scroll bytes (SGR wheel reports and page keys alike) into
|
||||
// one send per 40 ms, bounded at 512 bytes so a fling cannot build a backlog
|
||||
// that keeps scrolling after it stops. A narrow
|
||||
// twin of the primary pane's _queueScrollBytes / _flushWheelSgrQueue
|
||||
// (terminal-ui.js; keep the two in step), which flushes to the active
|
||||
// session only. Sent ephemeral (no seq, never persisted) to THIS pane's
|
||||
|
||||
@@ -107,6 +107,32 @@
|
||||
: delta / 25; // DOM_DELTA_PIXEL (Chrome/WebKit, and every trackpad)
|
||||
}
|
||||
|
||||
// The same travel rounded to whole lines for the SGR wheel reports: a pure
|
||||
// horizontal swipe is 0 (nothing to send), and anything else moves at least
|
||||
// one line, so the small pixel deltas of a precision touchpad still scroll.
|
||||
// The body of the primary pane's _wheelScrollLines.
|
||||
function wheelDeltaWholeLines(ev, rows) {
|
||||
const lines = wheelDeltaLines(ev, rows);
|
||||
if (!lines) return 0;
|
||||
return Math.round(lines) || (lines > 0 ? 1 : -1);
|
||||
}
|
||||
|
||||
// Ticks one gesture batch may report: Claude applies its own scroll-speed
|
||||
// multiplier and acceleration on top, so a bigger batch only overshoots.
|
||||
const SGR_WHEEL_MAX_TICKS = 5;
|
||||
|
||||
// Whole wheel lines → SGR wheel reports at a 1-based cell `pos` ({ col, row },
|
||||
// live-screen relative): button 64 per line up, 65 per line down, capped at
|
||||
// SGR_WHEEL_MAX_TICKS. '' when there is nothing to send. The encoding of the
|
||||
// primary pane's _sendSyntheticSgrWheel, pure so a TerminalTile forwards
|
||||
// byte-identical reports to its own session.
|
||||
function sgrWheelReports(lines, pos) {
|
||||
if (!lines || !pos) return '';
|
||||
const btn = lines < 0 ? 64 : 65;
|
||||
const ticks = Math.min(Math.abs(lines), SGR_WHEEL_MAX_TICKS);
|
||||
return `\x1b[<${btn};${pos.col};${pos.row}M`.repeat(ticks);
|
||||
}
|
||||
|
||||
// Gesture travel → PageUp/PageDown keys for a terminal `rows` tall: adds
|
||||
// `lines` to the sub-page travel already `pending`, and returns the travel
|
||||
// left over plus the keys to send ('' below one page). The arithmetic of the
|
||||
@@ -260,6 +286,9 @@
|
||||
PAGE_KEY_SCREEN_FRACTION,
|
||||
PAGE_KEY_MAX_PER_BATCH,
|
||||
wheelDeltaLines,
|
||||
wheelDeltaWholeLines,
|
||||
SGR_WHEEL_MAX_TICKS,
|
||||
sgrWheelReports,
|
||||
pageKeysForTravel,
|
||||
TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM,
|
||||
MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR,
|
||||
@@ -3627,24 +3656,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
* the unbounded path. Must be called AFTER scrollLines(), since the check is on
|
||||
* the resulting position, and it is deliberately not folded into
|
||||
* _noteTerminalUserScroll for exactly that reason.
|
||||
*
|
||||
* It is also what brings up the partial-history notice, and what retires it
|
||||
* once a downward scroll is back at live output (_setHistoryNoticeRevealed).
|
||||
* The reveal waits for the pull this gesture started, so the notice describes
|
||||
* what the pull left rather than flashing the state it is about to replace.
|
||||
*/
|
||||
_maybeLoadMoreHistoryOnScroll(lines) {
|
||||
if (lines > 0) {
|
||||
if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null);
|
||||
return;
|
||||
}
|
||||
if (lines === 0 || this.terminal?.buffer?.active?.viewportY !== 0) return;
|
||||
const sessionId = this.activeSessionId;
|
||||
Promise.resolve(this._maybeRefetchFullHistory?.())
|
||||
.catch(() => {})
|
||||
.then(() => {
|
||||
if (sessionId && this.activeSessionId === sessionId) this._setHistoryNoticeRevealed?.(sessionId);
|
||||
});
|
||||
if (lines >= 0) return;
|
||||
if (this.terminal?.buffer?.active?.viewportY === 0) this._maybeRefetchFullHistory?.();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -5577,9 +5592,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// the ±1 fallback — one line per notch, versus 4-5 for Chrome's ~110px. In
|
||||
// Claude mode the same value also capped the forwarded SGR report at one tick.
|
||||
_wheelScrollLines(ev) {
|
||||
const lines = this._wheelScrollLinesFloat(ev);
|
||||
if (!lines) return 0; // pure horizontal swipe: don't fall through to -1
|
||||
return Math.round(lines) || (lines > 0 ? 1 : -1);
|
||||
// Pure horizontal swipe: 0, never the ±1 fallback (wheelDeltaWholeLines).
|
||||
return window.CodemanTerminalInput.wheelDeltaWholeLines(ev, this.terminal?.rows);
|
||||
},
|
||||
|
||||
/** Unrounded variant for the smooth local-scroll path, which accumulates
|
||||
@@ -5653,13 +5667,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
// scroll-speed multiplier and acceleration on top), and the queue is bounded
|
||||
// so a wild scroll can't build a backlog that keeps scrolling after the finger
|
||||
// stops. Flushed via _sendInputEphemeral — loss-tolerant, off the durable queue.
|
||||
// The encoding is the pure CodemanTerminalInput.sgrWheelReports, which a
|
||||
// TerminalTile calls with its own cell (TerminalTile._maybeForwardWheelToCli).
|
||||
_sendSyntheticSgrWheel(clientX, clientY, lines) {
|
||||
if (!this.activeSessionId || !lines) return;
|
||||
const pos = this._clientPointToCell(clientX, clientY);
|
||||
if (!pos) return;
|
||||
const btn = lines < 0 ? 64 : 65;
|
||||
const ticks = Math.min(Math.abs(lines), 5);
|
||||
this._queueScrollBytes(`\x1b[<${btn};${pos.col};${pos.row}M`.repeat(ticks));
|
||||
this._queueScrollBytes(window.CodemanTerminalInput.sgrWheelReports(lines, pos));
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -3225,12 +3225,6 @@ export function registerSessionRoutes(
|
||||
// damage that does not exist.
|
||||
captureCols: hasLiveMuxBuffer ? captureOpts.capturedGeometry?.cols : undefined,
|
||||
captureRows: hasLiveMuxBuffer ? captureOpts.capturedGeometry?.rows : undefined,
|
||||
// Rows tmux holds above the visible frame, which is the most a `full=1`
|
||||
// pull can add. `truncated` measures the BYTE stream, and for a pane that
|
||||
// keeps no scrollback (a fullscreen CLI in the alternate screen) the bytes
|
||||
// a tail cut drops are old repaints that no request can bring back, so a
|
||||
// client must not offer to load them. Absent when the pane was not read.
|
||||
paneHistoryLines: hasLiveMuxBuffer ? captureOpts.capturedHistoryLines : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -1517,8 +1517,6 @@ export const SettingsUpdateSchema = z
|
||||
browserNotifications: z.boolean().optional(),
|
||||
audioAlerts: z.boolean().optional(),
|
||||
stuckThresholdMs: z.number().optional(),
|
||||
toastDurationMs: z.number().optional(),
|
||||
browserAutoCloseMs: z.number().optional(),
|
||||
muteCritical: z.boolean().optional(),
|
||||
muteWarning: z.boolean().optional(),
|
||||
muteInfo: z.boolean().optional(),
|
||||
|
||||
@@ -1,278 +0,0 @@
|
||||
/**
|
||||
* @fileoverview The partial-history notice waits until the user reaches for history.
|
||||
*
|
||||
* Every tab switch after the first replays a 1 MiB TAIL of the session's byte
|
||||
* stream, which is truncated for any session that has run for a while, so the
|
||||
* notice ("Showing the most recent 1.0 MB of this session. 4.8 MB more may still
|
||||
* be retained.") covered the top rows on nearly every switch. Its × only lasted
|
||||
* until the next switch. Now:
|
||||
* - it appears only once a scroll gesture reaches the top of the browser's
|
||||
* buffer, after the history pull that gesture starts has settled;
|
||||
* - a scroll back down to live output retires it, and so does a tab switch;
|
||||
* - a dismissal sticks for that session until the page reloads.
|
||||
*
|
||||
* Runs the REAL methods (app.js banner + state, terminal-ui.js scroll hook,
|
||||
* constants.js notice decision) in a `vm` against a stub DOM, the same way
|
||||
* shell-scroll-history-pull.test.ts does (no jsdom on this box).
|
||||
*/
|
||||
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 PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const APP = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
|
||||
function methodSource(source: string, method: string): string {
|
||||
const start = source.search(new RegExp(`^ {2}(?:async )?${method}\\(`, 'm'));
|
||||
expect(start, `${method} not found`).toBeGreaterThan(-1);
|
||||
const next = /^ {2}(?:async )?[A-Za-z_$][\w$]*\(/m.exec(source.slice(start + 1));
|
||||
return next ? source.slice(start, start + 1 + next.index) : source.slice(start);
|
||||
}
|
||||
|
||||
interface FakeEl {
|
||||
tagName: string;
|
||||
hidden: boolean;
|
||||
className: string;
|
||||
type: string;
|
||||
disabled: boolean;
|
||||
children: FakeEl[];
|
||||
attrs: Record<string, string>;
|
||||
onclick: null | (() => void);
|
||||
textContent: string;
|
||||
appendChild(child: FakeEl): void;
|
||||
setAttribute(name: string, value: string): void;
|
||||
}
|
||||
|
||||
function fakeEl(tagName: string): FakeEl {
|
||||
let text = '';
|
||||
const el: FakeEl = {
|
||||
tagName,
|
||||
hidden: false,
|
||||
className: '',
|
||||
type: '',
|
||||
disabled: false,
|
||||
children: [],
|
||||
attrs: {},
|
||||
onclick: null,
|
||||
get textContent() {
|
||||
return text + el.children.map((c) => c.textContent).join('');
|
||||
},
|
||||
set textContent(value: string) {
|
||||
text = value;
|
||||
el.children = [];
|
||||
},
|
||||
appendChild(child) {
|
||||
el.children.push(child);
|
||||
},
|
||||
setAttribute(name, value) {
|
||||
el.attrs[name] = value;
|
||||
},
|
||||
};
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Real terminal-ui.js mixin, for `_maybeLoadMoreHistoryOnScroll` / `isTerminalAtBottom`. */
|
||||
function loadTerminalMixin(): Record<string, (...args: unknown[]) => unknown> {
|
||||
const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8');
|
||||
const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, (...args: unknown[]) => unknown> };
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
performance,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
requestAnimationFrame: vi.fn(),
|
||||
CodemanApp: FakeCodemanApp,
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
document: { addEventListener: vi.fn() },
|
||||
});
|
||||
vm.runInContext(source, context);
|
||||
return FakeCodemanApp.prototype;
|
||||
}
|
||||
|
||||
function makeApp() {
|
||||
const bar = fakeEl('div');
|
||||
bar.hidden = true;
|
||||
const document = {
|
||||
getElementById: (id: string) => (id === 'historyTruncationBar' ? bar : null),
|
||||
createElement: (tag: string) => fakeEl(tag),
|
||||
};
|
||||
const methods = [
|
||||
'_setHistoryTruncation',
|
||||
'_clearHistoryTruncation',
|
||||
'_setHistoryNoticeRevealed',
|
||||
'_renderHistoryTruncationBanner',
|
||||
]
|
||||
.map((m) => methodSource(APP, m))
|
||||
.join(',\n');
|
||||
const context = vm.createContext({ document, console, window: {}, navigator: { userAgent: 'test' } });
|
||||
const appMethods = vm.runInContext(
|
||||
`${readFileSync(resolve(PUBLIC, 'constants.js'), 'utf8')}
|
||||
;({ ${methods} })`,
|
||||
context,
|
||||
{ filename: 'app-methods.js' }
|
||||
) as Record<string, (...args: unknown[]) => unknown>;
|
||||
const mixin = loadTerminalMixin();
|
||||
|
||||
const buffer = { viewportY: 500, baseY: 500 };
|
||||
let resolvePull: (() => void) | null = null;
|
||||
const app = {
|
||||
activeSessionId: 's1' as string | null,
|
||||
terminal: { buffer: { active: buffer } },
|
||||
// Each gesture's pull is held open until the test settles it.
|
||||
_maybeRefetchFullHistory: vi.fn(
|
||||
() =>
|
||||
new Promise<void>((res) => {
|
||||
resolvePull = res;
|
||||
})
|
||||
),
|
||||
...appMethods,
|
||||
_maybeLoadMoreHistoryOnScroll: mixin._maybeLoadMoreHistoryOnScroll,
|
||||
isTerminalAtBottom: mixin.isTerminalAtBottom,
|
||||
} as Record<string, any>;
|
||||
|
||||
const settle = async () => {
|
||||
resolvePull?.();
|
||||
resolvePull = null;
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
};
|
||||
const scrollTo = async (viewportY: number) => {
|
||||
const lines = viewportY - buffer.viewportY;
|
||||
buffer.viewportY = viewportY;
|
||||
app._maybeLoadMoreHistoryOnScroll(lines);
|
||||
await settle();
|
||||
};
|
||||
return { app, bar, buffer, scrollTo, settle };
|
||||
}
|
||||
|
||||
// What a tab switch's tail replay reports for a session with real scrollback.
|
||||
const TAIL = {
|
||||
truncated: true,
|
||||
truncationReason: 'tail',
|
||||
source: 'mux-visible',
|
||||
fullSize: 5 * 1024 * 1024,
|
||||
retainedBytes: 1024 * 1024,
|
||||
paneHistoryLines: 40000,
|
||||
};
|
||||
|
||||
const loadButton = (bar: FakeEl) => bar.children.find((c) => c.className === 'history-trunc-load');
|
||||
const dismissButton = (bar: FakeEl) => bar.children.find((c) => c.className === 'history-trunc-dismiss');
|
||||
|
||||
describe('partial-history notice: lazy reveal', () => {
|
||||
it('stays hidden after a truncated tab-switch replay', () => {
|
||||
const { app, bar } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
expect(bar.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('appears once a scroll reaches the top, after the pull that gesture started', async () => {
|
||||
const { app, bar, buffer, settle } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
|
||||
buffer.viewportY = 0;
|
||||
app._maybeLoadMoreHistoryOnScroll(-500);
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledTimes(1);
|
||||
// Still pulling: no notice describing the state the pull is about to replace.
|
||||
expect(bar.hidden).toBe(true);
|
||||
|
||||
await settle();
|
||||
expect(bar.hidden).toBe(false);
|
||||
expect(bar.textContent).toContain('40,000 lines of scrollback are retained.');
|
||||
expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
});
|
||||
|
||||
it('shows what the pull left: nothing, when the pull brought everything back', async () => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
app._maybeRefetchFullHistory.mockImplementation(async () => {
|
||||
app._setHistoryTruncation('s1', { truncated: false, source: 'mux-full-history', paneHistoryLines: 40000 });
|
||||
});
|
||||
buffer.viewportY = 0;
|
||||
app._maybeLoadMoreHistoryOnScroll(-500);
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
expect(app._historyNoticeRevealedFor).toBe('s1');
|
||||
expect(bar.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('does not appear on the way up, only at the top', async () => {
|
||||
const { app, bar, scrollTo } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
await scrollTo(200);
|
||||
expect(app._maybeRefetchFullHistory).not.toHaveBeenCalled();
|
||||
expect(bar.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('goes away once the user scrolls back down to live output', async () => {
|
||||
const { app, bar, scrollTo } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
await scrollTo(0);
|
||||
expect(bar.hidden).toBe(false);
|
||||
await scrollTo(300); // still reading history
|
||||
expect(bar.hidden).toBe(false);
|
||||
await scrollTo(500); // back at the bottom
|
||||
expect(bar.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('never appears for a pane with no scrollback (fullscreen CLI), even at the top', async () => {
|
||||
const { app, bar, scrollTo } = makeApp();
|
||||
app._setHistoryTruncation('s1', { ...TAIL, paneHistoryLines: 0 });
|
||||
await scrollTo(0);
|
||||
expect(app._historyNoticeRevealedFor).toBe('s1');
|
||||
expect(bar.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('is not revealed for a tab the user switched to while the pull ran', async () => {
|
||||
const { app, bar, buffer, settle } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
app._setHistoryTruncation('s2', TAIL);
|
||||
buffer.viewportY = 0;
|
||||
app._maybeLoadMoreHistoryOnScroll(-500);
|
||||
app.activeSessionId = 's2';
|
||||
await settle();
|
||||
expect(app._historyNoticeRevealedFor ?? null).toBe(null);
|
||||
expect(bar.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps a dismissal for that session, but only that session', async () => {
|
||||
const { app, bar, scrollTo } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
await scrollTo(0);
|
||||
dismissButton(bar)!.onclick!();
|
||||
expect(bar.hidden).toBe(true);
|
||||
|
||||
// A new replay and another trip to the top do not bring it back.
|
||||
await scrollTo(500);
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
await scrollTo(0);
|
||||
expect(bar.hidden).toBe(true);
|
||||
|
||||
// Another session still gets its notice.
|
||||
app.activeSessionId = 's2';
|
||||
app._setHistoryTruncation('s2', TAIL);
|
||||
await scrollTo(500);
|
||||
await scrollTo(0);
|
||||
expect(bar.hidden).toBe(false);
|
||||
});
|
||||
|
||||
it('forgets the dismissal with the session', async () => {
|
||||
const { app, bar, scrollTo } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
await scrollTo(0);
|
||||
dismissButton(bar)!.onclick!();
|
||||
app._clearHistoryTruncation('s1');
|
||||
expect(app._historyNoticeDismissed.has('s1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('partial-history notice: a tab switch retires it (static guard)', () => {
|
||||
it('selectSession clears the reveal before repainting the banner', () => {
|
||||
const body = methodSource(APP, 'selectSession');
|
||||
const reset = body.indexOf('this._historyNoticeRevealedFor = null;');
|
||||
const render = body.indexOf('this._renderHistoryTruncationBanner();');
|
||||
expect(reset).toBeGreaterThan(-1);
|
||||
expect(render).toBeGreaterThan(reset);
|
||||
});
|
||||
});
|
||||
@@ -45,11 +45,6 @@ describe('formatHistoryBytes', () => {
|
||||
expect(formatHistoryBytes(3 * 1024 * 1024)).toBe('3.0 MB');
|
||||
});
|
||||
|
||||
it('never prints "1024 KB" for a tail cut back to a line boundary just under 1 MiB', () => {
|
||||
expect(formatHistoryBytes(1048351)).toBe('1.0 MB');
|
||||
expect(formatHistoryBytes(1023 * 1024)).toBe('1023 KB');
|
||||
});
|
||||
|
||||
it('survives junk input rather than printing NaN into the UI', () => {
|
||||
expect(formatHistoryBytes(-5)).toBe('less than 1 KB');
|
||||
expect(formatHistoryBytes(NaN as unknown as number)).toBe('less than 1 KB');
|
||||
@@ -119,65 +114,6 @@ describe('computeHistoryTruncationNotice (issue #258)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeHistoryTruncationNotice: what a pull can really return (paneHistoryLines)', () => {
|
||||
const { computeHistoryTruncationNotice } = loadHelpers();
|
||||
// The tab-switch tail of a fullscreen claude pane, as measured on prod: the
|
||||
// server cut a 5.8 MB byte stream to 1 MB, and tmux held 0 scrollback rows.
|
||||
const fullscreenTail = {
|
||||
truncated: true,
|
||||
reason: 'tail',
|
||||
source: 'mux-visible',
|
||||
fullSize: 6158853,
|
||||
retainedBytes: 1048351,
|
||||
};
|
||||
|
||||
it('says nothing for a pane that keeps no scrollback, however much the byte stream lost', () => {
|
||||
// The dropped bytes were old repaints of one frame, and `full=1` returns
|
||||
// only the visible frame for such a pane, so the button could only ever end
|
||||
// in the downgrade refusal. That is the banner that showed on every switch.
|
||||
const notice = computeHistoryTruncationNotice({ ...fullscreenTail, paneHistoryLines: 0 });
|
||||
expect(notice).toEqual({ visible: false, message: '', canLoadMore: false });
|
||||
});
|
||||
|
||||
it('stays silent for such a pane in the exhausted and at-ceiling states too', () => {
|
||||
expect(computeHistoryTruncationNotice({ ...fullscreenTail, paneHistoryLines: 0, exhausted: true }).visible).toBe(
|
||||
false
|
||||
);
|
||||
expect(
|
||||
computeHistoryTruncationNotice({
|
||||
...fullscreenTail,
|
||||
source: 'mux-full-history',
|
||||
reason: 'capped',
|
||||
paneHistoryLines: 0,
|
||||
}).visible
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('names the scrollback lines a pull can load instead of the byte gap', () => {
|
||||
const notice = computeHistoryTruncationNotice({ ...fullscreenTail, source: 'history', paneHistoryLines: 48210 });
|
||||
expect(notice.visible).toBe(true);
|
||||
expect(notice.canLoadMore).toBe(true);
|
||||
expect(notice.message).toBe(
|
||||
'Showing the most recent 1.0 MB of this session. 48,210 lines of scrollback are retained.'
|
||||
);
|
||||
expect(notice.message).not.toContain('4.9 MB');
|
||||
});
|
||||
|
||||
it('uses the singular for one line', () => {
|
||||
const notice = computeHistoryTruncationNotice({ ...fullscreenTail, paneHistoryLines: 1 });
|
||||
expect(notice.message).toContain('1 line of scrollback is retained.');
|
||||
});
|
||||
|
||||
it('keeps the byte wording when the server did not report the pane (older server, byte-history fallback)', () => {
|
||||
for (const paneHistoryLines of [undefined, null, NaN]) {
|
||||
const notice = computeHistoryTruncationNotice({ ...fullscreenTail, paneHistoryLines });
|
||||
expect(notice.visible).toBe(true);
|
||||
expect(notice.canLoadMore).toBe(true);
|
||||
expect(notice.message).toContain('more may still be retained');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('the in-terminal truncation line is gone (static guard)', () => {
|
||||
it('no longer writes the notice into terminal output', () => {
|
||||
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
|
||||
@@ -199,6 +199,19 @@ export class FakeTerminal {
|
||||
}
|
||||
scrollToLine() {}
|
||||
scrollToTop() {}
|
||||
/** Every scrollLines() amount; the viewport moves within [0, baseY], as in xterm. */
|
||||
scrolledLines: number[] = [];
|
||||
scrollLines(amount: number) {
|
||||
this.scrolledLines.push(amount);
|
||||
const active = this.buffer.active;
|
||||
active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + amount));
|
||||
}
|
||||
/** Times scrollToBottom() was called; the viewport moves to the live screen, as in xterm. */
|
||||
scrolledToBottom = 0;
|
||||
scrollToBottom() {
|
||||
this.scrolledToBottom++;
|
||||
this.buffer.active.viewportY = this.buffer.active.baseY;
|
||||
}
|
||||
dispose() {}
|
||||
type(data: string) {
|
||||
this.dataCb?.(data);
|
||||
|
||||
@@ -23,10 +23,6 @@ type Manager = {
|
||||
getStorageKey: () => string;
|
||||
normalizePreferences: (preferences: Record<string, unknown>) => NotificationPreferences;
|
||||
notify: (notification: Record<string, unknown>) => void;
|
||||
getToastDurationMs: () => number;
|
||||
unreadCount: number;
|
||||
markAllRead: () => void;
|
||||
clearAll: () => void;
|
||||
};
|
||||
|
||||
const openWindows: JSDOM[] = [];
|
||||
@@ -52,10 +48,6 @@ function loadManager(
|
||||
STUCK_THRESHOLD_DEFAULT_MS: number;
|
||||
GROUPING_TIMEOUT_MS: number;
|
||||
NOTIFICATION_LIST_CAP: number;
|
||||
AUTO_CLOSE_NOTIFICATION_MS: number;
|
||||
DEFAULT_TOAST_DURATION_MS: number;
|
||||
MIN_NOTIFICATION_DURATION_MS: number;
|
||||
MAX_NOTIFICATION_DURATION_MS: number;
|
||||
};
|
||||
win.MobileDetection = {
|
||||
getDeviceType: () => device.deviceType ?? 'desktop',
|
||||
@@ -64,10 +56,6 @@ function loadManager(
|
||||
win.STUCK_THRESHOLD_DEFAULT_MS = 600_000;
|
||||
win.GROUPING_TIMEOUT_MS = 5_000;
|
||||
win.NOTIFICATION_LIST_CAP = 100;
|
||||
win.AUTO_CLOSE_NOTIFICATION_MS = 8_000;
|
||||
win.DEFAULT_TOAST_DURATION_MS = 3_000;
|
||||
win.MIN_NOTIFICATION_DURATION_MS = 1_000;
|
||||
win.MAX_NOTIFICATION_DURATION_MS = 300_000;
|
||||
win.requestAnimationFrame = ((callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 1;
|
||||
@@ -78,7 +66,6 @@ function loadManager(
|
||||
}
|
||||
|
||||
win.eval(`
|
||||
window.escapeHtml = (value) => String(value).replace(/[&<>"']/g, (c) => '&#' + c.charCodeAt(0) + ';');
|
||||
${SOURCE}
|
||||
window.__testNotificationManager = NotificationManager;
|
||||
`);
|
||||
@@ -161,23 +148,3 @@ describe('notification noise defaults', () => {
|
||||
expect(manager.getStorageKey()).toBe('codeman-notification-prefs-mobile');
|
||||
});
|
||||
});
|
||||
|
||||
describe('notification display time', () => {
|
||||
it('defaults to 3s toasts and 8s browser notifications', () => {
|
||||
const { manager } = loadManager();
|
||||
expect(manager.getToastDurationMs()).toBe(3000);
|
||||
expect((manager.preferences as unknown as Record<string, number>).browserAutoCloseMs).toBe(8000);
|
||||
});
|
||||
|
||||
it('honours a configured toast time and clamps unusable values', () => {
|
||||
const { manager } = loadManager({ toastDurationMs: 15_000 });
|
||||
expect(manager.getToastDurationMs()).toBe(15_000);
|
||||
|
||||
const clamp = (value: unknown) =>
|
||||
(manager.normalizePreferences({ toastDurationMs: value }) as unknown as Record<string, number>).toastDurationMs;
|
||||
expect(clamp(10)).toBe(1000);
|
||||
expect(clamp(9_999_999)).toBe(300_000);
|
||||
expect(clamp('soon')).toBe(3000);
|
||||
expect(clamp(undefined)).toBe(3000);
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
/**
|
||||
* @fileoverview The kill path's waits end when the processes do, not on a timer.
|
||||
*
|
||||
* Closing a session used to sleep a fixed 100 + 200 + 100 ms across its signals
|
||||
* and then verify in 100 ms steps, so a session whose processes were gone in a
|
||||
* few ms still took ~0.45 s to close. `waitForProcessesExit()` keeps each of
|
||||
* those deadlines but returns as soon as nothing is left running, and
|
||||
* `isProcessRunning()` counts a zombie as exited (it holds nothing but its pid
|
||||
* until its reaper gets to it, and `kill(pid, 0)` cannot tell it apart).
|
||||
*
|
||||
* Port: N/A.
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { isProcessRunning, waitForProcessesExit } from '../src/utils/process-exit-wait.js';
|
||||
|
||||
describe('waitForProcessesExit', () => {
|
||||
it('returns as soon as every pid has exited, long before the deadline', async () => {
|
||||
let polls = 0;
|
||||
const isRunning = (): boolean => ++polls < 4;
|
||||
const started = Date.now();
|
||||
|
||||
const survivors = await waitForProcessesExit([101, 102], { timeoutMs: 5000, pollMs: 5, isRunning });
|
||||
|
||||
expect(survivors).toEqual([]);
|
||||
expect(Date.now() - started).toBeLessThan(1000);
|
||||
});
|
||||
|
||||
it('returns the survivors at the deadline instead of throwing', async () => {
|
||||
const started = Date.now();
|
||||
|
||||
const survivors = await waitForProcessesExit([7, 8], {
|
||||
timeoutMs: 60,
|
||||
pollMs: 10,
|
||||
isRunning: (pid) => pid === 8,
|
||||
});
|
||||
|
||||
expect(survivors).toEqual([8]);
|
||||
expect(Date.now() - started).toBeGreaterThanOrEqual(50);
|
||||
});
|
||||
|
||||
it('does not wait at all when nothing is running', async () => {
|
||||
const started = Date.now();
|
||||
expect(await waitForProcessesExit([], { timeoutMs: 5000 })).toEqual([]);
|
||||
expect(await waitForProcessesExit([9], { timeoutMs: 5000, isRunning: () => false })).toEqual([]);
|
||||
expect(Date.now() - started).toBeLessThan(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isProcessRunning', () => {
|
||||
it('is true for a live process and false for a pid that does not exist', () => {
|
||||
expect(isProcessRunning(process.pid)).toBe(true);
|
||||
// Above the default pid_max on Linux and macOS alike.
|
||||
expect(isProcessRunning(4_194_304 + 12_345)).toBe(false);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== 'linux')('counts a zombie as exited, which kill(pid, 0) cannot', async () => {
|
||||
// `sleep 0` exits at once, and its parent then becomes `sleep 5`, which never
|
||||
// reaps anything: the child stays a zombie until the parent itself goes.
|
||||
const parent = spawn('sh', ['-c', 'sleep 0 & echo $!; exec sleep 5'], { stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
try {
|
||||
const zombie = await new Promise<number>((resolve, reject) => {
|
||||
parent.stdout.once('data', (chunk: Buffer) => resolve(parseInt(chunk.toString(), 10)));
|
||||
parent.once('error', reject);
|
||||
});
|
||||
const state = (): string => {
|
||||
const stat = readFileSync(`/proc/${zombie}/stat`, 'utf8');
|
||||
return stat.charAt(stat.lastIndexOf(')') + 2);
|
||||
};
|
||||
for (let i = 0; i < 100 && state() !== 'Z'; i++) await new Promise((r) => setTimeout(r, 10));
|
||||
expect(state()).toBe('Z');
|
||||
|
||||
expect(() => process.kill(zombie, 0)).not.toThrow();
|
||||
expect(isProcessRunning(zombie)).toBe(false);
|
||||
} finally {
|
||||
parent.kill('SIGKILL');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -946,53 +946,6 @@ describe('session-routes', () => {
|
||||
expect(body.data.captureRows).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reports how many scrollback rows tmux holds for the captured pane', async () => {
|
||||
// `truncated` measures the byte stream; this is what a `full=1` pull can
|
||||
// return. 0 (a fullscreen CLI in the alternate screen) is the case where
|
||||
// the client must not offer to load the rest.
|
||||
harness.ctx._session.terminalBuffer = 'x'.repeat(4096);
|
||||
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = vi.fn(
|
||||
(
|
||||
_name: string,
|
||||
opts?: { capturedGeometry?: { cols: number; rows: number }; capturedHistoryLines?: number }
|
||||
) => {
|
||||
if (opts) {
|
||||
opts.capturedGeometry = { cols: 100, rows: 50 };
|
||||
opts.capturedHistoryLines = 0;
|
||||
}
|
||||
return 'visible frame';
|
||||
}
|
||||
);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal?tail=1024`,
|
||||
});
|
||||
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.truncated).toBe(true);
|
||||
expect(body.data.paneHistoryLines).toBe(0);
|
||||
});
|
||||
|
||||
it('omits paneHistoryLines when the body is the byte history, not a capture', async () => {
|
||||
harness.ctx._session.terminalBuffer = 'byte history only';
|
||||
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = vi.fn(
|
||||
(_name: string, opts?: { capturedHistoryLines?: number }) => {
|
||||
if (opts) opts.capturedHistoryLines = 12;
|
||||
return null;
|
||||
}
|
||||
);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal`,
|
||||
});
|
||||
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.source).toBe('history');
|
||||
expect(body.data.paneHistoryLines).toBeUndefined();
|
||||
});
|
||||
|
||||
// ── COD-47: full tmux scrollback replay on full page reload ──
|
||||
it('full reload (?full=1) requests full tmux history and replays boundary markers', async () => {
|
||||
// A realistic scrollback-length capture: ~5000 lines, well past one screen.
|
||||
|
||||
@@ -16,11 +16,6 @@
|
||||
* leaves the active-session handoff alone for a close this tab started. A delete
|
||||
* from anywhere else still lands on the welcome screen.
|
||||
*
|
||||
* The close is also OPTIMISTIC: the tab goes and the next one is selected before
|
||||
* the DELETE is even sent (the server's kill takes a few hundred ms, and a tab
|
||||
* sitting there that long read as a dead button). A refused delete puts the row
|
||||
* back where it was; one whose reply was lost is checked with a GET first.
|
||||
*
|
||||
* Loaded via `vm` with a stubbed context (no jsdom), like input-send-order.test.ts.
|
||||
* Port: N/A.
|
||||
*/
|
||||
@@ -79,11 +74,7 @@ function makeApp(active: string | null, order = [A, B]): TestApp {
|
||||
app.isSoloWindow = false;
|
||||
app._wsSessionId = null;
|
||||
app.terminal = { clear: vi.fn() };
|
||||
// Shaped like the Response the real helper resolves with (or null: no answer).
|
||||
app._apiDelete = vi.fn(async () => ({ ok: true, status: 200 }));
|
||||
// The failure path's "is it still there?" check: yes, by default.
|
||||
app._api = vi.fn(async () => ({ ok: true, status: 200 }));
|
||||
app.saveSessionOrder = vi.fn();
|
||||
app._apiDelete = vi.fn(async () => ({ success: true }));
|
||||
// The real one touches ~20 maps; the parts this behavior depends on are the
|
||||
// session map and the tab order, so those are pruned for real.
|
||||
app._cleanupSessionData = vi.fn((id: string) => {
|
||||
@@ -110,7 +101,7 @@ describe('closing the active session', () => {
|
||||
// delete lands before the request resolves.
|
||||
app._apiDelete = vi.fn(async () => {
|
||||
app._onSessionDeleted({ id: A });
|
||||
return { ok: true, status: 200 };
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
await app.closeSession(A);
|
||||
@@ -183,84 +174,3 @@ describe('closing the active session', () => {
|
||||
expect(app.showToast).toHaveBeenCalledWith('Failed to close session', 'error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('closing is optimistic', () => {
|
||||
it('drops the tab and selects the next one BEFORE the server answers', async () => {
|
||||
const app = makeApp(A);
|
||||
let answer: (value: unknown) => void = () => {};
|
||||
app._apiDelete = vi.fn(() => new Promise((r) => (answer = r)));
|
||||
|
||||
const closing = app.closeSession(A);
|
||||
|
||||
expect(app.sessions.has(A)).toBe(false);
|
||||
expect(app.selectSession).toHaveBeenCalledWith(B, { auto: true });
|
||||
// Rendered now, not on the debounce that every session update restarts.
|
||||
expect(app.renderSessionTabs).toHaveBeenCalledWith({ immediate: true });
|
||||
expect(app.showToast).not.toHaveBeenCalled();
|
||||
|
||||
answer({ ok: true, status: 200 });
|
||||
await closing;
|
||||
expect(app.showToast).toHaveBeenCalledWith('Session closed and tmux killed', 'success');
|
||||
});
|
||||
|
||||
it('a refused delete puts the row back where it was, and says so', async () => {
|
||||
const app = makeApp(B, [A, B]);
|
||||
app._apiDelete = vi.fn(async () => ({ ok: false, status: 500 }));
|
||||
|
||||
await app.closeSession(A);
|
||||
|
||||
expect(app._api).toHaveBeenCalledWith(`/api/sessions/${A}`);
|
||||
expect(app.sessions.has(A)).toBe(true);
|
||||
expect(app.sessionOrder).toEqual([A, B]);
|
||||
expect(app.showToast).toHaveBeenCalledWith('Failed to close session', 'error');
|
||||
});
|
||||
|
||||
it('a delete that landed but lost its reply counts as closed', async () => {
|
||||
const app = makeApp(A);
|
||||
app._apiDelete = vi.fn(async () => null);
|
||||
app._api = vi.fn(async () => ({ ok: false, status: 404 }));
|
||||
|
||||
await app.closeSession(A);
|
||||
|
||||
expect(app.sessions.has(A)).toBe(false);
|
||||
expect(app.showToast).toHaveBeenCalledWith('Session closed and tmux killed', 'success');
|
||||
});
|
||||
|
||||
it('a 404 from the delete is a close that already happened', async () => {
|
||||
const app = makeApp(A);
|
||||
app._apiDelete = vi.fn(async () => ({ ok: false, status: 404 }));
|
||||
|
||||
await app.closeSession(A);
|
||||
|
||||
expect(app._api).not.toHaveBeenCalled();
|
||||
expect(app.sessions.has(A)).toBe(false);
|
||||
expect(app.showToast).toHaveBeenCalledWith('Session closed and tmux killed', 'success');
|
||||
});
|
||||
|
||||
it('a session update arriving mid-close does not bring the tab back', async () => {
|
||||
const app = makeApp(A);
|
||||
app.updateCost = vi.fn();
|
||||
app.updateSubagentParentNames = vi.fn();
|
||||
app._apiDelete = vi.fn(async () => {
|
||||
(app as unknown as { _onSessionUpdated: (d: unknown) => void })._onSessionUpdated({ id: A, status: 'idle' });
|
||||
return { ok: true, status: 200 };
|
||||
});
|
||||
|
||||
await app.closeSession(A);
|
||||
|
||||
expect(app.sessions.has(A)).toBe(false);
|
||||
});
|
||||
|
||||
it('a second close of the same tab while the first is in flight is a no-op', async () => {
|
||||
const app = makeApp(A);
|
||||
let answer: (value: unknown) => void = () => {};
|
||||
app._apiDelete = vi.fn(() => new Promise((r) => (answer = r)));
|
||||
|
||||
const first = app.closeSession(A);
|
||||
await app.closeSession(A);
|
||||
answer({ ok: true, status: 200 });
|
||||
await first;
|
||||
|
||||
expect(app._apiDelete).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -68,7 +68,6 @@ import * as fs from 'fs';
|
||||
import * as fsPromises from 'node:fs/promises';
|
||||
import { createInterface } from 'readline';
|
||||
import { execSync } from 'child_process';
|
||||
import { execFile as nodeExecFile } from 'node:child_process';
|
||||
|
||||
/**
|
||||
* Flush the microtask queue to allow async scanForSubagents() to complete.
|
||||
@@ -1629,66 +1628,6 @@ describe('SubagentWatcher', () => {
|
||||
expect(result).toBe(true);
|
||||
expect(completedHandler).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("killSubagentsForSession scans the process table ONCE for all of a session's agents", async () => {
|
||||
// Closing a session ran a full `pgrep -f claude` + /proc read per recently
|
||||
// active subagent (~85ms each on a busy box); one scan now serves them all.
|
||||
// One readline per transcript: discovery reads each agent's file in turn.
|
||||
const rls: ReturnType<typeof createMockRl>[] = [];
|
||||
mockCreateInterface.mockImplementation(() => {
|
||||
const rl = createMockRl();
|
||||
rls.push(rl);
|
||||
return rl;
|
||||
});
|
||||
mockCreateReadStream.mockReturnValue({ destroy: vi.fn() });
|
||||
mockExistsSync.mockReturnValue(true);
|
||||
mockReaddirSync.mockImplementation((path: string) => {
|
||||
if (path.includes('subagents')) return ['agent-k1.jsonl', 'agent-k2.jsonl', 'agent-k3.jsonl'];
|
||||
if (path.includes('session1')) return ['subagents'];
|
||||
if (path.includes('-home-user-project')) return ['session1'];
|
||||
return ['-home-user-project'];
|
||||
});
|
||||
mockStatSync.mockReturnValue({ isDirectory: () => true, birthtime: new Date(), mtime: new Date(), size: 100 });
|
||||
mockReadFileSync.mockReturnValue(createUserEntry('Test subagent task'));
|
||||
|
||||
watcher.start();
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await flushAsyncScan();
|
||||
rls.forEach((rl) => rl.emit('close'));
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
}
|
||||
const agents = watcher.getSubagentsForSession('/home/user/project');
|
||||
expect(agents.map((a) => a.agentId).sort()).toEqual(['k1', 'k2', 'k3']);
|
||||
|
||||
const execFileMock = vi.mocked(nodeExecFile) as unknown as Mock;
|
||||
const originalExecFile = execFileMock.getMockImplementation();
|
||||
let pgrepCalls = 0;
|
||||
execFileMock.mockImplementation(
|
||||
(cmd: string, _args: string[], _opts: unknown, cb: (err: Error | null, stdout: string) => void) => {
|
||||
if (cmd === 'pgrep') pgrepCalls++;
|
||||
cb(null, '4242\n4343\n');
|
||||
}
|
||||
);
|
||||
mockReadFile.mockImplementation(async (path: string) => {
|
||||
if (path === '/proc/4242/environ') return 'HOME=/x\0PARENT=session1\0';
|
||||
if (path.startsWith('/proc/')) return 'HOME=/x\0';
|
||||
return mockReadFileSync(path);
|
||||
});
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
|
||||
let killCalls: unknown[][] = [];
|
||||
try {
|
||||
await watcher.killSubagentsForSession('/home/user/project', 'session1');
|
||||
killCalls = [...killSpy.mock.calls];
|
||||
} finally {
|
||||
killSpy.mockRestore();
|
||||
execFileMock.mockImplementation(originalExecFile as never);
|
||||
}
|
||||
|
||||
expect(pgrepCalls).toBe(1);
|
||||
expect(agents.every((a) => a.status === 'completed')).toBe(true);
|
||||
// Only the matching process, and only once.
|
||||
expect(killCalls).toEqual([[4242, 'SIGTERM']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
|
||||
@@ -14,6 +14,12 @@
|
||||
* wheel-down scrolls xterm home instead of being paged, and paging resumes
|
||||
* from the live screen.
|
||||
*
|
||||
* - a fullscreen Claude tile sends the wheel to the CLI as SGR wheel reports
|
||||
* at the pointer's cell in the TILE (Claude scrolls its own transcript on
|
||||
* them), and xterm's viewport stays on the live screen instead of
|
||||
* scrolling the stale replayed frames above it. Shift+wheel scrolls the
|
||||
* local scrollback, which xterm alone turns into a horizontal no-op.
|
||||
*
|
||||
* The wheel is a real one (`page.mouse.wheel()`), and the last step proves it
|
||||
* reaches xterm: a wheel the tile does not page scrolls xterm's viewport, so
|
||||
* "xterm did not scroll" on a paged wheel means something. What keeps xterm
|
||||
@@ -200,4 +206,95 @@ describe('TerminalTile wheel paging in a real browser', () => {
|
||||
}, PROBE_ID);
|
||||
}
|
||||
});
|
||||
|
||||
it("forwards a fullscreen Claude tile's wheel as SGR reports from its own cells, and keeps xterm on the live screen", async () => {
|
||||
await page.evaluate(async (id) => {
|
||||
const w = window as any;
|
||||
const app = w.app;
|
||||
const CAPTURE_ROWS = 40;
|
||||
const capture = Array.from({ length: CAPTURE_ROWS }, (_, i) => `frame ${i}`).join('\r\n');
|
||||
|
||||
// The tile's session: Claude in its fullscreen renderer (mouse tracking on).
|
||||
app.sessions.set(id, { id, mode: 'claude', cliVersion: '2.1.295', cliMouseTracking: true });
|
||||
const sent: Array<[string, string]> = [];
|
||||
const realEphemeral = app._sendInputEphemeral;
|
||||
app._sendInputEphemeral = (sessionId: string, data: string) => sent.push([sessionId, data]);
|
||||
const realFetch = w.fetch;
|
||||
w.fetch = async (url: string, init?: unknown) =>
|
||||
String(url).includes(`/api/sessions/${id}/terminal`)
|
||||
? new Response(JSON.stringify({ data: { terminalBuffer: capture, captureRows: CAPTURE_ROWS } }))
|
||||
: realFetch(url, init);
|
||||
const RealWebSocket = w.WebSocket;
|
||||
w.WebSocket = class {
|
||||
static OPEN = 1;
|
||||
readyState = 0;
|
||||
send() {}
|
||||
close() {}
|
||||
};
|
||||
|
||||
// Offset from the page corner, so a cell computed against the wrong
|
||||
// element (the primary pane's) would come out different.
|
||||
const mount = document.createElement('div');
|
||||
mount.style.cssText =
|
||||
'position:fixed;left:100px;top:120px;width:640px;height:300px;z-index:99999;background:#000';
|
||||
document.body.appendChild(mount);
|
||||
const tile = new w.TerminalTile(id, mount, { mode: 'claude' });
|
||||
try {
|
||||
await tile.connect();
|
||||
} finally {
|
||||
w.fetch = realFetch;
|
||||
w.WebSocket = RealWebSocket;
|
||||
}
|
||||
w.__tileProbe = { tile, mount, sent, realEphemeral };
|
||||
}, PROBE_ID);
|
||||
|
||||
try {
|
||||
// Where the pointer will be, as the tile's own screen maps it (1-based).
|
||||
const expected = await page.evaluate(() => {
|
||||
const term = (window as any).__tileProbe.tile.terminal;
|
||||
const rect = term.element.querySelector('.xterm-screen').getBoundingClientRect();
|
||||
const cell = term._core._renderService.dimensions.css.cell;
|
||||
const x = rect.left + cell.width * 7.5;
|
||||
const y = rect.top + cell.height * 3.5;
|
||||
return { x, y, col: 8, row: 4 };
|
||||
});
|
||||
// The stale frames sit above the live screen: something xterm COULD scroll.
|
||||
const before = await snap();
|
||||
expect(before.baseY).toBeGreaterThan(0);
|
||||
expect(before.viewportY).toBe(before.baseY);
|
||||
|
||||
await page.mouse.move(expected.x, expected.y);
|
||||
await page.mouse.wheel(0, -100); // one Chrome-on-Windows notch up
|
||||
await page.waitForTimeout(150);
|
||||
await page.mouse.wheel(0, 50); // half a notch down
|
||||
await page.waitForTimeout(150);
|
||||
|
||||
const after = await snap();
|
||||
expect(after.viewportY).toBe(before.baseY); // xterm never scrolled the stale frames
|
||||
expect(after.sent.every(([sid]) => sid === PROBE_ID)).toBe(true);
|
||||
const up = `\x1b[<64;${expected.col};${expected.row}M`;
|
||||
const down = `\x1b[<65;${expected.col};${expected.row}M`;
|
||||
expect(after.sent.map(([, data]) => data)).toEqual([up.repeat(4), down.repeat(2)]);
|
||||
|
||||
// Shift+wheel is the explicit "local scrollback" gesture: scrolled locally
|
||||
// by the tile (xterm alone turns it into a horizontal no-op), unforwarded.
|
||||
await page.keyboard.down('Shift');
|
||||
await page.mouse.wheel(0, -100);
|
||||
await page.keyboard.up('Shift');
|
||||
await page.waitForTimeout(150);
|
||||
const shifted = await snap();
|
||||
expect(shifted.sent.length).toBe(after.sent.length);
|
||||
expect(shifted.viewportY).toBeLessThan(before.baseY);
|
||||
} finally {
|
||||
await page.evaluate((id) => {
|
||||
const w = window as any;
|
||||
const probe = w.__tileProbe;
|
||||
probe.tile.destroy();
|
||||
probe.mount.remove();
|
||||
w.app.sessions.delete(id);
|
||||
w.app._sendInputEphemeral = probe.realEphemeral;
|
||||
delete w.__tileProbe;
|
||||
}, PROBE_ID);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,13 @@
|
||||
* history, so the tile discounts them (`_localRows`); the overflow cases below
|
||||
* fail without that discount.
|
||||
*
|
||||
* Claude's fullscreen renderer is the other half: it scrolls its own
|
||||
* transcript on SGR wheel reports, which the primary pane sends it, while a
|
||||
* tile's xterm holds only replayed repaint frames. A tile left that wheel to
|
||||
* xterm too, so in a grid of fullscreen Claude sessions the wheel dragged
|
||||
* stale frames around or did nothing; it now forwards the reports to its own
|
||||
* session, from its own geometry (`_maybeForwardWheelToCli`).
|
||||
*
|
||||
* Real code under test: constants.js + app.js + terminal-ui.js +
|
||||
* terminal-tile.js in one `vm` context, as in terminal-tile-input.test.ts.
|
||||
* xterm, the fit addon and WebSocket are fakes (test/mocks/terminal-tile-fakes.ts),
|
||||
@@ -260,7 +267,8 @@ describe('a tile pages a hollow buffer through the primary pane gates', () => {
|
||||
expect(ev.stopPropagation).not.toHaveBeenCalled();
|
||||
};
|
||||
|
||||
fireAndCheck(wheelLines(-12, { shiftKey: true })); // the explicit "local scrollback" gesture
|
||||
// The explicit "local scrollback" gesture: scrolled locally, never paged.
|
||||
mount.fire('wheel', wheelLines(-12, { shiftKey: true }));
|
||||
|
||||
term.modes.mouseTrackingMode = 'any'; // xterm's own encoder forwards the wheel
|
||||
fireAndCheck(wheelLines(-12));
|
||||
@@ -280,18 +288,207 @@ describe('a tile pages a hollow buffer through the primary pane gates', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("the forwarding gate behaves as in the primary pane, for the tile's session", () => {
|
||||
it('leaves a fullscreen Claude tile to xterm (tiles do not forward SGR wheel yet)', async () => {
|
||||
const app = makeApp({ 's-tile': { mode: 'claude', cliVersion: '2.1.223', cliMouseTracking: true } });
|
||||
const { ws, mount } = await connectTile(app, { mode: 'claude' });
|
||||
describe('a fullscreen Claude tile forwards the wheel to the CLI as SGR reports', () => {
|
||||
const FULLSCREEN: Session = { mode: 'claude', cliVersion: '2.1.295', cliMouseTracking: true };
|
||||
// 10 + 8 * 20 + 1, 20 + 16 * 5 + 1 inside the tile's own screen: column 21, row 6.
|
||||
const AT = { clientX: 171, clientY: 101 };
|
||||
const UP = '\x1b[<64;21;6M';
|
||||
const DOWN = '\x1b[<65;21;6M';
|
||||
|
||||
const ev = wheelLines(-12);
|
||||
mount.fire('wheel', ev);
|
||||
it("sends ephemeral reports on the tile's socket, from the tile's own geometry, and keeps xterm out", async () => {
|
||||
const { ws, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
|
||||
const up = wheelLines(-3, AT);
|
||||
mount.fire('wheel', up);
|
||||
|
||||
expect(up.preventDefault).toHaveBeenCalled();
|
||||
expect(up.stopPropagation).toHaveBeenCalled();
|
||||
expect(ws.inputFrames()).toEqual([]); // coalesced, not sent per event
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: UP.repeat(3) }]); // no seq: never persisted
|
||||
|
||||
mount.fire('wheel', wheelLines(2, AT));
|
||||
expect(flushed(ws).at(-1)).toEqual({ t: 'i', d: DOWN.repeat(2) });
|
||||
});
|
||||
|
||||
it('forwards a Chrome-on-Windows notch (100 px) as four ticks and caps a fling at five', async () => {
|
||||
const { ws, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
|
||||
mount.fire('wheel', wheel(-100, AT));
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: UP.repeat(4) }]);
|
||||
|
||||
mount.fire('wheel', wheelLines(-1000, AT));
|
||||
expect(flushed(ws).at(-1)).toEqual({ t: 'i', d: UP.repeat(5) });
|
||||
});
|
||||
|
||||
it('moves a precision touchpad delta one line, and consumes a pure horizontal swipe without sending', async () => {
|
||||
const { ws, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
|
||||
mount.fire('wheel', wheel(-3, AT)); // 0.12 of a line
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: UP }]);
|
||||
|
||||
const sideways = wheel(0, { ...AT, deltaX: 120 });
|
||||
mount.fire('wheel', sideways);
|
||||
expect(sideways.preventDefault).toHaveBeenCalled(); // never xterm's stale frames
|
||||
expect(flushed(ws)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('coalesces the reports of wheels within 40 ms into one frame', async () => {
|
||||
const { ws, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
|
||||
mount.fire('wheel', wheelLines(-2, AT));
|
||||
vi.advanceTimersByTime(20);
|
||||
mount.fire('wheel', wheelLines(-2, AT));
|
||||
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: UP.repeat(4) }]);
|
||||
});
|
||||
|
||||
it('snaps a scrolled-up viewport home before reporting, since SGR rows address the live screen', async () => {
|
||||
const { ws, term, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
term.buffer.active.baseY = 10;
|
||||
term.buffer.active.viewportY = 0;
|
||||
|
||||
mount.fire('wheel', wheelLines(-1, AT));
|
||||
|
||||
expect(term.scrolledToBottom).toBe(1);
|
||||
expect(term.buffer.active.viewportY).toBe(10);
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: UP }]);
|
||||
});
|
||||
|
||||
it("follows the tile session's gate, never the active session's", async () => {
|
||||
// Active session is a shell; the tile shows fullscreen Claude: the tile forwards.
|
||||
const forwarded = await connectTile(makeApp({ other: { mode: 'shell' }, 's-tile': FULLSCREEN }, 'other'), {
|
||||
mode: 'claude',
|
||||
});
|
||||
forwarded.mount.fire('wheel', wheelLines(-1, AT));
|
||||
expect(flushed(forwarded.ws)).toEqual([{ t: 'i', d: UP }]);
|
||||
|
||||
// Active session is fullscreen Claude; the tile shows inline Claude (no
|
||||
// tracking): no reports, the hollow buffer is paged instead.
|
||||
const inline = await connectTile(
|
||||
makeApp({ other: FULLSCREEN, 's-tile': { ...FULLSCREEN, cliMouseTracking: false } }, 'other'),
|
||||
{ mode: 'claude' }
|
||||
);
|
||||
inline.mount.fire('wheel', wheelLines(-12, AT));
|
||||
expect(flushed(inline.ws)).toEqual([{ t: 'i', d: PAGE_UP }]);
|
||||
});
|
||||
|
||||
it('scrolls Shift locally, and leaves a tracking xterm and the alternate buffer to xterm', async () => {
|
||||
const { ws, term, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
const fireAndCheck = (ev: ReturnType<typeof wheel>) => {
|
||||
mount.fire('wheel', ev);
|
||||
expect(ev.preventDefault).not.toHaveBeenCalled();
|
||||
expect(ev.stopPropagation).not.toHaveBeenCalled();
|
||||
};
|
||||
|
||||
const shifted = wheelLines(-3, { ...AT, shiftKey: true }); // the explicit "local scrollback" gesture
|
||||
mount.fire('wheel', shifted);
|
||||
expect(shifted.preventDefault).toHaveBeenCalled();
|
||||
expect(term.scrolledLines).toEqual([-3]);
|
||||
|
||||
term.modes.mouseTrackingMode = 'any'; // xterm's own encoder forwards the wheel
|
||||
fireAndCheck(wheelLines(-3, AT));
|
||||
term.modes.mouseTrackingMode = 'none';
|
||||
|
||||
term.buffer.active.type = 'alternate'; // xterm's alt-scroll owns it
|
||||
fireAndCheck(wheelLines(-3, AT));
|
||||
|
||||
expect(ev.preventDefault).not.toHaveBeenCalled();
|
||||
expect(flushed(ws)).toEqual([]);
|
||||
});
|
||||
|
||||
it('pages, never reports, a Claude older than 2.1.187', async () => {
|
||||
const app = makeApp({ 's-tile': { ...FULLSCREEN, cliVersion: '2.1.100' } });
|
||||
const { ws, mount } = await connectTile(app, { mode: 'claude' });
|
||||
|
||||
mount.fire('wheel', wheelLines(-12, AT));
|
||||
|
||||
expect(flushed(ws)).toEqual([{ t: 'i', d: PAGE_UP }]);
|
||||
});
|
||||
|
||||
it('sends exactly the bytes the primary pane sends for the same wheel sequence', async () => {
|
||||
const sequence = [-1, -3, 2, -100, 40, -0.2, 7].map((n) => wheelLines(n, AT));
|
||||
const { ws, mount } = await connectTile(makeApp({ 's-tile': FULLSCREEN }), { mode: 'claude' });
|
||||
const tileBytes: string[] = [];
|
||||
for (const ev of sequence) {
|
||||
mount.fire('wheel', ev);
|
||||
tileBytes.push(
|
||||
...flushed(ws)
|
||||
.splice(tileBytes.length)
|
||||
.map((f) => f.d as string)
|
||||
);
|
||||
}
|
||||
|
||||
const primary = makeApp({ other: FULLSCREEN }, 'other') as App & {
|
||||
terminal: unknown;
|
||||
_sendSyntheticSgrWheel(x: number, y: number, lines: number): void;
|
||||
_wheelScrollLines(ev: unknown): number;
|
||||
_flushWheelSgrQueue(): void;
|
||||
};
|
||||
const sent: string[] = [];
|
||||
primary._sendInputEphemeral = (_id: string, data: string) => sent.push(data);
|
||||
primary.terminal = new FakeTerminal({});
|
||||
for (const ev of sequence) {
|
||||
primary._sendSyntheticSgrWheel(ev.clientX, ev.clientY, primary._wheelScrollLines(ev));
|
||||
primary._flushWheelSgrQueue();
|
||||
}
|
||||
|
||||
expect(tileBytes.join('')).not.toBe('');
|
||||
expect(tileBytes).toEqual(sent);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Shift+wheel scrolls the tile's local scrollback itself", () => {
|
||||
// xterm's own scroller turns a Shift+vertical wheel into a horizontal one off
|
||||
// macOS, and Chrome on Windows already delivers Shift+wheel as deltaX, so
|
||||
// left to xterm the gesture moved nothing.
|
||||
it.each(['claude', 'opencode', 'shell'])('scrolls a %s tile with real history, and sends nothing', async (mode) => {
|
||||
const { ws, term, mount } = await connectTile(makeApp({ 's-tile': { mode } }), { mode });
|
||||
term.write(lines(40));
|
||||
const bottom = term.buffer.active.baseY;
|
||||
expect(bottom).toBeGreaterThan(5);
|
||||
|
||||
const up = wheelLines(-3, { shiftKey: true });
|
||||
mount.fire('wheel', up);
|
||||
|
||||
expect(up.preventDefault).toHaveBeenCalled();
|
||||
expect(up.stopPropagation).toHaveBeenCalled();
|
||||
expect(term.buffer.active.viewportY).toBe(bottom - 3);
|
||||
mount.fire('wheel', wheelLines(3, { shiftKey: true }));
|
||||
expect(term.buffer.active.viewportY).toBe(bottom);
|
||||
expect(flushed(ws)).toEqual([]);
|
||||
});
|
||||
|
||||
it("reads Chrome-on-Windows' horizontal Shift+wheel (deltaX) as vertical travel", async () => {
|
||||
const { term, mount } = await connectTile(makeApp({ 's-tile': { mode: 'claude' } }), { mode: 'claude' });
|
||||
|
||||
mount.fire('wheel', wheel(0, { deltaX: -100, shiftKey: true }));
|
||||
|
||||
expect(term.scrolledLines).toEqual([-4]);
|
||||
});
|
||||
|
||||
it('carries sub-line travel to the next event, so a trackpad still scrolls', async () => {
|
||||
const { term, mount } = await connectTile(makeApp({ 's-tile': { mode: 'claude' } }), { mode: 'claude' });
|
||||
|
||||
mount.fire('wheel', wheel(-10, { shiftKey: true })); // 0.4 of a line
|
||||
mount.fire('wheel', wheel(-10, { shiftKey: true }));
|
||||
expect(term.scrolledLines).toEqual([]);
|
||||
mount.fire('wheel', wheel(-10, { shiftKey: true }));
|
||||
|
||||
expect(term.scrolledLines).toEqual([-1]);
|
||||
});
|
||||
|
||||
it('still pulls history on a Shift+wheel-up at the top of a shell tile', async () => {
|
||||
const { mount } = await connectTile(makeApp({ 's-tile': { mode: 'shell' } }), { mode: 'shell' });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1); // the initial load
|
||||
|
||||
mount.fire('wheel', wheelLines(-3, { shiftKey: true }));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetchMock.mock.calls[1][0])).toContain('full=1&tail=');
|
||||
});
|
||||
});
|
||||
|
||||
describe("the forwarding gate behaves as in the primary pane, for the tile's session", () => {
|
||||
it('pages that same tile under the "Wheel scrolls local history" opt-out (the footgun rescue)', async () => {
|
||||
const app = makeApp({ 's-tile': { mode: 'claude', cliVersion: '2.1.223', cliMouseTracking: true } });
|
||||
app.loadAppSettingsFromStorage = () => ({ terminalWheelLocalScrollback: true });
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
* pick that, with the grid open, would be refused (auto never collapses the
|
||||
* grid) and leave nothing focused. So the fallback is grid-aware, and it lives
|
||||
* IN closeSession: the delete broadcast routinely lands while the request is in
|
||||
* flight, and the delete handlers skip ids in `_closingSessions`. The close is
|
||||
* optimistic, so the tile goes and the neighbour takes focus before the request
|
||||
* is even sent; the broadcast then finds nothing left to do.
|
||||
* flight, and the delete handlers skip ids in `_closingSessions`. The neighbour
|
||||
* is captured BEFORE the await, like `wasActive`, because that broadcast may
|
||||
* already have removed the tile.
|
||||
*
|
||||
* - closing the focused tile: next tile in grid order, else the previous one;
|
||||
* `s-other` is FIRST in sessionOrder and never tiled, so the old pick would
|
||||
@@ -33,8 +33,7 @@ function setup(ids = IDS, focus = ids[0]) {
|
||||
app.selectSession = vi.fn();
|
||||
app.markIdleAlertSeen.mockClear();
|
||||
let finish: () => void = () => {};
|
||||
// Resolves like the real helper's Response once `finish()` is called.
|
||||
app._apiDelete = vi.fn(() => new Promise((r) => (finish = () => r({ ok: true, status: 200 }))));
|
||||
app._apiDelete = vi.fn(() => new Promise<void>((r) => (finish = r)));
|
||||
// The real cleanup touches a lot of panels; what the fallback reads is the session list.
|
||||
app._cleanupSessionData = vi.fn((id: string) => {
|
||||
app.sessions.delete(id);
|
||||
@@ -78,12 +77,11 @@ describe('closeSession on the focused tile', () => {
|
||||
const { app, finish } = setup(IDS, 's-b');
|
||||
const closing = app.closeSession('s-b');
|
||||
await settle();
|
||||
// The close already moved focus to the neighbour before the request went
|
||||
// out; the broadcast for it must not move it again.
|
||||
expect(app.activeSessionId).toBe('s-c');
|
||||
app._onSessionDeleted({ id: 's-b' });
|
||||
// Only the tile went; closeSession owns the follow-up (as the split's
|
||||
// wrapper does for ids in _closingSessions), so focus has not moved yet.
|
||||
expect(app._tileGrid.ids).toEqual(['s-a', 's-c']);
|
||||
expect(app.activeSessionId).toBe('s-c');
|
||||
expect(app.activeSessionId).toBe('s-b');
|
||||
expect(app.showWelcome).not.toHaveBeenCalled();
|
||||
finish();
|
||||
await closing;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatCursorRestore, formatPaneSnapshot, hasVisibleContent, queryPaneCursor } from '../src/tmux-manager.js';
|
||||
import { formatCursorRestore, formatPaneSnapshot, hasVisibleContent } from '../src/tmux-manager.js';
|
||||
|
||||
describe('tmux full-history pane capture (COD-47)', () => {
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/tmux-manager.ts'), 'utf8');
|
||||
@@ -153,48 +153,6 @@ describe('the geometry a capture reports back', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('the capture reports how much scrollback tmux holds (#{history_size})', () => {
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/tmux-manager.ts'), 'utf8');
|
||||
const methodStart = source.indexOf('capturePaneBuffer(muxName: string');
|
||||
const methodBody = source.slice(methodStart, source.indexOf('captureActivePaneBuffer(muxName: string', methodStart));
|
||||
|
||||
it('reads it from the one cursor query the capture already makes', () => {
|
||||
// No extra tmux call: every capture is a synchronous exec on the server.
|
||||
expect(methodBody).toContain("'#{cursor_x} #{cursor_y} #{pane_width} #{pane_height} #{history_size}'");
|
||||
expect(methodBody.match(/display-message/g)).toHaveLength(1);
|
||||
expect(methodBody).toContain('opts.capturedHistoryLines = geometry.historyLines');
|
||||
});
|
||||
|
||||
it('parses the fifth field as historyLines', () => {
|
||||
expect(queryPaneCursor(() => '3 5 120 40 812\n')).toEqual({
|
||||
cursorX: 3,
|
||||
cursorY: 5,
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
historyLines: 812,
|
||||
});
|
||||
// A pane in the alternate screen (fullscreen claude) holds none.
|
||||
expect(queryPaneCursor(() => '0 31 187 32 0')?.historyLines).toBe(0);
|
||||
});
|
||||
|
||||
it('never lets a missing or bad history field void the caret', () => {
|
||||
for (const raw of ['3 5 120 40', '3 5 120 40 ', '3 5 120 40 x', '3 5 120 40 -1']) {
|
||||
const geometry = queryPaneCursor(() => raw);
|
||||
expect(geometry).toEqual({ cursorX: 3, cursorY: 5, cols: 120, rows: 40 });
|
||||
expect(geometry && 'historyLines' in geometry).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('still returns null when the geometry itself is bad', () => {
|
||||
expect(queryPaneCursor(() => 'x 5 120 40 812')).toBeNull();
|
||||
expect(
|
||||
queryPaneCursor(() => {
|
||||
throw new Error('no pane');
|
||||
})
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('why a capture has to report its height', () => {
|
||||
it('a snapshot addresses rows the receiving terminal may not have', () => {
|
||||
// formatPaneSnapshot positions every row absolutely. A terminal shorter
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* @fileoverview showToast() display time and drawer logging: a toast with no explicit
|
||||
* `duration` uses the notification preference, an explicit `duration` (0 = sticky) still wins,
|
||||
* and every toast is recorded in the notification drawer.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const windows: JSDOM[] = [];
|
||||
|
||||
function loadApp(notificationManager?: unknown) {
|
||||
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost/' });
|
||||
windows.push(dom);
|
||||
const CodemanApp = function CodemanApp() {} as unknown as { prototype: Record<string, unknown> };
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
document: dom.window.document,
|
||||
requestAnimationFrame: (cb: () => void) => cb(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
console,
|
||||
});
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/panels-ui.js'), 'utf8');
|
||||
vm.runInContext(source, context, { filename: 'panels-ui.js' });
|
||||
const app = new (CodemanApp as unknown as new () => Record<string, any>)();
|
||||
app.notificationManager = notificationManager;
|
||||
return app;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
for (const dom of windows.splice(0)) dom.window.close();
|
||||
});
|
||||
|
||||
describe('showToast', () => {
|
||||
it('uses the configured display time when no duration is given', () => {
|
||||
vi.useFakeTimers();
|
||||
const app = loadApp({ getToastDurationMs: () => 10_000 });
|
||||
app.showToast('hello');
|
||||
expect(windows[0].window.document.querySelectorAll('.toast')).toHaveLength(1);
|
||||
vi.advanceTimersByTime(9_000);
|
||||
expect(windows[0].window.document.querySelector('.toast.show')).not.toBeNull();
|
||||
vi.advanceTimersByTime(1_500);
|
||||
expect(windows[0].window.document.querySelector('.toast.show')).toBeNull();
|
||||
});
|
||||
|
||||
it('falls back to 3s without a notification manager', () => {
|
||||
vi.useFakeTimers();
|
||||
const app = loadApp();
|
||||
app.showToast('hello');
|
||||
vi.advanceTimersByTime(3_100);
|
||||
expect(windows[0].window.document.querySelector('.toast.show')).toBeNull();
|
||||
});
|
||||
|
||||
it('lets an explicit duration of 0 stay until dismissed', () => {
|
||||
vi.useFakeTimers();
|
||||
const app = loadApp({ getToastDurationMs: () => 1_000 });
|
||||
app.showToast('sticky', 'error', { duration: 0 });
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(windows[0].window.document.querySelector('.toast.show')).not.toBeNull();
|
||||
});
|
||||
});
|
||||