mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 20:49:41 +02:00
Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4b74415ee | ||
|
|
d8a9e2f2bb | ||
|
|
708cb2cbf0 | ||
|
|
90ac13da1a | ||
|
|
48f30f3055 | ||
|
|
c211461500 | ||
|
|
37929cb671 | ||
|
|
e0ebbbdc91 | ||
|
|
8c237223b0 | ||
|
|
dae2ac580f | ||
|
|
7767b16d4f | ||
|
|
a017e9a8e0 | ||
|
|
65ddedd1d4 | ||
|
|
8b23f3e260 | ||
|
|
02b0e27898 | ||
|
|
9d664ffe01 | ||
|
|
a28b04c368 | ||
|
|
e35b68e253 | ||
|
|
77d9ad59f7 | ||
|
|
0cedf05d13 | ||
|
|
d9eeb039db | ||
|
|
bd61735393 | ||
|
|
58b4cb06d8 | ||
|
|
5b667264b4 | ||
|
|
e3d5fd90cd | ||
|
|
713f632a64 | ||
|
|
92b5dfacb0 | ||
|
|
890a1b0902 | ||
|
|
a360763890 | ||
|
|
57899f879e | ||
|
|
d4fe3afc9d | ||
|
|
77fcd65b4a | ||
|
|
2b57c595df | ||
|
|
070e8da81b | ||
|
|
0e82443222 | ||
|
|
323730a29d | ||
|
|
5ac516dd3b | ||
|
|
5130ca6633 | ||
|
|
b87bc6871b | ||
|
|
c367b12f77 | ||
|
|
797f0d387c | ||
|
|
88243e9ffa | ||
|
|
0a5bc1ac2e | ||
|
|
e8a93ada1f | ||
|
|
a164c07f92 | ||
|
|
4f2dfb4e6d | ||
|
|
344e93c824 | ||
|
|
f1b7283393 | ||
|
|
a49be03f96 | ||
|
|
82b090c74a | ||
|
|
2f9663e389 | ||
|
|
327e440607 | ||
|
|
8285fff91c | ||
|
|
51957e2ed4 |
+164
@@ -1,5 +1,169 @@
|
||||
# aicodeman
|
||||
|
||||
## 1.28.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 708cb2c: fix(tabs): let a wrapped desktop tab strip grow the header instead of clipping itself
|
||||
|
||||
The wrapped tab strip carried fixed height caps (120px for the manual two-row layout,
|
||||
96px for measured auto-wrap) that were row counts in disguise. A third row of tabs was
|
||||
clipped into a roughly 4px scroller, so the tab being looked for sat off-screen inside a
|
||||
container nothing invites you to scroll, while the header had the whole page below it to
|
||||
grow into. The header is `min-height` plus `flex-shrink: 0`, and terminal-ui's
|
||||
ResizeObserver refits the terminal on its own, so growing it costs nothing.
|
||||
|
||||
Both wrapped layouts now share one rule capped at `var(--tab-strip-max-height, 40vh)`.
|
||||
That cap is a safety net for an absurd session count rather than a row limit: past it the
|
||||
scroller comes back, which still beats a header that swallows the terminal. Nothing sets
|
||||
`--tab-strip-max-height` yet, so today it is the 40vh fallback plus a hook for a future
|
||||
control.
|
||||
|
||||
Desktop only in effect. `tabs-auto-wrap` is applied by `updateTabOverflowMode()`, which
|
||||
returns early for anything that is not a desktop viewport, and below 1024px `mobile.css`
|
||||
pins the header to `max-height: 48px` so it cannot grow at all. The two rules are
|
||||
comma-grouped rather than wrapped in `:is()`, so each arm keeps its own (0,2,0)
|
||||
specificity and `mobile.css`'s matching overrides still win on source order.
|
||||
|
||||
## 1.28.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 58b4cb0: feat(files): let the path picker jump to a typed path and sort by name or date
|
||||
|
||||
The picker's current-folder line was read-only, so reaching a deep folder meant tapping
|
||||
through every level, and its listing was fixed to name order, so the file an agent had
|
||||
just written was somewhere in a 500-entry list. The current folder is now an editable
|
||||
field (Enter or Go jumps there, a full file path lands in its folder with the file
|
||||
selected, and a typo keeps the listing you had instead of resetting to the root), the
|
||||
listing can be sorted by name or modified time in either direction with folders always
|
||||
first (the choice is remembered per device), and each entry shows a compact modified
|
||||
time. `GET /api/filesystem/browse` entries carry `mtimeMs` to make that possible, with
|
||||
one stat per entry.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- c211461: fix(terminal): swallow Ctrl+Z in agent sessions so it cannot suspend a running CLI
|
||||
|
||||
Ctrl+Z raises SIGTSTP on the pane's tty. In a `shell` session that is ordinary job control and
|
||||
is left alone, but in an agent session suspending the CLI stops an unattended loop dead with no
|
||||
visible output, the same failure shape as an XOFF freeze. The key is now swallowed in
|
||||
`attachCustomKeyEventHandler` for every non-shell mode, and unconditionally in the
|
||||
subagent/teammate terminals, which always run an agent CLI. The match is case-insensitive,
|
||||
because Caps Lock flips `ev.key` to `'Z'` without setting `shiftKey` and a plain `=== 'z'`
|
||||
check would let exactly the keystroke this exists to catch through.
|
||||
|
||||
This is defence in depth rather than a fix for the steady state: an agent CLI holds its tty in
|
||||
raw mode with ISIG off, where ^Z is already inert. It covers the moments that are not the
|
||||
steady state: the window before the CLI takes the tty at startup, and any point where it hands
|
||||
the tty back. Two input paths are deliberately not covered and still reach the PTY: the mobile
|
||||
keyboard accessory bar's one-shot Ctrl, and the CJK composition textarea when `cjkInputEnabled`
|
||||
is on. Both are separate choke points to the PTY, and both are worth covering if this ever
|
||||
turns out to matter in practice.
|
||||
|
||||
- 7767b16: fix(terminal): let Claude use truecolor so its themed backgrounds render
|
||||
|
||||
Claude draws the user's own messages as a block of background color, and it renders as an
|
||||
approximation of the theme color at best. Claude's registry entry deleted `COLORTERM`, which
|
||||
left it the only agent CLI here besides `opencode` not asking for 24-bit color, so every RGB
|
||||
color its theme asks for was quantized down to whatever palette `TERM` alone implies. Claude
|
||||
now exports `COLORTERM=truecolor` like codex, gemini, antigravity, pi, grok, deepseek and omp
|
||||
already do, and the block renders in the color the theme actually names.
|
||||
|
||||
How bad the quantization was depends on `TERM`, which is why this looks different on different
|
||||
machines. On tmux 3.2 and newer, whose `default-terminal` defaults to `tmux-256color`,
|
||||
supports-color reports 256 colors and `rgb(55, 55, 55)` lands on `ESC[48;5;237m`: visible, but
|
||||
not the color the theme asked for. Where `TERM` resolves to a 16-color entry instead (tmux
|
||||
older than 3.2, or a `~/.tmux.conf` setting `default-terminal screen`, which Codeman's tmux
|
||||
server does read), every dark background collapses to `ESC[40m`, the terminal's own black, and
|
||||
the block disappears entirely. That is the case this was reported from, and a custom Claude
|
||||
theme could change the color there with nothing on screen moving.
|
||||
|
||||
Those seven CLIs also unset `NO_COLOR`; Claude does not, so a user who exports `NO_COLOR`
|
||||
globally keeps the monochrome panes they asked for. `CLAUDECODE` stays unset, because Claude
|
||||
reads it as a signal that it is running nested inside itself.
|
||||
|
||||
`buildClaudeEnv()`, the direct-PTY fallback used when tmux is unavailable, now reads the same
|
||||
registry entry as the tmux pane and its attach client instead of deleting `COLORTERM` from a
|
||||
hand-maintained list of its own. It applies that entry before assigning Codeman's own
|
||||
variables, mirroring `buildEnvExports()`, so a `clis.json` override naming one of them cannot
|
||||
strip it on this path while the tmux pane keeps it. A remote pane still exports nothing,
|
||||
because `buildRemoteLaunchCommand()` never carried these declarations, so an SSH-remote Claude
|
||||
session keeps the old rendering.
|
||||
|
||||
PR #3 introduced the `unset COLORTERM` in February, citing xterm.js#484 for the claim that
|
||||
xterm.js mishandles truecolor, and aiming to fall back to 256-color mode. xterm.js closed that
|
||||
issue in April 2019, Codeman now depends on `@xterm/xterm` 6, and `TmuxManager` sets
|
||||
`terminal-overrides ",*:Tc"` on its own tmux server, so 24-bit color already reaches the
|
||||
browser for the CLIs that ask for it.
|
||||
|
||||
## 1.27.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Session lists that answer "which of these wants me next?", loopback links that work from a phone, and a batch of input and remote-session fixes.
|
||||
|
||||
**The vertical tab rail sorts by activity and wears the home screen's cards.** A new per-device setting (App Settings → Appearance → Tabs → **Vertical Rail Order**, default _By activity_) orders rail rows with the same comparator both home screens use: whatever is blocked on you first, then whatever has been running longest, then the most recently quiet. Detailed rail rows become cards, with the state dot keeping its working ring and gaining the home rail's green halo. ⚠️ Existing vertical-rail users get sorting on upgrade, and a self-sorting list cannot also be drag-reorderable: choose _Manual_ to get your own order and drag-reordering back. The lineage bracket also moves 4px further from the rail's left edge, where its glow was being clipped by the window frame.
|
||||
|
||||
**The Claude Response Viewer's brief view shows the whole last turn.** It used to render one row, so the eye button often showed the "Done." tail of an answer whose substance was in the rows above it. A multi-row turn now also opens at its newest text instead of its first narration line.
|
||||
|
||||
**A `localhost` link in agent output opens as a proxied web tab.** An agent prints `http://localhost:5173/` and you tap it on a phone: that address only exists on the Codeman box, so the link was a guaranteed connection error from any other device. It now opens through the proxy, reusing a saved dashboard for the same dev server (one tab per server, not per host spelling) or saving one under its `host:port`. LAN and tailnet addresses still open directly, and on the box itself every link opens directly. `*.localhost` is deliberately not auto-routed: it is the only spelling that is a DNS name rather than an address literal, and these links come from agent output; add such a dashboard by hand instead. Trusted (non-sandboxed) dashboards are likewise never auto-reused by a tapped link.
|
||||
|
||||
**Remote omp and remote claude sessions continue their conversation across a respawn or reattach.** Remote claude now launches an idempotent `--session-id || --resume` pair and remote omp respawns with `--continue`, instead of starting a fresh conversation each time. An omp session id is never resolved from the local `~/.omp` for a remote session, which would have pinned an unrelated local conversation.
|
||||
|
||||
**Android and IME keyboards no longer drop committed characters.** Chrome on Android delivers a `composed: true` input event preceded by a keydown, which is exactly the shape xterm refuses to forward, so the character vanished. A recovery controller forwards it when, and only when, xterm produced nothing for that keystroke, so dictation and soft-keyboard input cannot be delivered twice either.
|
||||
|
||||
### Thanks
|
||||
- **@shenlvkang-collab** for the Response Viewer last-turn fix (#400) and for loopback links as web tabs (#401), both carefully measured, #400 against 285 real transcripts.
|
||||
- **@timkjr** for remote-omp resume/continue through respawn and reattach (#362), including dropping a half that had already landed and verifying the merge kept none of it.
|
||||
- **@aakhter** for the Android/IME input recovery (#388), and in particular for finding that an earlier version of their own browser test was passing vacuously, and saying so.
|
||||
|
||||
## 1.26.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Terminal rendering fixes, a Ctrl+V paste fix, an iOS Safari toolbar fix, a 2GB download cap, and a Blur entrance animation.
|
||||
|
||||
### Terminal rendering
|
||||
|
||||
Three independent causes behind #398, where opening a session rendered a frame with characters spliced into each other and left the caret on the composer's border instead of its input line, until the CLI next wrote anything:
|
||||
- **The full-history replay now keeps row alignment** (#395). The linear capture path never restored the cursor, so every cursor-relative update the CLI sent afterwards was measured from the status line instead of the pane's real position, and four transforms that each can delete a line (trailing-blank stripping, redraw-bloat stripping, the pre-banner trim, leading-whitespace removal) shifted the frame out from under it. The full-history path now appends the pane's own cursor position and keeps every row, so row N of the reply is row N of the pane. The visible-frame and tail paths are untouched.
|
||||
- **The first fit waits for the terminal font** (#396). A cell measured against a fallback font gives the wrong column and row count, so the pane was sized twice and the CLI repainted for a shape that no longer matched the frame on screen. `selectSession` now holds for the font before measuring, bounded at 2s so a font that never arrives cannot strand a session, and it ends by re-measuring explicitly — `FitAddon.proposeDimensions()` divides by a cached cell size and nothing in it listens for font loading, so waiting alone would still divide by the fallback cell.
|
||||
- **A detached session's own window owns its pane size** (#397). Popping a session out left both windows sizing one PTY, and the dashboard's terminal is narrower than the popup because the session rail takes width the popup does not have, so the CLI drew frames that fit neither. The dashboard now withholds the resize send (never the local reflow) for a session showing in its own window, and takes sizing back on redock.
|
||||
|
||||
### Other fixes
|
||||
- **Ctrl+V no longer pastes twice** (#394). One keypress delivered two paste events to the clipboard trap: Firefox dispatches a trusted event for `document.execCommand('paste')` and then returns `false`, and the key's own default action fires another, because xterm's custom key handler returns false without cancelling the keydown. Right-click → Paste has no keydown, which is why only the keyboard duplicated. The trap now consumes exactly one event per keypress.
|
||||
- **iOS Safari: the phone toolbar sits on Safari's bottom bar** (#391, #392). The toolbar was lifted by `100vh - --app-height`, which on iPhone Safari measures the bar's collapsible height rather than an overlap — fixed elements there already stop above the bar — leaving an empty ~40px band and padding the terminal by the same amount. The lift is now `--chrome-overlap` (`innerHeight` minus the visual viewport height), which is 0 on iPhone Safari and equals the real overlap anywhere fixed elements do land behind the chrome.
|
||||
|
||||
### Downloads
|
||||
|
||||
`file-raw`, the attachment `/raw` route and `GET /api/download` now cap at **2GB** instead of 50MB, configurable via `CODEMAN_MAX_DOWNLOAD_BYTES` (`0` = unlimited). The old cap was memory protection for a `readFile()` that no longer exists: those bodies stream and answer `Range` requests, so size costs a read stream rather than RSS (measured: a 600MB download moved peak RSS by ~37MB), and all the cap still did was refuse legitimate downloads of build artifacts, videos and archives. `/api/download` was the last route that really did buffer the whole file; it now streams, advertises `Accept-Ranges` and is resumable. Refusals move from `400` to `413`, the correct status for the case.
|
||||
|
||||
### Blur entrance animation
|
||||
|
||||
A new opt-in `Blur` style on all four entrance surfaces (tabs, agent windows, the terminal pane, connection lines), plus a `Soft focus` theme that sets all four: an iOS-style focus pull where the thing arrives out of focus and the blur fades off it as the opacity comes up. App Settings → Appearance → Entrance Animations, or mix per surface at `?animlab=1`. Entrance animations stay off by default, so an untouched install is unchanged.
|
||||
|
||||
### Maintainer tooling
|
||||
|
||||
The PR bot now fails fast when the review model's budget is spent, instead of hanging a review for the full 40-minute timeout and burning its retry cap.
|
||||
|
||||
### Thanks
|
||||
- @irisitymichaelgrundberg for #394, #395, #396 and #397, and for the #398 investigation that separated three causes behind one symptom
|
||||
- @JDProfresh for reporting #391 and fixing it in #392
|
||||
|
||||
## 1.26.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Codex sessions no longer report idle for their entire life, and Codex conversations now appear in Past Sessions and can be resumed.
|
||||
|
||||
**Per-CLI work detection (#385, irisitymichaelgrundberg).** The composer glyph and the working status line are now registry data (`capabilities.workDetect`) rather than Claude constants. Claude keeps its exact current pair, Codex declares `›` plus its `esc to interrupt` footer, and any CLI that declares neither falls back to Claude's, which is what every session used before. Work detection had been gated Claude-mode-only on the reasoning that an external CLI has no `❯`, which was true and still left every Codex session reporting `idle` from the moment it started. `workingLine` is config-supplied and its compiled pattern runs on the PTY hot path, so it goes through `compileVersionRegex()` in both the schema refine and the runtime compile: a nested quantifier there would backtrack on the event loop for the whole server. The Codex footer is matched case-insensitively on the E, so a future version capitalising it cannot make the fix silently inert.
|
||||
|
||||
**Codex conversations in Past Sessions (#386, irisitymichaelgrundberg).** A bounded scanner reads codex's `~/.codex/sessions` rollout store, so the unified session list now merges three transcript stores rather than one (Claude's `~/.claude/projects`, omp's `~/.omp/agent/sessions`, codex's `~/.codex/sessions`). A scanned row carries a `resumeId`, the rollout's own thread id, which lets it resume through `codexConfig.resumeSessionId`; a live session never carries one, so a row without it stays a genuinely fresh session. Live and resumed Codex sessions fold into their rollout row through the existing alias map, including a `session_meta.originator` match for fresh panes, so a conversation never shows up twice. The phone overview carries `resumeId` through its own row projection, without which a tapped Codex past row started a fresh session on a thread already on disk.
|
||||
|
||||
### Thanks
|
||||
- @irisitymichaelgrundberg for both PRs (#385, #386), and for turning a full review round on #386 in a day.
|
||||
|
||||
## 1.26.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -691,6 +691,7 @@ The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for t
|
||||
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right |
|
||||
| `Ctrl/Cmd+C` | Copy selection, or interrupt when nothing is selected |
|
||||
| `Ctrl+Shift+C` | Copy selection (never interrupts) |
|
||||
| `Ctrl/Cmd+V` | Paste, or upload a clipboard image and paste its path |
|
||||
| `Ctrl/Cmd+L` | Clear terminal |
|
||||
| `Ctrl+Shift+R` | Restore terminal size |
|
||||
| `Ctrl+Shift+V` | Toggle voice input |
|
||||
|
||||
@@ -26,6 +26,7 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/opencode-resize.test.ts',
|
||||
'test/webgl-fallback.test.ts',
|
||||
'test/terminal-copy-shortcut.test.ts',
|
||||
'test/terminal-keycode229-recovery.browser.test.ts',
|
||||
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
|
||||
];
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -36,12 +36,19 @@ interface CliEntry {
|
||||
launch: CliLaunch; // the structured argv template
|
||||
env: CliEnv; // exports, tmux setenv keys, the env-override allowlist
|
||||
capabilities: CliCapabilities; // what every call site reads instead of the id
|
||||
// .workDetect?: { promptGlyph, workingLine } — how this CLI's pane shows work
|
||||
overlays: CliOverlays; // remote-SSH / Docker pane commands, credential store
|
||||
}
|
||||
```
|
||||
|
||||
`capabilities` is the important part. It is what `isExternalCliMode()`, `isAltScreenStripMode()`, `hooksAvailableForMode()` and every other former per-mode branch actually read.
|
||||
|
||||
### Regexes that come from config
|
||||
|
||||
Two capability fields carry a regular expression an override file can set: `discovery.version.regex` and `capabilities.workDetect.workingLine`. Both go through `compileVersionRegex()`, which caps the source at 200 characters, refuses the nested-quantifier shapes that cause catastrophic backtracking, and returns `null` rather than throwing so every caller degrades instead of crashing.
|
||||
|
||||
`workingLine` is the one that matters most, because it is compiled once per session and then run against every accumulated PTY chunk and every pane capture. A nested quantifier there is a ReDoS against the event loop for the whole server, not just that session. The guard therefore runs in two places, and neither is redundant: `schema.ts` rejects the entry at LOAD time so a bad pattern never reaches a session, and `_workingLinePattern()` in `session.ts` compiles through the same helper so the runtime cannot end up with a pattern the schema would have refused.
|
||||
|
||||
### Three capabilities that must stay independent
|
||||
|
||||
`external`, `hooks` and `altScreen` describe three different, deliberately unequal sets, and deriving any one from another has already shipped a bug. `shell` has no hooks but is **not** an external CLI, so a hooks predicate written as `!isExternalCliMode()` accepted `until=stop` on a shell session and then blocked the caller for their entire timeout. `deepseek` is the mirror image: it IS external and it DOES have hooks.
|
||||
|
||||
@@ -153,6 +153,14 @@ shared nor seeded.
|
||||
include `~/.local/bin`. Per-session config and `envOverrides` do not cross ssh and are
|
||||
rejected rather than silently ignored; use the per-host command override instead.
|
||||
|
||||
⚠️ A **respawn or reattach** of a remote omp session runs `omp --continue`, not a
|
||||
bare `omp`, so it lands back in the same conversation. It is deliberately
|
||||
`--continue` rather than the exact `--resume <id>` the local and docker paths
|
||||
pin: `omp-session-resolver.ts` only ever reads THIS host's `~/.omp/agent/sessions/`,
|
||||
and a remote conversation's session file lives on the remote host under the
|
||||
remote user's home, so resolving locally would pin a stranger's id. See
|
||||
[Respawn / reattach continuation](remote-sessions.md#respawn--reattach-continuation).
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **No idle/completion hook.** Idle detection falls back to output-stabilization
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ has to be copied; set them here to use a different bot.
|
||||
| `PR_BOT_POLL_INTERVAL` | `600` | Seconds between GitHub polls (minimum 60). |
|
||||
| `PR_BOT_MAIN_CHECKOUT` | the repo this script is in | The repository the clones share objects with and fetch from. |
|
||||
| `PR_BOT_DATA_DIR` | `~/.codeman/pr-bot` | State, briefs, reports, clones. |
|
||||
| `PR_BOT_MODEL` | unset (the session default) | Codeman `modelOverride` for the review sessions, e.g. `claude-fable-5-1`. |
|
||||
| `PR_BOT_MODEL` | unset (the session default) | Codeman `modelOverride` for the review sessions, e.g. `opus[1m]`. ⚠️ Pick a model whose budget can absorb a re-review of every open PR on every head commit: when it runs out, Claude Code answers the limit **inside the turn** and the reviewer has nothing to write. The bot now names that failure in seconds (`findModelLimitNotice`) instead of burning the whole `PR_BOT_REVIEW_TIMEOUT`, and a limit does not spend the per-head retry budget, so the queue resumes by itself once the budget does. |
|
||||
| `PR_BOT_EFFORT` | unset | Codeman `effort` for the review sessions. |
|
||||
| `PR_BOT_REVIEW_TIMEOUT` | `40` | Minutes before a review is abandoned. |
|
||||
| `PR_BOT_FOLLOWUP_TIMEOUT` | `20` | Minutes before a follow-up is abandoned. |
|
||||
|
||||
+50
-1
@@ -30,7 +30,7 @@ Types live in `src/types/session.ts`; persistence in `src/remote-hosts.ts`.
|
||||
| `RemoteHost` (extends `RemoteSshOptions`) | A saved host: `id`, `label`, `host`, `username`, `port?`, `commands?` (per-mode launch command override). |
|
||||
| `RemoteCase` | A working directory on a host: `name`, `type: 'remote'`, `hostId`, `remotePath`. |
|
||||
| `SessionRemote` (extends `RemoteSshOptions`) | The resolved bundle stamped onto a live session: host coordinates + `remotePath` + `commands`, plus **`owned?`** and **`remoteSessionName?`** (COD-105 — see [Ownership](#ownership-launched-vs-discovered-and-attached-cod-105)). Built by `toSessionRemote(host, case)` (sets `owned: true`) for the launch path, or `toAttachedSessionRemote(host, name, path)` (sets `owned: false`) for the attach path. Both copy the advanced SSH options through so every connection is identical. |
|
||||
| `RemoteCommandMode` | `Extract<SessionMode, 'shell' \| 'claude' \| 'opencode' \| 'codex' \| 'gemini' \| 'antigravity' \| 'pi' \| 'grok'>` — the modes that can run remotely. |
|
||||
| `RemoteCommandMode` | `Extract<SessionMode, 'shell' \| 'claude' \| 'opencode' \| 'codex' \| 'gemini' \| 'antigravity' \| 'pi' \| 'grok' \| 'deepseek' \| 'omp'>` — the modes that can run remotely. |
|
||||
| `RemoteSessionInfo` (COD-105) | One discovered remote tmux session: `name` (always `codeman-*`), `attached` (a client is connected), `created` (epoch s), `windows`. Returned by `listRemoteCodemanSessions()`. |
|
||||
|
||||
Persistence is two flat JSON arrays in the instance data dir:
|
||||
@@ -116,6 +116,11 @@ Key points:
|
||||
the agent. The per-mode command comes from `remote.commands?.[mode]` or
|
||||
`defaultRemoteCommandForMode(mode)` (`exec claude` / `exec opencode` /
|
||||
`exec codex` / `exec gemini` / `exec agy` / `exec bash -l`).
|
||||
⚠️ **claude and omp no longer take that path**: both have their own arm in
|
||||
`buildRemoteLaunchCommand` so a respawn can continue the same conversation
|
||||
(see [Respawn / reattach continuation](#respawn--reattach-continuation)), and
|
||||
because the claude arm is an `a || b` pair under `-c`, its pane PID is the
|
||||
**login shell**, not the agent.
|
||||
- The **whole tmux invocation is a single shell-quoted ssh argument**, and the
|
||||
pane command is independently quoted, so a `remotePath` with spaces is safe.
|
||||
- Connection options come from the **same `buildSshConnectionArgs(remote)`** as
|
||||
@@ -202,6 +207,50 @@ The early return is a structural guarantee that **no code path can ever issue a
|
||||
remote `kill-session` for a session we don't own** — the only `kill-session` run is
|
||||
on the local socket, which never reaches the remote socket.
|
||||
|
||||
## Respawn / reattach continuation
|
||||
|
||||
A dropped connection or a dead pane must reconnect to the **same conversation**,
|
||||
not launch a fresh one — the whole point of a durable remote session.
|
||||
|
||||
- **Claude**: the launch command is idempotent — `claude --session-id <id> ||
|
||||
claude --resume <id>` (see `buildRemoteLaunchCommand`'s claude branch). The
|
||||
first run creates the conversation under the deterministic session id; every
|
||||
later reattach/respawn re-runs the same line, `--session-id` fails
|
||||
("already in use"), and the `||` fallback resumes it.
|
||||
- **OMP**: `omp` has no equivalent idempotent single-line form, so
|
||||
`Session._pinOmpRespawnId()` resolves and pins an explicit `--resume <id>`
|
||||
before a respawn (mirroring the local/docker builders, rendered through the
|
||||
same `buildSpawnCommandFromRegistry` engine — not a hand-rolled command and
|
||||
not `appendResumeFlag()`, which is docker-only and cannot work here: appending
|
||||
a flag after the quoted `-c 'omp'` hands the id to the login shell as `$0`
|
||||
instead of to `omp`). ⚠️ **The resolver only ever reads THIS host's local
|
||||
`~/.omp/agent/sessions/`**, which is meaningless for a remote session — the
|
||||
conversation and its session file live on the remote host, under the remote
|
||||
user's home. For a remote session, `_pinOmpRespawnId()` therefore skips local
|
||||
resolution entirely and falls back to `omp`'s own ambiguous `--continue`
|
||||
(`ompConfig.continueSession`), which the remote pane command already renders.
|
||||
This is a known, accepted degradation versus the local/docker paths' exact
|
||||
`--resume` pin — safe in practice because each remote respawn talks to
|
||||
exactly one remote pane's own omp history, so "most recent" is normally
|
||||
correct, but it can drift the same way `--continue` always could if two
|
||||
remote sessions ever share one remote directory.
|
||||
|
||||
## Auto-reconnect vs. a clean agent exit
|
||||
|
||||
`remoteAutoReconnect` (default ON) watches for a dropped SSH connection and
|
||||
reconnects with bounded backoff. It must **never** revive a session whose agent
|
||||
exited cleanly (Ctrl-C, Ctrl-D, `exit`) — that tears down the durable remote
|
||||
tmux session itself, and a transport-level `isPaneDead()` cannot tell that apart
|
||||
from a plain network drop. `remoteTmuxSessionAlive()` (#355) resolves this by
|
||||
probing the remote host directly: `tmux -L codeman-remote has-session -t
|
||||
codeman-ssh-<id8>` over the same `buildSshConnectionArgs` as launch, classified
|
||||
by **exit status alone** (`classifyRemoteAliveExit`: `0` = alive, ssh's `255` or
|
||||
a timeout = unknown, anything else = gone) — `has-session` prints nothing on
|
||||
success, so reading stdout would misclassify every live session as gone. An
|
||||
unreachable host answers "unknown", which also means do not revive. The answer
|
||||
is cached per session and cleared whenever the pane is next seen alive, so a
|
||||
stale `true` from one transport drop can never revive the NEXT clean exit.
|
||||
|
||||
## API
|
||||
|
||||
Routes are registered in `src/web/routes/case-routes.ts`:
|
||||
|
||||
@@ -312,8 +312,8 @@ TOCTOU window.
|
||||
| Route | Cap | Notes |
|
||||
|-------|-----|-------|
|
||||
| `file-content` | 10 MB | text preview |
|
||||
| `file-raw` | 50 MB | inline MIME map; **`X-Content-Type-Options: nosniff` on all responses**; streamed, `Range`-aware (206 slices come from the same validated path, and the cap is checked before the range) |
|
||||
| `POST /api/download` | 50 MB | forced `attachment`; sensitive‑path blocklist |
|
||||
| `file-raw` | 2 GB (`CODEMAN_MAX_DOWNLOAD_BYTES`, `0` = unlimited) | inline MIME map; **`X-Content-Type-Options: nosniff` on all responses**; streamed, `Range`-aware (206 slices come from the same validated path, and the cap is checked before the range) |
|
||||
| `GET /api/download` | same cap | forced `attachment`; sensitive‑path blocklist; streamed, `Range`-aware |
|
||||
|
||||
### SVG / content‑type XSS
|
||||
|
||||
@@ -340,7 +340,7 @@ the attachment guard below.
|
||||
|
||||
Live external attachments (`src/attachment-registry.ts`) mint an `att_<uuid>` id
|
||||
for a host file so browser requests carry the id, never an absolute path. Serving
|
||||
is by id (`GET /api/sessions/:id/attachments/:attachmentId/raw`, 50 MB cap,
|
||||
is by id (`GET /api/sessions/:id/attachments/:attachmentId/raw`, same download cap,
|
||||
`nosniff`) and re‑resolves the symlink + re‑checks the **attachment guard**
|
||||
(`src/config/attachment-guard.ts`: the shared sensitive‑path blocklist **plus**
|
||||
the `/root` and `/etc` trees, extendable via `attachmentBlockedPaths` /
|
||||
|
||||
@@ -52,6 +52,37 @@ sandbox, cookies, CORS, CSP, or any reverse proxy sitting in front of Codeman, s
|
||||
passing Test does not guarantee the embedded page will render (see the
|
||||
cookie-authenticated reverse proxy caveat below).
|
||||
|
||||
## Links to `localhost` from another device
|
||||
|
||||
An agent prints `http://localhost:5173/` (a dev server, a preview, a report it just
|
||||
served) and you tap it on your phone. That address only exists on the Codeman box, so
|
||||
the phone's browser can never load it — but the web-tab proxy fetches from the server,
|
||||
where it works.
|
||||
|
||||
So a **loopback** link (`localhost`, `127.0.0.0/8`, `0.0.0.0`, `::1`) clicked
|
||||
in the terminal or in the Response Viewer opens as a **proxied web tab** whenever the
|
||||
Codeman page itself is not on that box. A saved proxied dashboard on the same origin is
|
||||
reused (one tab per dev server, with the link's own path opened inside it, and one tab
|
||||
per dev server rather than per host spelling, so `localhost:5173` and `127.0.0.1:5173`
|
||||
share it); otherwise one is saved under its `host:port` so it is in the Run dropdown
|
||||
next time, and a toast tells you it was saved. Sandboxed by default, like any other web
|
||||
tab.
|
||||
|
||||
⚠️ **`*.localhost` is deliberately not auto-routed**, even though a browser treats it as
|
||||
loopback. Every other name in that list is an address literal that can only mean this
|
||||
box; a `*.localhost` DNS name is not one, and on a resolver with a search domain
|
||||
configured `evil.localhost` can be retried as `evil.localhost.<search domain>`, which
|
||||
someone else can control. Since the links come from agent output, one tap would then
|
||||
make Codeman fetch an agent-chosen origin server-side and save it. If you really run
|
||||
`api.localhost` dev hosts, add that dashboard by hand: doing so is an explicit action,
|
||||
which is the difference that matters here. A **trusted** (non-sandboxed) dashboard is
|
||||
likewise never auto-reused by a tapped link, for the same reason.
|
||||
|
||||
Only loopback is routed this way. A LAN or tailnet address (`192.168.…`, `100.…`,
|
||||
`box.ts.net`) may well be reachable from the device — a VPN, the same Wi-Fi — and a
|
||||
direct open is the cheaper, richer path, so those links still open in a new browser tab.
|
||||
On the box itself (a browser on `localhost`) every link opens directly.
|
||||
|
||||
## The sandbox, and when to turn it off
|
||||
|
||||
Because a proxied dashboard is served from Codeman's own address, it is
|
||||
|
||||
@@ -14,6 +14,7 @@ works, slash commands included.
|
||||
| `Shift+Enter` / `Ctrl+Enter` | Newline without sending. |
|
||||
| `Ctrl+C` | Copy if text is selected, otherwise interrupt. |
|
||||
| `Ctrl+Shift+C` | Copy, never interrupts. |
|
||||
| `Ctrl+V` | Paste. A clipboard image uploads instead. |
|
||||
| `Ctrl+L` | Clear the terminal. |
|
||||
|
||||
### Exactly-once delivery
|
||||
|
||||
@@ -25,6 +25,7 @@ Press `Ctrl+?` in the app for the same list in a floating overlay.
|
||||
| `Ctrl+Enter` | Same. |
|
||||
| `Ctrl+C` | Copy the selection, or interrupt when nothing is selected. |
|
||||
| `Ctrl+Shift+C` | Copy the selection. Never interrupts. |
|
||||
| `Ctrl+V` | Paste. An image on the clipboard uploads and pastes its file path instead. |
|
||||
| `Ctrl+L` | Clear the terminal. |
|
||||
| `Ctrl+Shift+R` | Restore terminal size. |
|
||||
| `Ctrl` `+` / `Ctrl` `-` | Font size. |
|
||||
|
||||
@@ -19,7 +19,9 @@ It renders what it can:
|
||||
| PDF and Office documents | Converted for preview when a converter is available. |
|
||||
| Anything else | Download. |
|
||||
|
||||
Caps: 10 MB for text preview, 50 MB for raw and download. Sensitive paths (`.env`, anything
|
||||
Caps: 10 MB for text preview, 2 GB for raw and download (set `CODEMAN_MAX_DOWNLOAD_BYTES`
|
||||
to change it, `0` for no limit — these bodies are streamed, so a large file costs a read
|
||||
stream rather than server memory). Sensitive paths (`.env`, anything
|
||||
matching credentials, `~/.ssh`, AWS credentials) are blocked from download, and SVG and HTML
|
||||
are served as downloads rather than rendered, so they cannot execute in the page.
|
||||
|
||||
@@ -115,10 +117,14 @@ For choosing a path rather than typing one. It appears in two places:
|
||||
- **Browse** in **Add Case → Link Existing**.
|
||||
- The **📁 Path** key on the mobile keyboard bar.
|
||||
|
||||
It browses one directory at a time and can show hidden entries on request. The picker
|
||||
inserts the path into your prompt **without** pressing Enter, so nothing is submitted by
|
||||
accident. Its sibling **⌫ All** key clears the unsent prompt, and never sends the agent's
|
||||
`/clear` command.
|
||||
It browses one directory at a time and can show hidden entries on request. The current
|
||||
folder is an editable field: type or paste a path and press Enter (or **Go**) to jump
|
||||
straight there, and a full file path lands in its folder with that file selected. The
|
||||
**Sort** control orders each listing by name or by modified time (newest first is the
|
||||
quick way to the file an agent just wrote), with folders always ahead of files; the
|
||||
choice is remembered per device. The picker inserts the path into your prompt
|
||||
**without** pressing Enter, so nothing is submitted by accident. Its sibling **⌫ All**
|
||||
key clears the unsent prompt, and never sends the agent's `/clear` command.
|
||||
|
||||
This is a separate file-serving surface from the viewer, with its own rules: it allowlists
|
||||
your home directory, the cases directory, and anything in `CODEMAN_FILE_PICKER_ROOTS`, and
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.26.0",
|
||||
"version": "1.28.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "1.26.0",
|
||||
"version": "1.28.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.26.0",
|
||||
"version": "1.28.1",
|
||||
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -83,6 +83,7 @@ appendFileSync(
|
||||
|
||||
// 4. Minify frontend assets
|
||||
run('minify input-cjk.js', 'npx esbuild dist/web/public/input-cjk.js --minify --outfile=dist/web/public/input-cjk.js --allow-overwrite');
|
||||
run('minify terminal-keycode229-recovery.js', 'npx esbuild dist/web/public/terminal-keycode229-recovery.js --minify --outfile=dist/web/public/terminal-keycode229-recovery.js --allow-overwrite');
|
||||
run('minify i18n.js', 'npx esbuild dist/web/public/i18n.js --minify --outfile=dist/web/public/i18n.js --allow-overwrite');
|
||||
run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --minify --outfile=dist/web/public/sanitize-html.js --allow-overwrite');
|
||||
run('minify app.js', 'npx esbuild dist/web/public/app.js --minify --outfile=dist/web/public/app.js --allow-overwrite');
|
||||
@@ -110,6 +111,7 @@ console.log('\n[build] content-hash cache busting');
|
||||
'notification-manager.js',
|
||||
'keyboard-accessory.js',
|
||||
'input-cjk.js',
|
||||
'terminal-keycode229-recovery.js',
|
||||
'sanitize-html.js',
|
||||
'app.js',
|
||||
'tab-rail-resize.js',
|
||||
|
||||
+19
-5
@@ -19,7 +19,7 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { CodemanClient, stripAnsi, type TurnOutcome } from './codeman-client.js';
|
||||
import { CodemanClient, ModelLimitError, stripAnsi, type TurnOutcome } from './codeman-client.js';
|
||||
import type { PrBotConfig } from './config.js';
|
||||
import {
|
||||
approveWorkflowRun,
|
||||
@@ -434,7 +434,10 @@ export class PrBot {
|
||||
if (report && !existsSync(reportMdPath)) writeFileSync(reportMdPath, last);
|
||||
}
|
||||
await this.recordClaudeSessionId(sessionId, rec);
|
||||
if (!report) throw new Error(await this.describeFailure(sessionId, outcome, started, last));
|
||||
if (!report) {
|
||||
const why = await this.describeFailure(sessionId, outcome, started, last);
|
||||
throw outcome.kind === 'limit' ? new ModelLimitError(why) : new Error(why);
|
||||
}
|
||||
|
||||
const durationMin = Math.max(1, Math.round((Date.now() - started) / 60_000));
|
||||
Object.assign(rec, {
|
||||
@@ -460,9 +463,15 @@ export class PrBot {
|
||||
if (rec) {
|
||||
rec.status = 'failed';
|
||||
rec.lastError = reason;
|
||||
rec.failedAttempts = rec.failedSha === rec.headSha ? (rec.failedAttempts ?? 0) + 1 : 1;
|
||||
rec.failedSha = rec.headSha;
|
||||
const givingUp = rec.failedAttempts >= MAX_AUTO_RETRIES;
|
||||
// A spent model budget is an account condition, not a bad PR, so it must not
|
||||
// spend the per-head retry budget: otherwise one exhausted afternoon marks every
|
||||
// open PR "not retrying on my own" and none of them come back when credits do.
|
||||
const accountCondition = err instanceof ModelLimitError;
|
||||
if (!accountCondition) {
|
||||
rec.failedAttempts = rec.failedSha === rec.headSha ? (rec.failedAttempts ?? 0) + 1 : 1;
|
||||
rec.failedSha = rec.headSha;
|
||||
}
|
||||
const givingUp = !accountCondition && (rec.failedAttempts ?? 0) >= MAX_AUTO_RETRIES;
|
||||
await this.telegram
|
||||
.sendMessage(
|
||||
formatReviewFailure(rec, reason) +
|
||||
@@ -523,6 +532,11 @@ export class PrBot {
|
||||
}
|
||||
case 'exit':
|
||||
return 'the session exited before writing a report';
|
||||
case 'limit':
|
||||
return (
|
||||
`the model budget for these review sessions is spent, so the reviewer never started:\n${outcome.message}\n` +
|
||||
'Point PR_BOT_MODEL in ~/.codeman/pr-bot.env at a model with headroom and restart codeman-pr-bot.'
|
||||
);
|
||||
case 'timeout':
|
||||
return `timed out after ${minutes} min without a report`;
|
||||
default:
|
||||
|
||||
@@ -50,7 +50,42 @@ export interface SessionRecord {
|
||||
mode: string;
|
||||
}
|
||||
|
||||
export type TurnOutcome = { kind: 'stop' } | { kind: 'blocked' } | { kind: 'exit' } | { kind: 'timeout' };
|
||||
export type TurnOutcome =
|
||||
| { kind: 'stop' }
|
||||
| { kind: 'blocked' }
|
||||
| { kind: 'exit' }
|
||||
| { kind: 'timeout' }
|
||||
| { kind: 'limit'; message: string };
|
||||
|
||||
/**
|
||||
* Claude Code answers a spent model budget INSIDE the turn ("You've reached your Fable
|
||||
* limit. Run /usage-credits to continue or switch models with /model.") and then simply
|
||||
* sits there with nothing to write. Measured 2026-09-08: four reviews each burned their
|
||||
* whole 40-minute deadline and reported a bare "timed out without a report", which reads
|
||||
* as a hung reviewer rather than an account that needs attention, and the retries spent
|
||||
* the per-head budget so the PRs would not have been picked up again once credits
|
||||
* returned. Matching the notice turns 40 silent minutes into a named failure in seconds.
|
||||
*
|
||||
* Deliberately model-agnostic: the same sentence is printed for every model, and the
|
||||
* apostrophe is typographic on the pane, so neither the model name nor `'` is matched.
|
||||
*/
|
||||
const MODEL_LIMIT_PATTERN = /reached your [^\n]{0,40}?\blimit\b|\/usage-credits/i;
|
||||
|
||||
/**
|
||||
* Thrown instead of a plain Error when a review died on a spent model budget, so the
|
||||
* caller can tell an account condition apart from a review that genuinely failed.
|
||||
*/
|
||||
export class ModelLimitError extends Error {
|
||||
override readonly name = 'ModelLimitError';
|
||||
}
|
||||
|
||||
/** The limit notice as one clean line, or undefined if the screen does not carry it. */
|
||||
export function findModelLimitNotice(screen: string): string | undefined {
|
||||
const line = stripAnsi(screen)
|
||||
.split('\n')
|
||||
.find((l) => MODEL_LIMIT_PATTERN.test(l));
|
||||
return line?.replace(/^[\s>|]*(?:\u23bf|\u2514|\u256d|\u2570|\u23a2|\u2502|\u23bd)?\s*/u, '').trim() || undefined;
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
@@ -241,9 +276,22 @@ export class CodemanClient {
|
||||
if (!r.delivered) throw new Error('the prompt was not delivered (pane dead?)');
|
||||
let wait = r.wait;
|
||||
let nudged = false;
|
||||
// Only consulted when the turn produced nothing, so a review that merely QUOTES the
|
||||
// notice in its report cannot be mistaken for one that hit it.
|
||||
const limitNotice = async (): Promise<string | undefined> =>
|
||||
findModelLimitNotice(await this.terminalText(id).catch(() => ''));
|
||||
while (true) {
|
||||
if (wait && !wait.timedOut) return toOutcome(wait);
|
||||
if (wait && !wait.timedOut) {
|
||||
const outcome = toOutcome(wait);
|
||||
if (outcome.kind === 'stop' && !opts.isDone?.()) {
|
||||
const limit = await limitNotice();
|
||||
if (limit) return { kind: 'limit', message: limit };
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
if (opts.isDone?.()) return { kind: 'stop' };
|
||||
const limit = await limitNotice();
|
||||
if (limit) return { kind: 'limit', message: limit };
|
||||
const remaining = opts.deadlineMs - (Date.now() - started);
|
||||
if (remaining <= 0) return { kind: 'timeout' };
|
||||
if (!nudged) {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* worktree's project settings through the git common dir, i.e. the MAIN checkout's
|
||||
* `.claude/settings.local.json`, whose model pin then silently overrides anything
|
||||
* written into the worktree (measured 2026-09-05: a worktree pinned to
|
||||
* `claude-fable-5-1` reported `claude-opus-5[1m]`). A shared clone has its own
|
||||
* `claude-fable-5-1` reported `claude-opus-5[1m]`, the main checkout's pin). A shared clone has its own
|
||||
* project root, so Codeman's `modelOverride` and hooks land where the CLI reads them,
|
||||
* while `objects/info/alternates` keeps the object store shared (no duplication).
|
||||
*
|
||||
|
||||
@@ -284,6 +284,7 @@ than into an existing checkout.
|
||||
| send input | `POST /api/v1/sessions/:id/input` |
|
||||
| **read a worker's answer** (claude/codex/deepseek) | `GET /api/v1/sessions/:id/last-response` → `.data.{text,timestamp}`, clean transcript text, no TUI noise. ⚠️ **Poll it**, see [symptom 7](#7-last-response-returns-an-empty-string-right-after-stop) |
|
||||
| read the whole conversation | `GET /api/v1/sessions/:id/last-response?context=full` → `.data.messages[]`. ⚠️ **Only `{role,text}` is present for every mode.** `kind`/`label` come from claude (`prompt`/`response`), deepseek and the pane parser (which also emit `status`/`tool`) but NOT from codex; `timestamp` from claude and codex but not deepseek/pane; `turn` and `queued:true` (a prompt typed while the agent was working) from claude only. `.data.text` is unchanged by `context=full` — it stays the last assistant message, never `messages[-1]` |
|
||||
| read the last **answered turn** (claude only) | `GET /api/v1/sessions/:id/last-response?context=turn` → `.data.messages[]` holds every assistant message of the most recent turn that has one (the whole answer, not just its final row); `.data.text` is still the last assistant row. Other modes answer `text` only, with no `messages` |
|
||||
| read terminal (tail is in **BYTES**, raw ANSI) | `GET /api/v1/sessions/:id/terminal?tail=3000` → `.data.terminalBuffer`, for *diagnosis* (unsubmitted prompt?), not for reading answers |
|
||||
| full tmux scrollback (context bomb; post-mortems only) | `GET /api/v1/sessions/:id/terminal?full=1` |
|
||||
| background agents, one session | `GET /api/v1/sessions/:id/subagents` |
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
/**
|
||||
* @fileoverview Scan `~/.codex/sessions/<yyyy>/<mm>/<dd>/rollout-*.jsonl` for Past
|
||||
* Sessions rows, the codex analog of what `scanOmpSessionsHistory()`
|
||||
* (omp-transcript.ts) does for omp and `scanProjectDir()` (session-routes.ts)
|
||||
* does for Claude's own `~/.claude/projects` transcripts.
|
||||
*
|
||||
* Without this a codex conversation is invisible to Codeman the moment its
|
||||
* session record goes away, even though codex itself never forgot it: the
|
||||
* unified list is built from `~/.claude/projects` plus omp's own store, and
|
||||
* codex writes to neither. A user who wanted to pick a codex thread back up had
|
||||
* to find its id by hand and pass `codexConfig.resumeSessionId` to the API.
|
||||
*
|
||||
* ## Why this reads windows rather than whole files
|
||||
*
|
||||
* An omp session file is the conversation only, so its scanner reads each file
|
||||
* whole. A codex rollout is not comparable: it carries every reasoning block and
|
||||
* every tool call, and its `session_meta` line alone embeds the full base
|
||||
* instructions. Measured on a real store of 519 rollouts, the median file is
|
||||
* 407 KiB, the 90th percentile 1.3 MiB and the largest 25 MiB, for 381 MiB in
|
||||
* total. So this reads a head window for the identity and the opening prompt,
|
||||
* and a tail window for the most recent one.
|
||||
*
|
||||
* The head budget is 128 KiB because `session_meta` runs to roughly 19 KiB and
|
||||
* the first real user message lands near 69 KiB behind it, both measured on
|
||||
* codex 0.152.1.
|
||||
*
|
||||
* ## Where the prompt text comes from
|
||||
*
|
||||
* Codex has emitted user input under three shapes, and this reads all of them,
|
||||
* preferring the ones that carry real input only:
|
||||
*
|
||||
* - `event_msg` / `item_completed` with an `item.type` of `UserMessage`, which
|
||||
* is what codex 0.152.1 writes.
|
||||
* - `event_msg` / `user_message`, which older versions wrote.
|
||||
* - `response_item` rows with `role: 'user'`, the last resort. These mix real
|
||||
* input with injected context (AGENTS.md, environment context, compaction
|
||||
* summaries), so they are read only when neither shape above appears, and
|
||||
* the obvious injections are dropped.
|
||||
*
|
||||
* @module codex-transcript
|
||||
*/
|
||||
|
||||
import { open, readdir, stat } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
|
||||
/** Covers `session_meta` (~19 KiB) plus the first user message (~69 KiB behind it). */
|
||||
const HEAD_BYTES = 131072;
|
||||
|
||||
/** Enough to hold the last few turns' worth of lines without re-reading the file. */
|
||||
const TAIL_BYTES = 65536;
|
||||
|
||||
/**
|
||||
* Newest rollouts to REPORT. Counted in emitted rows, not files scanned: the
|
||||
* store is mostly sub-agent threads this never returns, so capping files first
|
||||
* would spend the budget on rows nobody sees.
|
||||
*/
|
||||
const MAX_ROLLOUTS = 400;
|
||||
|
||||
/**
|
||||
* How many emitted rows also get a tail read for `lastPrompt`. The head read is
|
||||
* cached (see below) but the tail cannot be, because appending to a rollout is
|
||||
* exactly what changes it, so this is the one genuinely per-request cost and it
|
||||
* stays bounded. Counted in emitted rows for the same reason as above — against
|
||||
* file index a store of sub-agent threads spends the whole budget before the
|
||||
* first row that needed it.
|
||||
*/
|
||||
const MAX_TAIL_READS = 100;
|
||||
|
||||
/** Directory nesting under `sessions/` is year/month/day; stop well past that. */
|
||||
const MAX_WALK_DEPTH = 5;
|
||||
|
||||
/** A rollout shorter than this cannot hold a complete `session_meta` line. */
|
||||
const MIN_ROLLOUT_BYTES = 100;
|
||||
|
||||
export interface CodexHistorySession {
|
||||
/** The rollout's own thread id — the token `codex resume <id>` expects. */
|
||||
sessionId: string;
|
||||
/**
|
||||
* `session_meta.originator`, which codex stamps from
|
||||
* CODEX_INTERNAL_ORIGINATOR_OVERRIDE — `codeman_<sessionId>` for every pane
|
||||
* Codeman spawns. The only link between a FRESH codex pane and the rollout it
|
||||
* is writing, since such a pane knows no thread id of its own.
|
||||
*/
|
||||
originator?: string;
|
||||
workingDir: string;
|
||||
sizeBytes: number;
|
||||
/** ISO timestamp, from the file's own mtime. */
|
||||
lastModified: string;
|
||||
firstPrompt?: string;
|
||||
lastPrompt?: string;
|
||||
}
|
||||
|
||||
/** The half of a rollout that never changes once codex has written it. */
|
||||
interface RolloutIdentity {
|
||||
threadId?: string;
|
||||
cwd?: string;
|
||||
/** `'subagent'` marks a thread codex spawned for itself. */
|
||||
threadSource?: string;
|
||||
/** `codeman_<sessionId>` for a pane Codeman spawned; codex's own default otherwise. */
|
||||
originator?: string;
|
||||
firstPrompt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `session_meta` is written once and never rewritten — the same fact
|
||||
* `readCodexRolloutMetaCached()` in session-routes.ts relies on — so a path's
|
||||
* identity is cached, and a rescan costs a `stat` per file plus head reads for
|
||||
* rollouts this process has not seen before.
|
||||
*
|
||||
* ⚠️ The first user message is NOT written up front: codex writes it when the
|
||||
* user submits. Caching before then pins `firstPrompt: undefined` for the life
|
||||
* of the process, and every scan of the home screen, the command palette and the
|
||||
* search-index refresh can land in that window — so the row reads as having no
|
||||
* prompt until a restart. `shouldCacheIdentity()` is the guard.
|
||||
*
|
||||
* Bounded, unlike a plain Map: this process runs for days and every sub-agent
|
||||
* rollout adds an entry. Same reason and same size as `codexRolloutMetaCache`.
|
||||
*/
|
||||
const identityCache = new LRUMap<string, RolloutIdentity>({ maxSize: 4096 });
|
||||
|
||||
/**
|
||||
* Is this identity settled enough to keep?
|
||||
*
|
||||
* A known `firstPrompt` settles it. So does a head read that FILLED its window,
|
||||
* which means the prompt is genuinely not in the first `HEAD_BYTES` rather than
|
||||
* not written yet. A short file with no prompt is the ambiguous case — codex is
|
||||
* still to write one — so that one is re-read next scan.
|
||||
*/
|
||||
function shouldCacheIdentity(identity: RolloutIdentity, fileSize: number): boolean {
|
||||
if (!identity.threadId) return false;
|
||||
return identity.firstPrompt !== undefined || fileSize >= HEAD_BYTES;
|
||||
}
|
||||
|
||||
function codexSessionsRoot(): string {
|
||||
const home = process.env.CODEX_HOME || join(homedir(), '.codex');
|
||||
return join(home, 'sessions');
|
||||
}
|
||||
|
||||
/** Read at most `bytes` from the front of a file. Returns '' when unreadable. */
|
||||
async function readHead(path: string, bytes: number): Promise<string> {
|
||||
const fh = await open(path, 'r').catch(() => null);
|
||||
if (!fh) return '';
|
||||
try {
|
||||
const buf = Buffer.alloc(bytes);
|
||||
const { bytesRead } = await fh.read(buf, 0, bytes, 0);
|
||||
return buf.subarray(0, bytesRead).toString('utf-8');
|
||||
} catch {
|
||||
return '';
|
||||
} finally {
|
||||
await fh.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read at most `bytes` from the end of a file, dropping the leading partial
|
||||
* line so every line handed back parses.
|
||||
*/
|
||||
async function readTail(path: string, size: number, bytes: number): Promise<string> {
|
||||
const fh = await open(path, 'r').catch(() => null);
|
||||
if (!fh) return '';
|
||||
try {
|
||||
const want = Math.min(bytes, size);
|
||||
const buf = Buffer.alloc(want);
|
||||
const { bytesRead } = await fh.read(buf, 0, want, size - want);
|
||||
const text = buf.subarray(0, bytesRead).toString('utf-8');
|
||||
if (want >= size) return text; // whole file, nothing was cut
|
||||
const nl = text.indexOf('\n');
|
||||
return nl === -1 ? '' : text.slice(nl + 1);
|
||||
} catch {
|
||||
return '';
|
||||
} finally {
|
||||
await fh.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** Flatten codex's message content, which is a string or an array of text blocks. */
|
||||
function contentText(content: unknown): string {
|
||||
if (typeof content === 'string') return content.trim();
|
||||
if (!Array.isArray(content)) return '';
|
||||
return content
|
||||
.filter(
|
||||
(b): b is { text: string } => !!b && typeof b === 'object' && typeof (b as { text?: unknown }).text === 'string'
|
||||
)
|
||||
.map((b) => b.text)
|
||||
.join('\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** One line's user-prompt text, whichever of the three shapes it is. */
|
||||
function userPromptFromLine(entry: {
|
||||
type?: string;
|
||||
payload?: {
|
||||
type?: string;
|
||||
role?: string;
|
||||
content?: unknown;
|
||||
message?: unknown;
|
||||
item?: { type?: string; content?: unknown };
|
||||
};
|
||||
}): { text: string; injectionProne: boolean } | null {
|
||||
const p = entry.payload;
|
||||
if (!p) return null;
|
||||
|
||||
if (entry.type === 'event_msg' && p.type === 'item_completed' && p.item?.type === 'UserMessage') {
|
||||
const text = contentText(p.item.content);
|
||||
return text ? { text, injectionProne: false } : null;
|
||||
}
|
||||
if (entry.type === 'event_msg' && p.type === 'user_message') {
|
||||
const text = typeof p.message === 'string' ? p.message.trim() : contentText(p.message);
|
||||
return text ? { text, injectionProne: false } : null;
|
||||
}
|
||||
if (entry.type === 'response_item' && p.role === 'user') {
|
||||
const text = contentText(p.content);
|
||||
return text ? { text, injectionProne: true } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injected context rather than something the user typed. Codex prepends the
|
||||
* repository's AGENTS.md and wraps environment context in a tag, and both arrive
|
||||
* as `response_item` user rows.
|
||||
*/
|
||||
function isInjectedContext(text: string): boolean {
|
||||
return text.startsWith('#') || text.startsWith('<');
|
||||
}
|
||||
|
||||
/** Collapse to one line and cap, so a row carries a title rather than an essay. */
|
||||
function asPreview(text: string): string {
|
||||
const flat = text.replace(/\s+/g, ' ').trim();
|
||||
return flat.length > 200 ? `${flat.slice(0, 200)}…` : flat;
|
||||
}
|
||||
|
||||
/** Parse a head window into the facts about a rollout that never change. */
|
||||
function parseIdentity(head: string): RolloutIdentity {
|
||||
const out: RolloutIdentity = {};
|
||||
let fallback: string | undefined;
|
||||
for (const line of head.split('\n')) {
|
||||
if (!line) continue;
|
||||
let entry: {
|
||||
type?: string;
|
||||
payload?: {
|
||||
id?: string;
|
||||
session_id?: string;
|
||||
cwd?: string;
|
||||
thread_source?: string;
|
||||
originator?: string;
|
||||
type?: string;
|
||||
role?: string;
|
||||
content?: unknown;
|
||||
message?: unknown;
|
||||
item?: { type?: string; content?: unknown };
|
||||
};
|
||||
};
|
||||
try {
|
||||
entry = JSON.parse(line);
|
||||
} catch {
|
||||
continue; // truncated tail of the window, or a malformed line
|
||||
}
|
||||
const p = entry.payload;
|
||||
if (entry.type === 'session_meta' && p) {
|
||||
out.threadId ??= p.id || p.session_id;
|
||||
out.cwd ??= p.cwd;
|
||||
out.threadSource ??= p.thread_source;
|
||||
out.originator ??= p.originator;
|
||||
} else if (entry.type === 'turn_context' && p) {
|
||||
out.cwd ??= p.cwd;
|
||||
}
|
||||
if (out.firstPrompt) continue;
|
||||
const prompt = userPromptFromLine(entry);
|
||||
if (!prompt) continue;
|
||||
if (!prompt.injectionProne) {
|
||||
out.firstPrompt = asPreview(prompt.text);
|
||||
} else if (!fallback && !isInjectedContext(prompt.text)) {
|
||||
fallback = asPreview(prompt.text);
|
||||
}
|
||||
}
|
||||
out.firstPrompt ??= fallback;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The most recent user prompt in a tail window, or undefined. */
|
||||
function parseLastPrompt(tail: string): string | undefined {
|
||||
let best: string | undefined;
|
||||
let fallback: string | undefined;
|
||||
for (const line of tail.split('\n')) {
|
||||
if (!line) continue;
|
||||
try {
|
||||
const prompt = userPromptFromLine(JSON.parse(line));
|
||||
if (!prompt) continue;
|
||||
if (!prompt.injectionProne) best = asPreview(prompt.text);
|
||||
else if (!isInjectedContext(prompt.text)) fallback = asPreview(prompt.text);
|
||||
} catch {
|
||||
// Malformed line — keep scanning.
|
||||
}
|
||||
}
|
||||
return best ?? fallback;
|
||||
}
|
||||
|
||||
/** Every rollout file under `sessions/`, newest first. */
|
||||
async function listRollouts(root: string): Promise<Array<{ path: string; mtimeMs: number; size: number }>> {
|
||||
const files: Array<{ path: string; mtimeMs: number; size: number }> = [];
|
||||
const walk = async (dir: string, depth: number): Promise<void> => {
|
||||
if (depth > MAX_WALK_DEPTH) return;
|
||||
const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);
|
||||
if (!entries) return;
|
||||
for (const entry of entries) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
await walk(full, depth + 1);
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue;
|
||||
const st = await stat(full).catch(() => null);
|
||||
if (!st || st.size < MIN_ROLLOUT_BYTES) continue;
|
||||
files.push({ path: full, mtimeMs: st.mtimeMs, size: st.size });
|
||||
}
|
||||
};
|
||||
await walk(root, 0);
|
||||
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex conversations on this host, newest first, for the unified session list.
|
||||
*
|
||||
* Sub-agent threads are left out: codex spawns them for itself, they are not
|
||||
* something a person picks back up, and on a real store they outnumber the
|
||||
* threads that are.
|
||||
*/
|
||||
export async function scanCodexSessionsHistory(): Promise<CodexHistorySession[]> {
|
||||
const files = await listRollouts(codexSessionsRoot());
|
||||
const out: CodexHistorySession[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (out.length >= MAX_ROLLOUTS) break;
|
||||
|
||||
let identity = identityCache.get(file.path);
|
||||
if (!identity) {
|
||||
identity = parseIdentity(await readHead(file.path, HEAD_BYTES));
|
||||
if (shouldCacheIdentity(identity, file.size)) identityCache.set(file.path, identity);
|
||||
}
|
||||
if (!identity.threadId || identity.threadSource === 'subagent') continue;
|
||||
// A row with no directory has nowhere to resume INTO, and emitting an empty
|
||||
// one makes a click post `workingDir: ''`. omp drops such a row; so does this.
|
||||
if (!identity.cwd) continue;
|
||||
|
||||
const lastPrompt =
|
||||
out.length < MAX_TAIL_READS ? parseLastPrompt(await readTail(file.path, file.size, TAIL_BYTES)) : undefined;
|
||||
|
||||
out.push({
|
||||
sessionId: identity.threadId,
|
||||
originator: identity.originator,
|
||||
workingDir: identity.cwd,
|
||||
sizeBytes: file.size,
|
||||
lastModified: new Date(file.mtimeMs).toISOString(),
|
||||
firstPrompt: identity.firstPrompt,
|
||||
lastPrompt: lastPrompt ?? identity.firstPrompt,
|
||||
});
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which codex thread each Codeman-spawned pane is writing, keyed by Codeman
|
||||
* session id.
|
||||
*
|
||||
* Codeman spawns every codex pane with
|
||||
* CODEX_INTERNAL_ORIGINATOR_OVERRIDE=codeman_<sessionId>, and codex stamps that
|
||||
* into `session_meta.originator`. That is the ONLY link between a fresh codex
|
||||
* pane and the rollout it is writing: such a pane knows no thread id of its own,
|
||||
* so it cannot be folded into its own Past-Sessions row from its own side.
|
||||
*
|
||||
* Newest wins. `/new` typed inside the codex TUI leaves several rollouts sharing
|
||||
* one originator, and the pane is on the most recent — so this expects `rows`
|
||||
* newest-first, as `scanCodexSessionsHistory()` returns them.
|
||||
*/
|
||||
export function codexThreadBySessionId(rows: CodexHistorySession[]): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const row of rows) {
|
||||
const owner = /^codeman_(.+)$/.exec(row.originator ?? '')?.[1];
|
||||
if (owner && !out.has(owner)) out.set(owner, row.sessionId);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Test seam: drop the per-path identity cache. */
|
||||
export function __clearCodexIdentityCache(): void {
|
||||
identityCache.clear();
|
||||
}
|
||||
@@ -112,3 +112,50 @@ export const FILE_PEEK_BYTES = 8 * 1024 - 1; // 8KB (inclusive end offset)
|
||||
* Override: CODEMAN_MAX_PASTE_IMAGE_BYTES (bytes)
|
||||
*/
|
||||
export const MAX_PASTE_IMAGE_BYTES = parseInt(process.env.CODEMAN_MAX_PASTE_IMAGE_BYTES || '') || 50 * 1024 * 1024; // 50MB
|
||||
|
||||
// ============================================================================
|
||||
// File Download Limits
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Parse a byte-limit env var, where `0` explicitly means "no limit".
|
||||
*
|
||||
* The `parseInt(...) || default` idiom used elsewhere in this file cannot
|
||||
* express that: it treats 0 as falsy and silently restores the default.
|
||||
*/
|
||||
function parseByteLimitEnv(raw: string | undefined, fallback: number): number {
|
||||
if (raw === undefined || raw.trim() === '') return fallback;
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) return fallback;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum size (bytes) of a file served by the raw/download file routes:
|
||||
* `GET /api/sessions/:id/file-raw` (the Files panel's download link and the
|
||||
* file-preview overlay), the attachment `/raw` route, and `GET /api/download`.
|
||||
*
|
||||
* ⚠️ This is a sanity bound, NOT memory protection. All three bodies are
|
||||
* STREAMED and `Range`-aware (`sendFileBody` in file-routes.ts), so a large
|
||||
* file costs one read stream rather than its size in RSS. The historical 50MB
|
||||
* cap predates that streaming rewrite and its "prevent memory exhaustion"
|
||||
* comment described a `readFile()` that no longer exists — all it did was
|
||||
* refuse legitimate downloads of build artifacts, videos and archives.
|
||||
*
|
||||
* Set `CODEMAN_MAX_DOWNLOAD_BYTES=0` to remove the cap entirely.
|
||||
* Override: CODEMAN_MAX_DOWNLOAD_BYTES (bytes)
|
||||
*/
|
||||
export const MAX_FILE_DOWNLOAD_BYTES = parseByteLimitEnv(
|
||||
process.env.CODEMAN_MAX_DOWNLOAD_BYTES,
|
||||
2 * 1024 * 1024 * 1024 // 2GB
|
||||
);
|
||||
|
||||
/** True when `size` exceeds the download cap (a cap of 0 means unlimited). */
|
||||
export function exceedsDownloadLimit(size: number): boolean {
|
||||
return MAX_FILE_DOWNLOAD_BYTES > 0 && size > MAX_FILE_DOWNLOAD_BYTES;
|
||||
}
|
||||
|
||||
/** Human-readable "File too large (…)" message for a refused download. */
|
||||
export function downloadTooLargeMessage(size: number): string {
|
||||
return `File too large (${Math.round(size / 1024 / 1024)}MB > ${Math.round(MAX_FILE_DOWNLOAD_BYTES / 1024 / 1024)}MB limit). Raise or remove it with CODEMAN_MAX_DOWNLOAD_BYTES (0 = unlimited).`;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import { TOKEN_PATTERNS } from './patterns.js';
|
||||
import { compileVersionRegex, TOKEN_PATTERNS } from './patterns.js';
|
||||
import { isKnownLauncherProfile, isKnownSetenvProfile } from './profiles.js';
|
||||
|
||||
/** A bare CLI id: lowercase, starts with a letter, at most 24 chars. Also used as a CSS/URL token. */
|
||||
@@ -274,6 +274,23 @@ const capabilitiesSchema = z
|
||||
effort: z.boolean(),
|
||||
agentSkillInjection: z.boolean(),
|
||||
statusLineTelemetry: z.boolean(),
|
||||
workDetect: z
|
||||
.object({
|
||||
promptGlyph: z.string().min(1).max(8),
|
||||
// Config-supplied regex, so it goes through the same guard as `version.regex`:
|
||||
// ~/.codeman/clis.json can set this, and the compiled pattern runs on the PTY
|
||||
// hot path, where a nested quantifier would be a ReDoS against the event loop.
|
||||
// A broken pattern must also fail at LOAD time rather than inside a data handler.
|
||||
workingLine: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
(src) => compileVersionRegex(src) !== null,
|
||||
'workingLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
model: z
|
||||
.object({ source: z.enum(['flag', 'claude-settings-file', 'none']), param: z.string().optional() })
|
||||
.strict(),
|
||||
|
||||
@@ -174,8 +174,19 @@ const CLAUDE: CliEntry = {
|
||||
legacyConfigAliases: { resumeId: 'resumeSessionId' },
|
||||
},
|
||||
env: {
|
||||
exports: [],
|
||||
unset: ['CLAUDECODE', 'COLORTERM'],
|
||||
// Claude asks for truecolor, like every CLI here except `shell` and `opencode`.
|
||||
// tmux hands the pane TERM=screen, which supports-color reads as 16 colors, and
|
||||
// Claude then quantizes every RGB color its theme asks for down to that palette.
|
||||
// Each dark background lands on ESC[40m, the terminal's own black, so the block
|
||||
// Claude draws behind the user's own messages renders invisible. PR #3 unset
|
||||
// COLORTERM here against xterm.js#484, which xterm.js had already closed in 2019,
|
||||
// and Codeman now ships @xterm/xterm 6 and sets `terminal-overrides *:Tc` itself.
|
||||
// The other truecolor CLIs also unset NO_COLOR. Claude does not, so a user who
|
||||
// exports NO_COLOR globally keeps the monochrome panes they asked for.
|
||||
// CLAUDECODE stays unset, because Claude reads it as a signal that it is running
|
||||
// nested inside itself.
|
||||
exports: [{ name: 'COLORTERM', value: 'truecolor' }],
|
||||
unset: ['CLAUDECODE'],
|
||||
tmuxSetenvKeys: [],
|
||||
dockerExecEnvNames: [],
|
||||
allowedPrefixes: ['CLAUDE_CODE_'],
|
||||
@@ -183,6 +194,13 @@ const CLAUDE: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
external: false,
|
||||
// The historical hard-coded pair, now stated as data. `workingLine` matches both the
|
||||
// `✻ Actualizing… (39s · ↓ 2.0k tokens)` status line and the bare `esc to interrupt`
|
||||
// footer, because tmux repaints partially and only one of the two may land in a chunk.
|
||||
workDetect: {
|
||||
promptGlyph: '❯',
|
||||
workingLine: String.raw`…\s*\((?:\d+h\s+)?(?:\d+m\s+)?\d+s\b|esc to interrupt`,
|
||||
},
|
||||
requiresMux: false,
|
||||
// Claude installs Codeman's own hooks block into every workspace it runs in, so its
|
||||
// stop/idle signals are unconditional — no per-session veto, unlike deepseek's bridge.
|
||||
@@ -418,6 +436,11 @@ const CODEX: CliEntry = {
|
||||
},
|
||||
capabilities: {
|
||||
...agentDefaults(),
|
||||
// Codex draws `› Ask Codex to do anything` on its composer row and
|
||||
// `Working (2m 49s • esc to interrupt)` above it while a turn runs. It animates no
|
||||
// braille spinner, and it never prints `esc to interrupt` at rest, so that phrase
|
||||
// alone separates a running turn from an idle one.
|
||||
workDetect: { promptGlyph: '›', workingLine: '[Ee]sc to interrupt' },
|
||||
transcript: 'codex-rollout',
|
||||
altScreen: 'strip-full',
|
||||
echo: { policy: 'predict', anchor: { kind: 'cursor' }, predictProfile: 'codex' },
|
||||
|
||||
@@ -306,6 +306,29 @@ export interface CliCapabilities {
|
||||
* independent — see this interface's own doc comment.
|
||||
*/
|
||||
external: boolean;
|
||||
/**
|
||||
* How to read this CLI's own TUI for whether it is mid-turn.
|
||||
*
|
||||
* Codeman infers a working agent from the pane, so the two strings it needs are the
|
||||
* ones that differ per CLI: the glyph on the composer row, and the status line the CLI
|
||||
* draws while a turn runs. Holding them here is what lets a non-Claude CLI report work
|
||||
* at all — `external` used to gate the whole detector, so every external CLI reported
|
||||
* itself permanently idle even mid-turn.
|
||||
*
|
||||
* `promptGlyph` only ARMS the idle confirmation and is never on its own evidence that a
|
||||
* turn ended, because a CLI redraws its composer throughout a turn. `workingLine` is
|
||||
* the evidence, and `_confirmIdle` consults it before believing the pane went quiet.
|
||||
*
|
||||
* An entry that omits this field keeps Codeman's historical behaviour: the Claude glyph
|
||||
* arms the confirmation and the Claude working line answers it. Leave it out for a CLI
|
||||
* whose TUI nobody has characterised, and its sessions report work exactly as before.
|
||||
*/
|
||||
workDetect?: {
|
||||
/** The glyph this CLI draws on its composer row, e.g. Claude's `❯`, Codex's `›`. */
|
||||
promptGlyph: string;
|
||||
/** Source of a regex matching the status line this CLI draws while a turn runs. */
|
||||
workingLine: string;
|
||||
};
|
||||
/** No direct-PTY fallback: the CLI must run inside tmux (secrets ride tmux setenv). */
|
||||
requiresMux: boolean;
|
||||
/**
|
||||
|
||||
@@ -137,7 +137,12 @@ export interface RespawnPaneOptions {
|
||||
|
||||
/** Options for pane buffer capture (COD-47 full-history mode). */
|
||||
export interface PaneCaptureOptions {
|
||||
/** Capture the entire tmux scrollback instead of just the visible frame. */
|
||||
/**
|
||||
* Capture the entire scrollback instead of just the visible frame, as linear
|
||||
* text ending with a cursor move back to the pane's caret position. An
|
||||
* implementation returns '' when the pane holds nothing visible, which the
|
||||
* caller reads as "nothing to replay" and keeps its existing history.
|
||||
*/
|
||||
fullHistory?: boolean;
|
||||
/** Bound the full-history capture to this many scrollback lines (`-S -<N>`). */
|
||||
historyLimitLines?: number;
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
* @fileoverview Pure merge/filter logic for the unified session list (COD-121).
|
||||
*
|
||||
* Combines four read-only views of a session — live (in-memory `Session`),
|
||||
* persisted (`state.json`), transcript history (`~/.claude/projects`), and the
|
||||
* lifecycle audit log — plus mux process stats, into one de-duplicated list
|
||||
* keyed by sessionId. Transcript-history rows are keyed by the Claude
|
||||
* conversation UUID (the `.jsonl` filename stem), which diverges from the
|
||||
* Codeman id for resumed sessions — an alias map (claudeSessionId → Codeman id,
|
||||
* built from the live/persisted views) folds them into the owning session item.
|
||||
* persisted (`state.json`), transcript history, and the lifecycle audit log —
|
||||
* plus mux process stats, into one de-duplicated list keyed by sessionId.
|
||||
*
|
||||
* Transcript history is not one source but three, because the CLIs keep their
|
||||
* conversations in their own stores: Claude's `~/.claude/projects`, omp's
|
||||
* `~/.omp/agent/sessions` and codex's `~/.codex/sessions`. Each row is keyed by
|
||||
* whatever id that CLI names the conversation with, which diverges from the
|
||||
* Codeman id for a resumed session and for every non-Claude one — an alias map
|
||||
* (claudeSessionId → Codeman id, built from the live/persisted views) folds them
|
||||
* into the owning session item.
|
||||
* Higher-precedence sources overwrite scalar fields when present
|
||||
* (history < lifecycle < persisted < live), while the `sources` array
|
||||
* always accumulates every contributing view. A "meaningfulness floor" drops
|
||||
@@ -39,6 +43,11 @@ export type UnifiedSessionItem = {
|
||||
/** Main repo root a worktree belongs to (#266). */
|
||||
worktreeRepo?: string;
|
||||
remote?: boolean;
|
||||
/**
|
||||
* Token this row's CLI resumes by, when that is not `sessionId`. Set only from
|
||||
* a transcript scanner — see the field of the same name on `HistoryInput`.
|
||||
*/
|
||||
resumeId?: string;
|
||||
/** Pinned to the top of the session manager list (COD-139). */
|
||||
pinned?: boolean;
|
||||
/** When the session was pinned (epoch ms) — orders the pinned group desc. */
|
||||
@@ -100,12 +109,21 @@ export type HistoryInput = {
|
||||
worktreeName?: string;
|
||||
worktreeRepo?: string;
|
||||
/**
|
||||
* Set only by a non-claude transcript source (currently omp); the Claude
|
||||
* scanner never stamps this; the meaningfulness floor below still counts a
|
||||
* row with a `mode` as real, since that also signals "not claude" — see
|
||||
* where it's read below for the isReal check this touches.
|
||||
* Set only by a non-claude transcript source (currently omp and codex); the
|
||||
* Claude scanner never stamps this; the meaningfulness floor below still
|
||||
* counts a row with a `mode` as real, since that also signals "not claude" —
|
||||
* see where it's read below for the isReal check this touches.
|
||||
*/
|
||||
mode?: string;
|
||||
/**
|
||||
* The token this CLI's own resume command expects, when it is NOT the row's
|
||||
* `sessionId`. Codex names a thread by an id of its own that lives in the
|
||||
* rollout, and a live codex session's `sessionId` is Codeman's uuid instead —
|
||||
* so a resume that reused `sessionId` would ask codex for a thread that does
|
||||
* not exist. Only a transcript scanner sets this, which is what keeps the two
|
||||
* kinds of row apart.
|
||||
*/
|
||||
resumeId?: string;
|
||||
};
|
||||
|
||||
/** Mux process-stat view. */
|
||||
@@ -186,6 +204,7 @@ export function mergeUnifiedSessions(sources: UnifiedSources): UnifiedSessionIte
|
||||
// transcript source (currently only omp) does, so a history-only row
|
||||
// still gets a mode badge instead of reading as claude by default.
|
||||
overwrite(item, 'mode', h.mode);
|
||||
overwrite(item, 'resumeId', h.resumeId);
|
||||
const ms = Date.parse(h.lastModified);
|
||||
if (!Number.isNaN(ms) && item.lastActivityAt === undefined) item.lastActivityAt = ms;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { isEffortLevel } from './types.js';
|
||||
import { getAugmentedPath } from './utils/index.js';
|
||||
import { compareVersions } from './utils/dependency-checker.js';
|
||||
import { dataPath } from './config/instance.js';
|
||||
import { getCli } from './config/cli-registry/registry.js';
|
||||
|
||||
/**
|
||||
* Build Claude CLI permission flags based on the configured mode.
|
||||
@@ -169,6 +170,36 @@ export function buildClaudeEnv(sessionId: string): Record<string, string | undef
|
||||
...process.env,
|
||||
LANG: 'en_US.UTF-8',
|
||||
LC_ALL: 'en_US.UTF-8',
|
||||
};
|
||||
|
||||
// The colour and identity vars come from the registry entry, the same source
|
||||
// buildEnvExports() and buildMuxAttachEnv() read, so this fallback cannot drift from
|
||||
// the tmux pane the way a hand-maintained list here did.
|
||||
// ⚠️ This block runs BEFORE Codeman's own keys are assigned, mirroring
|
||||
// buildEnvExports(), where `...cliEnv` is emitted ahead of `export CODEMAN_MUX=1`.
|
||||
// Applied afterwards it would outrank them: `unset` and `exports` are config
|
||||
// (`~/.codeman/clis.json` overrides any entry), so an entry naming
|
||||
// CODEMAN_HOOK_SECRET_FILE or PATH would strip or rewrite it on this path while the
|
||||
// tmux pane, where Codeman's exports come last, kept its own value.
|
||||
// COD-115: `delete`, not `= undefined` — node-pty serializes a present-with-undefined
|
||||
// key as the literal string "KEY=undefined" (see buildMuxAttachEnv below).
|
||||
const cliEnv = getCli('claude')?.env;
|
||||
for (const name of cliEnv?.unset ?? []) delete env[name];
|
||||
for (const item of cliEnv?.exports ?? []) {
|
||||
// A direct PTY has no mux, so `muxName` has no value to resolve against. Claude
|
||||
// declares literals only; an unresolvable engine value is skipped, never guessed.
|
||||
const value =
|
||||
typeof item.value === 'string'
|
||||
? item.value
|
||||
: item.value.engine === 'sessionId'
|
||||
? sessionId
|
||||
: item.value.engine === 'codemanPrefixedSessionId'
|
||||
? `codeman_${sessionId}`
|
||||
: undefined;
|
||||
if (value !== undefined) env[item.name] = value;
|
||||
}
|
||||
|
||||
Object.assign(env, {
|
||||
PATH: getAugmentedPath(),
|
||||
TERM: 'xterm-256color',
|
||||
// Inform Claude it's running within Codeman (helps prevent self-termination)
|
||||
@@ -180,11 +211,7 @@ export function buildClaudeEnv(sessionId: string): Record<string, string | undef
|
||||
// as the literal "CODEMAN_API_URL=undefined" (COD-115).
|
||||
// Path only (not the secret value) — hook curls cat it at execution time (COD-54)
|
||||
CODEMAN_HOOK_SECRET_FILE: dataPath('hook-secret'),
|
||||
};
|
||||
// COD-115: `delete`, not `= undefined` — node-pty serializes a present-with-undefined
|
||||
// key as the literal string "KEY=undefined" (see buildMuxAttachEnv below).
|
||||
delete env.COLORTERM;
|
||||
delete env.CLAUDECODE;
|
||||
});
|
||||
return env;
|
||||
}
|
||||
|
||||
|
||||
+108
-40
@@ -106,6 +106,7 @@ import {
|
||||
import { DEFAULT_TMUX_HISTORY_LIMIT } from './config/terminal-history.js';
|
||||
import { EXEC_TIMEOUT_MS } from './config/exec-timeout.js';
|
||||
import { getCli } from './config/cli-registry/registry.js';
|
||||
import { compileVersionRegex } from './config/cli-registry/patterns.js';
|
||||
import { resolveSessionCliVersion } from './utils/cli-resolver.js';
|
||||
import {
|
||||
buildInteractiveArgs,
|
||||
@@ -481,6 +482,8 @@ export class Session extends EventEmitter {
|
||||
private _activityStreak: ActivityStreak | null = null; // Unbroken run of PTY repaints (working detection)
|
||||
private _lastPaneProbeAt = 0; // Throttle for the tmux screen probe
|
||||
private _lastPaneProbeWorking: boolean | null = null; // Its last verdict (null = could not read)
|
||||
/** Lazily compiled `capabilities.workDetect.workingLine`. See _workingLinePattern(). */
|
||||
private _workingLineRe: RegExp | undefined = undefined;
|
||||
private _trustDialogAccepted: boolean = false; // Stops the trust-dialog scan (answered, or given up)
|
||||
private _trustDialogAttempts = 0; // Keystrokes sent at the trust dialog
|
||||
private _lastTrustDialogScanAt = 0; // Throttle for the trust-dialog screen read
|
||||
@@ -721,13 +724,20 @@ export class Session extends EventEmitter {
|
||||
this._wireActivityAt = config.lastActivityAt || Date.now();
|
||||
this._wireActivitySettleUntil = config.lastActivityAt ? Date.now() + WIRE_ACTIVITY_SETTLE_MS : 0;
|
||||
// Set claudeSessionId — when resuming, the Claude conversation ID is the resumed one.
|
||||
// For omp, `claudeSessionId` doubles as the generic "external transcript id"
|
||||
// alias key mergeUnifiedSessions() folds a history row into its owning
|
||||
// session by: omp mints its OWN uuid, unrelated to this Codeman id, so
|
||||
// without this an omp conversation's Past-Sessions row (keyed by omp's
|
||||
// id) would never merge with its own live/persisted row (keyed by this
|
||||
// id) — it would just show up a second time.
|
||||
this._claudeSessionId = config.resumeSessionId || config.ompConfig?.resumeSessionId || this.id;
|
||||
// For omp and codex, `claudeSessionId` doubles as the generic "external
|
||||
// transcript id" alias key mergeUnifiedSessions() folds a history row into
|
||||
// its owning session by: each mints its OWN thread id, unrelated to this
|
||||
// Codeman id, so without this the conversation's Past-Sessions row (keyed by
|
||||
// that thread id) would never merge with its own live/persisted row (keyed
|
||||
// by this id) — it would just show up a second time. For codex a duplicate
|
||||
// is worse than cosmetic: the stale row still resumes, so clicking it starts
|
||||
// a SECOND `codex resume` on a thread already open in another pane.
|
||||
//
|
||||
// This covers a RESUMED codex session, which knows its thread id up front. A
|
||||
// fresh one learns its id only once codex writes the rollout, so it is folded
|
||||
// from the other side — see the originator stamping in `gatherUnifiedInputs()`.
|
||||
this._claudeSessionId =
|
||||
config.resumeSessionId || config.ompConfig?.resumeSessionId || config.codexConfig?.resumeSessionId || this.id;
|
||||
// Restored from state.json on boot recovery. start() resets _claudeSessionId
|
||||
// to the launch id even when re-attaching to a mux session whose CLI has
|
||||
// moved on (a `/clear` before the restart), so this anchor is what lets the
|
||||
@@ -1765,6 +1775,19 @@ export class Session extends EventEmitter {
|
||||
// (reported live 2026-08-27, fixed in 13a19f79); this guard keeps that
|
||||
// fix intact now that resolution has moved out of the eager options build.
|
||||
if (!this._muxSession) return;
|
||||
// `resolveAndClaimOmpSessionId` scans THIS HOST's `~/.omp/agent/sessions/`, which is
|
||||
// meaningless for a remote session — the conversation and its session file live on the
|
||||
// remote host, under the REMOTE user's home. Worse than a no-op: `this.workingDir` for a
|
||||
// remote session is the remote path (e.g. `/home/user/dotfiles`), so if the local machine
|
||||
// happens to have its own omp history under a directory that mangles to the same name,
|
||||
// this would silently claim and pin a COMPLETELY UNRELATED local session's id onto a
|
||||
// remote respawn. Skip straight to the CLI's own `--continue` fallback, which the remote
|
||||
// pane command already renders (see buildRemoteLaunchCommand's omp branch) — safe there
|
||||
// because each remote respawn talks to exactly one remote pane's own omp history.
|
||||
if (this._remote) {
|
||||
this._ompConfig = { ...this._ompConfig, continueSession: true };
|
||||
return;
|
||||
}
|
||||
const resolvedId = resolveAndClaimOmpSessionId(this.workingDir);
|
||||
if (resolvedId) {
|
||||
this._ompConfig = { ...this._ompConfig, resumeSessionId: resolvedId };
|
||||
@@ -2065,16 +2088,23 @@ export class Session extends EventEmitter {
|
||||
// this to omp's own session uuid — that already-resolved id must win
|
||||
// over the generic `this.id` fallback, or this line clobbers it back
|
||||
// to the Codeman id
|
||||
// on every single respawn.
|
||||
// on every single respawn. codex needs the same fallback for the same
|
||||
// reason: its thread id lives in `_codexConfig`, so without it every
|
||||
// respawn drops a resumed codex session's alias and its Past-Sessions
|
||||
// row springs back as a duplicate that still resumes.
|
||||
// ⚠️ A RESTORED mux session is the one case where the launch id is a
|
||||
// lie: the CLI never stopped, so a `/clear` before the Codeman restart
|
||||
// already moved it to a conversation `this.id` knows nothing about. The
|
||||
// persisted chain's tail is that conversation, reported first-hand by
|
||||
// the CLI's own hook, so it outranks the fallback here. A NEW pane has
|
||||
// an empty chain and falls through to exactly today's expression.
|
||||
// the CLI's own hook, so it outranks every fallback here. A NEW pane has
|
||||
// an empty chain and falls through to the resume/alias fallbacks.
|
||||
restoredConversation = isRestored ? this._claudeSessionChain[this._claudeSessionChain.length - 1] : undefined;
|
||||
this._claudeSessionId =
|
||||
restoredConversation || this._resumeSessionId || this._ompConfig?.resumeSessionId || this.id;
|
||||
restoredConversation ||
|
||||
this._resumeSessionId ||
|
||||
this._ompConfig?.resumeSessionId ||
|
||||
this._codexConfig?.resumeSessionId ||
|
||||
this.id;
|
||||
|
||||
// For NEW mux sessions: wait for readiness then clean buffer
|
||||
// For RESTORED mux sessions: don't do anything - client will fetch buffer on tab switch
|
||||
@@ -2175,15 +2205,19 @@ export class Session extends EventEmitter {
|
||||
// Set claudeSessionId — when resuming, the Claude conversation ID is the resumed one.
|
||||
// Mirrors the mux branch above and must not clobber it: this line runs
|
||||
// unconditionally after both the mux and direct-PTY paths, so it also needs
|
||||
// the ompConfig fallback or it stomps the mux branch's correctly-resolved
|
||||
// OMP alias back to this.id on every mux/plain-reattach boot recovery
|
||||
// (the "third reset point" — see DECISIONS.md). For the same reason it needs
|
||||
// `restoredConversation`: on a RESTORED mux attach the CLI never stopped and
|
||||
// may have `/clear`ed before the restart, so the launch id is a lie and the
|
||||
// chain's tail is the live conversation. Empty on every other path, which
|
||||
// leaves this expression exactly as it was.
|
||||
// the ompConfig and codexConfig fallbacks or it stomps the mux branch's
|
||||
// correctly-resolved OMP/codex alias back to this.id on every mux/plain-
|
||||
// reattach boot recovery (the "third reset point" — see DECISIONS.md).
|
||||
// For the same reason it needs `restoredConversation`: on a RESTORED mux
|
||||
// attach the CLI never stopped and may have `/clear`ed before the restart,
|
||||
// so the launch id is a lie and the chain's tail is the live conversation.
|
||||
// It is empty on every other path, so those paths keep the alias chain.
|
||||
this._claudeSessionId =
|
||||
restoredConversation || this._resumeSessionId || this._ompConfig?.resumeSessionId || this.id;
|
||||
restoredConversation ||
|
||||
this._resumeSessionId ||
|
||||
this._ompConfig?.resumeSessionId ||
|
||||
this._codexConfig?.resumeSessionId ||
|
||||
this.id;
|
||||
|
||||
this._pid = this.ptyProcess.pid;
|
||||
console.log('[Session] Interactive PTY spawned with PID:', this._pid);
|
||||
@@ -2388,12 +2422,14 @@ export class Session extends EventEmitter {
|
||||
* @param data raw PTY chunk, ANSI included
|
||||
*/
|
||||
private _detectInteractiveActivity(data: string): void {
|
||||
// The prompt line contains "❯" when Claude is waiting for input. It only ARMS
|
||||
// the check and is NOT evidence the turn ended: Claude redraws the composer
|
||||
// about once a second all the way through a turn, which is exactly how a
|
||||
// working session used to flip to idle two seconds in. _confirmIdle() waits
|
||||
// for the pane to actually go quiet before believing it.
|
||||
if (data.includes('❯')) {
|
||||
const workDetect = getCli(this.mode)?.capabilities.workDetect;
|
||||
// The composer row carries this glyph when the CLI is waiting for input. It only
|
||||
// ARMS the check and is NOT evidence the turn ended: a CLI redraws its composer
|
||||
// about once a second all the way through a turn, which is exactly how a working
|
||||
// session used to flip to idle two seconds in. _confirmIdle() waits for the pane to
|
||||
// actually go quiet before believing it. A CLI that declares no glyph keeps Claude's,
|
||||
// which is the glyph every such session has been armed by until now.
|
||||
if (data.includes(workDetect?.promptGlyph ?? '❯')) {
|
||||
// Only start a new timeout if we're not already awaiting idle confirmation.
|
||||
// This prevents status bar redraws (which include the prompt) from resetting it.
|
||||
if (!this._awaitingIdleConfirmation) {
|
||||
@@ -2412,9 +2448,10 @@ export class Session extends EventEmitter {
|
||||
// new status line does not rescue it either (tmux repaints partially, so the
|
||||
// complete line reaches the PTY only every few tens of seconds). An unbroken run
|
||||
// of repaints is the signal that survives. See session-activity.ts for the
|
||||
// measurement. Claude only: an external CLI's TUI has no ❯, so nothing would
|
||||
// ever arm the idle confirmation and such a session would latch busy forever.
|
||||
if (!isExternalCliMode(this.mode)) {
|
||||
// measurement. This needs a pane Codeman can read: without a glyph to arm the idle
|
||||
// confirmation, a session latches busy forever. A CLI that declares work detection
|
||||
// supplies its own glyph, and the non-external modes keep the run they always had.
|
||||
if (workDetect || !isExternalCliMode(this.mode)) {
|
||||
this._activityStreak = trackActivityStreak(this._activityStreak, Date.now());
|
||||
// A streak is the TRIGGER to look, not the verdict: typing into the composer
|
||||
// also produces a steady stream of repaints. The screen settles it, and only
|
||||
@@ -2449,10 +2486,30 @@ export class Session extends EventEmitter {
|
||||
if (now - this._lastPaneProbeAt < PANE_PROBE_MIN_INTERVAL_MS) return this._lastPaneProbeWorking;
|
||||
this._lastPaneProbeAt = now;
|
||||
const text = this._mux.capturePaneText?.(this._muxSession.muxName) ?? null;
|
||||
this._lastPaneProbeWorking = text === null ? null : CLAUDE_WORKING_LINE_PATTERN.test(text);
|
||||
this._lastPaneProbeWorking = text === null ? null : this._workingLinePattern().test(text);
|
||||
return this._lastPaneProbeWorking;
|
||||
}
|
||||
|
||||
/**
|
||||
* The regex matching this CLI's "a turn is running" status line.
|
||||
*
|
||||
* Compiled once per session and cached: `_probePaneWorking` runs it against a whole
|
||||
* pane capture on a timer, and the throttled text detector runs it against every
|
||||
* accumulated chunk. A CLI that declares no pattern falls back to Claude's, which is
|
||||
* the pattern every session used before the registry carried one.
|
||||
*/
|
||||
private _workingLinePattern(): RegExp {
|
||||
if (this._workingLineRe === undefined) {
|
||||
const src = getCli(this.mode)?.capabilities.workDetect?.workingLine;
|
||||
// Same guard the schema applies, not a second opinion: `compileVersionRegex()` is
|
||||
// what keeps a nested quantifier out of this pattern, and this one runs on the PTY
|
||||
// hot path. It returns null rather than throwing, and Claude's pattern is the
|
||||
// fallback every session used before the registry carried one.
|
||||
this._workingLineRe = (src ? compileVersionRegex(src) : null) ?? CLAUDE_WORKING_LINE_PATTERN;
|
||||
}
|
||||
return this._workingLineRe;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the pane as working. Idempotent: `working` is emitted on the transition
|
||||
* only, so the per-chunk detectors can all call it freely.
|
||||
@@ -2524,6 +2581,11 @@ export class Session extends EventEmitter {
|
||||
*/
|
||||
private _maybeCaptureOmpSessionId(): void {
|
||||
if (getCli(this.mode)?.capabilities.transcript !== 'omp-jsonl' || this._claudeSessionId !== this.id) return;
|
||||
// Same host-local-filesystem trap as `_pinOmpRespawnId`: the omp session file for a
|
||||
// remote session lives on the remote host, not here, so scanning locally risks aliasing
|
||||
// this session onto an unrelated local omp conversation that happens to mangle to the
|
||||
// same directory name. Never resolvable from here — skip.
|
||||
if (this._remote) return;
|
||||
try {
|
||||
const resolvedId = resolveAndClaimOmpSessionId(this.workingDir);
|
||||
if (resolvedId) {
|
||||
@@ -2541,10 +2603,6 @@ export class Session extends EventEmitter {
|
||||
* PTY data chunk. Receives accumulated raw data to process in one batch.
|
||||
*/
|
||||
private _processExpensiveParsers(rawData: string): void {
|
||||
// Skip Claude-specific parsers for external CLI sessions (Ralph tracker,
|
||||
// BashToolParser, token + CLI-info parsing all depend on Claude's output format).
|
||||
if (isExternalCliMode(this.mode)) return;
|
||||
|
||||
// Lazy ANSI strip: only compute cleanData when a consumer actually needs it.
|
||||
let _cleanData: string | null = null;
|
||||
const getCleanData = (): string => {
|
||||
@@ -2554,6 +2612,19 @@ export class Session extends EventEmitter {
|
||||
return _cleanData;
|
||||
};
|
||||
|
||||
// Work detection by status line, ahead of the external-CLI gate below. The pattern
|
||||
// comes from the CLI's own registry entry, so this is the one parser here that is not
|
||||
// Claude-specific — and it sat under that gate, which is why an external CLI reported
|
||||
// itself idle through an entire turn. Guarded on the descriptor so a CLI without one
|
||||
// still skips the ANSI strip the gate used to save it.
|
||||
if (!this._isWorking && getCli(this.mode)?.capabilities.workDetect) {
|
||||
if (this._workingLinePattern().test(getCleanData())) this._markWorking();
|
||||
}
|
||||
|
||||
// Skip Claude-specific parsers for external CLI sessions (Ralph tracker,
|
||||
// BashToolParser, token + CLI-info parsing all depend on Claude's output format).
|
||||
if (isExternalCliMode(this.mode)) return;
|
||||
|
||||
// Forward to Ralph tracker to detect Ralph loops and todos
|
||||
// (opencode sessions already returned early at line 1209)
|
||||
if (this._ralphTracker.enabled || !this._ralphTracker.autoEnableDisabled) {
|
||||
@@ -2585,16 +2656,13 @@ export class Session extends EventEmitter {
|
||||
this.parseTaskDescriptionsFromTerminalData(getCleanData());
|
||||
}
|
||||
|
||||
// Work detection (text-based, needs clean data: the status line is coloured,
|
||||
// so raw data has escape sequences between the `…` and the elapsed timer).
|
||||
// Only check if a faster path didn't already trigger working state.
|
||||
// Legacy gerunds, Claude-only. The status-line pattern above already ran for every
|
||||
// CLI that declares one, so this adds only the older wording. Current Claude
|
||||
// randomizes the word ("Actualizing…", "Finagling…"), so these catch a fraction of
|
||||
// turns; the pattern above and the activity streak carry the rest.
|
||||
if (!this._isWorking) {
|
||||
const cleanData = getCleanData();
|
||||
if (
|
||||
CLAUDE_WORKING_LINE_PATTERN.test(cleanData) ||
|
||||
// Legacy gerunds. Current Claude randomizes the word ("Actualizing…",
|
||||
// "Finagling…"), so these catch only a fraction of turns; the pattern
|
||||
// above and the activity streak carry the rest.
|
||||
cleanData.includes('Thinking') ||
|
||||
cleanData.includes('Writing') ||
|
||||
cleanData.includes('Reading') ||
|
||||
|
||||
+177
-47
@@ -528,6 +528,73 @@ export function normalizeScrollbackEol(buffer: string): string {
|
||||
return buffer.replace(/\r?\n/g, '\r\n');
|
||||
}
|
||||
|
||||
/** Pane geometry and caret position, as `display-message` reports them. */
|
||||
interface PaneCursorGeometry {
|
||||
cols: number;
|
||||
rows: number;
|
||||
cursorX: number;
|
||||
cursorY: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the pane's cursor and size, or null when tmux cannot say.
|
||||
*
|
||||
* Every field is validated together: a caller that gets a value back can place
|
||||
* a caret with it, and one that gets null must not try.
|
||||
*/
|
||||
export function queryPaneCursor(run: () => string): PaneCursorGeometry | null {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = run().trim();
|
||||
} catch (cursorErr) {
|
||||
console.error('[TmuxManager] Failed to query pane cursor after capture:', cursorErr);
|
||||
return null;
|
||||
}
|
||||
const [cursorX, cursorY, cols, rows] = raw.split(/\s+/).map((value) => parseInt(value, 10));
|
||||
if (
|
||||
!Number.isFinite(cursorX) ||
|
||||
!Number.isFinite(cursorY) ||
|
||||
!Number.isFinite(cols) ||
|
||||
!Number.isFinite(rows) ||
|
||||
cursorX < 0 ||
|
||||
cursorY < 0 ||
|
||||
cols <= 0 ||
|
||||
rows <= 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return { cols, rows, cursorX, cursorY };
|
||||
}
|
||||
|
||||
/** SGR attributes, which is all `capture-pane -e` emits. */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CAPTURE_STYLE_SEQUENCE = /\x1b\[[0-9;:]*m/g;
|
||||
|
||||
/** Whether a capture holds anything a reader would see, styles discounted. */
|
||||
export function hasVisibleContent(capture: string): boolean {
|
||||
return /\S/.test(capture.replace(CAPTURE_STYLE_SEQUENCE, ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the caret back where the pane has it, counting UP from the bottom of what
|
||||
* was just replayed.
|
||||
*
|
||||
* Relative rather than absolute (`CUP`) on purpose. `\x1b[<row>;<col>H` numbers
|
||||
* rows from the top of the browser's screen, so it only lands correctly while
|
||||
* the browser's row count equals the pane's — and it need not, because
|
||||
* `resizeWindow` fires its tmux resize without waiting, so a capture can be
|
||||
* taken before a requested resize has been applied. Counting up from the last
|
||||
* replayed row is anchored to the content instead, which is the thing both ends
|
||||
* genuinely share.
|
||||
*/
|
||||
export function formatCursorRestore(geometry: PaneCursorGeometry): string {
|
||||
const up = Math.max(0, geometry.rows - 1 - geometry.cursorY);
|
||||
const right = Math.max(0, geometry.cursorX);
|
||||
// `\r` first so the column is known: the replay leaves the caret wherever the
|
||||
// last row's text ended.
|
||||
return `${up > 0 ? `\x1b[${up}A` : ''}\r${right > 0 ? `\x1b[${right}C` : ''}`;
|
||||
}
|
||||
|
||||
export function formatPaneSnapshot(
|
||||
lines: string[],
|
||||
geometry: { cols: number; rows: number; cursorX: number; cursorY: number }
|
||||
@@ -760,8 +827,11 @@ export function buildRemoteLaunchCommand(options: {
|
||||
sessionId: string;
|
||||
claudeMode?: ClaudeMode;
|
||||
allowedTools?: string;
|
||||
/** OMP only — resume/continue overrides for the remote omp relaunch (dead-pane respawn). */
|
||||
ompConfig?: OmpConfig;
|
||||
resumeSessionId?: string;
|
||||
}): string {
|
||||
const { mode, remote, sessionId, claudeMode, allowedTools } = options;
|
||||
const { mode, remote, sessionId, claudeMode, allowedTools, ompConfig, resumeSessionId } = options;
|
||||
// §6.3: honor the session's EFFECTIVE claude permission mode on remote instead of
|
||||
// hardcoding --dangerously-skip-permissions, so a non-granted multi-user user's
|
||||
// downgraded 'auto' actually reaches the remote agent (the default command otherwise
|
||||
@@ -770,11 +840,66 @@ export function buildRemoteLaunchCommand(options: {
|
||||
// `defaultRemoteCommandForMode`: `claude` lives under a per-user PATH entry that
|
||||
// only an interactive login shell resolves (see that function's comment).
|
||||
const override = remote.commands?.[mode];
|
||||
const modeCommand = override
|
||||
? override
|
||||
: mode === 'claude'
|
||||
? remoteLoginShellCommand(`claude${buildClaudePermissionFlags(claudeMode, allowedTools)}`)
|
||||
: defaultRemoteCommandForMode(mode);
|
||||
let modeCommand: string;
|
||||
if (override) {
|
||||
modeCommand = override;
|
||||
} else if (mode === 'claude') {
|
||||
// Deterministic conversation pinning for SSH-remote claude (mirrors the
|
||||
// docker-claude shape in claudeDockerPaneCommand, INCLUDING the distinct
|
||||
// resumeId branch it declares — this used to only mirror the same-id
|
||||
// fallback shape, silently dropping an explicit resumeSessionId that
|
||||
// differs from sessionId, e.g. a resume-from-history launch): the FIRST
|
||||
// run creates the conversation under --session-id <sessionId>; a respawn
|
||||
// / reattach re-runs the same idempotent command, --session-id exits
|
||||
// non-zero ("already in use"), and the `||` fallback RESUMES that same
|
||||
// conversation. Without a pinned id, every reattach relaunched a bare
|
||||
// `claude` and started a NEW conversation (found live 2026-08-29: remote
|
||||
// claude ctrl-d / ctrl-c relaunched a fresh session). A per-host
|
||||
// `commands.claude` override stays authoritative (admin's explicit
|
||||
// choice) and skips this entirely.
|
||||
const permFlags = buildClaudePermissionFlags(claudeMode, allowedTools);
|
||||
const cmd = `claude${permFlags}`;
|
||||
// Defense in depth, mirroring claudeDockerPaneCommand's own belt-and-braces check:
|
||||
// sessionId is server-minted and always safe in practice, but this command is built
|
||||
// as a single shellescaped string and then executed as shell code on the remote
|
||||
// host, so an unsafe value here is validated rather than trusted.
|
||||
if (!RESUME_ID_SAFE.test(sessionId)) {
|
||||
modeCommand = remoteLoginShellCommand(cmd);
|
||||
} else {
|
||||
const rid = resumeSessionId && RESUME_ID_SAFE.test(resumeSessionId) ? resumeSessionId : undefined;
|
||||
modeCommand = remoteLoginShellCommand(
|
||||
rid && rid !== sessionId
|
||||
? `${cmd} --resume ${rid} || ${cmd} --session-id ${sessionId}`
|
||||
: `${cmd} --session-id ${sessionId} || ${cmd} --resume ${sessionId}`
|
||||
);
|
||||
}
|
||||
} else if (mode === 'omp') {
|
||||
// Remote OMP respawn must RESUME the same conversation instead of
|
||||
// relaunching fresh (found live 2026-08-29: remote ctrl-c/ctrl-d relaunched
|
||||
// a brand-new omp session). The pinned id, when known, is passed as an
|
||||
// explicit --resume; otherwise fall back to omp's own "most recent"
|
||||
// --continue so a dead-pane respawn still lands back in the conversation.
|
||||
// Rendered through the CLI registry (buildSpawnCommandFromRegistry), the
|
||||
// SAME mode-agnostic path local/docker spawns use — not appendResumeFlag(),
|
||||
// which would hand the id to the login shell as $0 after the quoted `-c
|
||||
// 'omp'`, and not a raw buildOmpCommand() call, which the registry refactor
|
||||
// (#347) deleted. Gives every registry CLI with a resume form this
|
||||
// behaviour for free, and the flags can't drift from the local builder.
|
||||
const ompEntry = getCli('omp');
|
||||
const ompCmd = ompEntry
|
||||
? (buildSpawnCommandFromRegistry(ompEntry, {
|
||||
mode: 'omp',
|
||||
sessionId,
|
||||
ompConfig: {
|
||||
...ompConfig,
|
||||
resumeSessionId: resumeSessionId || ompConfig?.resumeSessionId,
|
||||
},
|
||||
}) ?? 'omp')
|
||||
: 'omp';
|
||||
modeCommand = remoteLoginShellCommand(ompCmd);
|
||||
} else {
|
||||
modeCommand = defaultRemoteCommandForMode(mode);
|
||||
}
|
||||
const remoteName = remoteTmuxSessionName(sessionId);
|
||||
|
||||
// Innermost: the command tmux runs in the new pane. Run via `/bin/sh -c` by
|
||||
@@ -1242,6 +1367,9 @@ function buildRemoteSessionCommand(options: {
|
||||
sessionId: string;
|
||||
claudeMode?: ClaudeMode;
|
||||
allowedTools?: string;
|
||||
/** OMP only — resume/continue overrides for a remote omp relaunch. */
|
||||
ompConfig?: OmpConfig;
|
||||
resumeSessionId?: string;
|
||||
}): string {
|
||||
const { remote, sessionId } = options;
|
||||
if (remote.owned === false) {
|
||||
@@ -1815,7 +1943,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const fullCmd = docker
|
||||
? buildDockerLaunchCommand(resolveDockerLaunchOptions(mode, docker, sessionId, resumeSessionId))
|
||||
: remote
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools })
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools, ompConfig, resumeSessionId })
|
||||
: localFullCmd;
|
||||
|
||||
// Create tmux session in three steps to handle cold-start (no server running)
|
||||
@@ -2066,7 +2194,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const fullCmd = docker
|
||||
? buildDockerLaunchCommand(resolveDockerLaunchOptions(mode, docker, sessionId, resumeSessionId))
|
||||
: remote
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools })
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools, ompConfig, resumeSessionId })
|
||||
: localFullCmd;
|
||||
|
||||
try {
|
||||
@@ -3199,11 +3327,14 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
* the browser xterm reproduces the live frame. Used for fast tab switches.
|
||||
* - Full history (`opts.fullHistory`): `capture-pane -p -e -J -S -<N>` grabs
|
||||
* the tmux scrollback (COD-47, bounded to the configured history limit),
|
||||
* returned as linear scrollback text with SGR codes preserved (NOT
|
||||
* repositioned — a multi-screen history can't be painted into a single
|
||||
* visible frame, so the snapshot repaint is skipped). `-J` re-joins lines
|
||||
* hard-wrapped at the pane width so they reflow in the browser xterm.
|
||||
* Used for full page reloads so the user gets back their scroll history.
|
||||
* returned as linear scrollback text with SGR codes preserved. Rows are not
|
||||
* repainted at absolute positions — a multi-screen history can't be painted
|
||||
* into a single visible frame — but the capture DOES end with a cursor move
|
||||
* putting the caret back where the pane has it, counted up from the last
|
||||
* replayed row. `-J` re-joins lines hard-wrapped at the pane width so they
|
||||
* reflow in the browser xterm. Used for full page reloads so the user gets
|
||||
* back their scroll history. Returns '' for a pane holding nothing visible,
|
||||
* so the caller keeps whatever history it already had.
|
||||
* Caveat: lines tmux has already evicted past its history-limit are gone.
|
||||
*/
|
||||
/**
|
||||
@@ -3262,42 +3393,41 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
execOpts.maxBuffer =
|
||||
(opts?.maxCaptureBytes ?? DEFAULT_TERMINAL_BUFFER_MAX_BYTES) + FULL_HISTORY_CAPTURE_SLACK_BYTES;
|
||||
}
|
||||
const buffer = execSync(`${this.tmux()} ${captureFlags} -t ${shellescape(target)}`, execOpts).replace(
|
||||
/\n+$/g,
|
||||
''
|
||||
);
|
||||
// Full-history spans many screens — return it as raw linear scrollback
|
||||
// rather than repainting rows at single-screen absolute positions. tmux
|
||||
// joins scrollback rows with a bare `\n`; normalize to `\r\n` so a fresh
|
||||
// xterm (convertEol:false) starts each replayed line at column 0 instead
|
||||
// of staircasing diagonally (COD-138).
|
||||
if (fullHistory) {
|
||||
return normalizeScrollbackEol(buffer);
|
||||
}
|
||||
try {
|
||||
const cursor = execSync(
|
||||
const rawCapture = execSync(`${this.tmux()} ${captureFlags} -t ${shellescape(target)}`, execOpts);
|
||||
// Query the cursor BEFORE deciding anything else. On the full-history path
|
||||
// it settles both how the capture is trimmed and whether a cursor move is
|
||||
// appended, and those two have to agree: trailing blank rows are only safe
|
||||
// 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}'`,
|
||||
{
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
}
|
||||
).trim();
|
||||
const [cursorX, cursorY, cols, rows] = cursor.split(/\s+/).map((value) => parseInt(value, 10));
|
||||
if (
|
||||
Number.isFinite(cursorX) &&
|
||||
Number.isFinite(cursorY) &&
|
||||
Number.isFinite(cols) &&
|
||||
Number.isFinite(rows) &&
|
||||
cursorX >= 0 &&
|
||||
cursorY >= 0 &&
|
||||
cols > 0 &&
|
||||
rows > 0
|
||||
) {
|
||||
return formatPaneSnapshot(buffer.split('\n'), { cols, rows, cursorX, cursorY });
|
||||
}
|
||||
} catch (cursorErr) {
|
||||
console.error('[TmuxManager] Failed to query pane cursor after capture:', cursorErr);
|
||||
{ encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }
|
||||
)
|
||||
);
|
||||
|
||||
if (fullHistory) {
|
||||
// Without geometry there is no cursor move, so fall back to the old trim.
|
||||
// Keeping the blank rows here would park the caret at the bottom of the
|
||||
// pane with nothing to correct it — worse than not trying at all.
|
||||
if (!geometry) return normalizeScrollbackEol(rawCapture.replace(/\n+$/g, ''));
|
||||
// Take the line terminator off and nothing else. The trailing blank rows
|
||||
// that remain are the real bottom of the screen, and the cursor move
|
||||
// below counts up from it. tmux joins rows with a bare `\n`; normalize to
|
||||
// `\r\n` so a fresh xterm (convertEol:false) starts each replayed line at
|
||||
// column 0 instead of staircasing diagonally (COD-138).
|
||||
const trimmed = rawCapture.replace(/\n$/, '');
|
||||
// An all-blank pane has to keep reading as "nothing to replay". The caller
|
||||
// treats an empty string as "capture unavailable" and keeps the byte
|
||||
// history; blank rows plus a cursor move are not empty, so without this a
|
||||
// blank pane REPLACES that history with a blank screen — the downgrade
|
||||
// `_replayWouldShrinkBuffer` exists to refuse, arriving from the server
|
||||
// side where that guard cannot see it.
|
||||
if (!hasVisibleContent(trimmed)) return '';
|
||||
return `${normalizeScrollbackEol(trimmed)}${formatCursorRestore(geometry)}`;
|
||||
}
|
||||
|
||||
const buffer = rawCapture.replace(/\n+$/g, '');
|
||||
if (geometry) return formatPaneSnapshot(buffer.split('\n'), geometry);
|
||||
// Cursor query failed or geometry was invalid, so we skip the absolute-
|
||||
// positioned snapshot repaint and fall back to the raw capture. Normalize
|
||||
// its bare `\n` line endings to `\r\n` so the replay doesn't staircase
|
||||
|
||||
@@ -77,6 +77,8 @@ export interface FilesystemBrowseEntry {
|
||||
path: string;
|
||||
type: 'file' | 'directory';
|
||||
size?: number;
|
||||
/** Last-modified time (ms since epoch) of the entry's target; lets the picker sort by date. */
|
||||
mtimeMs?: number;
|
||||
symlink?: boolean;
|
||||
previewKind?: FilesystemPreviewKind;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,23 @@ import { join, sep } from 'node:path';
|
||||
/** A real OMP session file is `<ISO-ish-timestamp>_<uuid>.jsonl`; only the uuid matters here. */
|
||||
const OMP_SESSION_FILE_PATTERN = /^.+_([a-zA-Z0-9-]+)\.jsonl$/;
|
||||
|
||||
/**
|
||||
* Strip a trailing `/` from a workingDir unless it is the root itself.
|
||||
*
|
||||
* Case paths routinely end in `/` — a remote case's `remotePath` is stored
|
||||
* verbatim (e.g. `/home/user/dotfiles/`) — but omp persists sessions under
|
||||
* the slash-less mangle (`-dotfiles`) with a header `cwd` of
|
||||
* `/home/user/dotfiles`. Without normalization, the trailing slash survives
|
||||
* the mangle (`-dotfiles-`), `readdirSync` returns null for a directory that
|
||||
* exists, and OMP respawn pinning silently degrades to the ambiguous
|
||||
* `--continue` (found live 2026-08-29: a remote OMP ctrl-c relaunched a fresh
|
||||
* conversation instead of resuming). Exported so the same normalization is
|
||||
* used for the header-`cwd` comparison in {@link resolveAndClaimOmpSessionId}.
|
||||
*/
|
||||
export function stripTrailingSlash(workingDir: string): string {
|
||||
return workingDir.length > 1 && workingDir.endsWith('/') ? workingDir.slice(0, -1) : workingDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors `omp`'s own directory mangling. Confirmed empirically against real
|
||||
* `~/.omp/agent/sessions/` directory names (2026-08-27): unlike Claude Code's
|
||||
@@ -45,8 +62,9 @@ export function mangleOmpWorkingDir(workingDir: string): string {
|
||||
// omp's actual behavior on a symlinked-home setup; guessing wrong here would
|
||||
// trade one silent mismatch for a different one.
|
||||
const home = homedir();
|
||||
const normalized = stripTrailingSlash(workingDir);
|
||||
const relative =
|
||||
workingDir === home || workingDir.startsWith(home + sep) ? workingDir.slice(home.length) : workingDir;
|
||||
normalized === home || normalized.startsWith(home + sep) ? normalized.slice(home.length) : normalized;
|
||||
return relative.replace(/\//g, '-');
|
||||
}
|
||||
|
||||
@@ -183,7 +201,9 @@ export function resolveAndClaimOmpSessionId(workingDir: string): string | null {
|
||||
}
|
||||
if (mtimeMs <= newestMtime) continue;
|
||||
const header = readOmpSessionHeader(filePath);
|
||||
if (!header || header.cwd !== workingDir || claimedOmpSessionIds.has(header.id)) continue;
|
||||
// Compare against the slash-normalized workingDir: the session's own
|
||||
// workingDir may carry a trailing slash while omp's header cwd never does.
|
||||
if (!header || header.cwd !== stripTrailingSlash(workingDir) || claimedOmpSessionIds.has(header.id)) continue;
|
||||
newestMtime = mtimeMs;
|
||||
newestId = header.id;
|
||||
}
|
||||
|
||||
+184
-6
@@ -1332,7 +1332,11 @@ class CodemanApp {
|
||||
this._redock(id);
|
||||
}
|
||||
|
||||
/** Clear all dashboard-side detached state/timers for a session. */
|
||||
/** Clear all dashboard-side detached state/timers for a session, and take its
|
||||
* sizing back: the popup owned the pane while it was open, so the dashboard's
|
||||
* record of it is stale and the session it is showing needs re-measuring.
|
||||
* ⚠️ Not idempotent — each call re-asserts, so a path that redocks twice for
|
||||
* one close sends two SIGWINCHs. */
|
||||
_redock(id) {
|
||||
const t = this._detachWatchTimers.get(id);
|
||||
if (t) { clearInterval(t); this._detachWatchTimers.delete(id); }
|
||||
@@ -1340,6 +1344,21 @@ class CodemanApp {
|
||||
this._detachOrphanStrikes.delete(id);
|
||||
this.detachedWindows.delete(id);
|
||||
this._markDetached(id, false);
|
||||
// While the popup owned this session the dashboard sent no resizes, so
|
||||
// `_lastResizeDims` — one value for the whole window — no longer describes
|
||||
// the PTY, which the popup has been sizing. Clearing it makes the next
|
||||
// sendResize report truthfully, on every redock path rather than only the
|
||||
// active one: `selectSession` reads that answer to decide whether to wait
|
||||
// for the TUI's redraw, and a false "unchanged" makes it fetch the frame
|
||||
// before the redraw lands.
|
||||
this._lastResizeDims = null;
|
||||
// Sizing comes back with the session. `force` buys a guaranteed repaint for
|
||||
// the case where popup and dashboard happened to agree on a size; the server
|
||||
// already resizes on its own comparison against the real pane whenever the
|
||||
// two differ.
|
||||
if (this.sessions.has(id) && id === this.activeSessionId) {
|
||||
this.sendResize(id, { force: true })?.catch?.(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** Defer a channel-driven redock briefly. A popup *reload* emits 'redocked'
|
||||
@@ -2130,6 +2149,16 @@ class CodemanApp {
|
||||
return;
|
||||
}
|
||||
|
||||
// A `localhost` URL in the agent's answer: from another device that can
|
||||
// only load through the server, so hand it to a proxied web tab
|
||||
// (webview-tabs.js). Every other link keeps its new-tab default.
|
||||
const urlLink = ev.target.closest('a[href]');
|
||||
if (urlLink && this.openLinkThroughWebTabIfLoopback?.(urlLink.href)) {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
// One-click copy: lift the raw source from the sibling <pre><code>.
|
||||
const copyBtn = ev.target.closest('.rv-copy-btn');
|
||||
if (copyBtn) {
|
||||
@@ -2306,10 +2335,19 @@ class CodemanApp {
|
||||
|
||||
if (!this.activeSessionId) return;
|
||||
try {
|
||||
// Source 1: Transcript JSONL (best quality — clean structured text from Claude)
|
||||
const res = await fetch(`/api/sessions/${this.activeSessionId}/last-response`);
|
||||
// Source 1: Transcript JSONL (best quality — clean structured text from Claude).
|
||||
// `context=turn` asks for the last ANSWERED turn as messages: a Claude
|
||||
// answer is a median of 3 model messages (p90 11), and `text` alone is
|
||||
// only the final one — usually a "Done." tail with the substance in the
|
||||
// rows before it. Readers that know no `turn` context (Codex, the pane
|
||||
// parser, an older server) answer with `text` only, and that path is
|
||||
// unchanged below.
|
||||
const res = await fetch(`/api/sessions/${this.activeSessionId}/last-response?context=turn`);
|
||||
const data = (await res.json())?.data ?? {};
|
||||
let lastResponse = data.text || '';
|
||||
const turnMessages = (Array.isArray(data.messages) ? data.messages : []).filter(
|
||||
(msg) => msg && msg.role === 'assistant' && typeof msg.text === 'string' && msg.text.trim()
|
||||
);
|
||||
|
||||
// Source 2: Terminal buffer fallback — strip ANSI, drop Claude CLI chrome.
|
||||
// Claude + shell only: _cleanTerminalBuffer knows Claude CLI's output, and
|
||||
@@ -2326,7 +2364,20 @@ class CodemanApp {
|
||||
}
|
||||
|
||||
const body = document.getElementById('responseViewerBody');
|
||||
if (lastResponse) {
|
||||
if (turnMessages.length > 0) {
|
||||
// The whole last turn, rendered exactly as the full view renders that
|
||||
// turn: one badge, then badge-less continuation segments. The same
|
||||
// numeric-`turn` gate as loadFullContext, never same-role adjacency.
|
||||
const agentLabel = this._getResponseViewerAgentLabel();
|
||||
body.innerHTML = '';
|
||||
let previous = null;
|
||||
for (const msg of turnMessages) {
|
||||
const continuation = !!previous && typeof msg.turn === 'number' && previous.turn === msg.turn;
|
||||
body.appendChild(this._buildResponseViewerMessage(msg.text, 'assistant', agentLabel, { ...msg, continuation }));
|
||||
previous = msg;
|
||||
}
|
||||
this._bindResponseViewerInteractions(body);
|
||||
} else if (lastResponse) {
|
||||
// Keep the brief view inside the same message wrapper as the full
|
||||
// conversation view. The wrapper supplies the card, role badge and
|
||||
// descendant markdown styles that direct body children do not get.
|
||||
@@ -2347,7 +2398,12 @@ class CodemanApp {
|
||||
|
||||
viewer.classList.add('visible');
|
||||
backdrop.classList.add('visible');
|
||||
body.scrollTop = 0;
|
||||
// A multi-row turn opens at its NEWEST text, matching loadFullContext's
|
||||
// "scroll to bottom (latest message)". `scrollTop = 0` was right when the
|
||||
// brief view was a single card holding the last row; with the whole turn
|
||||
// rendered, the top is the turn's first narration line and the answer the
|
||||
// eye button exists to show can be several screens down.
|
||||
body.scrollTop = turnMessages.length > 1 ? body.scrollHeight : 0;
|
||||
} catch (err) {
|
||||
console.error('Failed to load response:', err);
|
||||
}
|
||||
@@ -3971,6 +4027,71 @@ class CodemanApp {
|
||||
return this.isSessionSidebarRich() || this.isTabRailRich();
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the VERTICAL TAB RAIL orders its cards the way both home screens
|
||||
* do — blocked on you first, then running longest-first, then quiet
|
||||
* most-recently-quiet first (`CodemanSessionOrder`, constants.js) — instead of
|
||||
* leaving them in the user's tab order.
|
||||
*
|
||||
* Read off <html> like the other two rail gates, because the render loop asks
|
||||
* it once per pass and getSessionListLayout() re-parses localStorage.
|
||||
* `tabRailSort: 'manual'` is the opt-out, and it is what a user who reorders
|
||||
* by hand wants: a self-sorting list cannot also be drag-reorderable, so
|
||||
* setupTabDragHandlers() drops the drag affordance while this is on rather
|
||||
* than letting a card snap back to where the sort puts it.
|
||||
*
|
||||
* Deliberately NOT gated on `isTabRailRich()`: a simple rail lists the same
|
||||
* sessions and answers the same question, it just says less about each one.
|
||||
*/
|
||||
isTabRailSorted() {
|
||||
const root = document.documentElement;
|
||||
return root.getAttribute('data-tab-orientation') === 'vertical' && root.dataset.tabRailSort === 'activity';
|
||||
}
|
||||
|
||||
/**
|
||||
* Visual position per session id for the sorted rail, or null when the rail is
|
||||
* not sorting.
|
||||
*
|
||||
* The sort is applied as the flex `order` property, NOT by reordering the DOM.
|
||||
* That is the whole design: `#sessionTabs` stays in `sessionOrder`, so
|
||||
* drag-and-drop, the Alt+N badges, the arrow-key walk, the sidebar filter and
|
||||
* `_scrollActiveTabIntoView()` all keep reading the list they have always
|
||||
* read, and a session changing state moves one inline style instead of
|
||||
* forcing the full rebuild that would restart every card's animation.
|
||||
*
|
||||
* Rows are classified by `_mobileOverviewState()` and compared by
|
||||
* `CodemanSessionOrder` — the same two helpers both home screens use, so the
|
||||
* rail cannot disagree with them about what "working" means or what sorts
|
||||
* first. `orderIndex` is the tab-strip position, which the comparator uses as
|
||||
* its deterministic final tiebreak.
|
||||
*
|
||||
* Guarded like every other cross-file consumer: a stale cached constants.js or
|
||||
* mobile-overview.js degrades to tab order rather than taking the strip down.
|
||||
*
|
||||
* @param {Array<string>} ids live session ids, in tab order
|
||||
* @returns {Map<string, number>|null}
|
||||
*/
|
||||
_tabRailSortOrder(ids) {
|
||||
if (!this.isTabRailSorted()) return null;
|
||||
if (!window.CodemanSessionOrder || typeof this._mobileOverviewState !== 'function') return null;
|
||||
const rows = [];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const session = this.sessions.get(ids[i]);
|
||||
if (!session) continue;
|
||||
rows.push({
|
||||
id: ids[i],
|
||||
state: this._mobileOverviewState(session, this.pendingHooks?.get(ids[i])),
|
||||
lastActivityAt: Number(session.lastActivityAt) || 0,
|
||||
lastSubmitAt: Number(session.lastSubmitAt) || 0,
|
||||
orderIndex: i,
|
||||
});
|
||||
}
|
||||
const sorted = window.CodemanSessionOrder.sort(rows);
|
||||
const out = new Map();
|
||||
for (let i = 0; i < sorted.length; i++) out.set(sorted[i].id, i);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* True where the sidebar is a MODAL off-canvas drawer over the terminal
|
||||
* instead of a docked column.
|
||||
@@ -4592,11 +4713,21 @@ class CodemanApp {
|
||||
// Read once for the whole pass, like the full-rebuild path: this touches
|
||||
// the DOM and the loop below runs for every session on every SSE tick.
|
||||
const richRows = this.isRichTabRows();
|
||||
// Sorted vertical rail: a state change moves a card, and this is the path
|
||||
// that sees one — a session going working→idle never adds or removes a
|
||||
// tab, so the full rebuild below is not reached. Recomputed per pass for
|
||||
// the same reason the rich meta line is: the order IS the state.
|
||||
const railSortOrder = this._tabRailSortOrder(this.sessionOrder.filter((sid) => this.sessions.has(sid)));
|
||||
// Incremental update - only modify changed properties
|
||||
for (const [id, session] of this.sessions) {
|
||||
const tab = container.querySelector(`.session-tab[data-id="${id}"]`);
|
||||
if (!tab) continue;
|
||||
|
||||
// An empty string clears the property, which is also what un-sorts the
|
||||
// rail when the setting (or the layout) flips without a full rebuild.
|
||||
const railOrder = railSortOrder?.has(id) ? String(railSortOrder.get(id)) : '';
|
||||
if (tab.style.order !== railOrder) tab.style.order = railOrder;
|
||||
|
||||
// A web tab owns the active state while one is open. activeSessionId stays
|
||||
// set (the terminal keeps streaming underneath, and switching back is
|
||||
// instant): only the highlight moves. Without this the debounced render
|
||||
@@ -4903,10 +5034,17 @@ class CodemanApp {
|
||||
// Read once, not per session: isRichTabRows() touches the DOM and
|
||||
// this loop runs for every tab on every full rebuild.
|
||||
const richRows = this.isRichTabRows();
|
||||
// The sorted vertical rail (tabRailSort) moves cards with the flex `order`
|
||||
// property and leaves this loop iterating tab order, so the Alt+N badge
|
||||
// below still counts the strip, not the sorted list. Null in every other
|
||||
// layout, and the tabs then carry no inline order at all — the header
|
||||
// strip's markup is byte-identical to before.
|
||||
const railSortOrder = this._tabRailSortOrder(tabOrder.filter((id) => this.sessions.has(id)));
|
||||
let _tabIdx = 0;
|
||||
for (const id of tabOrder) {
|
||||
const session = this.sessions.get(id);
|
||||
if (!session) continue; // Skip if session was removed
|
||||
const railOrderStyle = railSortOrder?.has(id) ? ` style="order:${railSortOrder.get(id)}"` : '';
|
||||
|
||||
// See the note in the incremental path: a web tab owns the active highlight
|
||||
// while one is open, even though activeSessionId stays set.
|
||||
@@ -4960,7 +5098,7 @@ class CodemanApp {
|
||||
const inlineSessionActions = this.shouldInlineSessionActions();
|
||||
const tabActionsHtml = `<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">⚙</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">⧉</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">×</span><button type="button" class="tab-more" onclick="event.stopPropagation(); app.openTabRailActionMenu(event, ${escapeHtml(JSON.stringify(id))})" title="Session actions" aria-label="Session actions">⋯</button></span>`;
|
||||
|
||||
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}"${richData} data-id="${id}" data-color="${color}" ${loadState ? `data-load-phase="${escapeHtml(loadState.phase)}"` : ''} onclick="app.handleSessionTabClick(event, ${escapeHtml(JSON.stringify(id))})" oncontextmenu="event.preventDefault(); app.startInlineRename(${escapeHtml(JSON.stringify(id))})" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-busy="${loadState ? 'true' : 'false'}" aria-label="${escapeHtml(name)} session" ${tabTooltip ? `title="${escapeHtml(tabTooltip)}"` : ''}>
|
||||
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}"${richData}${railOrderStyle} data-id="${id}" data-color="${color}" ${loadState ? `data-load-phase="${escapeHtml(loadState.phase)}"` : ''} onclick="app.handleSessionTabClick(event, ${escapeHtml(JSON.stringify(id))})" oncontextmenu="event.preventDefault(); app.startInlineRename(${escapeHtml(JSON.stringify(id))})" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-busy="${loadState ? 'true' : 'false'}" aria-label="${escapeHtml(name)} session" ${tabTooltip ? `title="${escapeHtml(tabTooltip)}"` : ''}>
|
||||
${_tabIdx < 9 ? '<span class="tab-number">' + (_tabIdx + 1) + '</span>' : ''}
|
||||
${loadState ? '<span class="tab-load-spinner" aria-hidden="true"></span>' : ''}
|
||||
<span class="tab-status ${status}" aria-hidden="true"></span>
|
||||
@@ -5045,6 +5183,18 @@ class CodemanApp {
|
||||
|
||||
// Rows hidden by the sidebar filter must not be steppable.
|
||||
const tabs = [...container.querySelectorAll('.session-tab:not(.tab-filtered-out)')];
|
||||
// ⚠️ A sorted rail paints its rows with the flex `order` property while the
|
||||
// DOM stays in `sessionOrder` (that is what keeps the Alt+N badge and the
|
||||
// drag model honest), so a DOM-order walk steps around the screen instead of
|
||||
// down it: ArrowDown from the top card lands wherever that session happens to
|
||||
// sit in the tab order. Walk what the eye sees. Read the COMPUTED order, not
|
||||
// the inline one, or web tabs (pinned past the cards by a CSS `order: 9999`
|
||||
// rather than an inline style) read as 0 and the walk starts on them. Array
|
||||
// sort is stable, so equal orders keep DOM order, which is the unsorted case.
|
||||
if (this.isTabRailSorted()) {
|
||||
const orderOf = (el) => Number(getComputedStyle(el).order) || 0;
|
||||
tabs.sort((a, b) => orderOf(a) - orderOf(b));
|
||||
}
|
||||
const currentIndex = tabs.indexOf(document.activeElement);
|
||||
|
||||
// Enter or Space activates the tab
|
||||
@@ -5171,6 +5321,17 @@ class CodemanApp {
|
||||
const container = this.$('sessionTabs');
|
||||
const tabs = container.querySelectorAll('.session-tab[data-id]');
|
||||
|
||||
// A self-sorting list cannot also be hand-ordered: the drop below rewrites
|
||||
// sessionOrder correctly, the sort then puts the card straight back where it
|
||||
// was, and the user is left dragging a row that refuses to move. Drop the
|
||||
// affordance instead of lying about it — `tabRailSort: 'manual'` is the way
|
||||
// back to drag-reordering, and Alt+N / Ctrl+Shift+{ } still walk the strip
|
||||
// order this list is no longer showing.
|
||||
if (this.isTabRailSorted()) {
|
||||
tabs.forEach((tab) => tab.setAttribute('draggable', 'false'));
|
||||
return;
|
||||
}
|
||||
|
||||
tabs.forEach(tab => {
|
||||
tab.setAttribute('draggable', 'true');
|
||||
|
||||
@@ -5906,6 +6067,23 @@ class CodemanApp {
|
||||
}
|
||||
}
|
||||
|
||||
// Hold for the terminal font before measuring anything. A cell measured
|
||||
// against a fallback font gives the wrong column and row count, and the
|
||||
// correction would land after the replay, leaving the CLI drawing against a
|
||||
// frame the terminal no longer shows. Resolves immediately once the font is
|
||||
// in, so this costs a tab switch nothing after the first load, and it is
|
||||
// bounded, so a font that never arrives cannot strand the session.
|
||||
// ⚠️ BEFORE `_beginBufferLoad` on purpose: inside it, every live SSE event
|
||||
// for this session queues instead of painting, so a slow font would hold
|
||||
// output back rather than merely mis-measuring the grid.
|
||||
if (this._terminalFontReady) {
|
||||
await this._terminalFontReady;
|
||||
if (this._isStaleSelect(selectGen)) {
|
||||
this._clearTerminalLoadState(sessionId, selectGen);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Load terminal buffer for this session
|
||||
// Show cached content instantly while fetching fresh data in background.
|
||||
// Use tail mode for faster initial load (128KB is enough for recent visible content).
|
||||
|
||||
@@ -342,7 +342,13 @@ const LINEAGE_DIP_MAX_PX = 64;
|
||||
// apart bled into one thick band instead of reading as three separate lines.
|
||||
const LINEAGE_SIBLING_STEP_PX = 8;
|
||||
const LINEAGE_STRIP_TOLERANCE_PX = 4;
|
||||
const LINEAGE_VERTICAL_TRACK_INSET_PX = 6;
|
||||
// How far the vertical bracket sits in from the rail's left edge. It has to
|
||||
// clear the VIEWPORT edge, not just the tabs: the line carries an 11px outer
|
||||
// glow, so a track at 6px had half of that glow clipped away and the arc read
|
||||
// as a thin thread pinned to the window frame. The rail reserves the channel
|
||||
// itself (`--lineage-vertical-gutter` on the rail's .session-tabs), and
|
||||
// computeLineagePath still clamps the track to stay left of both tabs.
|
||||
const LINEAGE_VERTICAL_TRACK_INSET_PX = 10;
|
||||
const LINEAGE_VERTICAL_SIBLING_STEP_PX = 3;
|
||||
const LINEAGE_VERTICAL_ANCHOR_CLEARANCE_PX = 4;
|
||||
// Lineage palette, assigned per SPAWNING TAB in first-seen order and cycled
|
||||
@@ -659,6 +665,22 @@ function sortSessionsByActivity(rows) {
|
||||
// prompt icons (powerline segments, folder/git glyphs from p10k, starship,
|
||||
// oh-my-posh) render even though the text fonts carry no private-use-area
|
||||
// symbols — while all readable text keeps coming from the text fonts.
|
||||
/**
|
||||
* How long a terminal fit will wait for the terminal font, in ms.
|
||||
*
|
||||
* `FontFaceSet.ready` has no deadline of its own and the wait sits in front of
|
||||
* the buffer replay, so a font request that never settles would leave the
|
||||
* session unpainted. Past this we measure whatever is painted.
|
||||
*/
|
||||
const TERMINAL_FONT_WAIT_MS = 2000;
|
||||
|
||||
/**
|
||||
* Families in the stack that cannot move the measured cell, so nothing waits on
|
||||
* them: the generics match no `FontFace`, and the bundled symbols face carries
|
||||
* private-use-area glyphs only (xterm measures `W`) while weighing ~1.2MB.
|
||||
*/
|
||||
const TERMINAL_FONT_UNMEASURED = new Set(['monospace', 'serif', 'sans-serif', 'system-ui', 'symbols nerd font mono']);
|
||||
|
||||
const TERMINAL_FONT_DEFAULT_STACK =
|
||||
'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, "Symbols Nerd Font Mono", monospace';
|
||||
|
||||
|
||||
@@ -25,7 +25,10 @@
|
||||
* 3. The terminal pane is ONE shared element, so its entrance is marked at
|
||||
* session creation but played at selection: a session created in the
|
||||
* background must not animate the pane the user is currently looking at. Its
|
||||
* styles are also restricted to transform/opacity/clip-path (see below).
|
||||
* styles are also restricted to transform/opacity/clip-path (see below), with
|
||||
* `blur` the one documented exception - a filter is the only thing that
|
||||
* actually blurs a live xterm; styles.css carries the measurement and the
|
||||
* three alternatives that do not work.
|
||||
* 4. Nothing may animate on page load or reconnect replay. Only ids that pass
|
||||
* through `markSessionTabEntering()` animate, and `_tabEnterSeen` makes that
|
||||
* once-per-id even though the POST response and the SSE event both call
|
||||
@@ -50,6 +53,7 @@ const TAB_ANIM_STYLES = [
|
||||
{ key: 'unroll', label: 'Unroll', blurb: 'The strip makes room and the tab widens in.', duration: 480 },
|
||||
{ key: 'boot', label: 'Boot', blurb: 'Flickers on under a green scan sweep.', duration: 720 },
|
||||
{ key: 'flip', label: 'Flip', blurb: 'Drops in as a card hinged on its top edge.', duration: 520 },
|
||||
{ key: 'blur', label: 'Blur', blurb: 'Focus-pulls in as the blur fades off it.', duration: 440 },
|
||||
{ key: 'off', label: 'Off', blurb: 'Tabs just appear.', duration: 0 },
|
||||
];
|
||||
|
||||
@@ -65,6 +69,7 @@ const WIN_ANIM_STYLES = [
|
||||
{ key: 'unfold', label: 'Unfold', blurb: 'Hinges down from its top edge in 3D.', duration: 560 },
|
||||
{ key: 'beam', label: 'Beam down', blurb: 'Waits for its line to reach it, then materializes.', duration: 620 },
|
||||
{ key: 'pop', label: 'Pop', blurb: 'Springs open from its centre.', duration: 460 },
|
||||
{ key: 'blur', label: 'Blur', blurb: 'Focus-pulls in as the blur fades off it.', duration: 560 },
|
||||
{ key: 'off', label: 'Off', blurb: 'Windows just appear.', duration: 0 },
|
||||
];
|
||||
|
||||
@@ -73,6 +78,7 @@ const LINE_ANIM_STYLES = [
|
||||
{ key: 'draw', label: 'Draw', blurb: 'Draws itself from the tab down to the window.', duration: 420 },
|
||||
{ key: 'packet', label: 'Packet', blurb: 'Line fades in, then a bright packet runs down it.', duration: 700 },
|
||||
{ key: 'fade', label: 'Fade', blurb: 'Simply fades in.', duration: 300 },
|
||||
{ key: 'blur', label: 'Blur', blurb: 'Focus-pulls in as the blur fades off it.', duration: 380 },
|
||||
{ key: 'off', label: 'Off', blurb: 'Lines just appear.', duration: 0 },
|
||||
];
|
||||
|
||||
@@ -92,6 +98,7 @@ const TERM_ANIM_STYLES = [
|
||||
{ key: 'wipe', label: 'Wipe', blurb: 'Reveals top-to-bottom behind a bright edge.', duration: 520 },
|
||||
{ key: 'slide', label: 'Slide up', blurb: 'Rises into place from below.', duration: 420 },
|
||||
{ key: 'fade', label: 'Fade', blurb: 'Quiet fade with a touch of scale.', duration: 340 },
|
||||
{ key: 'blur', label: 'Blur', blurb: 'Focus-pulls in as the blur lifts off the pane.', duration: 520 },
|
||||
{ key: 'off', label: 'Off', blurb: 'Current behaviour: the pane just appears.', duration: 0 },
|
||||
];
|
||||
|
||||
@@ -102,6 +109,7 @@ const BEAM_HOLD_MS = 360;
|
||||
const ANIM_THEMES = [
|
||||
{ key: 'terminal', label: 'Terminal', tab: 'crt', win: 'crt', line: 'draw', term: 'crt' },
|
||||
{ key: 'beamdown', label: 'Beam down', tab: 'crt', win: 'beam', line: 'draw', term: 'wipe' },
|
||||
{ key: 'softfocus', label: 'Soft focus', tab: 'blur', win: 'blur', line: 'blur', term: 'blur' },
|
||||
{ key: 'quiet', label: 'Quiet', tab: 'slide', win: 'materialize', line: 'fade', term: 'fade' },
|
||||
{ key: 'playful', label: 'Playful', tab: 'pop', win: 'pop', line: 'packet', term: 'slide' },
|
||||
{ key: 'legacy', label: 'Legacy', tab: 'off', win: 'fly', line: 'off', term: 'off' },
|
||||
|
||||
@@ -60,9 +60,22 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.body.appendChild(trap);
|
||||
trap.focus();
|
||||
|
||||
// One Ctrl+V can deliver TWO paste events to this trap. The
|
||||
// execCommand('paste') below fires one wherever the browser honours that
|
||||
// command, and the key's own default action fires another, because xterm's
|
||||
// custom key handler returns false without cancelling the keydown. Handling
|
||||
// both sends the clipboard text to the PTY twice, which is the "Ctrl+V
|
||||
// pastes twice, right-click Paste does not" report: the context-menu paste
|
||||
// has no keydown, so it only ever produces one event. The trap therefore
|
||||
// accepts the first paste and drops every later one.
|
||||
var pasteConsumed = false;
|
||||
|
||||
// Listen for the paste event on our trap
|
||||
trap.addEventListener('paste', function(e) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
if (pasteConsumed) return;
|
||||
pasteConsumed = true;
|
||||
|
||||
// Check for images in clipboard items
|
||||
var imageFiles = [];
|
||||
@@ -84,7 +97,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}, 0);
|
||||
|
||||
if (imageFiles.length > 0) {
|
||||
e.preventDefault();
|
||||
self._uploadAndInsertImages(imageFiles);
|
||||
} else {
|
||||
// No image -- route text through xterm's paste() so bracketed-paste
|
||||
@@ -94,7 +106,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
// indistinguishable from typed input, weakening the CLI's
|
||||
// prompt-injection defenses.
|
||||
var text = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
|
||||
e.preventDefault();
|
||||
if (text && self.terminal) self.terminal.paste(text);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
app.js, NOT the handheld storage-key test `m`. Use a different predicate
|
||||
here and boot will contradict this value, animating the drawer open by
|
||||
itself on every load between 768 and 1023px. -->
|
||||
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var A=JSON.parse(localStorage.getItem(k)||'{}');var L=A.sessionListLayout;var F=Number(A.sessionSidebarFontSize);var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';var V=A.tabOrientation==='vertical'&&!S&&!solo&&window.innerWidth>=768;document.documentElement.dataset.tabOrientation=V?'vertical':'horizontal';document.documentElement.dataset.tabRailDetail=(A.tabRailDetail==='simple')?'simple':'rich';var W=Number(A.tabRailWidth);if(V){if(Number.isInteger(W)&&W>=208&&W<=360)document.documentElement.style.setProperty('--tab-rail-width',W+'px');else if(document.documentElement.dataset.tabRailDetail!=='simple')document.documentElement.style.setProperty('--tab-rail-width','320px');}if(Number.isInteger(F)&&F>=11&&F<=18)document.documentElement.style.setProperty('--session-sidebar-name-font-size',F+'px');}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';document.documentElement.dataset.tabOrientation='horizontal';document.documentElement.dataset.tabRailDetail='rich';}</script>
|
||||
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var A=JSON.parse(localStorage.getItem(k)||'{}');var L=A.sessionListLayout;var F=Number(A.sessionSidebarFontSize);var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';var V=A.tabOrientation==='vertical'&&!S&&!solo&&window.innerWidth>=768;document.documentElement.dataset.tabOrientation=V?'vertical':'horizontal';document.documentElement.dataset.tabRailDetail=(A.tabRailDetail==='simple')?'simple':'rich';document.documentElement.dataset.tabRailSort=(A.tabRailSort==='manual')?'manual':'activity';var W=Number(A.tabRailWidth);if(V){if(Number.isInteger(W)&&W>=208&&W<=360)document.documentElement.style.setProperty('--tab-rail-width',W+'px');else if(document.documentElement.dataset.tabRailDetail!=='simple')document.documentElement.style.setProperty('--tab-rail-width','320px');}if(Number.isInteger(F)&&F>=11&&F<=18)document.documentElement.style.setProperty('--session-sidebar-name-font-size',F+'px');}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';document.documentElement.dataset.tabOrientation='horizontal';document.documentElement.dataset.tabRailDetail='rich';document.documentElement.dataset.tabRailSort='activity';}</script>
|
||||
<!-- Inline critical CSS for instant skeleton paint (before styles.css loads) -->
|
||||
<style>
|
||||
.loading-skeleton{display:flex;flex-direction:column;height:100vh;height:100dvh;background:var(--bg-dark,#11151c)}
|
||||
@@ -1889,6 +1889,7 @@
|
||||
<option value="legacy">Off (default)</option>
|
||||
<option value="terminal">Terminal (CRT)</option>
|
||||
<option value="beamdown">Beam down</option>
|
||||
<option value="softfocus">Soft focus (blur)</option>
|
||||
<option value="quiet">Quiet</option>
|
||||
<option value="playful">Playful</option>
|
||||
<option value="custom">Custom (set in the lab)</option>
|
||||
@@ -1943,6 +1944,16 @@
|
||||
<option value="simple">Simple (name only)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="tab rail sort order activity manual drag reorder">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Vertical Rail Order</span>
|
||||
<span class="set-row-desc">By activity uses the home screen's order: blocked on you first, then whatever has been running longest, then the most recently quiet. Manual keeps your tab order and is the only mode you can drag rows in. Alt+1..9 always follows the tab order either way.</span>
|
||||
</div>
|
||||
<select id="appSettingsTabRailSort" class="set-select">
|
||||
<option value="activity">By activity (home screen order)</option>
|
||||
<option value="manual">Manual (drag to reorder)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="set-row has-field" data-search="tab rail width resize compact wide maximum">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Vertical Rail Width</span>
|
||||
@@ -3458,6 +3469,8 @@
|
||||
<script defer src="notification-manager.js"></script>
|
||||
<script defer src="keyboard-accessory.js"></script>
|
||||
<script defer src="input-cjk.js"></script>
|
||||
<!-- Forwards committed input events that xterm drops on Android/GBoard soft keyboards. Must precede terminal-ui.js. -->
|
||||
<script defer src="terminal-keycode229-recovery.js"></script>
|
||||
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
|
||||
<script defer src="sanitize-html.js"></script>
|
||||
<script defer src="app.js"></script>
|
||||
|
||||
@@ -47,11 +47,24 @@
|
||||
// the picker browses Home and every configured root, so wanting dotfiles in a
|
||||
// project does not imply wanting them in ~.
|
||||
const PATH_PICKER_SHOW_HIDDEN_KEY = 'codeman:pathPickerShowHidden';
|
||||
// Per-device like the hidden toggle: how you scan a folder is a habit of the
|
||||
// hand, not of the workspace.
|
||||
const PATH_PICKER_SORT_KEY = 'codeman:pathPickerSort';
|
||||
const PATH_PICKER_SORT_MODES = [
|
||||
{ value: 'name-asc', label: 'Name A→Z' },
|
||||
{ value: 'name-desc', label: 'Name Z→A' },
|
||||
{ value: 'mtime-desc', label: 'Newest first' },
|
||||
{ value: 'mtime-asc', label: 'Oldest first' },
|
||||
];
|
||||
const PATH_PICKER_DEFAULT_SORT = 'name-asc';
|
||||
|
||||
const PathPicker = {
|
||||
overlay: null,
|
||||
_options: null,
|
||||
_selectedPath: '',
|
||||
_currentPath: '',
|
||||
_entries: [],
|
||||
_truncated: false,
|
||||
_previousFocus: null,
|
||||
_keydownHandler: null,
|
||||
_loadSequence: 0,
|
||||
@@ -59,6 +72,7 @@ const PathPicker = {
|
||||
_previewRequestSequence: 0,
|
||||
_previewPreviousFocus: null,
|
||||
_showHidden: false,
|
||||
_sortMode: PATH_PICKER_DEFAULT_SORT,
|
||||
|
||||
/**
|
||||
* Open the lazy filesystem browser.
|
||||
@@ -69,7 +83,10 @@ const PathPicker = {
|
||||
this.close(false);
|
||||
this._options = options;
|
||||
this._selectedPath = '';
|
||||
this._currentPath = '';
|
||||
this._entries = [];
|
||||
this._showHidden = this._loadShowHidden();
|
||||
this._sortMode = this._loadSortMode();
|
||||
this._previousFocus = document.activeElement;
|
||||
this._previousFocus?.blur?.();
|
||||
|
||||
@@ -90,11 +107,19 @@ const PathPicker = {
|
||||
</div>
|
||||
<div class="path-picker-nav">
|
||||
<button type="button" class="path-picker-up" title="Parent folder" aria-label="Parent folder">↑</button>
|
||||
<div class="path-picker-current" title="Current folder"></div>
|
||||
<form class="path-picker-jump" title="Current folder — edit and press Enter to jump">
|
||||
<input type="text" class="path-picker-current" aria-label="Current folder path" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" enterkeyhint="go">
|
||||
<button type="submit" class="path-picker-go" title="Go to this path" aria-label="Go to this path">Go</button>
|
||||
</form>
|
||||
<button type="button" class="path-picker-hidden" title="Show hidden files and folders" aria-label="Show hidden files and folders" aria-pressed="false">.*</button>
|
||||
<button type="button" class="path-picker-refresh" title="Refresh" aria-label="Refresh">↻</button>
|
||||
</div>
|
||||
<div class="path-picker-status" aria-live="polite">Loading...</div>
|
||||
<div class="path-picker-toolbar">
|
||||
<div class="path-picker-status" aria-live="polite">Loading...</div>
|
||||
<label class="path-picker-sort-label">Sort
|
||||
<select class="path-picker-sort" aria-label="Sort entries"></select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="path-picker-list" role="listbox"></div>
|
||||
<div class="path-picker-selection">
|
||||
<span class="path-picker-selection-label">Selected</span>
|
||||
@@ -114,12 +139,27 @@ const PathPicker = {
|
||||
overlay.querySelector('.path-picker-cancel').addEventListener('click', () => this.close(true));
|
||||
overlay.querySelector('.path-picker-confirm').addEventListener('click', () => this.confirm());
|
||||
overlay.querySelector('.path-picker-current-select').addEventListener('click', () => {
|
||||
const current = overlay.querySelector('.path-picker-current').textContent;
|
||||
if (current) this.select(current);
|
||||
if (this._currentPath) this.select(this._currentPath);
|
||||
});
|
||||
overlay.querySelector('.path-picker-refresh').addEventListener('click', () => this.load());
|
||||
overlay.querySelector('.path-picker-refresh').addEventListener('click', () => this.load(this._currentPath));
|
||||
overlay.querySelector('.path-picker-hidden').addEventListener('click', () => this.toggleHidden());
|
||||
this._syncHiddenButton();
|
||||
// Typing a path is the fast way there. The listing is loaded ONLY on Enter/Go,
|
||||
// never on each keystroke: a half-typed path is a 404 the server has to
|
||||
// answer for nothing, and jumping mid-edit would yank the field around.
|
||||
overlay.querySelector('.path-picker-jump').addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
this.jumpTo(overlay.querySelector('.path-picker-current').value);
|
||||
});
|
||||
const sortSelect = overlay.querySelector('.path-picker-sort');
|
||||
for (const mode of PATH_PICKER_SORT_MODES) {
|
||||
const option = document.createElement('option');
|
||||
option.value = mode.value;
|
||||
option.textContent = mode.label;
|
||||
sortSelect.appendChild(option);
|
||||
}
|
||||
sortSelect.value = this._sortMode;
|
||||
sortSelect.addEventListener('change', (event) => this.setSortMode(event.target.value));
|
||||
overlay.querySelector('.path-picker-up').addEventListener('click', () => {
|
||||
const parent = overlay.querySelector('.path-picker-up').dataset.parent;
|
||||
if (parent) this.load(parent);
|
||||
@@ -169,15 +209,97 @@ const PathPicker = {
|
||||
// OFF inside a hidden folder makes the current path unbrowsable again; the
|
||||
// server answers 403 and load()'s catch falls back to the default root,
|
||||
// which is the only place left to stand.
|
||||
this.load(this.overlay.querySelector('.path-picker-current').textContent || '');
|
||||
this.load(this._currentPath || '');
|
||||
},
|
||||
|
||||
async load(path) {
|
||||
_loadSortMode() {
|
||||
try {
|
||||
const stored = localStorage.getItem(PATH_PICKER_SORT_KEY);
|
||||
return PATH_PICKER_SORT_MODES.some((mode) => mode.value === stored) ? stored : PATH_PICKER_DEFAULT_SORT;
|
||||
} catch {
|
||||
return PATH_PICKER_DEFAULT_SORT;
|
||||
}
|
||||
},
|
||||
|
||||
setSortMode(mode) {
|
||||
if (!PATH_PICKER_SORT_MODES.some((candidate) => candidate.value === mode)) return;
|
||||
this._sortMode = mode;
|
||||
try {
|
||||
localStorage.setItem(PATH_PICKER_SORT_KEY, mode);
|
||||
} catch {}
|
||||
const select = this.overlay?.querySelector('.path-picker-sort');
|
||||
if (select && select.value !== mode) select.value = mode;
|
||||
// Re-order what is already on screen; no round trip, no lost selection.
|
||||
if (this.overlay) this.renderEntries();
|
||||
},
|
||||
|
||||
/**
|
||||
* Order entries for display. Folders always come first, whatever the mode:
|
||||
* a date sort is for finding the file you just made, and the folders are the
|
||||
* way past it, not the thing being looked for. An entry without an mtime (an
|
||||
* older server, the in-container source) sorts after every dated one and then
|
||||
* by name, so a listing never degrades into an unstable order.
|
||||
*
|
||||
* ⚠️ This re-orders the listing the SERVER returned, and the server cuts at
|
||||
* FILESYSTEM_PICKER_ENTRY_LIMIT (500) after sorting by name. So in a folder past
|
||||
* that limit, "Newest first" is the newest of the first 500 BY NAME, not the newest
|
||||
* in the folder, which is the one case this sort exists for. The status line says
|
||||
* "(first 500 by name)" rather than "(first 500)" so the cut is legible; ordering
|
||||
* before the cut would have to happen server-side, and would cost a stat on every
|
||||
* entry in the directory rather than on the 500 that are returned.
|
||||
*/
|
||||
_sortEntries(entries) {
|
||||
const [key, direction] = this._sortMode.split('-');
|
||||
const sign = direction === 'desc' ? -1 : 1;
|
||||
const byName = (a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
|
||||
return entries.slice().sort((a, b) => {
|
||||
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
|
||||
if (key === 'mtime') {
|
||||
const aTime = typeof a.mtimeMs === 'number' ? a.mtimeMs : null;
|
||||
const bTime = typeof b.mtimeMs === 'number' ? b.mtimeMs : null;
|
||||
if (aTime !== null && bTime !== null && aTime !== bTime) return sign * (aTime - bTime);
|
||||
if (aTime === null && bTime !== null) return 1;
|
||||
if (aTime !== null && bTime === null) return -1;
|
||||
return byName(a, b);
|
||||
}
|
||||
return sign * byName(a, b);
|
||||
});
|
||||
},
|
||||
|
||||
/** Compact modified-time label: time of day today, month-day this year, else the date. */
|
||||
_formatModified(mtimeMs) {
|
||||
if (typeof mtimeMs !== 'number' || !Number.isFinite(mtimeMs)) return '';
|
||||
const date = new Date(mtimeMs);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const now = new Date();
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
if (date.toDateString() === now.toDateString()) return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||
if (date.getFullYear() === now.getFullYear()) return `${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Go to a path the user typed. A file path lands in its folder with the
|
||||
* file selected, so pasting a full path from a log or a message is one Enter
|
||||
* away from Select. A path that does not resolve lands in its parent folder
|
||||
* when that exists (the closest place to stand) and otherwise keeps the
|
||||
* current listing, and says so either way — unlike a stale initialPath, a
|
||||
* typo is not a reason to throw the user back to the root.
|
||||
*/
|
||||
jumpTo(rawPath) {
|
||||
const path = String(rawPath || '').trim();
|
||||
if (!path) return;
|
||||
this.load(path, { typed: true });
|
||||
},
|
||||
|
||||
async load(path, options = {}) {
|
||||
if (!this.overlay || !this._options) return;
|
||||
const loadSequence = ++this._loadSequence;
|
||||
const list = this.overlay.querySelector('.path-picker-list');
|
||||
const status = this.overlay.querySelector('.path-picker-status');
|
||||
list.replaceChildren();
|
||||
const typed = !!options.typed;
|
||||
if (!typed) list.replaceChildren();
|
||||
status.classList.remove('error');
|
||||
status.textContent = 'Loading...';
|
||||
|
||||
const params = new URLSearchParams();
|
||||
@@ -194,13 +316,40 @@ const PathPicker = {
|
||||
if (!result?.success) throw new Error(result?.error || 'Failed to browse this folder');
|
||||
if (!this.overlay || loadSequence !== this._loadSequence) return;
|
||||
this.render(result.data);
|
||||
if (options.selectIfListed) {
|
||||
// Landed in the typed path's folder: select the entry if it is there
|
||||
// (a file path), otherwise say what the server said about the full
|
||||
// path — the listing is still the closest place to stand.
|
||||
if (this._entries.some((entry) => entry.path === options.selectIfListed)) {
|
||||
this.select(options.selectIfListed);
|
||||
} else {
|
||||
status.textContent = options.failMessage || 'Path not found';
|
||||
status.classList.add('error');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!this.overlay || loadSequence !== this._loadSequence) return;
|
||||
const message = error.message || 'Failed to browse this folder';
|
||||
if (typed) {
|
||||
// The browse endpoint answers a FILE path with "not found" (it resolves
|
||||
// folders only), so one retry lands in the parent folder and selects
|
||||
// the entry from the listing. Only one level: a typo two segments up
|
||||
// is an error, not a reason to climb to the root.
|
||||
const slash = path.lastIndexOf('/');
|
||||
if (slash > 0 && !options.selectIfListed) {
|
||||
this.load(path.slice(0, slash), { typed: true, selectIfListed: path, failMessage: message });
|
||||
return;
|
||||
}
|
||||
this.renderEntries();
|
||||
status.textContent = options.failMessage || message;
|
||||
status.classList.add('error');
|
||||
return;
|
||||
}
|
||||
if (path) {
|
||||
this.load('');
|
||||
return;
|
||||
}
|
||||
status.textContent = error.message || 'Failed to browse this folder';
|
||||
status.textContent = message;
|
||||
status.classList.add('error');
|
||||
}
|
||||
},
|
||||
@@ -216,19 +365,29 @@ const PathPicker = {
|
||||
rootSelect.appendChild(option);
|
||||
}
|
||||
|
||||
this.overlay.querySelector('.path-picker-current').textContent = data.path;
|
||||
this._currentPath = data.path;
|
||||
this.overlay.querySelector('.path-picker-current').value = data.path;
|
||||
const up = this.overlay.querySelector('.path-picker-up');
|
||||
up.dataset.parent = data.parent || '';
|
||||
up.disabled = !data.parent;
|
||||
this._entries = Array.isArray(data.entries) ? data.entries : [];
|
||||
this._truncated = !!data.truncated;
|
||||
this.renderEntries();
|
||||
},
|
||||
|
||||
/** (Re)build the list from the last listing in the current sort order. */
|
||||
renderEntries() {
|
||||
if (!this.overlay) return;
|
||||
const entries = this._sortEntries(this._entries);
|
||||
const status = this.overlay.querySelector('.path-picker-status');
|
||||
status.classList.remove('error');
|
||||
status.textContent = data.entries.length === 0
|
||||
status.textContent = entries.length === 0
|
||||
? 'This folder is empty'
|
||||
: `${data.entries.length} item${data.entries.length === 1 ? '' : 's'}${data.truncated ? ' (first 500)' : ''}`;
|
||||
: `${entries.length} item${entries.length === 1 ? '' : 's'}${this._truncated ? ' (first 500 by name)' : ''}`;
|
||||
|
||||
const list = this.overlay.querySelector('.path-picker-list');
|
||||
list.replaceChildren();
|
||||
for (const entry of data.entries) {
|
||||
for (const entry of entries) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'path-picker-item';
|
||||
if (entry.type === 'file' && this._options.directoriesOnly && !entry.previewKind) {
|
||||
@@ -248,6 +407,14 @@ const PathPicker = {
|
||||
name.className = 'path-picker-item-name';
|
||||
name.textContent = entry.name;
|
||||
open.append(icon, name);
|
||||
const modified = this._formatModified(entry.mtimeMs);
|
||||
if (modified) {
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'path-picker-item-meta';
|
||||
meta.textContent = modified;
|
||||
meta.title = new Date(entry.mtimeMs).toLocaleString();
|
||||
open.appendChild(meta);
|
||||
}
|
||||
if (entry.symlink) {
|
||||
const link = document.createElement('span');
|
||||
link.className = 'path-picker-item-link';
|
||||
@@ -417,6 +584,8 @@ const PathPicker = {
|
||||
this._previousFocus = null;
|
||||
this._options = null;
|
||||
this._selectedPath = '';
|
||||
this._currentPath = '';
|
||||
this._entries = [];
|
||||
if (restoreFocus) previousFocus?.focus?.();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -148,6 +148,13 @@ const MobileDetection = {
|
||||
if (typeof KeyboardHandler !== 'undefined' && KeyboardHandler.keyboardVisible) return;
|
||||
const vh = window.visualViewport?.height || window.innerHeight;
|
||||
document.documentElement.style.setProperty('--app-height', `${vh}px`);
|
||||
// How far the layout viewport (which anchors position: fixed) extends below
|
||||
// the visual viewport, i.e. behind the browser's bottom bar. 0 on iPhone
|
||||
// Safari, where fixed elements already stop above the bar; the overlap
|
||||
// where they do not. mobile.css lifts the toolbar by this rather than by
|
||||
// (100vh - --app-height), which on iPhone measures the collapsible chrome
|
||||
// instead and left an empty band between the toolbar and the bar.
|
||||
document.documentElement.style.setProperty('--chrome-overlap', `${Math.max(0, window.innerHeight - vh)}px`);
|
||||
},
|
||||
|
||||
/** Initialize mobile detection and set up resize listener */
|
||||
|
||||
@@ -228,6 +228,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
name: item.name || '',
|
||||
title: title || item.name || dir.split('/').pop() || item.sessionId.slice(0, 8),
|
||||
mode: item.mode || 'claude',
|
||||
// Only the scanner sets this, and only for a codex rollout. Dropping it here
|
||||
// is not cosmetic: resumeMobileOverviewSession() passes row.resumeId on to
|
||||
// resumeHistorySession(), so without it a tapped Codex row starts a FRESH
|
||||
// session on a thread that is already on disk.
|
||||
resumeId: item.resumeId || undefined,
|
||||
caseName: matched ? matched.name : '',
|
||||
dir: this._shortenHomePath ? this._shortenHomePath(dir) : dir,
|
||||
at: item.lastActivityAt || item.createdAt || 0,
|
||||
@@ -389,7 +394,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
async resumeMobileOverviewSession(sessionId) {
|
||||
const row = (this._mobileOverviewPastRows || []).find((r) => r.id === sessionId);
|
||||
if (!row || !row.workingDir) return;
|
||||
await this.resumeHistorySession(row.claudeSessionId || row.id, row.workingDir, row.name || undefined, row.mode);
|
||||
await this.resumeHistorySession(
|
||||
row.claudeSessionId || row.id,
|
||||
row.workingDir,
|
||||
row.name || undefined,
|
||||
row.mode,
|
||||
row.resumeId
|
||||
);
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -471,11 +471,11 @@ html.mobile-init .file-browser-panel {
|
||||
padding-bottom: calc(40px + var(--safe-area-bottom));
|
||||
}
|
||||
|
||||
/* iOS Safari: toolbar is pushed up by (100vh - --app-height) to clear the
|
||||
browser's bottom bar. Match that offset in main's padding so the terminal
|
||||
doesn't extend behind the toolbar. */
|
||||
/* iOS Safari: the toolbar is lifted by --chrome-overlap where the browser's
|
||||
bottom bar would otherwise cover it. Match that offset in main's padding so
|
||||
the terminal doesn't extend behind the toolbar. */
|
||||
.ios-device.safari-browser .main {
|
||||
padding-bottom: calc(40px + var(--safe-area-bottom) + (100vh - var(--app-height, 100vh)));
|
||||
padding-bottom: calc(40px + var(--safe-area-bottom) + var(--chrome-overlap, 0px));
|
||||
}
|
||||
|
||||
.header-right {
|
||||
@@ -780,11 +780,14 @@ html.mobile-init .file-browser-panel {
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
/* iOS Safari with tab bar: position: fixed uses the layout viewport which
|
||||
extends behind the browser chrome. Offset the toolbar upward by the delta
|
||||
between 100vh (layout) and --app-height (visual). */
|
||||
/* iOS Safari: where position: fixed anchors to a layout viewport that
|
||||
extends behind the browser's bottom bar, lift the toolbar by that overlap.
|
||||
--chrome-overlap is innerHeight minus the visual viewport height, set in
|
||||
mobile-handlers.js. On iPhone Safari it is 0 because fixed elements already
|
||||
stop above the bar; the previous (100vh - --app-height) lift measured the
|
||||
collapsible chrome instead and left an empty band above the bar. */
|
||||
.ios-device.safari-browser .toolbar {
|
||||
bottom: calc(var(--safe-area-bottom) + (100vh - var(--app-height, 100vh)));
|
||||
bottom: calc(var(--safe-area-bottom) + var(--chrome-overlap, 0px));
|
||||
}
|
||||
|
||||
/* When keyboard is visible the JS translateY already accounts for the full
|
||||
|
||||
@@ -670,7 +670,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
} else if (record.workingDir) {
|
||||
// History rows are keyed by the Claude conversation UUID; resumed
|
||||
// sessions carry theirs separately as claudeSessionId.
|
||||
void this.resumeHistorySession(s.claudeSessionId || s.sessionId, record.workingDir, undefined, s.mode);
|
||||
void this.resumeHistorySession(
|
||||
s.claudeSessionId || s.sessionId,
|
||||
record.workingDir,
|
||||
undefined,
|
||||
s.mode,
|
||||
s.resumeId
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -2308,6 +2314,27 @@ Object.assign(CodemanApp.prototype, {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl+Z (SIGTSTP/job-control suspend): a teammate/subagent pane is always
|
||||
// running an agent CLI (Task-tool dispatched, never a plain shell), so
|
||||
// unlike the main terminal's mode-gated trap this one is unconditional.
|
||||
// Mirrors the main terminal's guard in terminal-ui.js's
|
||||
// attachCustomKeyEventHandler — case-insensitive so Caps Lock (which
|
||||
// flips ev.key to 'Z' without setting shiftKey) can't slip a suspend past it.
|
||||
terminal.attachCustomKeyEventHandler((ev) => {
|
||||
if (
|
||||
ev.type === 'keydown' &&
|
||||
ev.key.toLowerCase() === 'z' &&
|
||||
ev.ctrlKey &&
|
||||
!ev.altKey &&
|
||||
!ev.metaKey &&
|
||||
!ev.shiftKey
|
||||
) {
|
||||
ev.preventDefault();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Wait for terminal renderer to fully initialize before any writes.
|
||||
// xterm.js needs a few frames after open() before write() is safe.
|
||||
setTimeout(() => {
|
||||
|
||||
@@ -804,7 +804,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
btn.append(...parts);
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.resumeHistorySession(s.sessionId, s.workingDir, s.name, s.mode);
|
||||
this.resumeHistorySession(s.sessionId, s.workingDir, s.name, s.mode, s.resumeId);
|
||||
});
|
||||
container.appendChild(btn);
|
||||
}
|
||||
|
||||
@@ -431,6 +431,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.syncTabRailWidthSetting?.(tabRailWidth);
|
||||
document.getElementById('appSettingsTabRailDetail').value =
|
||||
settings.tabRailDetail ?? defaults.tabRailDetail ?? 'rich';
|
||||
document.getElementById('appSettingsTabRailSort').value =
|
||||
settings.tabRailSort ?? defaults.tabRailSort ?? 'activity';
|
||||
document.getElementById('appSettingsShowTabDetachButton').checked = settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false;
|
||||
document.getElementById('appSettingsSessionListLayout').value =
|
||||
settings.sessionListLayout ?? defaults.sessionListLayout ?? 'header';
|
||||
@@ -2097,6 +2099,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
tabOrientation: document.getElementById('appSettingsTabOrientation').value,
|
||||
tabRailWidth: this.readTabRailWidthSetting?.() ?? 256,
|
||||
tabRailDetail: document.getElementById('appSettingsTabRailDetail').value,
|
||||
tabRailSort: document.getElementById('appSettingsTabRailSort').value,
|
||||
showTabDetachButton: document.getElementById('appSettingsShowTabDetachButton').checked,
|
||||
sessionListLayout: document.getElementById('appSettingsSessionListLayout').value,
|
||||
sessionSidebarFontSize: this.resolveSessionSidebarFontSize(
|
||||
@@ -2500,6 +2503,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
tabOrientation: 'horizontal',
|
||||
tabRailWidth: 256,
|
||||
tabRailDetail: 'rich',
|
||||
tabRailSort: 'activity',
|
||||
sessionListLayout: 'header',
|
||||
sessionSidebarFontSize: 12,
|
||||
cjkInputEnabled: false,
|
||||
@@ -2766,6 +2770,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
const detail = (settings.tabRailDetail ?? defaults.tabRailDetail ?? 'rich') === 'simple' ? 'simple' : 'rich';
|
||||
root.dataset.tabRailDetail = detail;
|
||||
|
||||
// Row ORDER rides on a third attribute, for the same reason detail rides on
|
||||
// its own: a sort flip leaves orientation on 'vertical' both times, and the
|
||||
// order is applied as an inline `order` the render paths emit, not by CSS
|
||||
// that could just re-match. `isTabRailSorted()` (app.js) reads this.
|
||||
const previousSort = root.dataset.tabRailSort || 'activity';
|
||||
const sort = (settings.tabRailSort ?? defaults.tabRailSort ?? 'activity') === 'manual' ? 'manual' : 'activity';
|
||||
root.dataset.tabRailSort = sort;
|
||||
|
||||
const tabsEl = document.getElementById('sessionTabs');
|
||||
const rail = document.getElementById('tabRail');
|
||||
const headerHost = document.getElementById('sessionTabsHost');
|
||||
@@ -2789,7 +2801,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// the row template, not toggled by CSS — same reasoning as the sidebar's
|
||||
// detail half in applySessionListLayout(). Taller rows also move every
|
||||
// connector anchored to a tab rect.
|
||||
const changed = orientationChanged || previousDetail !== detail;
|
||||
const changed = orientationChanged || previousDetail !== detail || previousSort !== sort;
|
||||
if (orientationChanged) {
|
||||
this.updateTabOverflowMode?.();
|
||||
if (!settleRailWidth) this.fitAddon?.fit();
|
||||
@@ -3062,7 +3074,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
'showFontControls', 'showSystemStats', 'showTokenCount', 'showCost',
|
||||
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
|
||||
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
|
||||
'terminalFontFamily',
|
||||
'language',
|
||||
|
||||
+373
-22
@@ -545,18 +545,21 @@ body {
|
||||
contain: layout;
|
||||
}
|
||||
|
||||
.session-tabs.tabs-two-rows {
|
||||
flex-wrap: wrap;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
max-height: 120px;
|
||||
}
|
||||
|
||||
/* A wrapped strip GROWS the header instead of scrolling inside it. The old
|
||||
fixed caps (120px tall-tabs / 96px auto-wrap) were row counts in disguise:
|
||||
a third row of tabs was clipped into a 4px scroller, so the tabs you were
|
||||
looking for were off-screen in a container nothing tells you to scroll —
|
||||
while the header had the whole page below it to grow into (it is
|
||||
`min-height` + `flex-shrink: 0`, and terminal-ui's ResizeObserver refits
|
||||
the terminal on its own). `--tab-strip-max-height` is a safety net for an
|
||||
absurd session count, not a row limit: past it the scroller comes back,
|
||||
which beats a header that swallows the terminal. */
|
||||
.session-tabs.tabs-two-rows,
|
||||
.session-tabs.tabs-auto-wrap {
|
||||
flex-wrap: wrap;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
max-height: 96px;
|
||||
max-height: var(--tab-strip-max-height, 40vh);
|
||||
}
|
||||
|
||||
.session-tabs::-webkit-scrollbar {
|
||||
@@ -905,6 +908,28 @@ html[data-tab-anim="flip"] .session-tab.tab-enter {
|
||||
100% { opacity: 1; transform: perspective(700px) rotateX(0deg); }
|
||||
}
|
||||
|
||||
/* Blur, iOS-style focus pull: the tab arrives out of focus and the blur fades
|
||||
OFF it as the opacity comes up, so it reads as resolving rather than moving.
|
||||
Opacity leads the blur (full opacity around 45%, blur still lifting) - that
|
||||
offset is what separates it from a plain cross-fade.
|
||||
|
||||
`filter` here, not on ::before: the tab's own box-shadow and border have to
|
||||
blur with it or the shape stays sharp inside a blurred fill, and unlike
|
||||
background/box-shadow (which .session-tab.active sets !important) nothing
|
||||
overrides filter. */
|
||||
html[data-tab-anim="blur"] .session-tab.tab-enter {
|
||||
animation-name: tab-enter-blur;
|
||||
animation-duration: calc(440ms * var(--anim-enter-scale, 1));
|
||||
animation-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
will-change: transform, opacity, filter;
|
||||
}
|
||||
|
||||
@keyframes tab-enter-blur {
|
||||
0% { opacity: 0; filter: blur(10px); transform: scale(0.94); }
|
||||
45% { opacity: 1; }
|
||||
100% { opacity: 1; filter: blur(0px); transform: none; }
|
||||
}
|
||||
|
||||
/* ── Entrance lab (?animlab=1) ───────────────────────────────────────────── */
|
||||
|
||||
.anim-lab {
|
||||
@@ -1186,6 +1211,25 @@ html[data-win-anim="pop"] .ultracode-window.win-enter {
|
||||
100% { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
|
||||
/* Blur, iOS-style focus pull. `materialize` is the noisy cousin: it glitches the
|
||||
opacity and rides a brightness boost. This one only defocuses, so it stays
|
||||
readable next to a terminal. The scale is deliberately small (0.96): the
|
||||
connection line is aimed at getBoundingClientRect(), which reports the
|
||||
TRANSFORMED box, so a big scale would swing the line's target while it draws.
|
||||
applyWindowEntrance() redraws the lines once the animation ends. */
|
||||
html[data-win-anim="blur"] .subagent-window.win-enter,
|
||||
html[data-win-anim="blur"] .ultracode-window.win-enter {
|
||||
animation-name: win-enter-blur;
|
||||
animation-duration: calc(560ms * var(--anim-enter-scale, 1));
|
||||
animation-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
|
||||
@keyframes win-enter-blur {
|
||||
0% { opacity: 0; filter: blur(18px); transform: scale(0.96); }
|
||||
50% { opacity: 1; }
|
||||
100% { opacity: 1; filter: blur(0px); transform: none; }
|
||||
}
|
||||
|
||||
/* ── Main terminal pane entrance animations ────────────────────────────────
|
||||
⚠ transform / opacity / clip-path ONLY. xterm's FitAddon derives rows+cols
|
||||
from getComputedStyle(parent).width/height, the untransformed layout box -
|
||||
@@ -1327,6 +1371,47 @@ html[data-term-anim="fade"] .terminal-container.term-enter {
|
||||
100% { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
/* Blur, iOS-style focus pull.
|
||||
|
||||
⚠ THE ONE PLACE A `filter` GOES ON THE TERMINAL CONTAINER, and it is a
|
||||
deliberate exception to the rule above, not an oversight. Every other way of
|
||||
blurring this pane was tried against a real xterm and does not work:
|
||||
|
||||
- `backdrop-filter` on ::before blurs perfectly while it is STATIC, and
|
||||
Chrome silently drops the backdrop the moment ANY animation runs on that
|
||||
pseudo-element (measured: the veil computes `blur(15.3px)` and the text
|
||||
behind it stays razor sharp). Animating the container instead keeps the
|
||||
backdrop, so the veil would have to hold one fixed radius, which is a
|
||||
frosted pane that snaps off rather than a focus pull.
|
||||
- Driving the radius from rAF avoids the compositor promotion, at the cost
|
||||
of the same full-screen blur per frame plus main-thread work.
|
||||
|
||||
So the cost the rule exists to avoid is inherent to blurring a terminal at
|
||||
all, and this style buys it knowingly: it is opt-in, OFF by default, bounded
|
||||
to one ~520ms run when a session is opened (or switched to, with `Also on
|
||||
every tab switch`), and the class comes straight back off. `will-change` is
|
||||
still deliberately unset, per the base rule. Measured price on a headless
|
||||
SwiftShader rasterizer with no GPU at all, i.e. the worst case: frame deltas
|
||||
go 16.7ms -> 33.3ms for the length of the run, against 16.7ms flat for `fade`.
|
||||
|
||||
The blur must not change layout, or FitAddon would feed wrong dimensions into
|
||||
resize() and through to the PTY. `filter` is paint-only (measured live: 178x38
|
||||
before, during and after a run), and the property allowlist for every one of
|
||||
these keyframes is pinned by test/entrance-animations.test.ts. */
|
||||
html[data-term-anim="blur"] .terminal-container.term-enter {
|
||||
animation-name: term-enter-blur;
|
||||
animation-duration: calc(520ms * var(--anim-enter-scale, 1));
|
||||
animation-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
|
||||
/* Opacity leads the blur - full opacity around 45%, blur still lifting - which
|
||||
is what separates the effect from a plain cross-fade. */
|
||||
@keyframes term-enter-blur {
|
||||
0% { opacity: 0; filter: blur(14px); transform: scale(1.008); }
|
||||
45% { opacity: 1; }
|
||||
100% { opacity: 1; filter: blur(0px); transform: none; }
|
||||
}
|
||||
|
||||
/* ── Connection-line entrance animations ───────────────────────────────────
|
||||
`--line-len` is the measured path length, stamped inline by
|
||||
_applyLineEntrances(); `--line-enter-delay` is negative when an entrance is
|
||||
@@ -1393,6 +1478,26 @@ html[data-line-anim="packet"] .connection-line.line-enter {
|
||||
100% { stroke-dashoffset: calc(-1 * var(--line-len)); opacity: 0; }
|
||||
}
|
||||
|
||||
/* Blur, the line focuses in alongside a blurred tab and window. `filter` on an
|
||||
SVG path takes CSS filter functions, so the blur simply rides in front of the
|
||||
line's own glow (see --line-glow on .connection-line).
|
||||
|
||||
⚠ The 100% frame deliberately omits `opacity`, which makes the browser take
|
||||
the endpoint from the element's own computed value: a subagent line rests at
|
||||
0.9, a lineage line at 0.72, and a WORKING lineage line at 0.95. Pinning 0.9
|
||||
here - as `line-enter-fade` above still does - lands every lineage line on the
|
||||
wrong opacity and snaps it when the class comes off. */
|
||||
html[data-line-anim="blur"] .connection-line.line-enter {
|
||||
animation-name: line-enter-blur;
|
||||
animation-duration: calc(380ms * var(--anim-enter-scale, 1));
|
||||
animation-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
|
||||
@keyframes line-enter-blur {
|
||||
0% { opacity: 0; filter: blur(5px) var(--line-glow); }
|
||||
100% { filter: blur(0px) var(--line-glow); }
|
||||
}
|
||||
|
||||
.anim-lab-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -9833,10 +9938,17 @@ kbd {
|
||||
stroke-dasharray: 5 3;
|
||||
fill: none;
|
||||
opacity: 0.9;
|
||||
/* Dark outline for contrast, vibrant blue glow */
|
||||
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.8))
|
||||
drop-shadow(0 0 4px rgba(59, 130, 246, 0.8))
|
||||
drop-shadow(0 0 8px rgba(59, 130, 246, 0.5));
|
||||
/* Dark outline for contrast, vibrant blue glow. Held in a variable because the
|
||||
`blur` line entrance animates `filter`: a keyframe listing only the blur would
|
||||
drop the glow for the length of the run and pop it back at the end, and the
|
||||
lineage lines below - whose glow is a different colour entirely, set per
|
||||
element - make that obvious. Both of its keyframes say
|
||||
`blur(N) var(--line-glow)`, so the function lists match and interpolate while
|
||||
each kind of line keeps its own glow. */
|
||||
--line-glow: drop-shadow(0 0 2px rgba(0, 0, 0, 0.8))
|
||||
drop-shadow(0 0 4px rgba(59, 130, 246, 0.8))
|
||||
drop-shadow(0 0 8px rgba(59, 130, 246, 0.5));
|
||||
filter: var(--line-glow);
|
||||
transition: opacity 0.2s, stroke-width 0.2s, filter 0.2s;
|
||||
}
|
||||
|
||||
@@ -9930,8 +10042,10 @@ kbd {
|
||||
stroke-dasharray: 5 5;
|
||||
stroke-linecap: round;
|
||||
opacity: 0.72;
|
||||
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.7)) drop-shadow(0 0 5px var(--lineage-color, var(--session-blue, #2b8fd9)))
|
||||
--line-glow: drop-shadow(0 0 2px rgba(0, 0, 0, 0.7))
|
||||
drop-shadow(0 0 5px var(--lineage-color, var(--session-blue, #2b8fd9)))
|
||||
drop-shadow(0 0 11px var(--lineage-color, var(--session-blue, #2b8fd9)));
|
||||
filter: var(--line-glow);
|
||||
}
|
||||
|
||||
/* ⚠ OUTSIDE the reduced-motion block below on purpose. A working child is the case
|
||||
@@ -13506,24 +13620,95 @@ body.touch-device.cjk-input-visible .main {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.path-picker-current {
|
||||
/* The current path is an editable field: type or paste a path and press Enter
|
||||
* (or Go) to jump there. The Go button is part of the same rounded control so
|
||||
* the field keeps the width the read-only breadcrumb had. */
|
||||
.path-picker-jump {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 9px 11px;
|
||||
overflow-x: auto;
|
||||
color: var(--accent);
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
margin: 0;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.path-picker-status {
|
||||
padding: 0 14px 8px;
|
||||
.path-picker-jump:focus-within {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.path-picker-current {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 36px;
|
||||
padding: 0 10px;
|
||||
color: var(--accent);
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.path-picker-go {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 10px;
|
||||
color: var(--text-dim);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-left: 1px solid var(--border);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.path-picker-go:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.path-picker-toolbar {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 14px 8px;
|
||||
}
|
||||
|
||||
.path-picker-status {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--text-dim);
|
||||
font-size: 0.7rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.path-picker-sort-label {
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
color: var(--text-dim);
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.path-picker-sort {
|
||||
padding: 3px 6px;
|
||||
color: var(--text);
|
||||
font-size: 0.7rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.path-picker-item-meta {
|
||||
flex: 0 0 auto;
|
||||
margin-left: 8px;
|
||||
color: var(--text-dim);
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 0.65rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.path-picker-status.error {
|
||||
@@ -17643,6 +17828,172 @@ html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail
|
||||
margin-top: 0.15rem;
|
||||
}
|
||||
|
||||
/* --- Detailed rail rows wear the HOME SCREEN's card language -------------- */
|
||||
/* The desktop home rail (.home-sessions, home-sessions.js) and this rail list
|
||||
the same sessions with the same three lines — name, project, "created 3d ago
|
||||
· working 12m" + pill — so they now LOOK the same too: a bordered card per
|
||||
session instead of a flat strip row, a 9px state dot (pulsing and ringed
|
||||
while the session works), the name at full weight, and the stamps line
|
||||
wrapped onto its own full-width row with the pill parked at its right end.
|
||||
|
||||
⚠ RAIL ONLY, never the shared comma-grouped selectors above. The detailed
|
||||
SIDEBAR draws the same meta line and is deliberately left flat: it is a
|
||||
permanently-docked navigation column that sits next to the terminal all day,
|
||||
and 20 stacked cards there read as a wall. Widening one of those grouped
|
||||
rules instead of adding this block is what would silently restyle it.
|
||||
|
||||
⚠ The paint rules here are (0,5,1)-(0,6,1), so they outrank the plain
|
||||
`.session-tab .tab-status.idle` class rules (0,2,0) — which is the point —
|
||||
but they must NOT outrank the alert rules that turn a dot red or yellow when
|
||||
a session is blocked on a human. Those are (0,3,0), so every dot rule below
|
||||
excludes the two alert classes by hand rather than relying on the cascade.
|
||||
State and alert normally agree (_mobileOverviewState reads the same pending
|
||||
hooks the alert does), so this is a guard against them drifting, not a fix
|
||||
for a known disagreement. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tabs {
|
||||
gap: 0.35rem;
|
||||
padding-top: 0.5rem;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab {
|
||||
/* The stamps line rides a wrapped full-width row, exactly as on the home rail:
|
||||
that hands the whole width of the card to the session name, which is what
|
||||
stops a `w34-claudeman: mindreading` ellipsizing into `w34-claudeman: …`. */
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.6rem;
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab:hover {
|
||||
background: var(--bg-hover);
|
||||
border-color: rgba(34, 197, 94, 0.35);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* The name is what tells one card from another, so it carries the weight the
|
||||
home rail gives it rather than the strip's dim 0.75rem label. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab .tab-name {
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
/* One step up from the shared vertical-list size, which is 12px because that
|
||||
is what the SIDEBAR has always been; a card row has the height for the
|
||||
~13px the home rail renders at. Still driven by the same setting (App
|
||||
Settings → Session Name Font Size), so it moves with it. */
|
||||
font-size: calc(var(--session-sidebar-name-font-size, 12px) + 1px);
|
||||
/* Three lines rather than two: the card is wrapped, so a long name costs
|
||||
height instead of pushing the pill or the stamps off the row. */
|
||||
-webkit-line-clamp: 3;
|
||||
line-clamp: 3;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab .tab-folder {
|
||||
font-size: 0.66rem;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
/* The state line gets the full width of the card (`flex: 0 0 100%` wraps it),
|
||||
so the stamps stop competing with the gear/close column for the sliver of
|
||||
room left beside the name. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .tab-meta {
|
||||
flex: 0 0 100%;
|
||||
margin-top: 0;
|
||||
font-size: 0.64rem;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
/* Bigger than the strip's 6px pip, because a card row has the room and the dot
|
||||
is the one thing on it readable at a glance. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab .tab-status {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
margin-top: 0.3rem;
|
||||
}
|
||||
|
||||
/* Idle is green, but a MUTED green — same mix the home rail uses, for the same
|
||||
reason: a glance down the rail must separate "running right now" from
|
||||
"sitting there" without reading a word. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact)
|
||||
.tab-rail
|
||||
.session-tab.tab-state-idle:not(.tab-alert-action):not(.tab-alert-idle)
|
||||
.tab-status {
|
||||
background: color-mix(in srgb, var(--green) 42%, var(--text-muted));
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact)
|
||||
.tab-rail
|
||||
.session-tab.tab-state-done:not(.tab-alert-action):not(.tab-alert-idle)
|
||||
.tab-status {
|
||||
background: var(--text-muted);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* The working halo. The orbiting ring is the shared `.tab-status.busy::after`
|
||||
already declared above — only its inset moves, to clear the wider dot. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact)
|
||||
.tab-rail
|
||||
.session-tab.tab-state-working:not(.tab-alert-action):not(.tab-alert-idle)
|
||||
.tab-status {
|
||||
background: var(--green);
|
||||
box-shadow: 0 0 8px 2px color-mix(in srgb, var(--green) 55%, transparent);
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact)
|
||||
.tab-rail
|
||||
.session-tab
|
||||
.tab-status.busy::after {
|
||||
inset: -4px;
|
||||
border-width: 2px;
|
||||
}
|
||||
|
||||
/* Card accents: the same three colours as every other session surface, and the
|
||||
same two blinks the home rail runs. `tab-alert-*` draws its own ::before ring
|
||||
on top of this for the sessions that are genuinely blocked on a human; these
|
||||
border accents are the calmer, always-on half. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab.tab-state-needs,
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab.tab-state-error {
|
||||
border-color: color-mix(in srgb, var(--red) 50%, transparent);
|
||||
animation: home-sessions-blink-red 2.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab.tab-state-waiting {
|
||||
border-color: color-mix(in srgb, var(--yellow) 50%, transparent);
|
||||
animation: home-sessions-blink-yellow 3.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab.tab-state-working {
|
||||
border-color: color-mix(in srgb, var(--green) 35%, transparent);
|
||||
}
|
||||
|
||||
/* No `.active` rule here on purpose: `.session-tab.active` (and its per-skin
|
||||
twin) already paints background, border and box-shadow with !important, so a
|
||||
card rule would be dead weight that reads as if it were doing something. The
|
||||
selected card keeps the accent its skin gives every selected tab, which is
|
||||
what makes it legible against the card background the state accents above
|
||||
paint on. */
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail .session-tab {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Activity-sorted rail (tabRailSort) ---------------------------------- */
|
||||
/* Visual order only: the DOM stays in the user's tab order, so drag-reorder,
|
||||
Alt+N badges, the arrow-key walk and the sidebar filter all keep reading the
|
||||
list they always read. `order` is set inline per tab by the render paths
|
||||
(app.js `_tabRailSortOrder`).
|
||||
|
||||
Web tabs carry no session state to sort by and keep their place at the end of
|
||||
the list, so they are pinned past every session card rather than being given
|
||||
an inline order of their own — `renderWebviewTabs()` emits the same markup for
|
||||
every layout and must stay that way. */
|
||||
html[data-tab-orientation='vertical'][data-tab-rail-sort='activity'] .tab-rail .session-tab[data-webview-id] {
|
||||
order: 9999;
|
||||
}
|
||||
|
||||
/* --- Collapsed rail ---------------------------------------------------- */
|
||||
/* Collapsed is a 44px icon rail, not "hidden": the ambient signal (status dot,
|
||||
task/subagent/ultracode badges) is the whole point of mission control and
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* @fileoverview Orphaned-input forwarder for xterm's helper textarea.
|
||||
*
|
||||
* xterm's `CoreBrowserTerminal._inputEvent` only forwards an `insertText`
|
||||
* input event while `(!ev.composed || !this._keyDownSeen)` holds. A soft
|
||||
* keyboard that delivers a `composed: true` input event after a keydown fails
|
||||
* that guard, so xterm returns without emitting and the committed character is
|
||||
* silently dropped.
|
||||
*
|
||||
* ⚠ The gap is NARROWER than "keyCode 229", and assuming otherwise produces a
|
||||
* controller that looks useful while doing nothing. For a keydown that really
|
||||
* does report `keyCode: 229`, xterm ALREADY self-rescues: `CompositionHelper
|
||||
* .keydown()` calls `_handleAnyTextareaChanges()`, which snapshots
|
||||
* `textarea.value` and diffs it on a 0 ms timer, emitting the difference
|
||||
* itself. Measured in headless chromium against a real terminal: for a 229
|
||||
* keydown xterm emits and this controller correctly stands down. What is left
|
||||
* unrescued is a refused `insertText` where NO 229 diff was scheduled — that is
|
||||
* the case this module exists for, and the case its browser test asserts by
|
||||
* checking WHO delivered the byte rather than merely that one arrived.
|
||||
*
|
||||
* The recovery never guesses the character: the `input` event already carries
|
||||
* the real committed text in `ev.data`, which is exactly what xterm itself
|
||||
* would have forwarded. We only decide WHETHER to forward it, by asking
|
||||
* whether xterm produced any canonical data since the keydown that started the
|
||||
* keystroke. That snapshot must be taken at KEYDOWN, not at the input event:
|
||||
* xterm's `_keyPress` emits and sets `_keyPressHandled` before `input` fires,
|
||||
* so a snapshot read at input time would already contain that emission and the
|
||||
* character would be delivered twice.
|
||||
*
|
||||
* Listener registration is load-bearing, in BOTH phase and order. xterm
|
||||
* registers its own `input` listener in `terminal.open()` with `capture:
|
||||
* true`, and ours is added afterwards, so at-target it runs second. It must
|
||||
* also be a CAPTURE listener; see the measured table at the addEventListener
|
||||
* call below.
|
||||
*
|
||||
* @dependency none (standalone IIFE; consumed by terminal-ui.js)
|
||||
* @loadorder 5.55 (before app.js/terminal-ui.js, which create the controller)
|
||||
*/
|
||||
(function (global) {
|
||||
'use strict';
|
||||
|
||||
function create(options) {
|
||||
const textarea = options?.textarea;
|
||||
const emitRecovered = options?.emitRecovered;
|
||||
if (!textarea?.addEventListener || !textarea?.removeEventListener || typeof emitRecovered !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isScreenReaderMode = options.isScreenReaderMode;
|
||||
const setTimer = options.setTimer || global.setTimeout.bind(global);
|
||||
const clearTimer = options.clearTimer || global.clearTimeout.bind(global);
|
||||
|
||||
let destroyed = false;
|
||||
// Number of canonical data events xterm has emitted, bumped by the caller's
|
||||
// onData hook. Only its ORDER relative to a keydown matters.
|
||||
let canonicalCount = 0;
|
||||
// ⚠️ 0, never null. With `null` the `?? canonicalCount` fallback at the input
|
||||
// event reads a count xterm has ALREADY bumped: on a fresh page load with no
|
||||
// keydown yet (dictation, Android voice typing, any `insertText` with no key
|
||||
// held) xterm's own capture listener runs first, forwards the text itself and
|
||||
// bumps the counter, then this snapshot equals it, `count > snapshot` is false,
|
||||
// and the text is emitted a SECOND time. A baseline of 0 makes that comparison
|
||||
// true and stands the recovery down, which restores this file's invariant: a
|
||||
// missed recovery is acceptable, a duplicated keystroke is not.
|
||||
let keydownSnapshot = 0;
|
||||
let composing = false;
|
||||
const pending = [];
|
||||
|
||||
function cancelPending() {
|
||||
for (const candidate of pending.splice(0)) {
|
||||
candidate.active = false;
|
||||
if (candidate.timer !== null) {
|
||||
try {
|
||||
clearTimer(candidate.timer);
|
||||
} catch {
|
||||
// A broken timer host must not break input handling.
|
||||
}
|
||||
candidate.timer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resolveCandidate(candidate) {
|
||||
const index = pending.indexOf(candidate);
|
||||
if (index !== -1) pending.splice(index, 1);
|
||||
candidate.timer = null;
|
||||
if (!candidate.active || destroyed) return;
|
||||
candidate.active = false;
|
||||
// xterm (or its keypress path) spoke for this keystroke — it is already
|
||||
// on its way to the PTY, so there is nothing to recover.
|
||||
if (canonicalCount > candidate.snapshot) return;
|
||||
try {
|
||||
emitRecovered(candidate.data);
|
||||
} catch {
|
||||
// Recovery is best effort; a failed delivery must never throw into the
|
||||
// browser's input handling.
|
||||
}
|
||||
}
|
||||
|
||||
/** Called from xterm's onData hook: xterm produced canonical data. */
|
||||
function notifyCanonicalData() {
|
||||
canonicalCount += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot the canonical counter at every keydown. This deliberately reads
|
||||
* NOTHING else off the event — not `key`, not `keyCode`. Gating it on
|
||||
* keyCode 229 would make the recovery inert on exactly the devices it
|
||||
* exists for, whose keydowns report `key: 'Unidentified'`. It is a single
|
||||
* assignment, so running it for every keydown costs nothing.
|
||||
*/
|
||||
function handleKeyEvent(event) {
|
||||
if (destroyed || event?.type !== 'keydown') return;
|
||||
keydownSnapshot = canonicalCount;
|
||||
}
|
||||
|
||||
function onInput(event) {
|
||||
if (destroyed || composing || event?.isComposing) return;
|
||||
if (event.inputType !== 'insertText') return;
|
||||
const data = event.data;
|
||||
if (typeof data !== 'string' || data === '') return;
|
||||
try {
|
||||
if (isScreenReaderMode?.()) return;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const candidate = {
|
||||
data,
|
||||
snapshot: keydownSnapshot ?? canonicalCount,
|
||||
active: true,
|
||||
timer: null,
|
||||
};
|
||||
pending.push(candidate);
|
||||
try {
|
||||
candidate.timer = setTimer(() => resolveCandidate(candidate), 0);
|
||||
} catch {
|
||||
cancelPending();
|
||||
}
|
||||
}
|
||||
|
||||
function onCompositionStart() {
|
||||
if (destroyed) return;
|
||||
composing = true;
|
||||
cancelPending();
|
||||
}
|
||||
|
||||
function onCompositionEnd() {
|
||||
if (destroyed) return;
|
||||
composing = false;
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
cancelPending();
|
||||
try {
|
||||
textarea.removeEventListener('input', onInput, true);
|
||||
textarea.removeEventListener('compositionstart', onCompositionStart, true);
|
||||
textarea.removeEventListener('compositionend', onCompositionEnd, true);
|
||||
} catch {
|
||||
// Teardown is best effort; the terminal is being replaced anyway.
|
||||
}
|
||||
}
|
||||
|
||||
// capture: true, not bubble. The target (the textarea) is visited TWICE in
|
||||
// the event path, so a capture-phase listener on it calling
|
||||
// stopPropagation() still stops later BUBBLE-phase listeners on that same
|
||||
// target. xterm's `_inputEvent` calls `this.cancel(ev)` (preventDefault +
|
||||
// stopPropagation) exactly in the branch where it HANDLED the input, so on
|
||||
// bubble we would never see handled events — and whether we saw them at
|
||||
// all would hang off xterm's `options.cancelEvents`, which Codeman does not
|
||||
// set. Measured (jsdom and headless chromium agree):
|
||||
//
|
||||
// capture-then-BUBBLE, no stop: xterm -> ours
|
||||
// capture-then-BUBBLE, stopPropagation: xterm (ours never fires)
|
||||
// capture-then-CAPTURE, no stop: xterm -> ours
|
||||
// capture-then-CAPTURE, stopPropagation: xterm -> ours (still fires)
|
||||
//
|
||||
// On capture we therefore observe EVERY input event uniformly, and the
|
||||
// canonicalCount snapshot alone decides whether to forward.
|
||||
try {
|
||||
textarea.addEventListener('input', onInput, true);
|
||||
textarea.addEventListener('compositionstart', onCompositionStart, true);
|
||||
textarea.addEventListener('compositionend', onCompositionEnd, true);
|
||||
} catch {
|
||||
destroy();
|
||||
return null;
|
||||
}
|
||||
|
||||
return Object.freeze({ handleKeyEvent, notifyCanonicalData, destroy });
|
||||
}
|
||||
|
||||
global.CodemanKeyCode229Recovery = Object.freeze({ create });
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
+213
-15
@@ -232,12 +232,22 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Terminal Setup — xterm.js config and input handling
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
_destroyKeyCode229Recovery() {
|
||||
try {
|
||||
this._keyCode229Recovery?.destroy?.();
|
||||
} catch {
|
||||
// Recovery is optional; terminal replacement must continue.
|
||||
}
|
||||
this._keyCode229Recovery = null;
|
||||
},
|
||||
|
||||
initTerminal() {
|
||||
// Load scrollback setting from localStorage, treating DEFAULT_SCROLLBACK as a floor
|
||||
// so users who picked up the previous (smaller) default get the new minimum on upgrade.
|
||||
const stored = parseInt(localStorage.getItem('codeman-scrollback'));
|
||||
const scrollback = Number.isFinite(stored) && stored > 0 ? Math.max(stored, DEFAULT_SCROLLBACK) : DEFAULT_SCROLLBACK;
|
||||
|
||||
this._destroyKeyCode229Recovery();
|
||||
this.terminal = new Terminal({
|
||||
theme: { ...window.codemanCurrentXtermTheme() },
|
||||
fontFamily: window.CodemanTerminalFont.resolve(this.loadAppSettingsFromStorage?.().terminalFontFamily),
|
||||
@@ -292,6 +302,16 @@ Object.assign(CodemanApp.prototype, {
|
||||
// punctuation; returning false here would stop xterm before it can diff
|
||||
// the helper textarea and emit the committed Unicode text.
|
||||
this.terminal.attachCustomKeyEventHandler((ev) => {
|
||||
try {
|
||||
// Deliberately runs for EVERY keydown, not just keyCode 229: the
|
||||
// controller snapshots a counter and reads nothing off the event, and
|
||||
// the devices this exists for report `key: 'Unidentified'` with no
|
||||
// reliable identity to gate on. Gating it would make recovery inert
|
||||
// exactly where it is needed. Cost is one assignment.
|
||||
this._keyCode229Recovery?.handleKeyEvent?.(ev);
|
||||
} catch {
|
||||
// The fallback must never interfere with xterm's canonical handler.
|
||||
}
|
||||
if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return true;
|
||||
|
||||
// Let the app's Alt/Option session-nav and Command Palette shortcuts reach the document keydown handler
|
||||
@@ -363,6 +383,29 @@ Object.assign(CodemanApp.prototype, {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ctrl+Z (SIGTSTP/job-control suspend): in a plain shell session this is the
|
||||
// user's own job-control tool (suspend a foreground command, `fg` it back) —
|
||||
// leave it alone. In every other mode (claude/omp/pi/codex/... — Ink/TUI apps
|
||||
// that normally run in raw mode with ISIG off, so ^Z is usually inert there
|
||||
// already) suspending the CLI stops an unattended agent loop dead with no
|
||||
// visible output — the same failure shape as an XOFF freeze. Swallow it
|
||||
// before xterm can send \x1a into the PTY rather than relying on every CLI's
|
||||
// raw-mode state holding at every instant (startup, raw-mode toggles, etc).
|
||||
if (
|
||||
ev.type === 'keydown' &&
|
||||
ev.key.toLowerCase() === 'z' &&
|
||||
ev.ctrlKey &&
|
||||
!ev.altKey &&
|
||||
!ev.metaKey &&
|
||||
!ev.shiftKey
|
||||
) {
|
||||
const activeCtrlZSession = this.activeSessionId ? this.sessions.get(this.activeSessionId) : null;
|
||||
if (activeCtrlZSession && activeCtrlZSession.mode !== 'shell') {
|
||||
ev.preventDefault();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Shift+Enter / Ctrl+Enter: insert newline for multi-line input.
|
||||
// xterm.js sends plain \r for all Enter variants, so Claude Code (Ink) can't
|
||||
// distinguish them. We use tmux send-keys -H to send a line feed byte (0x0a)
|
||||
@@ -514,6 +557,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
} else {
|
||||
this.fitAddon.fit();
|
||||
}
|
||||
// Whenever that first fit runs — on this line, or a frame or two later on
|
||||
// the mobile-Safari branch above — it measures whatever font the browser has
|
||||
// painted with so far, which is not necessarily the terminal font. Start the
|
||||
// wait now so the buffer load can hold for it.
|
||||
this._terminalFontReady = this._awaitTerminalFont();
|
||||
|
||||
// Register link provider for clickable file paths in Bash tool output
|
||||
this.registerFilePathLinkProvider();
|
||||
@@ -935,7 +983,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
// causes Ink to re-render at the new row count, garbling terminal output.
|
||||
// Local fit() still runs so xterm knows the viewport size for scrolling.
|
||||
const keyboardUp = typeof KeyboardHandler !== 'undefined' && KeyboardHandler.keyboardVisible;
|
||||
if (this.activeSessionId && !keyboardUp) {
|
||||
// Same yield as sendResize: never resize a PTY whose session is showing
|
||||
// in its own window. Dragging the dashboard's border must not reshape it.
|
||||
const detachedElsewhere = !this.isSoloWindow && this.detachedSessions?.has(this.activeSessionId);
|
||||
if (this.activeSessionId && !keyboardUp && !detachedElsewhere) {
|
||||
const dims = this.fitAddon.proposeDimensions();
|
||||
// Enforce minimum dimensions to prevent layout issues
|
||||
const cols = dims ? Math.max(dims.cols, MIN_COLS) : MIN_COLS;
|
||||
@@ -1026,7 +1077,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// mobile connections. The overlay + localStorage persistence ensure input
|
||||
// survives tab switches and reconnects.
|
||||
|
||||
this.terminal.onData((data) => {
|
||||
const handleTerminalData = (data) => {
|
||||
// Mouse SGR reports (tap-to-position) are NOT IME input — they must reach
|
||||
// the PTY even while the CJK input field owns focus. Without this exception
|
||||
// tapping to move the cursor silently does nothing whenever Chinese input
|
||||
@@ -1348,6 +1399,49 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Chrome on Android delivers a `composed: true` input event preceded by a
|
||||
// keydown, which is exactly the shape xterm's _inputEvent refuses to
|
||||
// forward, so the committed character is silently dropped. The controller
|
||||
// forwards the input event's own `data` when xterm produced nothing for
|
||||
// that keystroke. Created AFTER terminal.open() on purpose: for an event
|
||||
// targeting the textarea, at-target listeners run in registration order,
|
||||
// so xterm's listener (added in open()) still runs first. The controller
|
||||
// registers its own listener with `capture: true`; on bubble xterm's
|
||||
// `cancel()` (stopPropagation) would swallow exactly the handled events —
|
||||
// see the measured table in terminal-keycode229-recovery.js.
|
||||
try {
|
||||
this._keyCode229Recovery = window.CodemanKeyCode229Recovery?.create?.({
|
||||
textarea: this.terminal.textarea,
|
||||
emitRecovered: (data) => handleTerminalData(data),
|
||||
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
||||
});
|
||||
} catch {
|
||||
this._keyCode229Recovery = null;
|
||||
}
|
||||
this.terminal.onData((data) => {
|
||||
// Canonical xterm data. Telling the controller is what lets it know a
|
||||
// keystroke was already delivered and needs no recovery.
|
||||
//
|
||||
// ⚠️ onData ALSO fires for output xterm produces on its own initiative:
|
||||
// the DA/DSR/CPR/OSC replies it answers during Ink redraws, and the SGR
|
||||
// mouse and focus reports (see the two predicates above, used for exactly
|
||||
// this question at the send sites). Any one of those landing between the
|
||||
// keydown and the candidate's zero-delay resolution would be read as
|
||||
// "xterm spoke for this keystroke", standing the recovery down and
|
||||
// leaving the character dropped, worst on a busy agent pane, which is
|
||||
// the case this exists for. Narrowing the counter cannot cause a
|
||||
// duplicate: it only ever makes the controller less sure it can stand down.
|
||||
try {
|
||||
const input = window.CodemanTerminalInput;
|
||||
if (!input?.shouldSuppressTerminalQueryResponse(data) && !input?.isTerminalFocusOrMouseReport(data)) {
|
||||
this._keyCode229Recovery?.notifyCanonicalData?.();
|
||||
}
|
||||
} catch {
|
||||
// Bookkeeping must never block real input.
|
||||
}
|
||||
handleTerminalData(data);
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1440,6 +1534,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
range: { start, end },
|
||||
decorations: { pointerCursor: true, underline: true },
|
||||
activate(_event, text) {
|
||||
// A `localhost` link tapped from another device can only work
|
||||
// through the server: route it into a proxied web tab
|
||||
// (webview-tabs.js). Anything else opens as before.
|
||||
if (self.openLinkThroughWebTabIfLoopback?.(text)) return;
|
||||
window.open(text, '_blank', 'noopener,noreferrer');
|
||||
},
|
||||
hover() {
|
||||
@@ -2193,7 +2291,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (isLive && this.sessions.has(s.sessionId)) {
|
||||
this.selectSession(s.sessionId);
|
||||
} else {
|
||||
this.resumeHistorySession(s.claudeSessionId || s.sessionId, s.workingDir || '', s.name, s.mode);
|
||||
this.resumeHistorySession(s.claudeSessionId || s.sessionId, s.workingDir || '', s.name, s.mode, s.resumeId);
|
||||
}
|
||||
})
|
||||
);
|
||||
@@ -2436,7 +2534,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
} else {
|
||||
// Resume by the Claude conversation UUID when present (resumed sessions
|
||||
// carry theirs separately from their Codeman id).
|
||||
this.resumeHistorySession(s.claudeSessionId || s.sessionId, s.workingDir || '', s.name, s.mode);
|
||||
this.resumeHistorySession(s.claudeSessionId || s.sessionId, s.workingDir || '', s.name, s.mode, s.resumeId);
|
||||
}
|
||||
this.closeSessionManager?.();
|
||||
closeMenu();
|
||||
@@ -2904,7 +3002,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
return `w${startNumber}-${dirName}`;
|
||||
},
|
||||
|
||||
async resumeHistorySession(sessionId, workingDir, existingName, mode) {
|
||||
async resumeHistorySession(sessionId, workingDir, existingName, mode, resumeId) {
|
||||
// Close the run mode menu if open
|
||||
document.getElementById('runModeMenu')?.classList.remove('active');
|
||||
// Close folder history modal if open
|
||||
@@ -2942,19 +3040,27 @@ Object.assign(CodemanApp.prototype, {
|
||||
grok: 'grokConfig',
|
||||
omp: 'ompConfig',
|
||||
}[effectiveMode];
|
||||
// codex/gemini/antigravity have no wired continuation here yet (their
|
||||
// configs use an exact conversation id, not a "continue most recent"
|
||||
// flag, and the row's own `sessionId` is not verified to carry that
|
||||
// id for these three modes) — `continuesSomething` below is what keeps
|
||||
// their row from being retired for a resume that didn't actually
|
||||
// continue anything.
|
||||
// codex names a thread by an id of its own, not by Codeman's session id,
|
||||
// so it continues only when the row carried that id: `resumeId` is set by
|
||||
// the rollout scanner (codex-transcript.ts) and by nothing else, which is
|
||||
// what stops a LIVE codex row — whose sessionId is Codeman's uuid — from
|
||||
// asking codex for a thread that does not exist.
|
||||
//
|
||||
// gemini/antigravity still have no wired continuation here (same reason
|
||||
// codex used to have none: an exact conversation id nothing supplies) —
|
||||
// `continuesSomething` below is what keeps their row from being retired
|
||||
// for a resume that didn't actually continue anything.
|
||||
const codexResumeId = effectiveMode === 'codex' ? resumeId : undefined;
|
||||
const modeConfig =
|
||||
modeConfigKey
|
||||
? { [modeConfigKey]: { continueSession: true } }
|
||||
: effectiveMode === 'deepseek'
|
||||
? { deepSeekConfig: { resumeSession: true } }
|
||||
: {};
|
||||
const continuesSomething = Boolean(modeConfigKey) || effectiveMode === 'deepseek';
|
||||
: codexResumeId
|
||||
? { codexConfig: { resumeSessionId: codexResumeId } }
|
||||
: {};
|
||||
const continuesSomething =
|
||||
Boolean(modeConfigKey) || effectiveMode === 'deepseek' || Boolean(codexResumeId);
|
||||
const createRes = await fetch('/api/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -2982,11 +3088,16 @@ Object.assign(CodemanApp.prototype, {
|
||||
// as a duplicate — click it 3 times, see the same name 3 times. Claude
|
||||
// rows are left alone: `sessionId` there is a claudeSessionId, which
|
||||
// usually has no live/persisted Codeman session of its own to delete.
|
||||
// Gated on `continuesSomething`: for codex/gemini/antigravity (no
|
||||
// continuation wired above), this is really a FRESH session with no
|
||||
// Gated on `continuesSomething`: for gemini/antigravity, and for a codex
|
||||
// row carrying no `resumeId`, this is really a FRESH session with no
|
||||
// relation to the old row's conversation, so retiring it would discard
|
||||
// the old conversation with no recovery — worse than the duplicate row
|
||||
// this guard exists to prevent for the modes that DO continue.
|
||||
//
|
||||
// A codex row that DOES continue passes this gate, but the DELETE is a
|
||||
// no-op for it: `sessionId` there is codex's thread id and no Codeman
|
||||
// session carries that id. Its duplicate is cleared from the other side
|
||||
// instead, by the alias fold in gatherUnifiedInputs()/Session.
|
||||
if (effectiveMode !== 'claude' && continuesSomething && sessionId !== newSessionId) {
|
||||
fetch(`/api/sessions/${sessionId}?killMux=true`, { method: 'DELETE' }).catch(() => {});
|
||||
}
|
||||
@@ -3830,6 +3941,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
return;
|
||||
}
|
||||
|
||||
// The pane belongs to the popup showing it, so this window has nothing to
|
||||
// restore. Say so rather than reporting a size that was never sent — the
|
||||
// same button in that window does the job.
|
||||
if (!this.isSoloWindow && this.detachedSessions?.has(this.activeSessionId)) {
|
||||
this.showToast('This session is sized by its own window', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const dims = this.getTerminalDimensions();
|
||||
if (!dims) {
|
||||
this.showToast('Could not determine terminal size', 'error');
|
||||
@@ -4772,6 +4891,15 @@ Object.assign(CodemanApp.prototype, {
|
||||
const resolved = window.CodemanTerminalFont.resolve(custom);
|
||||
if (!this.terminal || this.terminal.options.fontFamily === resolved) return;
|
||||
this.terminal.options.fontFamily = resolved;
|
||||
// Changing the family at runtime is the same race as the boot-time one: the
|
||||
// option write makes xterm re-measure immediately, against a family the
|
||||
// browser may not have loaded. Re-arm the wait for the new stack and fit
|
||||
// again once it settles, so the setting takes effect at the right size
|
||||
// without needing a tab switch. The fit below still runs, so the terminal
|
||||
// is never left unfitted if the wait is slow.
|
||||
this._terminalFontReady = this._awaitTerminalFont().then(() => {
|
||||
if (this.terminal?.options?.fontFamily === resolved) this.fitAddon?.fit();
|
||||
});
|
||||
this.fitAddon?.fit();
|
||||
this._localEchoOverlay?.refreshFont();
|
||||
this._predictiveEcho?.refreshFont();
|
||||
@@ -4788,6 +4916,65 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Wait for the terminal's own font, then make xterm re-measure against it.
|
||||
*
|
||||
* A character cell measured against a fallback font has a different width and
|
||||
* height from one measured against the terminal font, so a fit taken too early
|
||||
* produces the wrong column and row count. The correction then arrives after
|
||||
* the buffer has been replayed, and the CLI redraws a frame that no longer
|
||||
* matches what the terminal is showing.
|
||||
*
|
||||
* ⚠️ Waiting is not sufficient on its own, which is what the re-measure at the
|
||||
* end is for. `FitAddon.proposeDimensions()` divides the container by a CACHED
|
||||
* cell size, and xterm refreshes that cache only from `open()`, from a resize
|
||||
* that actually changed the grid, and on a device-pixel-ratio change — nothing
|
||||
* in it listens for font loading. So a fit that runs after the font arrives can
|
||||
* still divide by the fallback cell, propose the grid it already has, and
|
||||
* short-circuit before anything re-measures.
|
||||
*
|
||||
* `document.fonts.load` for each family is what actually REQUESTS the faces:
|
||||
* the WebGL renderer rasterises glyphs through a canvas texture atlas, and
|
||||
* canvas text never triggers a CSS font fetch, so `document.fonts.ready` can
|
||||
* resolve with a face never having been asked for at all.
|
||||
*
|
||||
* Every step is best-effort and the whole thing is bounded, because a font
|
||||
* request that never settles must not hold up the terminal: `FontFaceSet.ready`
|
||||
* has no deadline of its own, and the caller awaits this in front of the buffer
|
||||
* replay. Past the deadline we fit against whatever is painted, which is the
|
||||
* old behaviour rather than a new failure.
|
||||
*/
|
||||
async _awaitTerminalFont() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || !document.fonts?.load) return;
|
||||
const size = this.terminal?.options?.fontSize || 14;
|
||||
const families = String(this.terminal?.options?.fontFamily || '')
|
||||
.split(',')
|
||||
.map((family) => family.trim().replace(/^["']|["']$/g, ''))
|
||||
.filter(Boolean)
|
||||
// Only the faces that can supply the measured glyph are worth waiting on.
|
||||
// The bundled symbols font is ~1.2MB and carries private-use-area glyphs
|
||||
// only — xterm measures `W`, which it does not contain — so awaiting it
|
||||
// puts a megabyte between the user and their first frame for nothing.
|
||||
// Generic families match no FontFace at all.
|
||||
.filter((family) => !TERMINAL_FONT_UNMEASURED.has(family.toLowerCase()));
|
||||
const loaded = Promise.all(
|
||||
families.map((family) => document.fonts.load(`${size}px "${family}"`).catch(() => {}))
|
||||
).then(() => document.fonts.ready);
|
||||
await Promise.race([loaded, new Promise((resolve) => setTimeout(resolve, TERMINAL_FONT_WAIT_MS))]);
|
||||
} catch {
|
||||
/* font loading is unavailable or failed — fit against whatever is painted */
|
||||
}
|
||||
// Force the cache refresh xterm will not do for us. Without this the wait
|
||||
// buys nothing on the common path (see the warning above). Private API, as
|
||||
// FitAddon itself is; guarded because a terminal can be disposed mid-wait.
|
||||
try {
|
||||
this.terminal?._core?._charSizeService?.measure();
|
||||
} catch {
|
||||
/* renderer not ready or internals moved — the next real resize re-measures */
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get terminal dimensions with minimum enforcement.
|
||||
* Prevents extremely narrow terminals that cause vertical text wrapping.
|
||||
@@ -4814,6 +5001,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Fit terminal to container before reading dimensions — ensures local
|
||||
// terminal size matches what we report to the server PTY.
|
||||
if (this.fitAddon) this.fitAddon.fit();
|
||||
// One PTY cannot hold two sizes. A detached session is owned by its own
|
||||
// window, and the dashboard's terminal is narrower than that window because
|
||||
// the session rail takes width the popup does not have — so both sizing it
|
||||
// makes the CLI draw frames that fit neither, which garbles the popup. The
|
||||
// dashboard yields; the solo window sizes what it alone displays.
|
||||
// (_maybeRefetchFullHistory already stands aside for the same reason.)
|
||||
// ⚠️ AFTER the fit, never before: the local reflow keeps the dashboard's own
|
||||
// xterm right, and only the SERVER write is the dashboard's to withhold —
|
||||
// the mobile-keyboard guard below draws exactly this line. tab-rail-resize
|
||||
// performs its one settle-time refit through this call and has no fallback.
|
||||
if (!this.isSoloWindow && this.detachedSessions?.has(sessionId)) return false;
|
||||
const dims = this.getTerminalDimensions();
|
||||
if (!dims) return false;
|
||||
// Did the dimensions actually change since the last resize we sent? Callers
|
||||
|
||||
@@ -19,7 +19,170 @@
|
||||
* @loadorder 12.5 of 16, after session-ui.js (needs the tab strip), before api-client.js
|
||||
*/
|
||||
|
||||
// ── Loopback links ──────────────────────────────────────────────────────────
|
||||
//
|
||||
// An agent prints `http://localhost:5173/` and the user taps it on a phone.
|
||||
// That link can only ever resolve on the Codeman box itself, so opening it in
|
||||
// the browser is a guaranteed connection error from anywhere else — while the
|
||||
// proxied web tab fetches from the server, where it works. Only loopback is
|
||||
// routed this way: a LAN or tailnet address may well be reachable from the
|
||||
// device (a VPN, the same Wi-Fi), and a direct open is the cheaper, richer path.
|
||||
|
||||
const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0', '::1', '[::1]', '::', '[::]']);
|
||||
|
||||
function normalizeHostname(hostname) {
|
||||
return String(hostname || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\.$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* `localhost`, 127.0.0.0/8, 0.0.0.0 and the IPv6 loopback forms: names that can
|
||||
* only ever mean this box.
|
||||
*
|
||||
* ⚠️ `*.localhost` is deliberately NOT here. The link source is agent-written
|
||||
* terminal output and response-viewer markdown, i.e. prompt-injectable, and
|
||||
* this set is the whole confinement on a tap that makes Codeman fetch a URL
|
||||
* server-side and persist it. Every other member is an address literal; a
|
||||
* `*.localhost` DNS name is not one: on a resolver that does not synthesise it
|
||||
* locally and has a search domain configured, `evil.localhost` NXDOMAINs as
|
||||
* absolute and is retried as `evil.localhost.<search domain>`, which an
|
||||
* attacker can control. A user who really runs `api.localhost` dev hosts can
|
||||
* still save that dashboard by hand, which is an explicit action.
|
||||
*/
|
||||
function isLoopbackHostname(hostname) {
|
||||
const host = normalizeHostname(hostname);
|
||||
if (!host) return false;
|
||||
if (LOOPBACK_HOSTNAMES.has(host)) return true;
|
||||
const ipv4 = /^(\d{1,3})\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.exec(host);
|
||||
return !!ipv4 && Number(ipv4[1]) === 127;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the PAGE is being viewed on the box itself. Broader than the
|
||||
* auto-route set on purpose, and safe in the opposite direction: a false
|
||||
* positive here only ever DECLINES to proxy, leaving the caller's direct open.
|
||||
*/
|
||||
function isOnBoxHostname(hostname) {
|
||||
const host = normalizeHostname(hostname);
|
||||
return isLoopbackHostname(host) || host.endsWith('.localhost');
|
||||
}
|
||||
|
||||
/**
|
||||
* One key per dev server, so `localhost:5173` and `127.0.0.1:5173` reuse a
|
||||
* single saved dashboard and a single tab instead of one per host spelling.
|
||||
*/
|
||||
function webTabOriginKey(url) {
|
||||
return isLoopbackHostname(url.hostname) ? `${url.protocol}//loopback:${url.port}` : url.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a link should open through a proxied web tab rather than directly:
|
||||
* an http(s) URL on a loopback host, viewed from a page that is NOT itself on
|
||||
* that host (on the box, the browser can reach localhost and the direct open
|
||||
* keeps devtools, extensions and the real origin).
|
||||
*/
|
||||
function linkNeedsWebTabProxy(rawUrl, pageHostname) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(String(rawUrl || ''));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
||||
if (!isLoopbackHostname(url.hostname)) return false;
|
||||
return !isOnBoxHostname(pageHostname);
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.CodemanWebviewLinks = { isLoopbackHostname, isOnBoxHostname, webTabOriginKey, linkNeedsWebTabProxy };
|
||||
}
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
// ── Loopback links ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Take a link the device cannot reach and open it through a proxied web tab.
|
||||
* Returns true when it took the link; false leaves the caller's own opening
|
||||
* path (window.open, an anchor's default) untouched.
|
||||
*/
|
||||
openLinkThroughWebTabIfLoopback(rawUrl) {
|
||||
if (!linkNeedsWebTabProxy(rawUrl, window.location?.hostname)) return false;
|
||||
void this.openUrlInWebTab(rawUrl);
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Open an arbitrary URL as a proxied web tab, deep path included. A saved
|
||||
* proxied dashboard on the same origin is reused (one tab per dev server,
|
||||
* not one per link); otherwise one is saved under the host:port name so it
|
||||
* is there in the Run dropdown next time.
|
||||
*/
|
||||
async openUrlInWebTab(rawUrl) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(String(rawUrl || ''));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// ⚠️ "is `this.webviews` set" does NOT answer "is it loaded": initWebviews()
|
||||
// assigns a truthy EMPTY map synchronously and only then awaits the list, so
|
||||
// a tap during page load used to find nothing to reuse and POST a duplicate
|
||||
// record for an origin that already exists server-side. Join an in-flight
|
||||
// load; start one only when none has ever run.
|
||||
if (this._webviewsRefresh) await this._webviewsRefresh;
|
||||
else if (!this._webviewsLoaded) await this.refreshWebviews();
|
||||
if (!this.webviews) {
|
||||
this.showToast?.('Could not open URL', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const wantedKey = webTabOriginKey(url);
|
||||
let existing = null;
|
||||
for (const webview of this.webviews.values()) {
|
||||
// ⚠️ `trusted` is excluded alongside `managed` and direct-mode records: a
|
||||
// trusted frame runs with `allow-same-origin`, i.e. on Codeman's origin with
|
||||
// the user's cookie, and the link being followed came from agent output. An
|
||||
// agent that can write into the dev server's tree (it IS the workspace) could
|
||||
// otherwise print a path that one tap navigates that privileged frame to.
|
||||
// Opening such a dashboard from the Run dropdown is still an explicit action.
|
||||
if (webview.managed || webview.trusted || (webview.embedMode ?? 'proxy') !== 'proxy') continue;
|
||||
try {
|
||||
if (webTabOriginKey(new URL(webview.url)) === wantedKey) {
|
||||
existing = webview;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
/* a saved URL that no longer parses is not a match */
|
||||
}
|
||||
}
|
||||
|
||||
let id = existing?.id;
|
||||
if (!id) {
|
||||
const created = await this._apiJson('/api/webviews', {
|
||||
method: 'POST',
|
||||
body: { name: url.host.slice(0, 60), url: `${url.origin}/`, embedMode: 'proxy', trusted: false },
|
||||
});
|
||||
if (!created?.id) {
|
||||
this.showToast?.('Could not open URL', 'error');
|
||||
return;
|
||||
}
|
||||
await this.refreshWebviews();
|
||||
id = created.id;
|
||||
// The create is a persisted record: it writes webviews.json, broadcasts
|
||||
// over SSE, adds a Run-dropdown row on every device this owner is signed
|
||||
// in on and counts toward MAX_WEBVIEWS. Adding one by hand goes through a
|
||||
// modal; a tap should not do all that with a new tab as its only signal.
|
||||
this.showToast?.(`Saved ${url.host} as a web tab`, 'success');
|
||||
}
|
||||
// `/` is passed through rather than flattened to '': openWebview reads an
|
||||
// empty path as "no deep link" and leaves an already-open frame on whatever
|
||||
// page it was showing, so a link to the origin root did nothing visible.
|
||||
const path = `${url.pathname}${url.search}${url.hash}`;
|
||||
await this.openWebview(id, { path: path || '/' });
|
||||
},
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Load the saved list and restore which tabs were open. */
|
||||
@@ -45,11 +208,19 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
async refreshWebviews() {
|
||||
const data = await this._apiJson('/api/webviews');
|
||||
if (!data) return;
|
||||
this.webviews = new Map((data.webviews || []).map((w) => [w.id, w]));
|
||||
if (typeof data.maxLiveFrames === 'number') this._webviewMaxFrames = data.maxLiveFrames;
|
||||
this.renderWebviewMenuItems();
|
||||
const inFlight = this._apiJson('/api/webviews').then((data) => {
|
||||
if (!data) return;
|
||||
this.webviews = new Map((data.webviews || []).map((w) => [w.id, w]));
|
||||
if (typeof data.maxLiveFrames === 'number') this._webviewMaxFrames = data.maxLiveFrames;
|
||||
this._webviewsLoaded = true;
|
||||
this.renderWebviewMenuItems();
|
||||
});
|
||||
this._webviewsRefresh = inFlight;
|
||||
try {
|
||||
await inFlight;
|
||||
} finally {
|
||||
if (this._webviewsRefresh === inFlight) this._webviewsRefresh = null;
|
||||
}
|
||||
},
|
||||
|
||||
/** SSE: the saved list changed (possibly on another device). */
|
||||
@@ -133,7 +304,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
* memory-only and expire, so a tab reopened after a server restart must not reuse
|
||||
* the dead URL from the previous run.
|
||||
*/
|
||||
async openWebview(id) {
|
||||
/**
|
||||
* @param {string} id
|
||||
* @param {{path?: string}} [options] `path` (pathname+search+hash) opens a
|
||||
* deep link inside the dashboard: appended to the proxy prefix, or resolved
|
||||
* against the real URL in direct mode. A mounted frame is navigated there
|
||||
* rather than left on whatever page it was showing.
|
||||
*/
|
||||
async openWebview(id, options = {}) {
|
||||
const webview = this.webviews.get(id);
|
||||
if (!webview) return;
|
||||
|
||||
@@ -149,8 +327,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
if (data.webview) this.webviews.set(id, data.webview);
|
||||
|
||||
const src = data.embedUrl || data.webview?.url || webview.url;
|
||||
this._mountWebviewFrame(id, src, data.webview || webview);
|
||||
let src = data.embedUrl || data.webview?.url || webview.url;
|
||||
const path = typeof options.path === 'string' ? options.path : '';
|
||||
if (path) {
|
||||
// The proxy prefix is `/webview/<cap>/`; a wildcard rides after it. In
|
||||
// direct mode the deep link resolves against the dashboard's own origin.
|
||||
src = data.embedUrl ? `${data.embedUrl.replace(/\/?$/, '/')}${path.replace(/^\//, '')}` : new URL(path, src).href;
|
||||
}
|
||||
this._mountWebviewFrame(id, src, data.webview || webview, { navigate: !!path });
|
||||
this.activeWebviewId = id;
|
||||
this.hideWelcome?.();
|
||||
document.querySelector('.main')?.classList.add('webview-active');
|
||||
@@ -162,11 +346,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
/** Create the frame if absent, then reveal it and hide its siblings. */
|
||||
_mountWebviewFrame(id, src, webview) {
|
||||
_mountWebviewFrame(id, src, webview, { navigate = false } = {}) {
|
||||
const layer = document.getElementById('webviewLayer');
|
||||
if (!layer) return;
|
||||
|
||||
let wrap = layer.querySelector(`.webview-frame[data-webview-id="${CSS.escape(id)}"]`);
|
||||
if (wrap && navigate) {
|
||||
// A deep link into an already-mounted dashboard: navigate the live frame
|
||||
// instead of tearing it down, so its login and state survive.
|
||||
const frame = wrap.querySelector('iframe');
|
||||
if (frame) frame.src = CodemanBase.url(src);
|
||||
}
|
||||
if (!wrap) {
|
||||
wrap = document.createElement('div');
|
||||
wrap.className = 'webview-frame';
|
||||
|
||||
@@ -359,3 +359,30 @@ export function getLastTranscriptResponse(blocks: ResponseViewerTranscriptBlock[
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The messages of the most recent turn that has an answer: every assistant
|
||||
* message whose `turn` matches the highest turn any assistant message carries.
|
||||
*
|
||||
* This is what the viewer's brief ("Last Response") view renders for Claude.
|
||||
* The brief `text` is one row — the last assistant row — and a Claude turn is
|
||||
* a median of 3 rows (p90 11), so that row alone was usually the tail of the
|
||||
* answer ("Done.") with the substance in the rows before it. Reading the whole
|
||||
* turn gives the same cards the full view shows for it, and no more.
|
||||
*
|
||||
* Deliberately NOT "everything after the last user message": a prompt queued
|
||||
* while the agent works opens a new, still-unanswered turn, and the honest
|
||||
* brief view is then the previous, answered one — exactly the row `text`
|
||||
* already points at. Messages without a numeric `turn` (Codex, the pane
|
||||
* parser, an older reader) yield an empty list so callers fall back to `text`.
|
||||
*/
|
||||
export function selectLastAnsweredTurn<T extends { role: string; turn?: number }>(messages: T[]): T[] {
|
||||
let latest = -1;
|
||||
for (const message of messages) {
|
||||
if (message.role === 'assistant' && typeof message.turn === 'number' && message.turn > latest) {
|
||||
latest = message.turn;
|
||||
}
|
||||
}
|
||||
if (latest < 0) return [];
|
||||
return messages.filter((message) => message.role === 'assistant' && message.turn === latest);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
} from '../route-helpers.js';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import type { SessionAttachmentHistoryItem, SessionState } from '../../types/session.js';
|
||||
import { downloadTooLargeMessage, exceedsDownloadLimit } from '../../config/buffer-limits.js';
|
||||
import { parseByteRange } from '../http-range.js';
|
||||
import { isSensitivePath } from '../sensitive-path.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
@@ -183,16 +184,8 @@ async function serveRawFile(
|
||||
rangeHeader?: string | string[]
|
||||
): Promise<void> {
|
||||
const stat = await fs.stat(resolvedPath);
|
||||
const MAX_RAW_ATTACHMENT_SIZE = 50 * 1024 * 1024; // 50MB, matching file-raw / download
|
||||
if (stat.size > MAX_RAW_ATTACHMENT_SIZE) {
|
||||
reply
|
||||
.code(413)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
`File too large (${Math.round(stat.size / 1024 / 1024)}MB > ${MAX_RAW_ATTACHMENT_SIZE / 1024 / 1024}MB limit)`
|
||||
)
|
||||
);
|
||||
if (exceedsDownloadLimit(stat.size)) {
|
||||
reply.code(413).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, downloadTooLargeMessage(stat.size)));
|
||||
return;
|
||||
}
|
||||
// Markup is download-only: served with a renderable type on our own origin it
|
||||
@@ -883,6 +876,7 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
|
||||
let type: FilesystemBrowseEntry['type'];
|
||||
let size: number | undefined;
|
||||
let mtimeMs: number | undefined;
|
||||
const symlink = entry.isSymbolicLink();
|
||||
if (entry.isDirectory()) {
|
||||
type = 'directory';
|
||||
@@ -893,6 +887,7 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
const targetStat = await fs.stat(targetPath);
|
||||
type = targetStat.isDirectory() ? 'directory' : 'file';
|
||||
if (type === 'file') size = targetStat.size;
|
||||
mtimeMs = targetStat.mtimeMs;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
@@ -901,11 +896,15 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
}
|
||||
|
||||
if (isBlockedPickerPath(targetPath, blockedTrees, type === 'directory')) continue;
|
||||
if (type === 'file' && size === undefined) {
|
||||
if (mtimeMs === undefined) {
|
||||
// One stat per entry: the modified time lets the picker sort by date, and
|
||||
// a file's size rides along on the same call.
|
||||
try {
|
||||
size = (await fs.stat(targetPath)).size;
|
||||
const targetStat = await fs.stat(targetPath);
|
||||
mtimeMs = targetStat.mtimeMs;
|
||||
if (type === 'file') size = targetStat.size;
|
||||
} catch {
|
||||
// The path is still selectable even when a size lookup races a change.
|
||||
// The path is still selectable even when a stat races a change.
|
||||
}
|
||||
}
|
||||
entries.push({
|
||||
@@ -913,6 +912,7 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
path: visiblePath,
|
||||
type,
|
||||
size,
|
||||
mtimeMs,
|
||||
symlink: symlink || undefined,
|
||||
previewKind: type === 'file' ? getFilesystemPreviewKind(entry.name) : undefined,
|
||||
});
|
||||
@@ -1562,18 +1562,11 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
const { resolvedPath } = validated;
|
||||
|
||||
try {
|
||||
// Validate file size before reading (DoS protection - prevent memory exhaustion)
|
||||
const MAX_RAW_FILE_SIZE = 50 * 1024 * 1024; // 50MB for raw files
|
||||
// Sanity bound only: the body below is streamed and Range-aware, so size
|
||||
// does not translate into resident memory. Configurable, 0 = unlimited.
|
||||
const stat = await fs.stat(resolvedPath);
|
||||
if (stat.size > MAX_RAW_FILE_SIZE) {
|
||||
reply
|
||||
.code(400)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
`File too large (${Math.round(stat.size / 1024 / 1024)}MB > ${MAX_RAW_FILE_SIZE / 1024 / 1024}MB limit)`
|
||||
)
|
||||
);
|
||||
if (exceedsDownloadLimit(stat.size)) {
|
||||
reply.code(413).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, downloadTooLargeMessage(stat.size)));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1954,17 +1947,8 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
return;
|
||||
}
|
||||
|
||||
// 50MB size limit
|
||||
const MAX_DOWNLOAD_SIZE = 50 * 1024 * 1024;
|
||||
if (stat.size > MAX_DOWNLOAD_SIZE) {
|
||||
reply
|
||||
.code(400)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
`File too large (${Math.round(stat.size / 1024 / 1024)}MB > 50MB limit)`
|
||||
)
|
||||
);
|
||||
if (exceedsDownloadLimit(stat.size)) {
|
||||
reply.code(413).send(createErrorResponse(ApiErrorCode.INVALID_INPUT, downloadTooLargeMessage(stat.size)));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1988,15 +1972,13 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
|
||||
};
|
||||
|
||||
const filename = pathBasename(resolvedPath);
|
||||
const content = await fs.readFile(resolvedPath);
|
||||
// Bypass Fastify compression — write directly to raw response
|
||||
reply.raw.writeHead(200, {
|
||||
...inheritedHeaders(reply),
|
||||
'Content-Type': mimeTypes[ext] || 'application/octet-stream',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
'Content-Length': content.length,
|
||||
});
|
||||
reply.raw.end(content);
|
||||
// Streamed rather than read into memory, and Range-aware, so a multi-GB
|
||||
// artifact costs one read stream and can be resumed. sendFileBody()
|
||||
// hijacks the reply, which also keeps Fastify's compression out of it.
|
||||
reply.header('Content-Type', mimeTypes[ext] || 'application/octet-stream');
|
||||
reply.header('Content-Disposition', buildContentDisposition('attachment', filename));
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
sendFileBody(reply, resolvedPath, stat.size, req.headers.range);
|
||||
return;
|
||||
} catch (err) {
|
||||
reply
|
||||
|
||||
@@ -148,10 +148,12 @@ import {
|
||||
import { LRUMap } from '../../utils/lru-map.js';
|
||||
import { findLatestOmpSessionId } from '../../utils/omp-session-resolver.js';
|
||||
import { scanOmpSessionsHistory } from '../../omp-transcript.js';
|
||||
import { scanCodexSessionsHistory, codexThreadBySessionId } from '../../codex-transcript.js';
|
||||
import {
|
||||
getLastTranscriptResponse,
|
||||
isExternalCliTranscriptMode,
|
||||
parseExternalCliTranscript,
|
||||
selectLastAnsweredTurn,
|
||||
} from '../response-viewer-transcript.js';
|
||||
import { readDeepSeekLastResponse } from '../../deepseek-transcript.js';
|
||||
|
||||
@@ -2213,10 +2215,14 @@ export function registerSessionRoutes(
|
||||
}
|
||||
|
||||
const query = req.query as { context?: string };
|
||||
// `turn` is the brief view's context: the last ANSWERED turn's assistant
|
||||
// messages, so a multi-row answer is not reduced to its final row. `text`
|
||||
// stays the last assistant row in every mode (agent pollers hash it).
|
||||
const wantsMessages = query.context === 'full' || query.context === 'turn';
|
||||
const claudeSessionId = session.claudeSessionId || session.id;
|
||||
const transcript = await findClaudeTranscript(projectsDir, claudeSessionId, session.id);
|
||||
if (!transcript) {
|
||||
return query.context === 'full' ? { text: '', timestamp: '', messages: [] } : { text: '', timestamp: '' };
|
||||
return wantsMessages ? { text: '', timestamp: '', messages: [] } : { text: '', timestamp: '' };
|
||||
}
|
||||
|
||||
if (transcript.sessionId !== session.claudeSessionId && transcript.sessionId !== session.id) {
|
||||
@@ -2232,9 +2238,17 @@ export function registerSessionRoutes(
|
||||
|
||||
try {
|
||||
const content = await fs.readFile(transcript.path, 'utf8');
|
||||
return parseClaudeResponseTranscript(content, query.context === 'full');
|
||||
const parsed = parseClaudeResponseTranscript(content, wantsMessages);
|
||||
if (query.context === 'turn') {
|
||||
return {
|
||||
text: parsed.text,
|
||||
timestamp: parsed.timestamp,
|
||||
messages: selectLastAnsweredTurn(parsed.messages ?? []),
|
||||
};
|
||||
}
|
||||
return parsed;
|
||||
} catch {
|
||||
return query.context === 'full' ? { text: '', timestamp: '', messages: [] } : { text: '', timestamp: '' };
|
||||
return wantsMessages ? { text: '', timestamp: '', messages: [] } : { text: '', timestamp: '' };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2602,6 +2616,12 @@ export function registerSessionRoutes(
|
||||
? 'mux-full-history'
|
||||
: 'mux-visible'
|
||||
: 'history';
|
||||
// What the three row-preserving skips below must key on. `isFullReload` is
|
||||
// only what the CLIENT ASKED FOR: when the capture comes back null — ENOBUFS,
|
||||
// a timeout, a vanished pane, or a session with no mux at all — rawBuffer
|
||||
// falls back to the byte history, which is a stream of successive frames with
|
||||
// no row alignment to protect and every reason to be stripped.
|
||||
const isFullCapture = isFullReload && hasLiveMuxBuffer;
|
||||
let rawBuffer: string;
|
||||
if (liveMuxBuffer !== null && liveMuxBuffer.length > 0) {
|
||||
// Full-history capture is the RENDERED form of everything already in the
|
||||
@@ -2648,8 +2668,16 @@ export function registerSessionRoutes(
|
||||
// During long thinking phases, Ink rewrites the same rows thousands of times
|
||||
// (500KB+). Without stripping, tail mode returns only spinner frames and
|
||||
// the terminal appears empty when switching tabs.
|
||||
// A full reload's buffer IS the rendered pane, one line per screen row, and
|
||||
// it ends with an absolute cursor move back to the pane's own position.
|
||||
// Every transform below that can DELETE A LINE would shift the rows out from
|
||||
// under that position, leaving the caret a row off — on the composer's
|
||||
// border rather than its input line. Redraw-bloat stripping exists for a
|
||||
// byte stream of successive frames; a capture holds no successive frames.
|
||||
let strippedBuffer =
|
||||
getCli(session.mode)?.capabilities.stripInkBloat === false ? rawBuffer : stripInkRedrawBloat(rawBuffer);
|
||||
isFullCapture || getCli(session.mode)?.capabilities.stripInkBloat === false
|
||||
? rawBuffer
|
||||
: stripInkRedrawBloat(rawBuffer);
|
||||
|
||||
// Strip alt-screen toggles and scrollback-erase from Codex/Claude byte
|
||||
// streams. xterm.js obeys them by switching to its scrollback-less alt
|
||||
@@ -2687,7 +2715,10 @@ export function registerSessionRoutes(
|
||||
cleanBuffer = strippedBuffer;
|
||||
|
||||
// Find where Claude banner starts (has color codes before "Claude")
|
||||
const claudeMatch = cleanBuffer.match(CLAUDE_BANNER_PATTERN);
|
||||
// Skipped for a full reload: the banner sits at whatever row the pane has
|
||||
// it, and cutting to it would drop the blank rows above and move every
|
||||
// row up by that many.
|
||||
const claudeMatch = isFullCapture ? null : cleanBuffer.match(CLAUDE_BANNER_PATTERN);
|
||||
if (claudeMatch && claudeMatch.index !== undefined && claudeMatch.index > 0) {
|
||||
let lineStart = claudeMatch.index;
|
||||
while (lineStart > 0 && cleanBuffer[lineStart - 1] !== '\n') {
|
||||
@@ -2698,7 +2729,11 @@ export function registerSessionRoutes(
|
||||
}
|
||||
|
||||
// Remove Ctrl+L and leading whitespace (cheap on tailed subset)
|
||||
cleanBuffer = cleanBuffer.replace(CTRL_L_PATTERN, '').replace(LEADING_WHITESPACE_PATTERN, '');
|
||||
// Leading whitespace goes too, except on a full reload where a leading
|
||||
// blank line is the pane's own first row and dropping it shifts every row
|
||||
// up by one.
|
||||
cleanBuffer = cleanBuffer.replace(CTRL_L_PATTERN, '');
|
||||
if (!isFullCapture) cleanBuffer = cleanBuffer.replace(LEADING_WHITESPACE_PATTERN, '');
|
||||
|
||||
const finishedAt = performance.now();
|
||||
reply.header(
|
||||
@@ -4164,6 +4199,13 @@ export function registerSessionRoutes(
|
||||
// Persisted sessions (state.json). resumeSessionId is the Claude
|
||||
// conversation UUID a resumed session continues — feed it to the merge's
|
||||
// alias map so its transcript row folds into this session.
|
||||
//
|
||||
// codex keeps its thread id in `codexConfig` instead, and state.json stores
|
||||
// that, so read it here as well. Without it a resumed codex session that has
|
||||
// been demoted to a persisted-only record loses its alias and duplicates: the
|
||||
// originator fallback below cannot rescue that one, because a RESUMED rollout
|
||||
// keeps the original session_meta (see findActiveCodexFile) and so still
|
||||
// names whichever pane first created the thread.
|
||||
const persisted: PersistedSessionInput[] = Object.values(ctx.store.getState().sessions).map((p) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
@@ -4172,7 +4214,7 @@ export function registerSessionRoutes(
|
||||
workingDir: p.workingDir,
|
||||
createdAt: p.createdAt,
|
||||
lastActivityAt: p.lastActivityAt,
|
||||
claudeSessionId: p.resumeSessionId,
|
||||
claudeSessionId: p.resumeSessionId || p.codexConfig?.resumeSessionId,
|
||||
pinned: p.pinned,
|
||||
pinnedAt: p.pinnedAt,
|
||||
}));
|
||||
@@ -4240,6 +4282,49 @@ export function registerSessionRoutes(
|
||||
// Best-effort, same as the claude scan above.
|
||||
}
|
||||
|
||||
// Codex's own rollout store (~/.codex/sessions) — the same treatment omp
|
||||
// gets above, and for the same reason: codex writes no Claude transcript, so
|
||||
// without this a codex conversation disappears from the list as soon as its
|
||||
// session record does. `resumeId` is the rollout's own thread id, which is
|
||||
// what `codex resume` takes; see codex-transcript.ts.
|
||||
try {
|
||||
const codexRows = await scanCodexSessionsHistory();
|
||||
for (const h of codexRows) {
|
||||
history.push({
|
||||
sessionId: h.sessionId,
|
||||
workingDir: h.workingDir,
|
||||
sizeBytes: h.sizeBytes,
|
||||
lastModified: h.lastModified,
|
||||
firstPrompt: h.firstPrompt,
|
||||
lastPrompt: h.lastPrompt,
|
||||
mode: 'codex',
|
||||
resumeId: h.sessionId,
|
||||
});
|
||||
}
|
||||
|
||||
// Fold a FRESH codex pane into its own rollout row. A resumed one already
|
||||
// folds, because Session sets `claudeSessionId` from the resume id it was
|
||||
// given; a fresh one has no thread id until codex writes the rollout, so
|
||||
// the link has to come from the other side. Codeman spawns every codex pane
|
||||
// with CODEX_INTERNAL_ORIGINATOR_OVERRIDE=codeman_<sessionId>, and codex
|
||||
// stamps that into session_meta.originator, so the rollout names the pane.
|
||||
//
|
||||
// Newest rollout wins: `/new` typed inside the TUI leaves several rollouts
|
||||
// carrying the same originator, and the pane is on the most recent one.
|
||||
// Rows arrive newest-first, so the first match is it.
|
||||
//
|
||||
// Never overwrites an id a session already knows — that one came from the
|
||||
// resume path and is authoritative.
|
||||
const codexThreads = codexThreadBySessionId(codexRows);
|
||||
for (const row of [...live, ...persisted]) {
|
||||
if (row.claudeSessionId && row.claudeSessionId !== row.id) continue;
|
||||
const threadId = codexThreads.get(row.id);
|
||||
if (threadId) row.claudeSessionId = threadId;
|
||||
}
|
||||
} catch {
|
||||
// Best-effort, same as the two scans above.
|
||||
}
|
||||
|
||||
// Mux process stats (best-effort; guard against mocks lacking the method).
|
||||
let mux: MuxStatInput[] = [];
|
||||
try {
|
||||
|
||||
@@ -1255,6 +1255,15 @@ export const SettingsUpdateSchema = z
|
||||
tabOrientation: z.enum(['horizontal', 'vertical']).optional(),
|
||||
tabRailWidth: z.number().int().min(208).max(360).optional(),
|
||||
tabRailDetail: z.enum(['simple', 'rich']).optional(),
|
||||
/**
|
||||
* Vertical rail row order. Display key (per-device).
|
||||
* 'activity' = the home screens' order (CodemanSessionOrder): blocked on a
|
||||
* human first, then running longest-first, then quiet
|
||||
* most-recently-quiet first.
|
||||
* 'manual' = the user's tab order, and the only value that leaves the
|
||||
* rail drag-reorderable.
|
||||
*/
|
||||
tabRailSort: z.enum(['activity', 'manual']).optional(),
|
||||
/**
|
||||
* Session list layout. Display key (per-device).
|
||||
* 'header' = horizontal tab strip
|
||||
|
||||
@@ -93,6 +93,11 @@ const ALLOWED_BRANCHES: Record<string, string> = {
|
||||
"tmux-manager.ts::mode === 'claude'":
|
||||
"claude's remote pane command carries per-session permission flags, and its docker form is " +
|
||||
'`--session-id … || resume`; neither fits a static overlays.command string',
|
||||
"tmux-manager.ts::mode === 'omp'":
|
||||
'remote omp respawn needs the pinned/continue --resume override threaded through ' +
|
||||
'(resumeSessionId/ompConfig), which the static overlays.remote.command string has no ' +
|
||||
'room for; the command itself is still rendered through buildSpawnCommandFromRegistry, ' +
|
||||
'the same mode-agnostic engine local/docker spawns use — only the BRANCH is per-mode',
|
||||
|
||||
// --- Per-CLI prose and launch handling not yet generalised ---
|
||||
"web/session-wait-registry.ts::mode === 'deepseek'":
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { CliEntrySchema } from '../src/config/cli-registry/schema.js';
|
||||
import { compileVersionRegex } from '../src/config/cli-registry/patterns.js';
|
||||
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
|
||||
import type { CliEntry } from '../src/config/cli-registry/types.js';
|
||||
|
||||
@@ -75,6 +76,34 @@ describe('strictness', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('workDetect.workingLine is guarded like every other config regex', () => {
|
||||
it('rejects a nested quantifier', () => {
|
||||
expectRejected((e) => {
|
||||
(e.capabilities as Record<string, unknown>).workDetect = { promptGlyph: '>', workingLine: '(a+)+b' };
|
||||
}, 'this pattern is compiled once and then run against every accumulated PTY chunk, so catastrophic backtracking here freezes the event loop for the whole server');
|
||||
});
|
||||
|
||||
it('rejects a source longer than compileVersionRegex() will compile', () => {
|
||||
expectRejected((e) => {
|
||||
(e.capabilities as Record<string, unknown>).workDetect = { promptGlyph: '>', workingLine: 'a'.repeat(201) };
|
||||
}, 'the schema must not accept a pattern the runtime will then refuse to compile, or the CLI silently falls back to the Claude pattern');
|
||||
});
|
||||
|
||||
it('rejects a pattern that is not a regex at all', () => {
|
||||
expectRejected((e) => {
|
||||
(e.capabilities as Record<string, unknown>).workDetect = { promptGlyph: '>', workingLine: '([unclosed' };
|
||||
}, 'a broken pattern must fail at LOAD time, not inside the PTY data handler');
|
||||
});
|
||||
|
||||
it('accepts both shipped patterns unchanged', () => {
|
||||
for (const entry of STOCK_CLIS) {
|
||||
const src = entry.capabilities.workDetect?.workingLine;
|
||||
if (!src) continue;
|
||||
expect(compileVersionRegex(src), `${entry.id} declares a workingLine the guard refuses`).not.toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('no shell text can reach the command line', () => {
|
||||
it('rejects a literal carrying shell metacharacters', () => {
|
||||
for (const evil of ['pi; rm -rf /', 'pi && curl evil.sh', 'pi`whoami`', 'pi $(id)', 'pi | tee', 'pi > /etc/x']) {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* @fileoverview A resumed codex session must keep its thread-id alias across
|
||||
* `start()`, not just at construction.
|
||||
*
|
||||
* `claudeSessionId` doubles as the generic "external transcript id" the unified
|
||||
* list folds a Past-Sessions row into its owning session by. For codex that id
|
||||
* is the rollout's thread id, and losing it is not cosmetic: the stale row stays
|
||||
* in PAST and still resumes, so clicking it starts a SECOND `codex resume` on a
|
||||
* thread already open in the live pane.
|
||||
*
|
||||
* The bug this pins: the alias was wired into the constructor only. `start()`
|
||||
* recomputes `claudeSessionId` at two further points — the mux branch and the
|
||||
* unconditional "third reset point" that runs after both the mux and direct-PTY
|
||||
* paths — and both listed only Claude's `resumeSessionId` and omp's. For codex
|
||||
* both are undefined, so every mux reattach and every boot recovery reset the
|
||||
* alias back to the Codeman id and the duplicate came back. The existing comment
|
||||
* at the third reset point already warned that omitting omp's fallback there
|
||||
* "stomps the mux branch's correctly-resolved OMP alias"; codex needed the same.
|
||||
*
|
||||
* Mirrors `test/omp-fresh-run-no-resume.test.ts`, which drives a real `Session`
|
||||
* against the in-memory tmux layer that vitest substitutes.
|
||||
*/
|
||||
import { mkdirSync, rmSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { Session } from '../src/session.js';
|
||||
import { TmuxManager } from '../src/tmux-manager.js';
|
||||
|
||||
describe('codex: a resumed thread id survives start()', () => {
|
||||
const workingDir = join(homedir(), 'codeman-cases', 'codex-resume-alias');
|
||||
const THREAD_ID = '01a060f0-0361-7f91-abde-b283020db0d7';
|
||||
const sessions: Session[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const s of sessions.splice(0)) s.stop();
|
||||
rmSync(workingDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function makeSession(useMux: boolean): Session {
|
||||
mkdirSync(workingDir, { recursive: true });
|
||||
const session = new Session({
|
||||
workingDir,
|
||||
mode: 'codex',
|
||||
codexConfig: { resumeSessionId: THREAD_ID },
|
||||
mux: new TmuxManager(),
|
||||
useMux,
|
||||
});
|
||||
sessions.push(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
it('carries the thread id from construction', () => {
|
||||
expect(makeSession(true).claudeSessionId).toBe(THREAD_ID);
|
||||
});
|
||||
|
||||
it('still carries it after starting under mux', async () => {
|
||||
const session = makeSession(true);
|
||||
await session.startInteractive();
|
||||
expect(session.claudeSessionId).toBe(THREAD_ID);
|
||||
});
|
||||
|
||||
it('refuses to start without mux at all, so the mux path is the only one to cover', async () => {
|
||||
// codex declares `requiresMux`, so there is no direct-PTY codex session for
|
||||
// the third reset point to run against on its own — the assertion above is
|
||||
// the whole surface.
|
||||
await expect(makeSession(false).startInteractive()).rejects.toThrow(/require tmux/i);
|
||||
});
|
||||
|
||||
it('a fresh codex session keeps the Codeman id, having no thread of its own', async () => {
|
||||
mkdirSync(workingDir, { recursive: true });
|
||||
const session = new Session({ workingDir, mode: 'codex', mux: new TmuxManager(), useMux: true });
|
||||
sessions.push(session);
|
||||
|
||||
await session.startInteractive();
|
||||
|
||||
// Nothing to alias to yet — codex has not written the rollout. Such a
|
||||
// session is folded from the other side, by originator (codexThreadBySessionId).
|
||||
expect(session.claudeSessionId).toBe(session.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Reading codex's own rollout store for Past Sessions rows.
|
||||
*
|
||||
* Three of these assertions exist because the obvious implementation was
|
||||
* measured to be wrong against real files (codex CLI 0.152.1):
|
||||
*
|
||||
* - codex 0.152.1 emits NO `event_msg`/`user_message` rows at all. It writes
|
||||
* `event_msg`/`item_completed` carrying an `item.type` of `UserMessage`
|
||||
* instead, so a scanner that knew only the older shape found a prompt for
|
||||
* July rollouts and nothing for September ones.
|
||||
* - the `response_item` fallback sees codex's injected context, and on a real
|
||||
* store the FIRST such row is the repository's AGENTS.md every time. Taking
|
||||
* it literally titled every row with the same instructions block.
|
||||
* - codex spawns sub-agent threads into the same store, stamped
|
||||
* `thread_source: 'subagent'`. On the store this was built against they
|
||||
* outnumbered the threads a person can actually resume.
|
||||
*/
|
||||
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
|
||||
import { appendFile, mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
import {
|
||||
scanCodexSessionsHistory,
|
||||
codexThreadBySessionId,
|
||||
__clearCodexIdentityCache,
|
||||
} from '../src/codex-transcript.js';
|
||||
|
||||
let home: string;
|
||||
let prevCodexHome: string | undefined;
|
||||
|
||||
/** A rollout's opening line, as codex writes it. */
|
||||
const sessionMeta = (opts: { id: string; cwd?: string; threadSource?: string; originator?: string }) =>
|
||||
JSON.stringify({
|
||||
timestamp: '2026-09-02T07:05:37.421Z',
|
||||
type: 'session_meta',
|
||||
payload: {
|
||||
id: opts.id,
|
||||
session_id: opts.id,
|
||||
...(opts.cwd ? { cwd: opts.cwd } : {}),
|
||||
originator: opts.originator ?? 'codex-tui',
|
||||
...(opts.threadSource ? { thread_source: opts.threadSource } : {}),
|
||||
// The real thing embeds full base instructions here; padded so the file
|
||||
// clears the size floor and exercises the head window.
|
||||
base_instructions: { text: 'x'.repeat(500) },
|
||||
},
|
||||
});
|
||||
|
||||
/** codex 0.152.1's user-input row. */
|
||||
const itemCompletedUser = (text: string) =>
|
||||
JSON.stringify({
|
||||
type: 'event_msg',
|
||||
payload: { type: 'item_completed', item: { type: 'UserMessage', id: 'i1', content: [{ type: 'text', text }] } },
|
||||
});
|
||||
|
||||
/** The shape older codex versions wrote. */
|
||||
const legacyUserMessage = (text: string) =>
|
||||
JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: text } });
|
||||
|
||||
/** The last-resort shape, which also carries codex's injected context. */
|
||||
const responseItemUser = (text: string) =>
|
||||
JSON.stringify({ type: 'response_item', payload: { role: 'user', content: [{ type: 'text', text }] } });
|
||||
|
||||
async function writeRollout(id: string, lines: string[], mtime?: Date): Promise<string> {
|
||||
const dir = join(home, 'sessions', '2026', '09', '02');
|
||||
await mkdir(dir, { recursive: true });
|
||||
const path = join(dir, `rollout-2026-09-02T09-05-37-${id}.jsonl`);
|
||||
await writeFile(path, lines.join('\n') + '\n', 'utf-8');
|
||||
if (mtime) await utimes(path, mtime, mtime);
|
||||
return path;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
home = await mkdtemp(join(tmpdir(), 'codex-transcript-'));
|
||||
prevCodexHome = process.env.CODEX_HOME;
|
||||
process.env.CODEX_HOME = home;
|
||||
__clearCodexIdentityCache();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (prevCodexHome === undefined) delete process.env.CODEX_HOME;
|
||||
else process.env.CODEX_HOME = prevCodexHome;
|
||||
await rm(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('scanCodexSessionsHistory', () => {
|
||||
it('returns nothing when the store does not exist', async () => {
|
||||
process.env.CODEX_HOME = join(home, 'nope');
|
||||
expect(await scanCodexSessionsHistory()).toEqual([]);
|
||||
});
|
||||
|
||||
it('reads the thread id, working directory and opening prompt', async () => {
|
||||
await writeRollout('01a060f0-0361-7f91-abde-b283020db0d7', [
|
||||
sessionMeta({ id: '01a060f0-0361-7f91-abde-b283020db0d7', cwd: '/repo/one' }),
|
||||
itemCompletedUser('Continue the audit log architecture'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].sessionId).toBe('01a060f0-0361-7f91-abde-b283020db0d7');
|
||||
expect(rows[0].workingDir).toBe('/repo/one');
|
||||
expect(rows[0].firstPrompt).toBe('Continue the audit log architecture');
|
||||
expect(rows[0].sizeBytes).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('still reads the prompt shape older codex versions wrote', async () => {
|
||||
await writeRollout('11111111-1111-7111-8111-111111111111', [
|
||||
sessionMeta({ id: '11111111-1111-7111-8111-111111111111', cwd: '/repo/two' }),
|
||||
legacyUserMessage('$pr-review-comment-fixer 349'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].firstPrompt).toBe('$pr-review-comment-fixer 349');
|
||||
});
|
||||
|
||||
it('skips injected context when only the fallback shape is present', async () => {
|
||||
await writeRollout('22222222-2222-7222-8222-222222222222', [
|
||||
sessionMeta({ id: '22222222-2222-7222-8222-222222222222', cwd: '/repo/three' }),
|
||||
responseItemUser('# AGENTS.md instructions for /repo/three\n<INSTRUCTIONS> ...'),
|
||||
responseItemUser('<environment_context>cwd=/repo/three</environment_context>'),
|
||||
responseItemUser('Replace PanicOnError with Require().NoError'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].firstPrompt).toBe('Replace PanicOnError with Require().NoError');
|
||||
});
|
||||
|
||||
it('prefers a real user row over the injection-prone fallback', async () => {
|
||||
await writeRollout('33333333-3333-7333-8333-333333333333', [
|
||||
sessionMeta({ id: '33333333-3333-7333-8333-333333333333', cwd: '/repo/four' }),
|
||||
responseItemUser('Some earlier response_item row'),
|
||||
itemCompletedUser('The prompt the user actually typed'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].firstPrompt).toBe('The prompt the user actually typed');
|
||||
});
|
||||
|
||||
it('leaves out sub-agent threads, which nobody resumes', async () => {
|
||||
await writeRollout('44444444-4444-7444-8444-444444444444', [
|
||||
sessionMeta({ id: '44444444-4444-7444-8444-444444444444', cwd: '/repo/five' }),
|
||||
itemCompletedUser('a real conversation'),
|
||||
]);
|
||||
await writeRollout('55555555-5555-7555-8555-555555555555', [
|
||||
sessionMeta({ id: '55555555-5555-7555-8555-555555555555', cwd: '/repo/five', threadSource: 'subagent' }),
|
||||
itemCompletedUser('work codex gave itself'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows.map((r) => r.sessionId)).toEqual(['44444444-4444-7444-8444-444444444444']);
|
||||
});
|
||||
|
||||
it('reports the most recent prompt as well as the first', async () => {
|
||||
await writeRollout('66666666-6666-7666-8666-666666666666', [
|
||||
sessionMeta({ id: '66666666-6666-7666-8666-666666666666', cwd: '/repo/six' }),
|
||||
itemCompletedUser('the opening question'),
|
||||
itemCompletedUser('a follow-up'),
|
||||
itemCompletedUser('the latest thing asked'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].firstPrompt).toBe('the opening question');
|
||||
expect(rows[0].lastPrompt).toBe('the latest thing asked');
|
||||
});
|
||||
|
||||
it('orders rows newest first', async () => {
|
||||
await writeRollout(
|
||||
'77777777-7777-7777-8777-777777777777',
|
||||
[sessionMeta({ id: '77777777-7777-7777-8777-777777777777', cwd: '/repo/old' }), itemCompletedUser('older')],
|
||||
new Date('2026-08-01T00:00:00Z')
|
||||
);
|
||||
await writeRollout(
|
||||
'88888888-8888-7888-8888-888888888888',
|
||||
[sessionMeta({ id: '88888888-8888-7888-8888-888888888888', cwd: '/repo/new' }), itemCompletedUser('newer')],
|
||||
new Date('2026-09-05T00:00:00Z')
|
||||
);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows.map((r) => r.workingDir)).toEqual(['/repo/new', '/repo/old']);
|
||||
});
|
||||
|
||||
it('ignores a file too short to hold a session_meta line', async () => {
|
||||
const dir = join(home, 'sessions', '2026', '09', '02');
|
||||
await mkdir(dir, { recursive: true });
|
||||
await writeFile(join(dir, 'rollout-2026-09-02T09-05-37-short.jsonl'), '{}\n', 'utf-8');
|
||||
|
||||
expect(await scanCodexSessionsHistory()).toEqual([]);
|
||||
});
|
||||
|
||||
it('survives a rollout whose lines are malformed', async () => {
|
||||
await writeRollout('99999999-9999-7999-8999-999999999999', [
|
||||
sessionMeta({ id: '99999999-9999-7999-8999-999999999999', cwd: '/repo/seven' }),
|
||||
'{not json at all',
|
||||
itemCompletedUser('still found me'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].firstPrompt).toBe('still found me');
|
||||
});
|
||||
|
||||
it('reports the originator, which is how a fresh pane finds its own rollout', async () => {
|
||||
await writeRollout('bbbbbbbb-bbbb-7bbb-8bbb-bbbbbbbbbbbb', [
|
||||
sessionMeta({
|
||||
id: 'bbbbbbbb-bbbb-7bbb-8bbb-bbbbbbbbbbbb',
|
||||
cwd: '/repo/nine',
|
||||
originator: 'codeman_2f1c9a44-1111-2222-3333-444455556666',
|
||||
}),
|
||||
itemCompletedUser('hello'),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].originator).toBe('codeman_2f1c9a44-1111-2222-3333-444455556666');
|
||||
});
|
||||
|
||||
it('drops a rollout that records no working directory', async () => {
|
||||
// Emitting workingDir: '' would make a click post an empty directory.
|
||||
await writeRollout('cccccccc-cccc-7ccc-8ccc-cccccccccccc', [
|
||||
sessionMeta({ id: 'cccccccc-cccc-7ccc-8ccc-cccccccccccc' }),
|
||||
itemCompletedUser('nowhere to resume into'),
|
||||
]);
|
||||
|
||||
expect(await scanCodexSessionsHistory()).toEqual([]);
|
||||
});
|
||||
|
||||
it('picks up a prompt written after an earlier scan saw none', async () => {
|
||||
// The bug this pins: the identity cache was written as soon as the thread id
|
||||
// was known, but codex writes the first UserMessage only when the user
|
||||
// submits. Any scan in that window — the home screen, the command palette,
|
||||
// the search-index refresh — pinned `firstPrompt: undefined` until restart.
|
||||
const id = 'dddddddd-dddd-7ddd-8ddd-dddddddddddd';
|
||||
const path = await writeRollout(id, [sessionMeta({ id, cwd: '/repo/ten' })]);
|
||||
|
||||
const before = await scanCodexSessionsHistory();
|
||||
expect(before).toHaveLength(1);
|
||||
expect(before[0].firstPrompt).toBeUndefined();
|
||||
|
||||
await appendFile(path, itemCompletedUser('the prompt, typed a moment later') + '\n', 'utf-8');
|
||||
|
||||
const after = await scanCodexSessionsHistory();
|
||||
expect(after[0].firstPrompt).toBe('the prompt, typed a moment later');
|
||||
});
|
||||
|
||||
it('does not spend the lastPrompt budget on rollouts it never returns', async () => {
|
||||
// The budget used to count file index, so a store whose newest files are all
|
||||
// sub-agent threads exhausted it before the first row that needed it.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await writeRollout(
|
||||
`eeeeeeee-eeee-7eee-8eee-00000000000${i}`,
|
||||
[
|
||||
sessionMeta({ id: `eeeeeeee-eeee-7eee-8eee-00000000000${i}`, cwd: '/repo/sub', threadSource: 'subagent' }),
|
||||
itemCompletedUser('subagent work'),
|
||||
],
|
||||
new Date('2026-09-05T00:00:00Z')
|
||||
);
|
||||
}
|
||||
await writeRollout(
|
||||
'ffffffff-ffff-7fff-8fff-ffffffffffff',
|
||||
[
|
||||
sessionMeta({ id: 'ffffffff-ffff-7fff-8fff-ffffffffffff', cwd: '/repo/real' }),
|
||||
itemCompletedUser('opening'),
|
||||
itemCompletedUser('the latest thing asked'),
|
||||
],
|
||||
new Date('2026-09-04T00:00:00Z')
|
||||
);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].lastPrompt).toBe('the latest thing asked');
|
||||
});
|
||||
|
||||
it('collapses a long prompt to a single capped line', async () => {
|
||||
await writeRollout('aaaaaaaa-aaaa-7aaa-8aaa-aaaaaaaaaaaa', [
|
||||
sessionMeta({ id: 'aaaaaaaa-aaaa-7aaa-8aaa-aaaaaaaaaaaa', cwd: '/repo/eight' }),
|
||||
itemCompletedUser('line one\nline two\n' + 'y'.repeat(500)),
|
||||
]);
|
||||
|
||||
const rows = await scanCodexSessionsHistory();
|
||||
expect(rows[0].firstPrompt).not.toContain('\n');
|
||||
expect(rows[0].firstPrompt!.length).toBeLessThanOrEqual(201);
|
||||
expect(rows[0].firstPrompt!.endsWith('…')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('codexThreadBySessionId', () => {
|
||||
const row = (sessionId: string, originator?: string) =>
|
||||
({ sessionId, originator, workingDir: '/w', sizeBytes: 1, lastModified: '2026-09-02T00:00:00.000Z' }) as never;
|
||||
|
||||
it('maps a Codeman-spawned pane to the thread it is writing', () => {
|
||||
const map = codexThreadBySessionId([row('thread-a', 'codeman_sess-1')]);
|
||||
expect(map.get('sess-1')).toBe('thread-a');
|
||||
});
|
||||
|
||||
it('ignores a rollout codex started on its own', () => {
|
||||
expect(codexThreadBySessionId([row('thread-a', 'codex-tui')]).size).toBe(0);
|
||||
expect(codexThreadBySessionId([row('thread-a', undefined)]).size).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps the newest rollout when a pane has several', () => {
|
||||
// `/new` inside the codex TUI leaves the pane's originator on more than one
|
||||
// rollout; the pane is on the most recent, and rows arrive newest-first.
|
||||
const map = codexThreadBySessionId([row('thread-new', 'codeman_sess-1'), row('thread-old', 'codeman_sess-1')]);
|
||||
expect(map.get('sess-1')).toBe('thread-new');
|
||||
});
|
||||
});
|
||||
@@ -397,11 +397,13 @@ describe('Session Manager unified list', () => {
|
||||
expect(app.selectSession).toHaveBeenCalledWith('sess-alpha');
|
||||
expect(app.resumeHistorySession).not.toHaveBeenCalled();
|
||||
|
||||
// History row → resume by conversation UUID.
|
||||
// History row → resume by conversation UUID. The trailing `resumeId` is the
|
||||
// CLI's own thread token, which only a non-claude transcript scanner sets;
|
||||
// a Claude row carries none, so it arrives undefined here.
|
||||
const [historyRecord, , historyOptions] = app._buildHistoryItem.mock.calls[1];
|
||||
expect(historyRecord).toMatchObject({ sessionId: 'conv-uuid-1', sizeBytes: 2048, firstPrompt: 'old prompt' });
|
||||
historyOptions.onActivate();
|
||||
expect(app.resumeHistorySession).toHaveBeenCalledWith('conv-uuid-1', '/repo/old', undefined, undefined);
|
||||
expect(app.resumeHistorySession).toHaveBeenCalledWith('conv-uuid-1', '/repo/old', undefined, undefined, undefined);
|
||||
});
|
||||
|
||||
it('surfaces an error message instead of an empty list when the endpoint fails', async () => {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* @fileoverview A detached session's pane is sized by its own window, not by
|
||||
* the dashboard.
|
||||
*
|
||||
* One PTY holds one size. When a session is popped out, the dashboard keeps it
|
||||
* active and keeps measuring it, but the dashboard's terminal is narrower than
|
||||
* the popup because the session rail takes width the popup does not have. Both
|
||||
* windows sizing the same pane makes the CLI draw frames that fit neither, and
|
||||
* the popup shows the result as a garbled frame.
|
||||
*
|
||||
* `sendResize` therefore returns early for a session this window has marked
|
||||
* detached, and the debounced window-resize handler skips it for the same
|
||||
* reason. A solo window is exempt: it IS the owner. `_maybeRefetchFullHistory`
|
||||
* already stood aside on the same condition, so this follows a rule the code
|
||||
* had already established.
|
||||
*
|
||||
* Loaded via `vm` with a stubbed context (no jsdom — jsdom is broken on this
|
||||
* box; see connection-indicator.test.ts), the same way terminal-buffer-flush
|
||||
* extracts the real mixin methods from terminal-ui.js.
|
||||
*/
|
||||
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';
|
||||
|
||||
/** The mixin runs inside the vm context, so its `fetch` must live there too. */
|
||||
let currentFetch: ReturnType<typeof vi.fn> = vi.fn();
|
||||
|
||||
function loadTerminalMixin(): Record<string, unknown> {
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
|
||||
const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, 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(), innerWidth: 1600 },
|
||||
document: { addEventListener: vi.fn() },
|
||||
fetch: (...args: unknown[]) => currentFetch(...args),
|
||||
});
|
||||
vm.runInContext(source, context);
|
||||
return FakeCodemanApp.prototype;
|
||||
}
|
||||
|
||||
const mixin = loadTerminalMixin();
|
||||
|
||||
const SESSION = 'session-A';
|
||||
|
||||
function makeApp(overrides: Record<string, unknown> = {}) {
|
||||
const fetchMock = vi.fn(async () => ({ json: async () => ({ data: { changed: true } }) }));
|
||||
currentFetch = fetchMock;
|
||||
const app = {
|
||||
sendResize: mixin.sendResize,
|
||||
getTerminalDimensions: () => ({ cols: 120, rows: 40 }),
|
||||
fitAddon: { fit: vi.fn() },
|
||||
detachedSessions: new Set<string>(),
|
||||
isSoloWindow: false,
|
||||
_lastResizeDims: null as { cols: number; rows: number } | null,
|
||||
_wsReady: false,
|
||||
_wsSessionId: null as string | null,
|
||||
...overrides,
|
||||
} as Record<string, unknown> & { sendResize: (id: string, o?: object) => Promise<boolean> };
|
||||
return { app, fetchMock };
|
||||
}
|
||||
|
||||
describe('detached sessions own their pane size', () => {
|
||||
it('the dashboard does not resize a session showing in its own window', async () => {
|
||||
const { app, fetchMock } = makeApp();
|
||||
(app.detachedSessions as Set<string>).add(SESSION);
|
||||
const changed = await app.sendResize(SESSION);
|
||||
|
||||
expect(changed).toBe(false);
|
||||
// No request: the popup's size stands on the server.
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
// The LOCAL fit still runs, so the dashboard's own xterm stays correct and
|
||||
// tab-rail-resize's single settle-time refit is not swallowed. Same line the
|
||||
// mobile-keyboard guard draws: withhold the send, never the reflow.
|
||||
expect((app.fitAddon as { fit: ReturnType<typeof vi.fn> }).fit).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('the solo window still sizes the session it displays', async () => {
|
||||
const { app, fetchMock } = makeApp({ isSoloWindow: true });
|
||||
(app.detachedSessions as Set<string>).add(SESSION);
|
||||
await app.sendResize(SESSION);
|
||||
|
||||
// The popup is the owner, so being marked detached must not stop it.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect((app.fitAddon as { fit: ReturnType<typeof vi.fn> }).fit).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('the dashboard resizes a session that is not detached', async () => {
|
||||
const { app, fetchMock } = makeApp();
|
||||
await app.sendResize(SESSION);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* `_redock` lives on the CodemanApp class rather than the terminal mixin, so it
|
||||
* needs app.js loaded. Same `vm` approach as terminal-flush-budget.test.ts.
|
||||
*/
|
||||
function loadAppClass() {
|
||||
const dir = resolve(import.meta.dirname, '../src/web/public');
|
||||
const context = vm.createContext({
|
||||
console: { ...console, log: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
performance: { now: () => 0 },
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: { OPEN: 1 },
|
||||
fetch: vi.fn(),
|
||||
document: { addEventListener: vi.fn(), getElementById: () => null, querySelector: () => null },
|
||||
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
MobileDetection: { isTouchDevice: () => false },
|
||||
});
|
||||
const constants = readFileSync(resolve(dir, 'constants.js'), 'utf8');
|
||||
const appSource = readFileSync(resolve(dir, 'app.js'), 'utf8');
|
||||
vm.runInContext(`${constants}\n${appSource}\nglobalThis.__CodemanApp = CodemanApp;`, context);
|
||||
return (context as { __CodemanApp: { prototype: Record<string, unknown> } }).__CodemanApp;
|
||||
}
|
||||
|
||||
describe('redock takes the sizing back', () => {
|
||||
const CodemanApp = loadAppClass();
|
||||
|
||||
function makeDashboard(activeSessionId: string | null) {
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
|
||||
app.detachedSessions = new Set([SESSION]);
|
||||
app.detachedWindows = new Map();
|
||||
app._detachWatchTimers = new Map();
|
||||
app._redockGrace = new Map();
|
||||
app._detachOrphanStrikes = new Map();
|
||||
app.sessions = new Map([[SESSION, { id: SESSION }]]);
|
||||
app.activeSessionId = activeSessionId;
|
||||
app._lastResizeDims = { cols: 120, rows: 40 };
|
||||
app.$ = () => null;
|
||||
app.sendResize = vi.fn(() => Promise.resolve(true));
|
||||
return app;
|
||||
}
|
||||
|
||||
it('clears the stale dimensions so the next send reports truthfully', () => {
|
||||
// The popup sized the pane while it owned the session, so this window's one
|
||||
// global record of "what the PTY holds" is wrong. Left in place, the next
|
||||
// sendResize returns "unchanged" and selectSession skips its redraw wait.
|
||||
const app = makeDashboard(SESSION);
|
||||
app._redock(SESSION);
|
||||
expect(app._lastResizeDims).toBeNull();
|
||||
});
|
||||
|
||||
it('clears them even when the redocked session is not the active one', () => {
|
||||
// Pop out A, switch to B, close the popup: no resize is due, but the stale
|
||||
// record still has to go or selecting A later lies about it.
|
||||
const app = makeDashboard('some-other-session');
|
||||
app._redock(SESSION);
|
||||
expect(app._lastResizeDims).toBeNull();
|
||||
expect(app.sendResize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-asserts this window size for the session it is showing', () => {
|
||||
const app = makeDashboard(SESSION);
|
||||
app._redock(SESSION);
|
||||
expect(app.sendResize).toHaveBeenCalledWith(SESSION, { force: true });
|
||||
// Un-marked first, or the yield in sendResize would swallow the re-assert.
|
||||
expect(app.detachedSessions.has(SESSION)).toBe(false);
|
||||
});
|
||||
|
||||
it('sends nothing for a session that is gone', () => {
|
||||
// _onSessionDeleted redocks before cleanup, so the id can already be dead;
|
||||
// the resize would be a guaranteed 404.
|
||||
const app = makeDashboard(SESSION);
|
||||
app.sessions.delete(SESSION);
|
||||
app._redock(SESSION);
|
||||
expect(app.sendResize).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* @fileoverview Static guards for the entrance-animation styles (App Settings →
|
||||
* Appearance → Entrance Animations, plus the `?animlab=1` picker).
|
||||
*
|
||||
* A style is FOUR things that have to line up, and any one of them missing fails
|
||||
* silently rather than loudly: the entry in the style array in
|
||||
* entrance-animations.js (which is what the lab lists and what `_styleDuration`
|
||||
* reads), the `html[data-*-anim="<key>"]` rule in styles.css, the @keyframes
|
||||
* block that rule names, and — for a style that belongs to a theme — the theme's
|
||||
* `<option>` in index.html. A style with no CSS behind it renders as "the
|
||||
* animation silently does nothing"; a rule naming a keyframe block that does not
|
||||
* exist behaves the same way.
|
||||
*
|
||||
* The terminal pane carries an extra rule of its own, and it is the one with
|
||||
* teeth: xterm's FitAddon derives rows+cols from getComputedStyle(parent)
|
||||
* .width/height, so a terminal keyframe that animates a box-model property would
|
||||
* resize the PTY mid-animation. Only paint-level properties are allowed there.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const animSource = readFileSync(resolve('src/web/public/entrance-animations.js'), 'utf8');
|
||||
const stylesSource = readFileSync(resolve('src/web/public/styles.css'), 'utf8');
|
||||
const indexSource = readFileSync(resolve('src/web/public/index.html'), 'utf8');
|
||||
|
||||
/** Surfaces, keyed by the `data-*-anim` attribute their styles are selected by. */
|
||||
const SURFACES = [
|
||||
{ attr: 'tab', array: 'TAB_ANIM_STYLES', selector: '.session-tab.tab-enter' },
|
||||
{ attr: 'win', array: 'WIN_ANIM_STYLES', selector: '.subagent-window.win-enter' },
|
||||
{ attr: 'line', array: 'LINE_ANIM_STYLES', selector: '.connection-line.line-enter' },
|
||||
{ attr: 'term', array: 'TERM_ANIM_STYLES', selector: '.terminal-container.term-enter' },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Styles with no CSS of their own, by design: `off` means "do nothing" and `fly`
|
||||
* is the pre-existing JS transition in subagent-windows.js, which deliberately
|
||||
* skips the `win-enter` class entirely.
|
||||
*/
|
||||
const CSS_LESS_STYLES = new Set(['off', 'fly']);
|
||||
|
||||
function styleKeys(arrayName: string): string[] {
|
||||
const start = animSource.indexOf(`const ${arrayName} = [`);
|
||||
expect(start, `${arrayName} not found`).toBeGreaterThan(-1);
|
||||
const body = animSource.slice(start, animSource.indexOf('];', start));
|
||||
return [...body.matchAll(/\{ key: '([^']+)'/g)].map((m) => m[1]);
|
||||
}
|
||||
|
||||
function themes(): { key: string; tab: string; win: string; line: string; term: string }[] {
|
||||
const start = animSource.indexOf('const ANIM_THEMES = [');
|
||||
const body = animSource.slice(start, animSource.indexOf('];', start));
|
||||
return [
|
||||
...body.matchAll(/\{ key: '([^']+)'.*?tab: '([^']+)', win: '([^']+)', line: '([^']+)', term: '([^']+)' \}/g),
|
||||
].map((m) => ({ key: m[1], tab: m[2], win: m[3], line: m[4], term: m[5] }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every `animation-name:` a `html[data-<attr>-anim="<key>"]` block asks for,
|
||||
* tagged with whether it runs on the element itself or on its ::before overlay.
|
||||
* The distinction matters for the terminal: the FitAddon rule below binds to the
|
||||
* container, while ::before is a throwaway wash that may animate anything.
|
||||
*/
|
||||
function animationNamesFor(attr: string, key: string): { name: string; onPseudo: boolean }[] {
|
||||
const rules = [...stylesSource.matchAll(new RegExp(`html\\[data-${attr}-anim="${key}"\\]([^{]*)\\{([^}]*)\\}`, 'g'))];
|
||||
return rules.flatMap((rule) =>
|
||||
[...rule[2].matchAll(/animation-name:\s*([\w-]+);/g)].map((m) => ({
|
||||
name: m[1],
|
||||
onPseudo: rule[1].includes('::before'),
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
function keyframeBody(name: string): string | null {
|
||||
const start = stylesSource.indexOf(`@keyframes ${name} {`);
|
||||
if (start === -1) return null;
|
||||
return stylesSource.slice(start, stylesSource.indexOf('\n}', start));
|
||||
}
|
||||
|
||||
describe('entrance animation styles', () => {
|
||||
for (const surface of SURFACES) {
|
||||
describe(`${surface.attr} surface`, () => {
|
||||
it('backs every style with a rule that names a keyframe block that exists', () => {
|
||||
for (const key of styleKeys(surface.array)) {
|
||||
if (CSS_LESS_STYLES.has(key)) {
|
||||
expect(stylesSource).not.toContain(`html[data-${surface.attr}-anim="${key}"]`);
|
||||
continue;
|
||||
}
|
||||
const names = animationNamesFor(surface.attr, key);
|
||||
expect(names.length, `no animation-name for ${surface.attr}/${key}`).toBeGreaterThan(0);
|
||||
for (const { name } of names) {
|
||||
expect(keyframeBody(name), `@keyframes ${name} missing`).not.toBeNull();
|
||||
}
|
||||
// The style has to reach the element the surface actually animates,
|
||||
// not just any selector carrying the attribute.
|
||||
expect(stylesSource).toContain(`html[data-${surface.attr}-anim="${key}"] ${surface.selector}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
it('ships the blur style on all four surfaces', () => {
|
||||
for (const surface of SURFACES) expect(styleKeys(surface.array)).toContain('blur');
|
||||
});
|
||||
|
||||
it('gives every theme an <option> and only styles that exist', () => {
|
||||
for (const theme of themes()) {
|
||||
expect(indexSource, `no <option value="${theme.key}">`).toContain(`<option value="${theme.key}">`);
|
||||
for (const surface of SURFACES) {
|
||||
expect(styleKeys(surface.array), `theme ${theme.key} names an unknown ${surface.attr} style`).toContain(
|
||||
theme[surface.attr]
|
||||
);
|
||||
}
|
||||
}
|
||||
// 'custom' is a readout of a lab mix, never a theme you can select into.
|
||||
expect(indexSource).toContain('<option value="custom">');
|
||||
expect(themes().map((t) => t.key)).not.toContain('custom');
|
||||
});
|
||||
|
||||
it('keeps every entrance under the reduced-motion kill switch', () => {
|
||||
const start = stylesSource.indexOf('@media (prefers-reduced-motion: reduce) {\n .session-tab.tab-enter,');
|
||||
expect(start, 'the entrance reduced-motion block moved or was renamed').toBeGreaterThan(-1);
|
||||
const block = stylesSource.slice(
|
||||
start,
|
||||
stylesSource.indexOf('\n}', stylesSource.indexOf('animation: none', start))
|
||||
);
|
||||
for (const surface of SURFACES) expect(block).toContain(surface.selector);
|
||||
});
|
||||
|
||||
/**
|
||||
* ⚠ The FitAddon rule. It reads getComputedStyle(parent).width/height, i.e. the
|
||||
* untransformed LAYOUT box, so paint-level properties are invisible to it and a
|
||||
* box-model property here would resize the PTY mid-animation.
|
||||
*/
|
||||
it('animates only paint-level properties on the terminal pane', () => {
|
||||
const allowed = new Set(['opacity', 'transform', 'clip-path', 'filter']);
|
||||
for (const key of styleKeys('TERM_ANIM_STYLES')) {
|
||||
if (CSS_LESS_STYLES.has(key)) continue;
|
||||
for (const { name, onPseudo } of animationNamesFor('term', key)) {
|
||||
if (onPseudo) continue; // a wash over the pane, it has no layout of its own
|
||||
const body = keyframeBody(name);
|
||||
expect(body).not.toBeNull();
|
||||
for (const [, prop] of (body as string).matchAll(/(?:\{|;)\s*([a-z-]+):/g)) {
|
||||
expect(allowed.has(prop), `@keyframes ${name} animates ${prop} on the terminal pane`).toBe(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The `blur` line entrance animates `filter`, and a keyframe listing only the
|
||||
* blur would drop each line's own glow for the length of the run and pop it
|
||||
* back at the end. Both frames say `blur(N) var(--line-glow)` so the function
|
||||
* lists match and interpolate, which only works while both kinds of line
|
||||
* actually define that variable.
|
||||
*/
|
||||
it('routes both kinds of connection line through --line-glow', () => {
|
||||
for (const selector of ['.connection-line {', '.connection-line.lineage-line {']) {
|
||||
const start = stylesSource.indexOf(selector);
|
||||
expect(start, `${selector} not found`).toBeGreaterThan(-1);
|
||||
const block = stylesSource.slice(start, stylesSource.indexOf('\n}', start));
|
||||
expect(block, `${selector} must define --line-glow`).toContain('--line-glow:');
|
||||
expect(block, `${selector} must apply it`).toContain('filter: var(--line-glow);');
|
||||
}
|
||||
const blur = keyframeBody('line-enter-blur') as string;
|
||||
expect(blur).not.toBeNull();
|
||||
expect(blur.match(/var\(--line-glow\)/g)?.length).toBe(2);
|
||||
// The 100% frame deliberately omits opacity so the endpoint comes from the
|
||||
// element's own resting value: 0.9 on a subagent line, 0.72 on a lineage
|
||||
// line, 0.95 on a working one. Pinning a number here snaps three of them.
|
||||
expect(blur).toMatch(/100%\s*\{\s*filter:[^}]*\}/);
|
||||
expect(blur).not.toMatch(/100%\s*\{[^}]*opacity/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* @fileoverview Unit tests for the Ctrl+V paste trap in image-input.js.
|
||||
*
|
||||
* `_handleImagePaste()` appends a hidden contenteditable div (the "paste
|
||||
* trap"), focuses it, and reads the clipboard out of the paste event the
|
||||
* browser delivers there. Two things can deliver that event for a single
|
||||
* Ctrl+V: the `document.execCommand('paste')` the function issues itself, and
|
||||
* the keydown's own default action, which still runs because xterm's custom key
|
||||
* handler returns false without cancelling the event. A browser that honours
|
||||
* execCommand('paste') therefore fires the trap's listener twice, and the
|
||||
* clipboard text used to reach the PTY twice with it — while right-click →
|
||||
* Paste, which involves no keydown, stayed correct.
|
||||
*
|
||||
* Loads the browser module into a vm sandbox with a fake document, so the tests
|
||||
* drive the trap's listener directly rather than through a real browser.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
interface TrapListener {
|
||||
(e: Record<string, unknown>): void;
|
||||
}
|
||||
|
||||
interface FakeTrap {
|
||||
contentEditable: string;
|
||||
style: { cssText: string };
|
||||
parentNode: unknown;
|
||||
focus: () => void;
|
||||
addEventListener: (ev: string, fn: TrapListener) => void;
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
/** Fire a paste event on the trap the last _handleImagePaste() call created. */
|
||||
firePaste: (payload: { text?: string; images?: string[] }) => void;
|
||||
/** Text handed to xterm's terminal.paste(), one entry per call. */
|
||||
pastedText: string[];
|
||||
/** Image batches handed to _uploadAndInsertImages(), one entry per call. */
|
||||
uploadedBatches: Array<Array<{ type: string }>>;
|
||||
/** How many trap divs are still attached to the fake body. */
|
||||
attachedTraps: () => number;
|
||||
runTimers: () => void;
|
||||
}
|
||||
|
||||
function loadPasteHarness(): Harness {
|
||||
const traps: FakeTrap[] = [];
|
||||
const listeners: TrapListener[] = [];
|
||||
const attached = new Set<FakeTrap>();
|
||||
const timers: Array<() => void> = [];
|
||||
|
||||
const documentObj = {
|
||||
createElement: (): FakeTrap => {
|
||||
const trap: FakeTrap = {
|
||||
contentEditable: '',
|
||||
style: { cssText: '' },
|
||||
parentNode: null,
|
||||
focus: () => {},
|
||||
addEventListener: (ev: string, fn: TrapListener) => {
|
||||
if (ev === 'paste') listeners.push(fn);
|
||||
},
|
||||
};
|
||||
traps.push(trap);
|
||||
return trap;
|
||||
},
|
||||
body: {
|
||||
appendChild: (el: FakeTrap) => {
|
||||
attached.add(el);
|
||||
el.parentNode = documentObj.body;
|
||||
},
|
||||
removeChild: (el: FakeTrap) => {
|
||||
attached.delete(el);
|
||||
el.parentNode = null;
|
||||
},
|
||||
},
|
||||
// A browser that honours the command fires the trap's paste listener from
|
||||
// here as well; the tests model that by firing the listener twice.
|
||||
execCommand: () => true,
|
||||
getElementById: () => null,
|
||||
};
|
||||
|
||||
const context = vm.createContext({
|
||||
window: {},
|
||||
document: documentObj,
|
||||
setTimeout: (fn: () => void) => {
|
||||
timers.push(fn);
|
||||
return timers.length;
|
||||
},
|
||||
clearTimeout: () => {},
|
||||
console,
|
||||
});
|
||||
|
||||
vm.runInContext('class CodemanApp {}', context);
|
||||
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/image-input.js'), 'utf8');
|
||||
vm.runInContext(src, context, { filename: 'image-input.js' });
|
||||
const CodemanApp = vm.runInContext('CodemanApp', context) as new () => Record<string, unknown>;
|
||||
|
||||
const pastedText: string[] = [];
|
||||
const uploadedBatches: Array<Array<{ type: string }>> = [];
|
||||
const app = new CodemanApp();
|
||||
app.activeSessionId = 'session-1';
|
||||
app.terminal = {
|
||||
paste: (text: string) => pastedText.push(text),
|
||||
focus: () => {},
|
||||
};
|
||||
app._uploadAndInsertImages = (files: Array<{ type: string }>) => {
|
||||
uploadedBatches.push(Array.from(files));
|
||||
};
|
||||
app.showToast = () => {};
|
||||
|
||||
(app._handleImagePaste as () => void).call(app);
|
||||
|
||||
return {
|
||||
firePaste({ text = '', images = [] }) {
|
||||
const items = images.map((type) => ({ type, getAsFile: () => ({ type }) }));
|
||||
const event = {
|
||||
clipboardData: {
|
||||
items,
|
||||
getData: () => text,
|
||||
},
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
};
|
||||
for (const fn of listeners) fn(event);
|
||||
},
|
||||
pastedText,
|
||||
uploadedBatches,
|
||||
attachedTraps: () => attached.size,
|
||||
runTimers: () => {
|
||||
const pending = timers.splice(0, timers.length);
|
||||
for (const fn of pending) fn();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('Ctrl+V paste trap', () => {
|
||||
it('sends clipboard text to the terminal once for a single paste event', () => {
|
||||
const h = loadPasteHarness();
|
||||
|
||||
h.firePaste({ text: 'hello world' });
|
||||
|
||||
expect(h.pastedText).toEqual(['hello world']);
|
||||
});
|
||||
|
||||
it('ignores a second paste event for the same Ctrl+V', () => {
|
||||
const h = loadPasteHarness();
|
||||
|
||||
// execCommand('paste') and the uncancelled keydown's default action both
|
||||
// land on the same trap in browsers that honour the command.
|
||||
h.firePaste({ text: 'hello world' });
|
||||
h.firePaste({ text: 'hello world' });
|
||||
|
||||
expect(h.pastedText).toEqual(['hello world']);
|
||||
});
|
||||
|
||||
it('uploads a pasted image once when the trap sees two paste events', () => {
|
||||
const h = loadPasteHarness();
|
||||
|
||||
h.firePaste({ images: ['image/png'] });
|
||||
h.firePaste({ images: ['image/png'] });
|
||||
|
||||
expect(h.uploadedBatches).toHaveLength(1);
|
||||
expect(h.uploadedBatches[0]).toEqual([{ type: 'image/png' }]);
|
||||
expect(h.pastedText).toEqual([]);
|
||||
});
|
||||
|
||||
it('removes the trap and hands focus back after the paste it accepted', () => {
|
||||
const h = loadPasteHarness();
|
||||
|
||||
h.firePaste({ text: 'hello world' });
|
||||
expect(h.attachedTraps()).toBe(1);
|
||||
|
||||
h.runTimers();
|
||||
expect(h.attachedTraps()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -224,6 +224,37 @@ describe('mobile overview model', () => {
|
||||
expect(model.past[0].title).toBe('w4-claudeman');
|
||||
});
|
||||
|
||||
it('carries resumeId through to the past row so a Codex tap resumes its thread', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: [],
|
||||
cases: CASES,
|
||||
history: [
|
||||
{
|
||||
sessionId: 'rollout-1',
|
||||
workingDir: '/home/arkon/codeman-cases/beta',
|
||||
firstPrompt: 'port the parser',
|
||||
mode: 'codex',
|
||||
resumeId: 'codex-thread-id',
|
||||
lastActivityAt: 300,
|
||||
},
|
||||
// A claude row carries none, and must not grow one.
|
||||
{
|
||||
sessionId: 'claude-1',
|
||||
workingDir: '/home/arkon/default/claudeman',
|
||||
claudeSessionId: 'claude-uuid-a',
|
||||
lastActivityAt: 200,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// resumeMobileOverviewSession() reads row.resumeId off exactly this projection and
|
||||
// hands it to resumeHistorySession(); an undefined here is a fresh codex session on
|
||||
// a thread that already exists, which is the phone-only half of the resume feature.
|
||||
expect(model.past[0]).toMatchObject({ mode: 'codex', resumeId: 'codex-thread-id' });
|
||||
expect(model.past[1].resumeId).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not title a past row with the transcript reader placeholder', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
|
||||
@@ -25,7 +25,7 @@ import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { Session } from '../src/session.js';
|
||||
import { TmuxManager } from '../src/tmux-manager.js';
|
||||
import type { MuxSession } from '../src/types.js';
|
||||
import type { MuxSession, SessionRemote } from '../src/types.js';
|
||||
|
||||
describe('OMP: fresh session vs. reattach must not share resumeSessionId resolution', () => {
|
||||
const workingDir = join(homedir(), 'codeman-cases', 'resume-test');
|
||||
@@ -126,4 +126,91 @@ describe('OMP: fresh session vs. reattach must not share resumeSessionId resolut
|
||||
expect(session.toState().ompConfig?.resumeSessionId).toBe('real-omp-uuid');
|
||||
expect(session.claudeSessionId).toBe('real-omp-uuid');
|
||||
});
|
||||
|
||||
it("a remote session never resolves --resume from this host's local ~/.omp, even when a same-named local session file exists", () => {
|
||||
// Seed a LOCAL session file whose directory mangle happens to match this
|
||||
// remote session's remotePath. If _pinOmpRespawnId() ever fell through to
|
||||
// resolveAndClaimOmpSessionId() for a remote session, it would wrongly
|
||||
// claim/pin this unrelated local conversation's id onto the remote respawn.
|
||||
seedOmpSessionFile('wrong-local-conversation-id');
|
||||
|
||||
const remote: SessionRemote = {
|
||||
hostId: 'remote-box',
|
||||
label: 'remote-box',
|
||||
host: 'remote-box',
|
||||
username: 'someone',
|
||||
remotePath: workingDir,
|
||||
owned: true,
|
||||
};
|
||||
|
||||
const muxSession: MuxSession = {
|
||||
sessionId: 'placeholder',
|
||||
muxName: 'codeman-deadbeef',
|
||||
pid: 1,
|
||||
createdAt: Date.now(),
|
||||
workingDir,
|
||||
mode: 'omp',
|
||||
attached: false,
|
||||
};
|
||||
|
||||
const session = new Session({
|
||||
workingDir,
|
||||
mode: 'omp',
|
||||
mux: new TmuxManager(),
|
||||
useMux: true,
|
||||
muxSession,
|
||||
remote,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
(session as unknown as { _pinOmpRespawnId(): void })._pinOmpRespawnId();
|
||||
|
||||
const state = session.toState();
|
||||
expect(state.ompConfig?.resumeSessionId).toBeUndefined();
|
||||
expect(state.ompConfig?.continueSession).toBe(true);
|
||||
expect(session.claudeSessionId).toBe(session.id);
|
||||
});
|
||||
|
||||
it('_maybeCaptureOmpSessionId() is subject to the same remote guard, so a first idle turn cannot alias a remote session onto a local conversation', () => {
|
||||
// The sibling guard in _pinOmpRespawnId has the test above; this one runs on
|
||||
// the FIRST turn going idle, before any respawn, and reads the same local
|
||||
// ~/.omp tree. Without the `this._remote` early return it would claim this
|
||||
// unrelated local conversation's uuid as the remote session's identity, and
|
||||
// every later respawn would then inherit the wrong pin.
|
||||
seedOmpSessionFile('wrong-local-conversation-id');
|
||||
|
||||
const remote: SessionRemote = {
|
||||
hostId: 'remote-box',
|
||||
label: 'remote-box',
|
||||
host: 'remote-box',
|
||||
username: 'someone',
|
||||
remotePath: workingDir,
|
||||
owned: true,
|
||||
};
|
||||
|
||||
const muxSession: MuxSession = {
|
||||
sessionId: 'placeholder',
|
||||
muxName: 'codeman-deadbeef',
|
||||
pid: 1,
|
||||
createdAt: Date.now(),
|
||||
workingDir,
|
||||
mode: 'omp',
|
||||
attached: false,
|
||||
};
|
||||
|
||||
const session = new Session({
|
||||
workingDir,
|
||||
mode: 'omp',
|
||||
mux: new TmuxManager(),
|
||||
useMux: true,
|
||||
muxSession,
|
||||
remote,
|
||||
});
|
||||
sessions.push(session);
|
||||
|
||||
(session as unknown as { _maybeCaptureOmpSessionId(): void })._maybeCaptureOmpSessionId();
|
||||
|
||||
expect(session.claudeSessionId).toBe(session.id);
|
||||
expect(session.toState().ompConfig?.resumeSessionId).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,11 @@ import { mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { findLatestOmpSessionId, mangleOmpWorkingDir } from '../src/utils/omp-session-resolver.js';
|
||||
import {
|
||||
findLatestOmpSessionId,
|
||||
mangleOmpWorkingDir,
|
||||
resolveAndClaimOmpSessionId,
|
||||
} from '../src/utils/omp-session-resolver.js';
|
||||
import { resolveOmpConfigForCreate } from '../src/web/routes/session-routes.js';
|
||||
|
||||
describe('mangleOmpWorkingDir', () => {
|
||||
@@ -41,6 +45,15 @@ describe('mangleOmpWorkingDir', () => {
|
||||
const sibling = `${homedir()}-other/dev/foo`;
|
||||
expect(mangleOmpWorkingDir(sibling)).toBe(sibling.replace(/\//g, '-'));
|
||||
});
|
||||
|
||||
it('normalizes a trailing slash so a remote case path resolves to the same dir', () => {
|
||||
// Regression (2026-08-29): remote case paths are stored verbatim with a
|
||||
// trailing slash (e.g. `/home/user/dotfiles/`), but omp persists sessions
|
||||
// under the slash-less mangle (`-dotfiles`). Before the fix this produced
|
||||
// `-dotfiles-`, readdirSync returned null for an existing dir, and OMP
|
||||
// respawn pinning silently degraded to the ambiguous `--continue`.
|
||||
expect(mangleOmpWorkingDir(join(homedir(), 'dotfiles') + '/')).toBe('-dotfiles');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findLatestOmpSessionId', () => {
|
||||
@@ -69,6 +82,33 @@ describe('findLatestOmpSessionId', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveAndClaimOmpSessionId: header-cwd trailing-slash normalization', () => {
|
||||
// Sibling of the directory-mangle trailing-slash regression above, but for
|
||||
// the OTHER half of the same fix: resolveAndClaimOmpSessionId additionally
|
||||
// verifies each candidate file's own header `cwd` against workingDir (the
|
||||
// mangle is lossy, so the filename-derived id alone isn't enough — see the
|
||||
// function's doc comment). A remote case's workingDir carries a trailing
|
||||
// slash (e.g. `/home/user/dotfiles/`) but omp's header `cwd` never does;
|
||||
// without stripTrailingSlash() on BOTH sides of that comparison, a real
|
||||
// on-disk session would be found by directory but rejected by the cwd
|
||||
// check, silently degrading pinning to the ambiguous `--continue`.
|
||||
const workingDirNoSlash = join(homedir(), 'dotfiles');
|
||||
const workingDirWithSlash = `${workingDirNoSlash}/`;
|
||||
const sessionDir = join(homedir(), '.omp', 'agent', 'sessions', '-dotfiles');
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(join(homedir(), '.omp'), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('matches a header cwd with no trailing slash against a workingDir that has one', () => {
|
||||
mkdirSync(sessionDir, { recursive: true });
|
||||
const header = `${JSON.stringify({ type: 'session', id: 'remote-dotfiles-uuid', cwd: workingDirNoSlash })}\n`;
|
||||
writeFileSync(join(sessionDir, '2026-08-29T00-00-00-000Z_remote-dotfiles-uuid.jsonl'), header);
|
||||
|
||||
expect(resolveAndClaimOmpSessionId(workingDirWithSlash)).toBe('remote-dotfiles-uuid');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveOmpConfigForCreate', () => {
|
||||
// The exact pipeline "resume this OMP row from the history list" drives:
|
||||
// POST /api/sessions with mode:'omp' + ompConfig:{continueSession:true}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* @fileoverview Path picker: sort order and the editable path field.
|
||||
*
|
||||
* Same jsdom harness as path-picker-hidden.test.ts: keyboard-accessory.js is
|
||||
* evaluated against a jsdom window with a scripted fetch, so the assertions
|
||||
* run against the real DOM the picker builds rather than string matches.
|
||||
* Port: N/A
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const accessoryJs = readFileSync(resolve(PUBLIC, 'keyboard-accessory.js'), 'utf8');
|
||||
const stylesCss = readFileSync(resolve(PUBLIC, 'styles.css'), 'utf8');
|
||||
|
||||
const SORT_KEY = 'codeman:pathPickerSort';
|
||||
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { url: 'https://localhost/' });
|
||||
const jsdomWindow = dom.window as unknown as Window & typeof globalThis;
|
||||
const jsdomDocument = jsdomWindow.document;
|
||||
|
||||
function loadPathPicker(fetchImpl: (url: string) => Promise<unknown>): any {
|
||||
const MobileDetection = { isTouchDevice: () => false };
|
||||
const factory = new Function(
|
||||
'window',
|
||||
'document',
|
||||
'localStorage',
|
||||
'fetch',
|
||||
'MobileDetection',
|
||||
`${accessoryJs}\nreturn PathPicker;`
|
||||
);
|
||||
return factory(jsdomWindow, jsdomDocument, jsdomWindow.localStorage, fetchImpl, MobileDetection);
|
||||
}
|
||||
|
||||
type Entry = { name: string; type: 'file' | 'directory'; mtimeMs?: number };
|
||||
|
||||
function browseResponse(entries: Entry[], path = '/home/dev/project') {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
success: true,
|
||||
data: {
|
||||
path,
|
||||
parent: path === '/home/dev' ? null : '/home/dev',
|
||||
root: '/home/dev',
|
||||
roots: [{ label: 'Home', path: '/home/dev' }],
|
||||
entries: entries.map((e) => ({ ...e, path: `${path}/${e.name}` })),
|
||||
truncated: false,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function errorResponse(error: string) {
|
||||
return { ok: false, json: async () => ({ success: false, error }) };
|
||||
}
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const NOW = Date.now();
|
||||
const LISTING: Entry[] = [
|
||||
{ name: 'zeta.txt', type: 'file', mtimeMs: NOW - 3 * DAY },
|
||||
{ name: 'alpha.txt', type: 'file', mtimeMs: NOW - 1 * DAY },
|
||||
{ name: 'mid.txt', type: 'file', mtimeMs: NOW - 2 * DAY },
|
||||
{ name: 'old-dir', type: 'directory', mtimeMs: NOW - 30 * DAY },
|
||||
{ name: 'new-dir', type: 'directory', mtimeMs: NOW - 1000 },
|
||||
];
|
||||
|
||||
describe('PathPicker sort order', () => {
|
||||
let PathPicker: any;
|
||||
let urls: string[];
|
||||
let respond: (url: string) => unknown;
|
||||
|
||||
beforeEach(() => {
|
||||
jsdomWindow.localStorage.clear();
|
||||
jsdomDocument.body.replaceChildren();
|
||||
urls = [];
|
||||
respond = () => browseResponse(LISTING);
|
||||
PathPicker = loadPathPicker(async (url: string) => {
|
||||
urls.push(url);
|
||||
return respond(url);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
PathPicker?.close?.(false);
|
||||
jsdomDocument.body.replaceChildren();
|
||||
});
|
||||
|
||||
const open = async (options: Record<string, unknown> = {}) => {
|
||||
PathPicker.open({ onSelect: () => {}, ...options });
|
||||
await vi.waitFor(() => expect(jsdomDocument.querySelectorAll('.path-picker-item').length).toBeGreaterThan(0));
|
||||
};
|
||||
const names = () => Array.from(jsdomDocument.querySelectorAll('.path-picker-item-name')).map((el) => el.textContent);
|
||||
const sortSelect = () => jsdomDocument.querySelector('.path-picker-sort') as HTMLSelectElement;
|
||||
const setSort = (value: string) => {
|
||||
sortSelect().value = value;
|
||||
sortSelect().dispatchEvent(new jsdomWindow.Event('change', { bubbles: true }));
|
||||
};
|
||||
|
||||
it('sorts by name with folders first by default', async () => {
|
||||
await open();
|
||||
expect(sortSelect().value).toBe('name-asc');
|
||||
expect(names()).toEqual(['new-dir', 'old-dir', 'alpha.txt', 'mid.txt', 'zeta.txt']);
|
||||
});
|
||||
|
||||
it('re-orders the listing without another request, keeping folders first', async () => {
|
||||
await open();
|
||||
const requests = urls.length;
|
||||
|
||||
setSort('mtime-desc');
|
||||
expect(names()).toEqual(['new-dir', 'old-dir', 'alpha.txt', 'mid.txt', 'zeta.txt']);
|
||||
|
||||
setSort('mtime-asc');
|
||||
expect(names()).toEqual(['old-dir', 'new-dir', 'zeta.txt', 'mid.txt', 'alpha.txt']);
|
||||
|
||||
setSort('name-desc');
|
||||
expect(names()).toEqual(['old-dir', 'new-dir', 'zeta.txt', 'mid.txt', 'alpha.txt']);
|
||||
|
||||
expect(urls.length).toBe(requests);
|
||||
});
|
||||
|
||||
it('remembers the sort mode across reopenings', async () => {
|
||||
await open();
|
||||
setSort('mtime-desc');
|
||||
expect(jsdomWindow.localStorage.getItem(SORT_KEY)).toBe('mtime-desc');
|
||||
PathPicker.close(false);
|
||||
|
||||
await open();
|
||||
expect(sortSelect().value).toBe('mtime-desc');
|
||||
});
|
||||
|
||||
it('ignores a corrupt stored mode and a localStorage that throws', async () => {
|
||||
jsdomWindow.localStorage.setItem(SORT_KEY, 'bogus');
|
||||
await open();
|
||||
expect(sortSelect().value).toBe('name-asc');
|
||||
PathPicker.close(false);
|
||||
|
||||
const getItem = vi.spyOn(jsdomWindow.localStorage.__proto__, 'getItem').mockImplementation(() => {
|
||||
throw new Error('private mode');
|
||||
});
|
||||
try {
|
||||
await open();
|
||||
expect(sortSelect().value).toBe('name-asc');
|
||||
setSort('mtime-asc');
|
||||
expect(names()[0]).toBe('old-dir');
|
||||
} finally {
|
||||
getItem.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('places entries without a modified time after dated ones on a date sort', async () => {
|
||||
respond = () =>
|
||||
browseResponse([
|
||||
{ name: 'undated.txt', type: 'file' },
|
||||
{ name: 'dated.txt', type: 'file', mtimeMs: NOW - DAY },
|
||||
]);
|
||||
await open();
|
||||
setSort('mtime-desc');
|
||||
expect(names()).toEqual(['dated.txt', 'undated.txt']);
|
||||
setSort('mtime-asc');
|
||||
expect(names()).toEqual(['dated.txt', 'undated.txt']);
|
||||
});
|
||||
|
||||
it('shows a compact modified time only when the server supplied one', async () => {
|
||||
respond = () =>
|
||||
browseResponse([
|
||||
{ name: 'undated.txt', type: 'file' },
|
||||
{ name: 'today.txt', type: 'file', mtimeMs: NOW },
|
||||
]);
|
||||
await open();
|
||||
const rows = Array.from(jsdomDocument.querySelectorAll('.path-picker-item'));
|
||||
const meta = (row: Element) => row.querySelector('.path-picker-item-meta')?.textContent ?? null;
|
||||
expect(meta(rows[0])).toMatch(/^\d{2}:\d{2}$/);
|
||||
expect(meta(rows[1])).toBeNull();
|
||||
});
|
||||
|
||||
it('styles the sort control and the modified column', () => {
|
||||
expect(stylesCss).toContain('.path-picker-sort {');
|
||||
expect(stylesCss).toContain('.path-picker-item-meta {');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PathPicker editable path', () => {
|
||||
let PathPicker: any;
|
||||
let urls: string[];
|
||||
let respond: (url: string) => unknown;
|
||||
|
||||
beforeEach(() => {
|
||||
jsdomWindow.localStorage.clear();
|
||||
jsdomDocument.body.replaceChildren();
|
||||
urls = [];
|
||||
respond = () => browseResponse(LISTING);
|
||||
PathPicker = loadPathPicker(async (url: string) => {
|
||||
urls.push(url);
|
||||
return respond(url);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
PathPicker?.close?.(false);
|
||||
jsdomDocument.body.replaceChildren();
|
||||
});
|
||||
|
||||
const open = async (options: Record<string, unknown> = {}) => {
|
||||
PathPicker.open({ onSelect: () => {}, ...options });
|
||||
await vi.waitFor(() => expect(jsdomDocument.querySelectorAll('.path-picker-item').length).toBeGreaterThan(0));
|
||||
};
|
||||
const field = () => jsdomDocument.querySelector('.path-picker-current') as HTMLInputElement;
|
||||
const submit = (value: string) => {
|
||||
field().value = value;
|
||||
(jsdomDocument.querySelector('.path-picker-jump') as HTMLFormElement).dispatchEvent(
|
||||
new jsdomWindow.Event('submit', { bubbles: true, cancelable: true })
|
||||
);
|
||||
};
|
||||
const pathParam = (url: string) => new URL(url, 'https://localhost').searchParams.get('path');
|
||||
const status = () => jsdomDocument.querySelector('.path-picker-status') as HTMLElement;
|
||||
|
||||
it('shows the current folder in an editable field and jumps on Enter', async () => {
|
||||
await open({ initialPath: '/home/dev/project' });
|
||||
expect(field().value).toBe('/home/dev/project');
|
||||
const before = urls.length;
|
||||
|
||||
// Typing alone never fetches.
|
||||
field().value = '/home/dev/oth';
|
||||
field().dispatchEvent(new jsdomWindow.Event('input', { bubbles: true }));
|
||||
expect(urls.length).toBe(before);
|
||||
|
||||
respond = () => browseResponse([{ name: 'readme.md', type: 'file' }], '/home/dev/other');
|
||||
submit(' /home/dev/other ');
|
||||
await vi.waitFor(() => expect(field().value).toBe('/home/dev/other'));
|
||||
expect(pathParam(urls[urls.length - 1])).toBe('/home/dev/other');
|
||||
expect(jsdomDocument.querySelector('.path-picker-item-name')?.textContent).toBe('readme.md');
|
||||
});
|
||||
|
||||
it('keeps the current listing and reports the error when neither a typed path nor its parent resolves', async () => {
|
||||
await open({ initialPath: '/home/dev/project' });
|
||||
respond = () => errorResponse('Path not found: /home/dev/nope/deeper');
|
||||
submit('/home/dev/nope/deeper');
|
||||
await vi.waitFor(() => expect(status().classList.contains('error')).toBe(true));
|
||||
expect(status().textContent).toBe('Path not found: /home/dev/nope/deeper');
|
||||
// One retry on the parent, then stop: never a climb to the root.
|
||||
expect(urls.slice(-2).map(pathParam)).toEqual(['/home/dev/nope/deeper', '/home/dev/nope']);
|
||||
expect(jsdomDocument.querySelectorAll('.path-picker-item').length).toBe(LISTING.length);
|
||||
// The typed text stays in the field so the typo can be corrected in place.
|
||||
expect(field().value).toBe('/home/dev/nope/deeper');
|
||||
});
|
||||
|
||||
it('lands in the parent folder, unselected, when only the last segment is wrong', async () => {
|
||||
await open({ initialPath: '/home/dev' });
|
||||
respond = (url) =>
|
||||
pathParam(url) === '/home/dev/project/typo.txt'
|
||||
? errorResponse('Path not found: /home/dev/project/typo.txt')
|
||||
: browseResponse(LISTING);
|
||||
submit('/home/dev/project/typo.txt');
|
||||
await vi.waitFor(() => expect(field().value).toBe('/home/dev/project'));
|
||||
await vi.waitFor(() => expect(status().classList.contains('error')).toBe(true));
|
||||
expect(status().textContent).toBe('Path not found: /home/dev/project/typo.txt');
|
||||
expect(jsdomDocument.querySelector('.path-picker-selection-value')?.textContent).toBe('None');
|
||||
expect((jsdomDocument.querySelector('.path-picker-confirm') as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('lands a typed file path in its folder with the file selected', async () => {
|
||||
await open({ initialPath: '/home/dev/project' });
|
||||
respond = (url) =>
|
||||
pathParam(url) === '/home/dev/project/alpha.txt'
|
||||
? errorResponse('Path not found: /home/dev/project/alpha.txt')
|
||||
: browseResponse(LISTING);
|
||||
submit('/home/dev/project/alpha.txt');
|
||||
await vi.waitFor(() =>
|
||||
expect(jsdomDocument.querySelector('.path-picker-selection-value')?.textContent).toBe(
|
||||
'/home/dev/project/alpha.txt'
|
||||
)
|
||||
);
|
||||
expect(field().value).toBe('/home/dev/project');
|
||||
expect(jsdomDocument.querySelector('.path-picker-item.selected .path-picker-item-name')?.textContent).toBe(
|
||||
'alpha.txt'
|
||||
);
|
||||
expect((jsdomDocument.querySelector('.path-picker-confirm') as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('selects the current folder from the field value and refreshes in place', async () => {
|
||||
await open({ initialPath: '/home/dev/project' });
|
||||
(jsdomDocument.querySelector('.path-picker-current-select') as HTMLButtonElement).click();
|
||||
expect(jsdomDocument.querySelector('.path-picker-selection-value')?.textContent).toBe('/home/dev/project');
|
||||
|
||||
const before = urls.length;
|
||||
(jsdomDocument.querySelector('.path-picker-refresh') as HTMLButtonElement).click();
|
||||
await vi.waitFor(() => expect(urls.length).toBe(before + 1));
|
||||
expect(pathParam(urls[urls.length - 1])).toBe('/home/dev/project');
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
} from '../scripts/pr-bot/report.js';
|
||||
import { classifyCi, latestRunPerWorkflow, type PrSummary, type WorkflowRun } from '../scripts/pr-bot/github.js';
|
||||
import { parseCallback, parseCommand, prNumberFromMessageText } from '../scripts/pr-bot/telegram.js';
|
||||
import { trustDialogKey } from '../scripts/pr-bot/codeman-client.js';
|
||||
import { findModelLimitNotice, trustDialogKey } from '../scripts/pr-bot/codeman-client.js';
|
||||
import { buildConfig, parseEnvFile } from '../scripts/pr-bot/config.js';
|
||||
import { buildReviewBrief } from '../scripts/pr-bot/review-task.js';
|
||||
|
||||
@@ -302,6 +302,38 @@ describe('trustDialogKey', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('findModelLimitNotice', () => {
|
||||
// Captured off prbot-394's pane on 2026-09-08, the run that lost 40 minutes: Claude
|
||||
// Code answers a spent budget inside the turn and then simply sits there.
|
||||
const SPENT_PANE = [
|
||||
'\x1b[38;5;153m\u276f\x1b[39m Read /home/arkon/.codeman/pr-bot/jobs/pr-394/brief.md and do the review.',
|
||||
" \u23bf You've reached your Fable limit. Run /usage-credits to continue or switch models with /model.",
|
||||
'\u273b Saut\u00e9ed for 1s \u00b7 done 7:16 PM',
|
||||
].join('\n');
|
||||
|
||||
it('finds the notice on a real pane, ANSI and gutter glyph stripped', () => {
|
||||
expect(findModelLimitNotice(SPENT_PANE)).toBe(
|
||||
"You've reached your Fable limit. Run /usage-credits to continue or switch models with /model."
|
||||
);
|
||||
});
|
||||
|
||||
it('is not tied to one model name or to a straight apostrophe', () => {
|
||||
// The pane renders a typographic apostrophe, and every model prints this sentence.
|
||||
expect(
|
||||
findModelLimitNotice(' \u23bf You\u2019ve reached your Opus limit. Run /usage-credits to continue.')
|
||||
).toContain('reached your Opus limit');
|
||||
expect(findModelLimitNotice('You have reached your Sonnet 5 limit.')).toContain('Sonnet 5');
|
||||
});
|
||||
|
||||
it('says nothing about an ordinary working pane', () => {
|
||||
expect(findModelLimitNotice('\u273b Actualizing\u2026 (13m 23s \u00b7 esc to interrupt)')).toBeUndefined();
|
||||
expect(findModelLimitNotice('')).toBeUndefined();
|
||||
// The bare word is not the notice: a review whose own findings discuss usage limits
|
||||
// must not be reported as an exhausted account.
|
||||
expect(findModelLimitNotice('the usage limit parser handles the 5-hour reset')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('config', () => {
|
||||
it('parses env files with quotes, comments and export prefixes', () => {
|
||||
const env = parseEnvFile('# c\nexport A="x y"\nB=\'z\'\nC=plain\nbad line\n=nokey\n');
|
||||
|
||||
@@ -24,6 +24,31 @@ describe('COD-106 shared remote sessions', () => {
|
||||
expect(cmd).toContain('new-session -A -s codeman-ssh-cod106aa');
|
||||
});
|
||||
|
||||
it('remote omp relaunch resumes the pinned conversation instead of starting fresh (2026-08-29)', () => {
|
||||
const cmd = buildRemoteLaunchCommand({
|
||||
mode: 'omp',
|
||||
remote,
|
||||
sessionId: 'cod106aaa',
|
||||
ompConfig: { model: 'llm-proxy/crof/glm-5.3-flash' },
|
||||
resumeSessionId: '01a04eb1-d883-75f0-bdfa-74cc315b09ce',
|
||||
});
|
||||
// The remote pane command must carry the pinned omp session id so a
|
||||
// dead-pane respawn lands back in the same conversation.
|
||||
expect(cmd).toContain('omp --model llm-proxy/crof/glm-5.3-flash --resume 01a04eb1-d883-75f0-bdfa-74cc315b09ce');
|
||||
// still a durable, idempotent remote tmux session
|
||||
expect(cmd).toContain('new-session -A -s codeman-ssh-cod106aa');
|
||||
});
|
||||
|
||||
it('remote omp relaunch falls back to --continue when no id is pinned', () => {
|
||||
const cmd = buildRemoteLaunchCommand({
|
||||
mode: 'omp',
|
||||
remote,
|
||||
sessionId: 'cod106aaa',
|
||||
ompConfig: { continueSession: true },
|
||||
});
|
||||
expect(cmd).toContain('omp --continue');
|
||||
});
|
||||
|
||||
it('parses session_attached as a CLIENT COUNT (>1 = shared)', () => {
|
||||
const rows = parseRemoteSessionList(
|
||||
['codeman-solo\\t1\\t100\\t1', 'codeman-shared\\t2\\t200\\t3', 'codeman-idle\\t0\\t300\\t1'].join('\n')
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* @fileoverview The brief ("Last Response") view renders the last ANSWERED turn.
|
||||
*
|
||||
* `data.text` is one row — the last assistant row — and a Claude turn is a
|
||||
* median of 3 rows, so the eye button used to show the tail of an answer
|
||||
* ("Done.") while the More view showed the whole thing. The brief view now asks
|
||||
* for `context=turn` and renders those rows the way the full view does: one
|
||||
* badge, then continuation segments. Pinned here:
|
||||
*
|
||||
* 1. `selectLastAnsweredTurn` picks the highest turn that HAS an assistant
|
||||
* message, so a prompt queued after the answer (a new, unanswered turn)
|
||||
* does not blank the view; and it yields nothing without numeric turns.
|
||||
* 2. The brief view falls back to `text` when the server sends no messages
|
||||
* (Codex, the pane parser, an older server), so those keep their one card.
|
||||
* 3. The continuation gate is the numeric `turn`, as in loadFullContext.
|
||||
*
|
||||
* app.js is loaded via `vm` with a jsdom document, as in
|
||||
* response-viewer-turn-segments.test.ts.
|
||||
* Port: N/A
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { selectLastAnsweredTurn } from '../src/web/response-viewer-transcript.js';
|
||||
|
||||
describe('selectLastAnsweredTurn', () => {
|
||||
const user = (text: string, turn: number) => ({ role: 'user', text, turn });
|
||||
const assistant = (text: string, turn: number) => ({ role: 'assistant', text, turn });
|
||||
|
||||
it('returns every assistant message of the highest answered turn', () => {
|
||||
const messages = [
|
||||
user('a', 1),
|
||||
assistant('a1', 1),
|
||||
user('b', 2),
|
||||
assistant('b1', 2),
|
||||
assistant('b2', 2),
|
||||
user('c', 3),
|
||||
];
|
||||
expect(selectLastAnsweredTurn(messages).map((m) => m.text)).toEqual(['b1', 'b2']);
|
||||
});
|
||||
|
||||
it('yields nothing for messages without numeric turns, so callers fall back to text', () => {
|
||||
const messages = [
|
||||
{ role: 'user', text: 'a' },
|
||||
{ role: 'assistant', text: 'a1' },
|
||||
{ role: 'assistant', text: 'a2' },
|
||||
];
|
||||
expect(selectLastAnsweredTurn(messages)).toEqual([]);
|
||||
expect(selectLastAnsweredTurn([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps turn-0 output emitted before the first prompt', () => {
|
||||
expect(selectLastAnsweredTurn([assistant('hello', 0)]).map((m) => m.text)).toEqual(['hello']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('response viewer brief view (last answered turn)', () => {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
|
||||
const { document, NodeFilter } = dom.window;
|
||||
|
||||
function loadCodemanAppClass() {
|
||||
const constants = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
performance,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
fetch: vi.fn(),
|
||||
document,
|
||||
NodeFilter,
|
||||
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
MobileDetection: {},
|
||||
});
|
||||
vm.runInContext(`${constants}\n${source}\nglobalThis.__CodemanApp = CodemanApp;`, context);
|
||||
return { CodemanApp: (context as { __CodemanApp: { prototype: object } }).__CodemanApp, context };
|
||||
}
|
||||
|
||||
const { CodemanApp, context: appContext } = loadCodemanAppClass();
|
||||
|
||||
interface ViewerApp {
|
||||
toggleResponseViewer(): Promise<void>;
|
||||
activeSessionId?: string;
|
||||
sessions?: Map<string, { mode: string }>;
|
||||
}
|
||||
|
||||
function mountViewer() {
|
||||
const viewer = document.createElement('div');
|
||||
viewer.id = 'responseViewer';
|
||||
const backdrop = document.createElement('div');
|
||||
backdrop.id = 'responseViewerBackdrop';
|
||||
const body = document.createElement('div');
|
||||
body.id = 'responseViewerBody';
|
||||
const title = document.createElement('div');
|
||||
title.id = 'responseViewerTitle';
|
||||
const more = document.createElement('button');
|
||||
more.id = 'responseViewerMore';
|
||||
document.body.append(viewer, backdrop, body, title, more);
|
||||
return { viewer, body, title, more };
|
||||
}
|
||||
|
||||
function makeApp(payload: unknown): { app: ViewerApp; fetchMock: ReturnType<typeof vi.fn> } {
|
||||
const app = Object.create(CodemanApp.prototype) as ViewerApp;
|
||||
app.activeSessionId = 's1';
|
||||
app.sessions = new Map([['s1', { mode: 'claude' }]]);
|
||||
const fetchMock = vi.fn(async () => ({ json: async () => ({ data: payload }) }));
|
||||
(appContext as { fetch: unknown }).fetch = fetchMock;
|
||||
return { app, fetchMock };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('asks for context=turn and renders the whole turn as one badged card with segments', async () => {
|
||||
const { body, viewer } = mountViewer();
|
||||
const { app, fetchMock } = makeApp({
|
||||
text: 'Done.',
|
||||
timestamp: 't',
|
||||
messages: [
|
||||
{ role: 'assistant', text: 'Looking at the file.', turn: 2 },
|
||||
{ role: 'assistant', text: 'The bug is on line 3.', turn: 2 },
|
||||
{ role: 'assistant', text: 'Done.', turn: 2 },
|
||||
],
|
||||
});
|
||||
|
||||
await app.toggleResponseViewer();
|
||||
|
||||
expect(String(fetchMock.mock.calls[0][0])).toBe('/api/sessions/s1/last-response?context=turn');
|
||||
const cards = body.querySelectorAll('.rv-message');
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(body.querySelectorAll('.rv-role')).toHaveLength(1);
|
||||
expect(cards[0].classList.contains('rv-msg-cont')).toBe(false);
|
||||
expect(cards[1].classList.contains('rv-msg-cont')).toBe(true);
|
||||
expect(cards[2].classList.contains('rv-msg-cont')).toBe(true);
|
||||
expect(body.textContent).toContain('The bug is on line 3.');
|
||||
expect(viewer.classList.contains('visible')).toBe(true);
|
||||
});
|
||||
|
||||
it('opens a multi-row turn at its NEWEST text, and a single card at the top', async () => {
|
||||
// `body.scrollTop = 0` was right when the brief view was one card holding
|
||||
// the last row. With the whole turn rendered, the top of the scroller is
|
||||
// the turn's FIRST narration line and the answer the eye button exists to
|
||||
// show can be several screens below it; loadFullContext already scrolls to
|
||||
// the bottom for the same turn, so the two views disagreed.
|
||||
// jsdom does no layout, so scrollHeight is stubbed and the write recorded.
|
||||
const spyScroll = (body: HTMLElement) => {
|
||||
const writes: number[] = [];
|
||||
Object.defineProperty(body, 'scrollHeight', { configurable: true, get: () => 4200 });
|
||||
Object.defineProperty(body, 'scrollTop', {
|
||||
configurable: true,
|
||||
get: () => writes[writes.length - 1] ?? 0,
|
||||
set: (v: number) => void writes.push(v),
|
||||
});
|
||||
return writes;
|
||||
};
|
||||
|
||||
const many = mountViewer();
|
||||
const manyWrites = spyScroll(many.body);
|
||||
await makeApp({
|
||||
text: 'Done.',
|
||||
timestamp: 't',
|
||||
messages: [
|
||||
{ role: 'assistant', text: 'Looking at the file.', turn: 2 },
|
||||
{ role: 'assistant', text: 'Done.', turn: 2 },
|
||||
],
|
||||
}).app.toggleResponseViewer();
|
||||
expect(manyWrites.at(-1)).toBe(4200);
|
||||
|
||||
document.body.innerHTML = '';
|
||||
const one = mountViewer();
|
||||
const oneWrites = spyScroll(one.body);
|
||||
await makeApp({
|
||||
text: 'Done.',
|
||||
timestamp: 't',
|
||||
messages: [{ role: 'assistant', text: 'Done.', turn: 2 }],
|
||||
}).app.toggleResponseViewer();
|
||||
expect(oneWrites.at(-1)).toBe(0);
|
||||
});
|
||||
|
||||
it('falls back to text when the server sends no messages, keeping one badged card', async () => {
|
||||
const { body } = mountViewer();
|
||||
const { app } = makeApp({ text: 'Only the last row.', timestamp: 't' });
|
||||
|
||||
await app.toggleResponseViewer();
|
||||
|
||||
expect(body.querySelectorAll('.rv-message')).toHaveLength(1);
|
||||
expect(body.querySelectorAll('.rv-role')).toHaveLength(1);
|
||||
expect(body.textContent).toContain('Only the last row.');
|
||||
});
|
||||
|
||||
it('ignores user rows and blank rows in a turn payload', async () => {
|
||||
const { body } = mountViewer();
|
||||
const { app } = makeApp({
|
||||
text: 'answer',
|
||||
timestamp: 't',
|
||||
messages: [
|
||||
{ role: 'user', text: 'prompt', turn: 1 },
|
||||
{ role: 'assistant', text: ' ', turn: 1 },
|
||||
{ role: 'assistant', text: 'answer', turn: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
await app.toggleResponseViewer();
|
||||
|
||||
expect(body.querySelectorAll('.rv-message')).toHaveLength(1);
|
||||
expect(body.textContent).not.toContain('prompt');
|
||||
expect(body.textContent).toContain('answer');
|
||||
});
|
||||
});
|
||||
@@ -90,7 +90,7 @@ describe('resumeHistorySession: row retirement is gated on actual continuation',
|
||||
fetchMock = stubFetch('new-session-id');
|
||||
});
|
||||
|
||||
it.each(['codex', 'gemini', 'antigravity'])(
|
||||
it.each(['gemini', 'antigravity'])(
|
||||
'does NOT retire the old row for %s (no continuation is wired for it)',
|
||||
async (mode) => {
|
||||
const app = makeApp();
|
||||
@@ -104,6 +104,44 @@ describe('resumeHistorySession: row retirement is gated on actual continuation',
|
||||
}
|
||||
);
|
||||
|
||||
// codex continues only when the row carried its thread id. A row without one
|
||||
// is a live session's row, whose sessionId is Codeman's own uuid — sending
|
||||
// THAT to `codex resume` asks for a thread that does not exist, so it must
|
||||
// stay a fresh session and must not retire the row it came from.
|
||||
it('does NOT continue or retire a codex row that carries no resumeId', async () => {
|
||||
const app = makeApp();
|
||||
await app.resumeHistorySession.call(app, 'codeman-uuid', '/repo', 'w1-repo', 'codex');
|
||||
|
||||
expect(createBody(fetchMock)).toMatchObject({ mode: 'codex' });
|
||||
expect(createBody(fetchMock).codexConfig).toBeUndefined();
|
||||
expect(deleteCalls(fetchMock)).toEqual([]);
|
||||
});
|
||||
|
||||
it('resumes a codex row by the thread id the row carried', async () => {
|
||||
const app = makeApp();
|
||||
await app.resumeHistorySession.call(
|
||||
app,
|
||||
'01a060f0-0361-7f91-abde-b283020db0d7',
|
||||
'/repo',
|
||||
'w1-repo',
|
||||
'codex',
|
||||
'01a060f0-0361-7f91-abde-b283020db0d7'
|
||||
);
|
||||
|
||||
expect(createBody(fetchMock)).toMatchObject({
|
||||
mode: 'codex',
|
||||
codexConfig: { resumeSessionId: '01a060f0-0361-7f91-abde-b283020db0d7' },
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a resumeId on a row that is not codex', async () => {
|
||||
const app = makeApp();
|
||||
await app.resumeHistorySession.call(app, 'old-id', '/repo', 'w1-repo', 'gemini', 'some-thread-id');
|
||||
|
||||
expect(createBody(fetchMock).codexConfig).toBeUndefined();
|
||||
expect(deleteCalls(fetchMock)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['opencode', 'openCodeConfig'],
|
||||
['pi', 'piConfig'],
|
||||
|
||||
@@ -191,7 +191,9 @@ describe('file-raw range requests', () => {
|
||||
});
|
||||
|
||||
it('still refuses files past the raw size cap before looking at Range', async () => {
|
||||
mockedStat.mockResolvedValue({ size: 100 * 1024 * 1024, isFile: () => true } as never);
|
||||
// 3GB, past the 2GB CODEMAN_MAX_DOWNLOAD_BYTES default. The cap is checked
|
||||
// before the range, so a small slice of an oversized file is refused too.
|
||||
mockedStat.mockResolvedValue({ size: 3 * 1024 * 1024 * 1024, isFile: () => true } as never);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
@@ -199,6 +201,18 @@ describe('file-raw range requests', () => {
|
||||
headers: { range: 'bytes=0-99' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.statusCode).toBe(413);
|
||||
});
|
||||
|
||||
it('serves a 100MB file that the historical 50MB cap would have refused', async () => {
|
||||
mockedStat.mockResolvedValue({ size: 100 * 1024 * 1024, isFile: () => true } as never);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: rawUrl('big.mp4'),
|
||||
headers: { range: 'bytes=0-99' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(206);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,6 +115,50 @@ describe('file-routes', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('stamps every entry with its modified time so the picker can sort by date', async () => {
|
||||
mockedReaddir.mockResolvedValueOnce([
|
||||
{ name: 'notes.txt', isDirectory: () => false, isFile: () => true, isSymbolicLink: () => false },
|
||||
{ name: 'src', isDirectory: () => true, isFile: () => false, isSymbolicLink: () => false },
|
||||
{ name: 'link', isDirectory: () => false, isFile: () => false, isSymbolicLink: () => true },
|
||||
] as never);
|
||||
mockedStat.mockImplementation(async (candidate) => {
|
||||
const target = String(candidate);
|
||||
if (target.endsWith('/notes.txt')) {
|
||||
return { size: 42, mtimeMs: 1_700_000_000_000, isFile: () => true, isDirectory: () => false } as never;
|
||||
}
|
||||
if (target.endsWith('/src')) {
|
||||
return { size: 4096, mtimeMs: 1_700_000_001_000, isFile: () => false, isDirectory: () => true } as never;
|
||||
}
|
||||
if (target.endsWith('/link')) {
|
||||
return { size: 7, mtimeMs: 1_700_000_002_000, isFile: () => true, isDirectory: () => false } as never;
|
||||
}
|
||||
return { size: 0, mtimeMs: 0, isFile: () => false, isDirectory: () => true } as never;
|
||||
});
|
||||
|
||||
const path = harness.ctx._session.workingDir;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/filesystem/browse?sessionId=${harness.ctx._sessionId}&path=${encodeURIComponent(path)}`,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const entries = JSON.parse(res.body).data.entries as Array<{
|
||||
name: string;
|
||||
type: string;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}>;
|
||||
expect(entries.map((entry) => [entry.name, entry.type, entry.size, entry.mtimeMs])).toEqual([
|
||||
['src', 'directory', undefined, 1_700_000_001_000],
|
||||
['link', 'file', 7, 1_700_000_002_000],
|
||||
['notes.txt', 'file', 42, 1_700_000_000_000],
|
||||
]);
|
||||
// One stat per entry: the date and the size ride on the same call.
|
||||
const statsFor = (name: string) =>
|
||||
mockedStat.mock.calls.filter(([candidate]) => String(candidate).endsWith(`/${name}`)).length;
|
||||
expect([statsFor('notes.txt'), statsFor('src'), statsFor('link')]).toEqual([1, 1, 1]);
|
||||
});
|
||||
|
||||
it('defaults to the Codeman Cases root, not Home, when linking a case with no path chosen yet', async () => {
|
||||
// The "Link Existing" case picker opens with an empty path and no
|
||||
// sessionId. `Home` and `Codeman Cases` are unrelated bind mounts under
|
||||
@@ -802,14 +846,27 @@ describe('file-routes', () => {
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('rejects overly large raw files', async () => {
|
||||
mockedStat.mockResolvedValue({ size: 100 * 1024 * 1024 } as never); // 100MB
|
||||
it('serves a file past the historical 50MB cap', async () => {
|
||||
// The body is streamed and Range-aware, so size costs a read stream, not
|
||||
// RSS. The old 50MB refusal only blocked legitimate artifact downloads.
|
||||
mockedStat.mockResolvedValue({ size: 100 * 1024 * 1024, isFile: () => true } as never); // 100MB
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/file-raw?path=huge.bin`,
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('still refuses a file past the configured download cap', async () => {
|
||||
mockedStat.mockResolvedValue({ size: 3 * 1024 * 1024 * 1024, isFile: () => true } as never); // 3GB > 2GB default
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/file-raw?path=enormous.bin`,
|
||||
});
|
||||
expect(res.statusCode).toBe(413);
|
||||
expect(JSON.parse(res.body).error).toContain('CODEMAN_MAX_DOWNLOAD_BYTES');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -863,8 +920,9 @@ describe('file-routes', () => {
|
||||
});
|
||||
|
||||
it('downloads files scoped to the session working directory', async () => {
|
||||
const content = Buffer.from('download content');
|
||||
mockedReadFile.mockResolvedValue(content as never);
|
||||
// The body is streamed (shared sendFileBody path), so the bytes come from
|
||||
// the createReadStream mock rather than from readFile.
|
||||
const content = Buffer.from('fake file bytes');
|
||||
mockedStat.mockResolvedValue({ size: content.length, isFile: () => true } as never);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
@@ -874,7 +932,19 @@ describe('file-routes', () => {
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-disposition']).toContain('filename="report.txt"');
|
||||
expect(res.body).toBe('download content');
|
||||
expect(res.headers['accept-ranges']).toBe('bytes');
|
||||
expect(res.body).toBe('fake file bytes');
|
||||
});
|
||||
|
||||
it('refuses a download past the configured cap', async () => {
|
||||
mockedStat.mockResolvedValue({ size: 3 * 1024 * 1024 * 1024, isFile: () => true } as never); // 3GB > 2GB default
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/download?sessionId=${harness.ctx._sessionId}&path=enormous.bin`,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(413);
|
||||
});
|
||||
|
||||
it('rejects absolute paths outside the session working directory', async () => {
|
||||
|
||||
@@ -336,6 +336,69 @@ describe('GET /api/sessions/:id/last-response (claude)', () => {
|
||||
expect(body.data.text).toBe('Let me look.');
|
||||
});
|
||||
|
||||
it('answers context=turn with the last answered turn only, text still on the last row', async () => {
|
||||
const sessionId = harness.ctx._session.id;
|
||||
const session = harness.ctx._session as typeof harness.ctx._session & {
|
||||
claudeSessionId: string;
|
||||
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
session.claudeSessionId = sessionId;
|
||||
session.adoptClaudeSessionId = vi.fn();
|
||||
writeTranscript(sessionId, [
|
||||
userEntry('first'),
|
||||
assistantEntry('Old answer.', '2026-07-21T00:00:01Z'),
|
||||
userEntry('second'),
|
||||
assistantEntry('Looking at the file.', '2026-07-21T00:00:02Z'),
|
||||
{ type: 'assistant', message: { content: [{ type: 'tool_use', id: 'x' }] } },
|
||||
{ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'x' }] } },
|
||||
assistantEntry('The bug is on line 3.', '2026-07-21T00:00:03Z'),
|
||||
assistantEntry('Done.', '2026-07-21T00:00:04Z'),
|
||||
// A prompt queued after the answer opens a new, unanswered turn.
|
||||
queuedEntry('third', '2026-07-21T00:00:05Z'),
|
||||
]);
|
||||
|
||||
const response = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/last-response?context=turn`,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
const data = JSON.parse(response.body).data as {
|
||||
text: string;
|
||||
timestamp: string;
|
||||
messages: Array<{ role: string; text: string; turn: number }>;
|
||||
};
|
||||
// The frozen brief contract holds: still the last assistant row.
|
||||
expect(data.text).toBe('Done.');
|
||||
expect(data.timestamp).toBe('2026-07-21T00:00:04Z');
|
||||
// The turn view is that row's whole turn, assistant rows only, and not the
|
||||
// queued prompt that has no answer yet.
|
||||
expect(data.messages.map((m) => [m.role, m.text, m.turn])).toEqual([
|
||||
['assistant', 'Looking at the file.', 2],
|
||||
['assistant', 'The bug is on line 3.', 2],
|
||||
['assistant', 'Done.', 2],
|
||||
]);
|
||||
|
||||
const brief = await getLastResponse(sessionId);
|
||||
expect(brief.body.data).toEqual({ text: 'Done.', timestamp: '2026-07-21T00:00:04Z' });
|
||||
});
|
||||
|
||||
it('answers context=turn with an empty list when nothing has been answered yet', async () => {
|
||||
const sessionId = harness.ctx._session.id;
|
||||
const session = harness.ctx._session as typeof harness.ctx._session & {
|
||||
claudeSessionId: string;
|
||||
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
session.claudeSessionId = sessionId;
|
||||
session.adoptClaudeSessionId = vi.fn();
|
||||
writeTranscript(sessionId, [userEntry('go')]);
|
||||
|
||||
const response = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/last-response?context=turn`,
|
||||
});
|
||||
expect(JSON.parse(response.body).data).toEqual({ text: '', timestamp: '', messages: [] });
|
||||
});
|
||||
|
||||
/**
|
||||
* A multi-line paste absorbed mid-turn arrives as N queued rows within a few
|
||||
* hundred milliseconds (observed: 5 rows inside ~360ms). They are one turn, so
|
||||
|
||||
@@ -851,6 +851,85 @@ describe('session-routes', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('full reload (?full=1) keeps every leading row so the restored cursor lands on the right line', async () => {
|
||||
// The capture ends with an absolute cursor move, so its rows and the pane's
|
||||
// rows must line up one for one. Three transforms used to run over it and
|
||||
// each could delete a leading line: redraw-bloat stripping, the trim that
|
||||
// cuts everything above the Claude banner, and a leading-whitespace strip.
|
||||
// Any one of them shifted the frame up and left the caret a row off.
|
||||
harness.ctx._session.mode = 'claude';
|
||||
harness.ctx._session.terminalBuffer = '';
|
||||
// A blank first row, then the banner — the shape a real pane has.
|
||||
const rendered = ['', '\x1b[1mClaude Code v2.1.266', 'conversation', '\u276f ', '\x1b[4;3H'].join('\r\n');
|
||||
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = vi.fn(
|
||||
(_name: string, opts?: { fullHistory?: boolean }) => (opts?.fullHistory ? rendered : 'visible frame')
|
||||
);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal?full=1`,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.source).toBe('mux-full-history');
|
||||
// The blank first row survives, so row N of the reply is row N of the pane.
|
||||
expect(body.data.terminalBuffer.startsWith('\r\n')).toBe(true);
|
||||
expect(body.data.terminalBuffer.split('\r\n')).toHaveLength(rendered.split('\r\n').length);
|
||||
});
|
||||
|
||||
it('full reload (?full=1) still strips the byte history when no capture came back', async () => {
|
||||
// The row-preserving skips exist for a rendered pane. When the capture is
|
||||
// unavailable the reply IS the byte stream — successive Ink frames, no row
|
||||
// alignment to protect — so keying the skips on the query parameter rather
|
||||
// than on the capture returned it unstripped, which is the whole reason
|
||||
// stripInkRedrawBloat exists. A session with no mux takes this path on
|
||||
// every first selection, not just during an outage.
|
||||
harness.ctx._session.mode = 'claude';
|
||||
// A VPA cluster the stripper will collapse: >= 10 sequences, spanning the
|
||||
// 32KB minimum, with real content after it.
|
||||
const frame = '\x1b[12d' + 'spinner frame '.repeat(240);
|
||||
harness.ctx._session.terminalBuffer = frame.repeat(20) + 'REAL CONTENT AFTER THE BLOAT';
|
||||
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = vi.fn(() => null);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal?full=1`,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.source).toBe('history');
|
||||
expect(body.data.terminalBuffer).toContain('REAL CONTENT AFTER THE BLOAT');
|
||||
// Stripped, not passed through whole.
|
||||
expect(body.data.terminalBuffer.length).toBeLessThan(harness.ctx._session.terminalBuffer.length);
|
||||
});
|
||||
|
||||
it('full reload (?full=1) keeps the byte history when the capture is empty', async () => {
|
||||
// Pins the contract the capture side relies on: an empty capture means
|
||||
// "nothing to replay" and the byte history survives. capturePaneBuffer
|
||||
// returns '' for an all-blank pane precisely to reach this branch, since
|
||||
// retaining trailing blank rows and appending a cursor move would
|
||||
// otherwise make a blank screen non-empty and replace the history with it.
|
||||
// (The blank-pane decision itself is unit-tested on hasVisibleContent —
|
||||
// capturePaneBuffer short-circuits under IS_TEST_MODE and cannot run here.)
|
||||
harness.ctx._session.mode = 'claude';
|
||||
harness.ctx._session.terminalBuffer = 'a real conversation worth keeping';
|
||||
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = vi.fn(
|
||||
(_name: string, opts?: { fullHistory?: boolean }) => (opts?.fullHistory ? '' : 'visible frame')
|
||||
);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal?full=1`,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.source).toBe('history');
|
||||
expect(body.data.terminalBuffer).toContain('a real conversation worth keeping');
|
||||
});
|
||||
|
||||
it('full reload (?full=1) falls back to the byte history when the capture is unavailable', async () => {
|
||||
harness.ctx._session.mode = 'claude';
|
||||
harness.ctx._session.terminalBuffer = 'byte history survives';
|
||||
|
||||
@@ -14,6 +14,94 @@ import {
|
||||
} from '../../src/services/unified-session-service.js';
|
||||
|
||||
describe('mergeUnifiedSessions', () => {
|
||||
// A codex conversation showing twice is worse than cosmetic: the stale PAST row
|
||||
// still resumes, so clicking it starts a SECOND `codex resume` on a thread
|
||||
// already open in another pane. Both folds below are what prevent that.
|
||||
it('folds a RESUMED codex session into its own rollout row', () => {
|
||||
// Session sets claudeSessionId from codexConfig.resumeSessionId, so the live
|
||||
// row already names the thread the rollout is keyed by.
|
||||
const merged = mergeUnifiedSessions({
|
||||
live: [{ id: 'codeman-uuid', status: 'idle', mode: 'codex', claudeSessionId: 'codex-thread-id' }],
|
||||
history: [
|
||||
{
|
||||
sessionId: 'codex-thread-id',
|
||||
workingDir: '/w',
|
||||
sizeBytes: 4000,
|
||||
lastModified: '2026-09-02T00:00:00.000Z',
|
||||
mode: 'codex',
|
||||
resumeId: 'codex-thread-id',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(merged).toHaveLength(1);
|
||||
expect(merged[0].sessionId).toBe('codeman-uuid');
|
||||
expect([...merged[0].sources].sort()).toEqual(['history', 'live']);
|
||||
});
|
||||
|
||||
it('folds a FRESH codex session once its rollout has been matched by originator', () => {
|
||||
// A fresh pane knows no thread id, so gatherUnifiedInputs() stamps one onto
|
||||
// the live row from session_meta.originator (see codexThreadBySessionId).
|
||||
// This is that stamped row.
|
||||
const merged = mergeUnifiedSessions({
|
||||
live: [{ id: 'codeman-uuid', status: 'busy', mode: 'codex', claudeSessionId: 'fresh-thread-id' }],
|
||||
persisted: [{ id: 'codeman-uuid', status: 'idle', mode: 'codex', claudeSessionId: 'fresh-thread-id' }],
|
||||
history: [
|
||||
{
|
||||
sessionId: 'fresh-thread-id',
|
||||
workingDir: '/w',
|
||||
sizeBytes: 900,
|
||||
lastModified: '2026-09-02T00:00:00.000Z',
|
||||
mode: 'codex',
|
||||
resumeId: 'fresh-thread-id',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(merged).toHaveLength(1);
|
||||
expect(merged[0].sessionId).toBe('codeman-uuid');
|
||||
expect(merged[0].status).toBe('busy');
|
||||
});
|
||||
|
||||
it('leaves an unrelated codex rollout as its own row', () => {
|
||||
const merged = mergeUnifiedSessions({
|
||||
live: [{ id: 'codeman-uuid', status: 'idle', mode: 'codex', claudeSessionId: 'thread-one' }],
|
||||
history: [
|
||||
{
|
||||
sessionId: 'thread-two',
|
||||
workingDir: '/w',
|
||||
sizeBytes: 4000,
|
||||
lastModified: '2026-09-02T00:00:00.000Z',
|
||||
mode: 'codex',
|
||||
resumeId: 'thread-two',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(merged.map((m) => m.sessionId).sort()).toEqual(['codeman-uuid', 'thread-two']);
|
||||
});
|
||||
|
||||
it("carries a transcript row's own resume token, and stamps none on a live row", () => {
|
||||
// codex names a thread by an id in its rollout, not by Codeman's session id.
|
||||
// The scanner sets `resumeId`; a live session never does, which is what stops
|
||||
// a resume from asking codex for a thread whose id is really Codeman's uuid.
|
||||
const merged = mergeUnifiedSessions({
|
||||
live: [{ id: 'codeman-uuid', status: 'idle', mode: 'codex' }],
|
||||
history: [
|
||||
{
|
||||
sessionId: 'codex-thread-id',
|
||||
workingDir: '/w',
|
||||
sizeBytes: 4000,
|
||||
lastModified: '2026-09-02T00:00:00.000Z',
|
||||
mode: 'codex',
|
||||
resumeId: 'codex-thread-id',
|
||||
},
|
||||
],
|
||||
});
|
||||
const fromTranscript = merged.find((m) => m.sessionId === 'codex-thread-id');
|
||||
const fromLive = merged.find((m) => m.sessionId === 'codeman-uuid');
|
||||
expect(fromTranscript?.resumeId).toBe('codex-thread-id');
|
||||
expect(fromTranscript?.mode).toBe('codex');
|
||||
expect(fromLive?.resumeId).toBeUndefined();
|
||||
});
|
||||
|
||||
it('dedupes the same sessionId across live + persisted into one item', () => {
|
||||
const merged = mergeUnifiedSessions({
|
||||
live: [{ id: 's1', status: 'working', isWorking: true }],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Working/idle detection for an interactive Claude pane.
|
||||
* Working/idle detection for an interactive agent pane, Claude's and Codex's.
|
||||
*
|
||||
* The bug this pins: Claude redraws the composer (`❯`) about once a second all
|
||||
* the way through a turn, so the old "saw a ❯, wait 2s, call it idle" rule
|
||||
@@ -7,11 +7,17 @@
|
||||
* worker: `GET /api/sessions` reported `idle` for a session that had been
|
||||
* running for 17 minutes and was mid-tool-call.
|
||||
*
|
||||
* A second bug this pins: work detection read Claude's glyph and Claude's status line
|
||||
* for every CLI, so a Codex session reported itself idle through an entire turn. Each CLI
|
||||
* now names its own pair in `capabilities.workDetect`, and a CLI that names none reports
|
||||
* work exactly as before.
|
||||
*
|
||||
* The status-line fixtures below are verbatim captures from live panes
|
||||
* (`tmux -L codeman capture-pane -p`) on Claude Code 2.1.220.
|
||||
* (`tmux -L codeman capture-pane -p`) on Claude Code 2.1.220 and Codex CLI 0.152.1.
|
||||
*/
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest';
|
||||
import { Session } from '../src/session.js';
|
||||
import { getCli } from '../src/config/cli-registry/index.js';
|
||||
import { CLAUDE_WORKING_LINE_PATTERN } from '../src/utils/regex-patterns.js';
|
||||
import {
|
||||
trackActivityStreak,
|
||||
@@ -38,7 +44,7 @@ function feed(session: Session, data: string): void {
|
||||
* A session whose mux reports a fixed (or scripted) screen, so the pane probe has
|
||||
* something to read. Only `capturePaneText` is exercised by these paths.
|
||||
*/
|
||||
function withFakePane(screen: string | (() => string)): Session {
|
||||
function withFakePane(screen: string | (() => string), mode: 'claude' | 'codex' = 'claude'): Session {
|
||||
const read = typeof screen === 'function' ? screen : () => screen;
|
||||
const mux = {
|
||||
isAvailable: () => true,
|
||||
@@ -46,12 +52,26 @@ function withFakePane(screen: string | (() => string)): Session {
|
||||
} as unknown as NonNullable<Parameters<typeof Session.prototype.constructor>[0]>['mux'];
|
||||
return new Session({
|
||||
workingDir: '/tmp',
|
||||
mode: 'claude',
|
||||
mode,
|
||||
mux,
|
||||
muxSession: { muxName: 'codeman-test', sessionId: 'test', createdAt: Date.now() },
|
||||
} as ConstructorParameters<typeof Session>[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex's pane, verbatim, while a turn runs and once it has finished. Codex draws `›` on
|
||||
* its composer row through the whole turn, exactly as Claude draws `❯`, and prints
|
||||
* `esc to interrupt` only while the turn is live.
|
||||
*/
|
||||
const CODEX_WORKING =
|
||||
'Working (2m 49s • esc to interrupt)\n› Ask Codex to do anything\n' +
|
||||
' gpt-5.6-sol high · Context 59% left · ~/innovi/irisplus-ent-2 · main\n';
|
||||
const CODEX_FINISHED =
|
||||
'─ Worked for 3m 47s ────────────────────\n› Ask Codex to do anything\n' +
|
||||
' gpt-5.6-sol high · Context 57% left · ~/innovi/irisplus-ent-2 · main\n';
|
||||
/** Codex's own composer repaint, the frame that arms the idle confirmation. */
|
||||
const CODEX_COMPOSER_REPAINT = '\x1b[31;1H\x1b[38;5;246m›\xa0\x1b[39m\x1b[0m';
|
||||
|
||||
/** A composer repaint: the frame Claude ships roughly once a second while working. */
|
||||
const COMPOSER_REPAINT =
|
||||
'\x1b[31;1H\x1b[38;5;246m❯\xa0\x1b[39m\x1b[0m\x1b[33;1H \x1b[38;5;246mOpus 5 in:143,699 out:669 ctx:14%\x1b[39m';
|
||||
@@ -230,11 +250,13 @@ describe('Session interactive idle detection', () => {
|
||||
expect(session.status).toBe('idle');
|
||||
});
|
||||
|
||||
it('does not mark an external CLI pane working off raw activity', () => {
|
||||
it('does not mark an uncharacterised CLI working off raw activity', () => {
|
||||
vi.useFakeTimers();
|
||||
// Codex/Gemini/OpenCode render their own TUIs and have no ❯, so nothing would
|
||||
// arm the idle confirmation, so a session marked working here would never recover.
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'codex' });
|
||||
// Gemini and OpenCode render their own TUIs, and Codeman knows neither one's glyph,
|
||||
// so nothing would arm the idle confirmation and a session marked working here would
|
||||
// never recover. A CLI that names no glyph therefore reports no work at all.
|
||||
expect(getCli('gemini')?.capabilities.workDetect).toBeUndefined();
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'gemini' });
|
||||
const events: string[] = [];
|
||||
session.on('working', () => events.push('working'));
|
||||
|
||||
@@ -245,6 +267,59 @@ describe('Session interactive idle detection', () => {
|
||||
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
|
||||
it('marks a Codex pane working, and lets the turn end', () => {
|
||||
vi.useFakeTimers();
|
||||
let screen = CODEX_WORKING;
|
||||
const session = withFakePane(() => screen, 'codex');
|
||||
const events: string[] = [];
|
||||
session.on('working', () => events.push('working'));
|
||||
session.on('idle', () => events.push('idle'));
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
feed(session, CODEX_COMPOSER_REPAINT);
|
||||
vi.advanceTimersByTime(1000);
|
||||
}
|
||||
vi.advanceTimersByTime(20_000);
|
||||
|
||||
// The old code reported this session idle for the whole turn.
|
||||
expect(events).toEqual(['working']);
|
||||
expect(session.status).toBe('busy');
|
||||
|
||||
// Turn over: the working footer gives way to the finished line, which must NOT
|
||||
// read as work — it sits on screen for the whole idle period afterwards.
|
||||
screen = CODEX_FINISHED;
|
||||
vi.advanceTimersByTime(20_000);
|
||||
|
||||
expect(events).toEqual(['working', 'idle']);
|
||||
expect(session.status).toBe('idle');
|
||||
});
|
||||
});
|
||||
|
||||
describe("codex's work-detection descriptor", () => {
|
||||
const codex = getCli('codex')?.capabilities.workDetect;
|
||||
|
||||
it('matches the footer Codex prints while a turn runs', () => {
|
||||
expect(new RegExp(codex!.workingLine).test(CODEX_WORKING)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not match the finished line, nor the idle footer', () => {
|
||||
expect(new RegExp(codex!.workingLine).test(CODEX_FINISHED)).toBe(false);
|
||||
});
|
||||
|
||||
it('matches the footer case-insensitively on the E', () => {
|
||||
// Characterised on codex-cli 0.152.1, which prints a lowercase `esc`. A future
|
||||
// version capitalising it would otherwise make the whole fix silently inert:
|
||||
// the pane would simply never look like it was working.
|
||||
expect(new RegExp(codex!.workingLine).test(CODEX_WORKING.replace('esc to interrupt', 'Esc to interrupt'))).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('names the glyph Codex actually draws on its composer row', () => {
|
||||
expect(CODEX_COMPOSER_REPAINT).toContain(codex!.promptGlyph);
|
||||
expect(CODEX_WORKING).toContain(codex!.promptGlyph);
|
||||
});
|
||||
});
|
||||
|
||||
describe('wire activity stamp across recovery', () => {
|
||||
|
||||
@@ -100,9 +100,11 @@ describe('Session claude conversation chain', () => {
|
||||
// before this existed. Every assignment built from the launch-id fallback
|
||||
// must therefore carry `restoredConversation` first.
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/session.ts'), 'utf8');
|
||||
const fallbackAssignments = source.match(
|
||||
/_claudeSessionId =\s*\n?\s*[^;]*?_resumeSessionId \|\| this\._ompConfig\?\.resumeSessionId \|\| this\.id;/g
|
||||
);
|
||||
// The tail of the chain grows as each CLI gains a resume alias of its own
|
||||
// (omp, then codex), so the pattern pins the two ends and lets the middle
|
||||
// widen. A `[^;]` run cannot cross a statement boundary, so each match is
|
||||
// still one assignment.
|
||||
const fallbackAssignments = source.match(/_claudeSessionId =[^;]*?_resumeSessionId[^;]*?this\.id;/g);
|
||||
expect(fallbackAssignments).not.toBeNull();
|
||||
expect(fallbackAssignments!.length).toBeGreaterThanOrEqual(2);
|
||||
for (const assignment of fallbackAssignments!) {
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
/**
|
||||
* @fileoverview The vertical tab rail's row ORDER and its card styling.
|
||||
*
|
||||
* The rail lists exactly the sessions both home screens list (the phone
|
||||
* overview and the desktop home rail), so it now answers their question the
|
||||
* same way: `CodemanSessionOrder` (constants.js) puts whatever is blocked on a
|
||||
* human first, then whatever has been running longest, then the most recently
|
||||
* quiet. Three things about that can go wrong silently and are pinned here.
|
||||
*
|
||||
* 1. THE ROW MODEL. The comparator reads `state` plus two raw stamps, and a
|
||||
* WORKING row is ranked by `lastSubmitAt` rather than `lastActivityAt`
|
||||
* (a working pane repaints about once a second, so its last-activity stamp
|
||||
* is always "now"). Dropping `lastSubmitAt` from the row would not throw and
|
||||
* would not fail a rendering test — every running turn would just quietly
|
||||
* rank as freshly started.
|
||||
*
|
||||
* 2. THE ALT+N BADGE. The sort is applied as the flex `order` property while
|
||||
* the DOM stays in `sessionOrder`, which is what keeps the number badge
|
||||
* honest: it names the Alt+N key, not the row's position, so it deliberately
|
||||
* does NOT run 1,2,3 down a sorted rail.
|
||||
*
|
||||
* 3. THE OPT-OUT. A self-sorting list cannot also be drag-reorderable, so the
|
||||
* drag affordance is dropped while sorting is on and `tabRailSort: 'manual'`
|
||||
* is the way back. That decision lives in one place and must stay wired to
|
||||
* the attribute the render paths read.
|
||||
*
|
||||
* Port: none (vm-loaded app.js + static source/markup assertions).
|
||||
*/
|
||||
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';
|
||||
import { SettingsUpdateSchema } from '../src/web/schemas.js';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const appJs = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
const html = readFileSync(resolve(PUBLIC, 'index.html'), 'utf8');
|
||||
const settingsUi = readFileSync(resolve(PUBLIC, 'settings-ui.js'), 'utf8');
|
||||
const styles = readFileSync(resolve(PUBLIC, 'styles.css'), 'utf8');
|
||||
|
||||
/** The rail's rich-row scope, spelled exactly as styles.css must spell it. */
|
||||
const RAIL_RICH = "html[data-tab-orientation='vertical'][data-tab-rail-detail='rich']:not(.tab-rail-compact) .tab-rail";
|
||||
|
||||
/** The <html> element the vm's app.js reads. Mutable, so the REAL gate runs. */
|
||||
type Root = { dataset: Record<string, string>; getAttribute: (name: string) => string | null };
|
||||
|
||||
/**
|
||||
* Load app.js + mobile-overview.js in one vm context, so `_tabRailSortOrder()`
|
||||
* runs against the REAL `_mobileOverviewState()` rather than a copy of it that
|
||||
* could drift. Same stubbing technique as session-close-fallback.test.ts, plus a
|
||||
* writable `document.documentElement`: `isTabRailSorted()` reads the layout off
|
||||
* <html>, and stubbing THAT out on the instance would leave the shipped gate
|
||||
* untested while these assertions kept passing.
|
||||
*/
|
||||
function loadCodemanAppClass(): { CodemanApp: new () => unknown; root: Root } {
|
||||
const attrs: Record<string, string> = {};
|
||||
const root: Root = { dataset: {}, getAttribute: (name: string) => attrs[name] ?? null };
|
||||
Object.defineProperty(root, '__attrs', { value: attrs });
|
||||
const context = vm.createContext({
|
||||
console: { ...console, log: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
performance,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: { OPEN: 1 },
|
||||
fetch: vi.fn(),
|
||||
document: {
|
||||
addEventListener: vi.fn(),
|
||||
getElementById: () => null,
|
||||
querySelector: () => null,
|
||||
documentElement: root,
|
||||
},
|
||||
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' },
|
||||
});
|
||||
const read = (f: string) => readFileSync(resolve(PUBLIC, f), 'utf8');
|
||||
vm.runInContext(
|
||||
`${read('constants.js')}\n${read('app.js')}\n${read('mobile-overview.js')}\nglobalThis.__CodemanApp = CodemanApp;`,
|
||||
context
|
||||
);
|
||||
return { CodemanApp: (context as { __CodemanApp: new () => unknown }).__CodemanApp, root };
|
||||
}
|
||||
|
||||
const { CodemanApp, root: railRoot } = loadCodemanAppClass();
|
||||
|
||||
/** Point the shared <html> stub at one rail configuration. */
|
||||
function setLayout(attrs: Record<string, string>): void {
|
||||
const raw = (railRoot as unknown as { __attrs: Record<string, string> }).__attrs;
|
||||
for (const key of Object.keys(raw)) delete raw[key];
|
||||
for (const key of Object.keys(railRoot.dataset)) delete railRoot.dataset[key];
|
||||
raw['data-tab-orientation'] = attrs['data-tab-orientation'] ?? 'vertical';
|
||||
railRoot.dataset.tabRailSort = attrs.tabRailSort ?? 'activity';
|
||||
railRoot.dataset.tabRailDetail = attrs.tabRailDetail ?? 'rich';
|
||||
}
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
status?: string;
|
||||
lastActivityAt?: number;
|
||||
lastSubmitAt?: number;
|
||||
hooks?: string[];
|
||||
};
|
||||
|
||||
type RailApp = {
|
||||
isTabRailSorted: () => boolean;
|
||||
_tabRailSortOrder: (ids: string[]) => Map<string, number> | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Instance with the two inputs the order needs real (`sessions`,
|
||||
* `pendingHooks`); the rail gate answers from the shared <html> stub, so the
|
||||
* shipped `isTabRailSorted()` is what decides.
|
||||
*/
|
||||
function makeApp(rows: Row[], attrs: Record<string, string> = {}): RailApp {
|
||||
setLayout(attrs);
|
||||
const app = Object.create((CodemanApp as { prototype: object }).prototype) as RailApp & Record<string, unknown>;
|
||||
app.sessions = new Map(rows.map((r) => [r.id, { ...r, mode: 'claude' }]));
|
||||
app.pendingHooks = new Map(rows.filter((r) => r.hooks).map((r) => [r.id, new Set(r.hooks)]));
|
||||
return app;
|
||||
}
|
||||
|
||||
/** Visual positions keyed by id, for readable assertions. */
|
||||
function positions(app: RailApp, ids: string[]): Record<string, number> | null {
|
||||
const map = app._tabRailSortOrder(ids);
|
||||
if (!map) return null;
|
||||
return Object.fromEntries(map);
|
||||
}
|
||||
|
||||
const NOW = 1_700_000_000_000;
|
||||
const minsAgo = (m: number) => NOW - m * 60_000;
|
||||
|
||||
describe('vertical tab rail row order', () => {
|
||||
it('puts a blocked session first, longest-blocked ahead of the newest block', () => {
|
||||
const ids = ['fresh-block', 'old-block', 'quiet'];
|
||||
const app = makeApp([
|
||||
{ id: 'fresh-block', status: 'idle', lastActivityAt: minsAgo(1), hooks: ['permission_prompt'] },
|
||||
{ id: 'old-block', status: 'idle', lastActivityAt: minsAgo(30), hooks: ['permission_prompt'] },
|
||||
{ id: 'quiet', status: 'idle', lastActivityAt: minsAgo(2) },
|
||||
]);
|
||||
expect(positions(app, ids)).toEqual({ 'old-block': 0, 'fresh-block': 1, quiet: 2 });
|
||||
});
|
||||
|
||||
it('ranks a running session by its last Enter, not by the repaint it just did', () => {
|
||||
// Both panes printed a byte a moment ago, which is what a working pane does
|
||||
// about once a second. Only lastSubmitAt says which turn actually started
|
||||
// first, so reading lastActivityAt here would call this a tie and fall
|
||||
// through to tab order — silently, and in the wrong direction.
|
||||
const ids = ['short-turn', 'long-turn'];
|
||||
const app = makeApp([
|
||||
{ id: 'short-turn', status: 'busy', lastActivityAt: minsAgo(0), lastSubmitAt: minsAgo(2) },
|
||||
{ id: 'long-turn', status: 'busy', lastActivityAt: minsAgo(0), lastSubmitAt: minsAgo(40) },
|
||||
]);
|
||||
expect(positions(app, ids)).toEqual({ 'long-turn': 0, 'short-turn': 1 });
|
||||
});
|
||||
|
||||
it('flips the tiebreak for quiet sessions: most recently quiet first', () => {
|
||||
const ids = ['yesterday', 'just-finished'];
|
||||
const app = makeApp([
|
||||
{ id: 'yesterday', status: 'idle', lastActivityAt: minsAgo(1440) },
|
||||
{ id: 'just-finished', status: 'idle', lastActivityAt: minsAgo(1) },
|
||||
]);
|
||||
expect(positions(app, ids)).toEqual({ 'just-finished': 0, yesterday: 1 });
|
||||
});
|
||||
|
||||
it('orders the whole fleet blocked → running → quiet', () => {
|
||||
const ids = ['idle-a', 'working', 'needs', 'waiting', 'idle-b'];
|
||||
const app = makeApp([
|
||||
{ id: 'idle-a', status: 'idle', lastActivityAt: minsAgo(2) },
|
||||
{ id: 'working', status: 'busy', lastActivityAt: minsAgo(0), lastSubmitAt: minsAgo(12) },
|
||||
{ id: 'needs', status: 'idle', lastActivityAt: minsAgo(5), hooks: ['permission_prompt'] },
|
||||
{ id: 'waiting', status: 'idle', lastActivityAt: minsAgo(3), hooks: ['idle_prompt'] },
|
||||
{ id: 'idle-b', status: 'idle', lastActivityAt: minsAgo(90) },
|
||||
]);
|
||||
expect(positions(app, ids)).toEqual({ needs: 0, waiting: 1, working: 2, 'idle-a': 3, 'idle-b': 4 });
|
||||
});
|
||||
|
||||
it('returns no order at all when the rail is horizontal or set to manual', () => {
|
||||
const rows: Row[] = [{ id: 'a', status: 'idle', lastActivityAt: minsAgo(1) }];
|
||||
const horizontal = makeApp(rows, { 'data-tab-orientation': 'horizontal' });
|
||||
expect(horizontal.isTabRailSorted()).toBe(false);
|
||||
expect(horizontal._tabRailSortOrder(['a'])).toBeNull();
|
||||
const manual = makeApp(rows, { tabRailSort: 'manual' });
|
||||
expect(manual.isTabRailSorted()).toBe(false);
|
||||
expect(manual._tabRailSortOrder(['a'])).toBeNull();
|
||||
expect(makeApp(rows).isTabRailSorted()).toBe(true);
|
||||
});
|
||||
|
||||
it('sorts a SIMPLE rail too — it lists the same sessions, it just says less', () => {
|
||||
const ids = ['quiet', 'blocked'];
|
||||
const app = makeApp(
|
||||
[
|
||||
{ id: 'quiet', status: 'idle', lastActivityAt: minsAgo(1) },
|
||||
{ id: 'blocked', status: 'idle', lastActivityAt: minsAgo(9), hooks: ['permission_prompt'] },
|
||||
],
|
||||
{ tabRailDetail: 'simple' }
|
||||
);
|
||||
expect(positions(app, ids)).toEqual({ blocked: 0, quiet: 1 });
|
||||
});
|
||||
|
||||
it('keeps the Alt+N badge on the tab index while the cards are sorted', () => {
|
||||
// `_tabIdx` counts the loop over sessionOrder, and only `style="order:…"`
|
||||
// moves the card — so the badge names a shortcut, not a row position.
|
||||
expect(appJs).toContain(
|
||||
'const railSortOrder = this._tabRailSortOrder(tabOrder.filter((id) => this.sessions.has(id)));'
|
||||
);
|
||||
expect(appJs).toContain('` style="order:${railSortOrder.get(id)}"`');
|
||||
expect(appJs).toMatch(/_tabIdx < 9 \? '<span class="tab-number">' \+ \(_tabIdx \+ 1\)/);
|
||||
// The loop itself still walks the user's order, which is what makes the
|
||||
// badge, drag-and-drop and the arrow-key walk agree with each other.
|
||||
expect(appJs).toContain('const tabOrder = this.sessionOrder;');
|
||||
});
|
||||
|
||||
it('re-applies the order from the incremental path, since a state change adds no tab', () => {
|
||||
// A session going working→idle never adds or removes a tab, so the full
|
||||
// rebuild is not reached — and a rebuild here would restart every card's
|
||||
// animation on every SSE tick anyway.
|
||||
expect(appJs).toContain(
|
||||
'const railSortOrder = this._tabRailSortOrder(this.sessionOrder.filter((sid) => this.sessions.has(sid)));'
|
||||
);
|
||||
expect(appJs).toContain('if (tab.style.order !== railOrder) tab.style.order = railOrder;');
|
||||
// An empty string is what clears the property when the rail stops sorting.
|
||||
expect(appJs).toContain("const railOrder = railSortOrder?.has(id) ? String(railSortOrder.get(id)) : '';");
|
||||
});
|
||||
|
||||
it('drops the drag affordance while sorting, so a card cannot snap back', () => {
|
||||
const drag = appJs.slice(appJs.indexOf('setupTabDragHandlers() {'));
|
||||
expect(drag.indexOf('if (this.isTabRailSorted()) {')).toBeLessThan(
|
||||
drag.indexOf("tab.setAttribute('draggable', 'true')")
|
||||
);
|
||||
expect(drag).toContain("tabs.forEach((tab) => tab.setAttribute('draggable', 'false'));");
|
||||
});
|
||||
|
||||
it('classifies and compares through the shared helpers, never a local copy', () => {
|
||||
const fn = appJs.slice(appJs.indexOf('_tabRailSortOrder(ids) {'), appJs.indexOf('_tabRailSortOrder(ids) {') + 1200);
|
||||
expect(fn).toContain('window.CodemanSessionOrder.sort(rows)');
|
||||
expect(fn).toContain('this._mobileOverviewState(session, this.pendingHooks?.get(ids[i]))');
|
||||
// Both raw stamps, or the comparator silently ranks every running turn as
|
||||
// freshly started (see the file header).
|
||||
expect(fn).toContain('lastActivityAt:');
|
||||
expect(fn).toContain('lastSubmitAt:');
|
||||
expect(fn).toContain('orderIndex: i');
|
||||
// Degrades to tab order rather than throwing when a cached constants.js or
|
||||
// mobile-overview.js is stale.
|
||||
expect(fn).toContain("!window.CodemanSessionOrder || typeof this._mobileOverviewState !== 'function'");
|
||||
});
|
||||
});
|
||||
|
||||
describe('vertical tab rail sort setting', () => {
|
||||
it('accepts only the two documented values', () => {
|
||||
for (const v of ['activity', 'manual']) {
|
||||
expect(SettingsUpdateSchema.safeParse({ tabRailSort: v }).success).toBe(true);
|
||||
}
|
||||
for (const v of ['', 'auto', 'Activity', 1, true]) {
|
||||
expect(SettingsUpdateSchema.safeParse({ tabRailSort: v }).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('is a per-device display key with a control the load/save path can find', () => {
|
||||
expect(settingsUi).toContain("'tabRailSort'");
|
||||
expect(settingsUi).toContain("tabRailSort: 'activity',");
|
||||
expect(settingsUi).toContain("document.getElementById('appSettingsTabRailSort').value");
|
||||
expect(settingsUi).toContain("tabRailSort: document.getElementById('appSettingsTabRailSort').value,");
|
||||
expect(html).toContain('id="appSettingsTabRailSort"');
|
||||
expect(html).toContain('<option value="activity">');
|
||||
expect(html).toContain('<option value="manual">');
|
||||
});
|
||||
|
||||
it('stamps the attribute before first paint and on every settings apply', () => {
|
||||
// Without the pre-paint stamp the rail renders unsorted for a frame and
|
||||
// then reshuffles, which is exactly the flash the other two rail attributes
|
||||
// are stamped there to avoid.
|
||||
expect(html).toContain(
|
||||
"document.documentElement.dataset.tabRailSort=(A.tabRailSort==='manual')?'manual':'activity';"
|
||||
);
|
||||
expect(html).toContain("document.documentElement.dataset.tabRailSort='activity';");
|
||||
expect(settingsUi).toContain('root.dataset.tabRailSort = sort;');
|
||||
// A sort flip leaves orientation on 'vertical' both times, so it has to
|
||||
// count as a change of its own or nothing re-renders.
|
||||
expect(settingsUi).toContain(
|
||||
'const changed = orientationChanged || previousDetail !== detail || previousSort !== sort;'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('vertical tab rail card styling', () => {
|
||||
it('gives detailed rail rows the home screen card, and only the rail', () => {
|
||||
const block = styles.slice(styles.indexOf(`${RAIL_RICH} .session-tabs {`));
|
||||
expect(block).toContain(`${RAIL_RICH} .session-tab {`);
|
||||
for (const decl of ['border-radius: 10px;', 'background: var(--bg-card);', 'flex-wrap: wrap;']) {
|
||||
expect(block.slice(0, 2000)).toContain(decl);
|
||||
}
|
||||
// The detailed SIDEBAR shares the meta line and must stay flat: every rule
|
||||
// in the card block is rail-scoped, never added to the comma-grouped
|
||||
// selectors that carry both surfaces.
|
||||
const cardBlock = block.slice(0, block.indexOf('/* --- Collapsed rail'));
|
||||
expect(cardBlock).not.toContain('.session-sidebar');
|
||||
});
|
||||
|
||||
it('states read in the same three colours as both home screens', () => {
|
||||
const block = styles.slice(styles.indexOf(`${RAIL_RICH} .session-tabs {`));
|
||||
const cardBlock = block.slice(0, block.indexOf('/* --- Collapsed rail'));
|
||||
expect(cardBlock).toContain('.session-tab.tab-state-needs');
|
||||
expect(cardBlock).toContain('.session-tab.tab-state-waiting');
|
||||
expect(cardBlock).toContain('.session-tab.tab-state-working');
|
||||
// Reuses the home rail's keyframes rather than declaring a second pair that
|
||||
// could drift out of step with it.
|
||||
expect(cardBlock).toContain('home-sessions-blink-red');
|
||||
expect(cardBlock).toContain('home-sessions-blink-yellow');
|
||||
});
|
||||
|
||||
it('never lets a state dot outrank the red/yellow alert dot', () => {
|
||||
// The dot rules are (0,5,1)+; the alert rules that mark a session blocked on
|
||||
// a human are only (0,3,0), so each state rule excludes them by hand.
|
||||
const block = styles.slice(styles.indexOf(`${RAIL_RICH} .session-tabs {`));
|
||||
const cardBlock = block.slice(0, block.indexOf('/* --- Collapsed rail'));
|
||||
const dotRules = cardBlock.match(/\.session-tab\.tab-state-\w+[^{]*\.tab-status\b/g) ?? [];
|
||||
expect(dotRules.length).toBeGreaterThanOrEqual(3);
|
||||
for (const rule of dotRules) {
|
||||
expect(rule).toContain(':not(.tab-alert-action):not(.tab-alert-idle)');
|
||||
}
|
||||
});
|
||||
|
||||
it('pins web tabs past the sorted cards instead of interleaving them at order 0', () => {
|
||||
expect(styles).toContain(
|
||||
"html[data-tab-orientation='vertical'][data-tab-rail-sort='activity'] .tab-rail .session-tab[data-webview-id] {"
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* @fileoverview A terminal is measured only once its own font can be measured.
|
||||
*
|
||||
* The first fit runs while the browser is still painting with a fallback font,
|
||||
* whose character cell is a different size from the terminal font's. The grid
|
||||
* that fit produces is therefore wrong, the pane is sized to it, and the
|
||||
* correction arrives after the session's buffer has been replayed — so the CLI
|
||||
* repaints for a shape that does not match what is on screen.
|
||||
*
|
||||
* Two properties carry the fix and both are pinned here:
|
||||
*
|
||||
* - The wait REQUESTS each measurable face and then forces xterm to re-measure.
|
||||
* Waiting alone buys nothing: `FitAddon.proposeDimensions()` divides by a
|
||||
* cached cell size that xterm refreshes only from `open()`, from a resize
|
||||
* that changed the grid, and on a device-pixel-ratio change. Nothing in it
|
||||
* listens for font loading, so a fit after the font arrives can still divide
|
||||
* by the fallback cell and short-circuit.
|
||||
* - The wait is BOUNDED. `FontFaceSet.ready` has no deadline, and `selectSession`
|
||||
* awaits this before painting, so an unbounded wait would strand the session
|
||||
* instead of merely mis-measuring it.
|
||||
*
|
||||
* Loaded via `vm` with a stubbed context (no jsdom — jsdom is broken on this
|
||||
* box; see connection-indicator.test.ts), the same way terminal-buffer-flush
|
||||
* extracts the real mixin methods from terminal-ui.js.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/** The mixin runs inside the vm context, so its `document` must live there. */
|
||||
let currentDocument: unknown;
|
||||
|
||||
function loadTerminalMixin(): Record<string, unknown> {
|
||||
const dir = resolve(import.meta.dirname, '../src/web/public');
|
||||
const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, 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() },
|
||||
get document() {
|
||||
return currentDocument;
|
||||
},
|
||||
});
|
||||
// constants.js supplies TERMINAL_FONT_WAIT_MS and TERMINAL_FONT_UNMEASURED.
|
||||
const constants = readFileSync(resolve(dir, 'constants.js'), 'utf8');
|
||||
const source = readFileSync(resolve(dir, 'terminal-ui.js'), 'utf8');
|
||||
vm.runInContext(`${constants}\n${source}`, context);
|
||||
return FakeCodemanApp.prototype;
|
||||
}
|
||||
|
||||
const mixin = loadTerminalMixin();
|
||||
|
||||
type FontApp = {
|
||||
_awaitTerminalFont: () => Promise<void>;
|
||||
terminal: unknown;
|
||||
};
|
||||
|
||||
function makeApp(fontFamily: string, opts: { measure?: () => void } = {}) {
|
||||
const measure = vi.fn(opts.measure);
|
||||
const app = {
|
||||
_awaitTerminalFont: mixin._awaitTerminalFont,
|
||||
terminal: {
|
||||
options: { fontFamily, fontSize: 14 },
|
||||
_core: { _charSizeService: { measure } },
|
||||
},
|
||||
} as unknown as FontApp & { terminal: { _core: { _charSizeService: { measure: typeof measure } } } };
|
||||
return { app, measure };
|
||||
}
|
||||
|
||||
/** A FontFaceSet stub recording what was asked for. */
|
||||
function fontsStub(overrides: { load?: unknown; ready?: Promise<unknown> } = {}) {
|
||||
const requested: string[] = [];
|
||||
return {
|
||||
requested,
|
||||
fonts: {
|
||||
load: overrides.load ?? ((spec: string) => (requested.push(spec), Promise.resolve([]))),
|
||||
ready: overrides.ready ?? Promise.resolve(),
|
||||
status: 'loaded',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
currentDocument = undefined;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('terminal font settle', () => {
|
||||
it('requests every measurable family in the stack, unquoted', async () => {
|
||||
const stub = fontsStub();
|
||||
currentDocument = stub;
|
||||
const { app } = makeApp('"Fira Code", "JetBrains Mono", monospace');
|
||||
|
||||
await app._awaitTerminalFont();
|
||||
|
||||
expect(stub.requested).toEqual(['14px "Fira Code"', '14px "JetBrains Mono"']);
|
||||
});
|
||||
|
||||
it('does not wait on faces that cannot move the measured cell', async () => {
|
||||
// The symbols face is ~1.2MB of private-use-area glyphs and xterm measures
|
||||
// `W`, so awaiting it puts a megabyte in front of the first frame for
|
||||
// nothing. The generics match no FontFace at all.
|
||||
const stub = fontsStub();
|
||||
currentDocument = stub;
|
||||
const { app } = makeApp('"JetBrains Mono", "Symbols Nerd Font Mono", monospace, serif, system-ui');
|
||||
|
||||
await app._awaitTerminalFont();
|
||||
|
||||
expect(stub.requested).toEqual(['14px "JetBrains Mono"']);
|
||||
});
|
||||
|
||||
it('forces xterm to re-measure, because loading a font does not', async () => {
|
||||
// The property the whole change rests on. Without this the fit that follows
|
||||
// still divides the container by the fallback cell.
|
||||
currentDocument = fontsStub();
|
||||
const { app, measure } = makeApp('"JetBrains Mono"');
|
||||
|
||||
await app._awaitTerminalFont();
|
||||
|
||||
expect(measure).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('gives up on a font that never arrives, and still re-measures', async () => {
|
||||
// FontFaceSet.ready has no deadline of its own, and selectSession awaits
|
||||
// this before painting: unbounded here means a session that never renders.
|
||||
currentDocument = fontsStub({ ready: new Promise(() => {}) });
|
||||
const { app, measure } = makeApp('"JetBrains Mono"');
|
||||
|
||||
const started = Date.now();
|
||||
await app._awaitTerminalFont();
|
||||
|
||||
expect(measure).toHaveBeenCalledTimes(1);
|
||||
// Bounded by TERMINAL_FONT_WAIT_MS (2s), not left pending.
|
||||
expect(Date.now() - started).toBeLessThan(4000);
|
||||
}, 10_000);
|
||||
|
||||
it('survives a rejecting load and a browser with no font API', async () => {
|
||||
currentDocument = fontsStub({ load: () => Promise.reject(new Error('network')) });
|
||||
const { app: rejecting, measure: m1 } = makeApp('"JetBrains Mono"');
|
||||
await expect(rejecting._awaitTerminalFont()).resolves.toBeUndefined();
|
||||
expect(m1).toHaveBeenCalledTimes(1);
|
||||
|
||||
currentDocument = {};
|
||||
const { app: noApi, measure: m2 } = makeApp('"JetBrains Mono"');
|
||||
await expect(noApi._awaitTerminalFont()).resolves.toBeUndefined();
|
||||
// No font API means nothing to wait for and nothing to re-measure against.
|
||||
expect(m2).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not throw when the terminal was disposed mid-wait', async () => {
|
||||
currentDocument = fontsStub();
|
||||
const app = { _awaitTerminalFont: mixin._awaitTerminalFont, terminal: null } as unknown as FontApp;
|
||||
|
||||
await expect(app._awaitTerminalFont()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('selectSession font gate', () => {
|
||||
const appSource = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
|
||||
const selectStart = appSource.indexOf('async selectSession(sessionId, options = {})');
|
||||
const body = appSource.slice(
|
||||
selectStart,
|
||||
appSource.indexOf('\n // Shared cleanup for all session data', selectStart)
|
||||
);
|
||||
|
||||
it('waits for the font before the first fit', () => {
|
||||
const wait = body.indexOf('await this._terminalFontReady');
|
||||
const fit = body.indexOf('if (this.fitAddon) this.fitAddon.fit();');
|
||||
expect(wait).toBeGreaterThan(-1);
|
||||
expect(fit).toBeGreaterThan(-1);
|
||||
expect(wait).toBeLessThan(fit);
|
||||
});
|
||||
|
||||
it('waits BEFORE opening the buffer-load gate', () => {
|
||||
// Inside the gate every live SSE event queues instead of painting, so a slow
|
||||
// font would hold output back rather than only mis-measuring the grid.
|
||||
const wait = body.indexOf('await this._terminalFontReady');
|
||||
const gate = body.indexOf('this._beginBufferLoad(selectGen)');
|
||||
expect(gate).toBeGreaterThan(-1);
|
||||
expect(wait).toBeLessThan(gate);
|
||||
});
|
||||
|
||||
it('keeps the synchronous focus ahead of the wait (iOS Safari)', () => {
|
||||
// iOS honours programmatic focus only inside the user-gesture call stack,
|
||||
// which the first await ends.
|
||||
const focus = body.indexOf('if (shouldFocusTerminal && this.terminal) this.terminal.focus();');
|
||||
const wait = body.indexOf('await this._terminalFontReady');
|
||||
expect(focus).toBeGreaterThan(-1);
|
||||
expect(focus).toBeLessThan(wait);
|
||||
});
|
||||
|
||||
it('re-checks for a newer selection after the wait', () => {
|
||||
const wait = body.indexOf('await this._terminalFontReady');
|
||||
const guard = body.indexOf('this._isStaleSelect(selectGen)', wait);
|
||||
expect(guard).toBeGreaterThan(-1);
|
||||
expect(guard - wait).toBeLessThan(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Wiring for the orphaned-input recovery controller, in a real browser.
|
||||
*
|
||||
* The controller's decision logic is unit-tested in
|
||||
* test/terminal-keycode229-recovery.test.ts. What can only be proven with a
|
||||
* real xterm instance is the wiring:
|
||||
*
|
||||
* - our `input` listener is registered AFTER xterm's, so xterm's `cancel()`
|
||||
* (stopPropagation, not stopImmediatePropagation) does not silence it;
|
||||
* - a `composed: true` insertText preceded by a keydown — the shape Chrome on
|
||||
* Android delivers — is dropped by xterm and recovered by us, exactly once;
|
||||
* - a keystroke xterm DOES handle is delivered exactly once, not twice.
|
||||
*
|
||||
* Browser-driven, so it is excluded from `npm run test:ci` like the other
|
||||
* Playwright suites. Run locally:
|
||||
* npm run test:browser -- test/terminal-keycode229-recovery.browser.test.ts
|
||||
*
|
||||
* Port: 3186 (per CLAUDE.md, ports 3150+ for tests)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { chromium, type Browser, type Page } from 'playwright';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
|
||||
const PORT = 3186;
|
||||
const BASE_URL = `http://localhost:${PORT}`;
|
||||
|
||||
describe('orphaned terminal input recovery wiring', () => {
|
||||
let server: WebServer;
|
||||
let browser: Browser;
|
||||
let page: Page;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = new WebServer(PORT, false, true);
|
||||
await server.start();
|
||||
browser = await chromium.launch({ headless: true });
|
||||
page = await browser.newPage();
|
||||
await page.goto(BASE_URL, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => (window as any).app?.terminal, null, { timeout: 30000 });
|
||||
await page.waitForFunction(() => (window as any).app?._keyCode229Recovery, null, { timeout: 30000 });
|
||||
}, 90000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (browser) await browser.close();
|
||||
if (server) await server.stop();
|
||||
}, 60000);
|
||||
|
||||
/**
|
||||
* Drive one keystroke through the real textarea and report what reached the
|
||||
* PTY send path. `dispatchInput` mirrors GBoard: a keydown with no usable key
|
||||
* identity, then a `composed: true` insertText that xterm refuses to forward.
|
||||
*/
|
||||
async function keystroke(options: { data: string; dispatchInput: boolean; keyCode: number }) {
|
||||
return page.evaluate(async ({ data, dispatchInput, keyCode }) => {
|
||||
const app = (window as any).app;
|
||||
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
|
||||
const originalSessionId = app.activeSessionId;
|
||||
const originalLocalEcho = app._localEchoEnabled;
|
||||
const originalSendInput = app._sendInputAsync;
|
||||
const originalPendingInput = app._pendingInput;
|
||||
const originalLastKeystrokeTime = app._lastKeystrokeTime;
|
||||
const sent: string[] = [];
|
||||
let xtermEmitted = 0;
|
||||
const rec = app._keyCode229Recovery;
|
||||
|
||||
try {
|
||||
app.activeSessionId = 'cod388-browser-regression';
|
||||
app._localEchoEnabled = false;
|
||||
app._pendingInput = '';
|
||||
app._lastKeystrokeTime = 0;
|
||||
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
|
||||
// The controller object is Object.freeze()d, so count xterm's own
|
||||
// canonical emissions by swapping the (writable) property on app.
|
||||
app._keyCode229Recovery = {
|
||||
handleKeyEvent: (e: any) => rec.handleKeyEvent(e),
|
||||
notifyCanonicalData: () => {
|
||||
xtermEmitted += 1;
|
||||
return rec.notifyCanonicalData();
|
||||
},
|
||||
destroy: () => rec.destroy(),
|
||||
};
|
||||
textarea.focus();
|
||||
|
||||
const down = new KeyboardEvent('keydown', {
|
||||
key: 'Unidentified',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true,
|
||||
});
|
||||
Object.defineProperties(down, { keyCode: { value: keyCode }, which: { value: keyCode } });
|
||||
textarea.dispatchEvent(down);
|
||||
|
||||
if (dispatchInput) {
|
||||
textarea.value = data;
|
||||
textarea.dispatchEvent(
|
||||
new InputEvent('input', { data, inputType: 'insertText', bubbles: true, composed: true })
|
||||
);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
return { sent, xtermEmitted };
|
||||
} finally {
|
||||
app.activeSessionId = originalSessionId;
|
||||
app._localEchoEnabled = originalLocalEcho;
|
||||
app._sendInputAsync = originalSendInput;
|
||||
app._pendingInput = originalPendingInput;
|
||||
app._lastKeystrokeTime = originalLastKeystrokeTime;
|
||||
app._keyCode229Recovery = rec;
|
||||
textarea.value = '';
|
||||
}
|
||||
}, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* ⚠ The gap this controller actually fills is NARROWER than "keyCode 229",
|
||||
* and that matters for what these tests can prove.
|
||||
*
|
||||
* xterm already self-recovers keyCode 229: `CompositionHelper.keydown()`
|
||||
* calls `_handleAnyTextareaChanges()`, which snapshots `textarea.value` and
|
||||
* diffs it on a 0 ms timer, emitting the difference itself. So for a 229
|
||||
* keydown there is nothing orphaned to recover, and a test asserting "we
|
||||
* recovered it" would pass while xterm did all the work — measured: xterm
|
||||
* emits, our controller correctly stands down.
|
||||
*
|
||||
* The real gap is an `insertText` input event that xterm's `_inputEvent`
|
||||
* refuses (`composed: true` with a keydown seen) where NO 229 diff was
|
||||
* scheduled to rescue it. These tests therefore assert WHO delivered the
|
||||
* byte, via `xtermEmitted`, not merely that a byte arrived.
|
||||
*/
|
||||
it('recovers a composed insertText that xterm dropped and did not self-rescue', async () => {
|
||||
const { sent, xtermEmitted } = await keystroke({ data: 'x', dispatchInput: true, keyCode: 65 });
|
||||
expect(xtermEmitted).toBe(0); // xterm delivered nothing: genuinely orphaned
|
||||
expect(sent.join('')).toBe('x'); // ...so this byte is ours
|
||||
});
|
||||
|
||||
it('does not duplicate a keystroke xterm self-rescued via its own 0 ms diff', async () => {
|
||||
const { sent, xtermEmitted } = await keystroke({ data: 'y', dispatchInput: true, keyCode: 229 });
|
||||
expect(xtermEmitted).toBe(1); // xterm's 229 textarea diff spoke
|
||||
expect(sent.join('')).toBe('y'); // exactly once — we must not add a second copy
|
||||
});
|
||||
|
||||
it('recovers the same character twice when both keystrokes are orphaned', async () => {
|
||||
const first = await keystroke({ data: 'z', dispatchInput: true, keyCode: 65 });
|
||||
const second = await keystroke({ data: 'z', dispatchInput: true, keyCode: 65 });
|
||||
expect(first.sent.join('')).toBe('z');
|
||||
expect(second.sent.join('')).toBe('z');
|
||||
});
|
||||
|
||||
it('sends nothing for a keydown that produces no input event', async () => {
|
||||
const { sent } = await keystroke({ data: 'q', dispatchInput: false, keyCode: 65 });
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,378 @@
|
||||
/**
|
||||
* Orphaned-input recovery for xterm's helper textarea (PR #388 / COD-27).
|
||||
*
|
||||
* xterm's CoreBrowserTerminal._inputEvent only forwards an `insertText` input
|
||||
* event when `(!ev.composed || !this._keyDownSeen)`. Chrome-on-Android's soft
|
||||
* keyboard produces `composed: true` input events preceded by a keydown, so
|
||||
* that guard is false and the committed character is silently dropped.
|
||||
*
|
||||
* The controller under test forwards the event's own `data` when — and only
|
||||
* when — xterm produced no canonical data for that keystroke. These tests
|
||||
* drive it with synthetic events and an injected timer; no browser is needed.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
type Listener = (event: Record<string, unknown>) => void;
|
||||
|
||||
function makeTextarea() {
|
||||
const listeners = new Map<string, Set<Listener>>();
|
||||
const registrations: Array<{ type: string; capture: unknown }> = [];
|
||||
return {
|
||||
addEventListener(type: string, listener: Listener, capture?: unknown) {
|
||||
const bucket = listeners.get(type) ?? new Set<Listener>();
|
||||
bucket.add(listener);
|
||||
listeners.set(type, bucket);
|
||||
registrations.push({ type, capture });
|
||||
},
|
||||
removeEventListener(type: string, listener: Listener) {
|
||||
listeners.get(type)?.delete(listener);
|
||||
},
|
||||
fire(type: string, event: Record<string, unknown> = {}) {
|
||||
for (const listener of [...(listeners.get(type) ?? [])]) listener({ type, ...event });
|
||||
},
|
||||
listenerCount() {
|
||||
return [...listeners.values()].reduce((total, bucket) => total + bucket.size, 0);
|
||||
},
|
||||
registrations() {
|
||||
return [...registrations];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A committed-text `input` event of the shape Chrome-on-Android delivers. */
|
||||
function inputEvent(data: string, overrides: Record<string, unknown> = {}) {
|
||||
return { data, inputType: 'insertText', isComposing: false, ...overrides };
|
||||
}
|
||||
|
||||
function harness({ screenReader = false } = {}) {
|
||||
const source = readFileSync(new URL('../src/web/public/terminal-keycode229-recovery.js', import.meta.url), 'utf8');
|
||||
const exposed: Record<string, any> = {};
|
||||
vm.runInNewContext(source, { window: exposed, globalThis: exposed }, { filename: 'terminal-keycode229-recovery.js' });
|
||||
|
||||
const textarea = makeTextarea();
|
||||
const emitted: string[] = [];
|
||||
const timers = new Map<number, () => void>();
|
||||
let timerId = 0;
|
||||
|
||||
const controller = exposed.CodemanKeyCode229Recovery.create({
|
||||
textarea,
|
||||
emitRecovered: (data: string) => emitted.push(data),
|
||||
isScreenReaderMode: () => screenReader,
|
||||
setTimer: (callback: () => void) => {
|
||||
const id = ++timerId;
|
||||
timers.set(id, callback);
|
||||
return id;
|
||||
},
|
||||
clearTimer: (id: number) => timers.delete(id),
|
||||
});
|
||||
|
||||
return {
|
||||
controller,
|
||||
emitted,
|
||||
textarea,
|
||||
/** A keydown that carries NO usable key identity, exactly like GBoard's. */
|
||||
keydown(overrides: Record<string, unknown> = {}) {
|
||||
controller.handleKeyEvent({ type: 'keydown', key: 'Unidentified', keyCode: 229, ...overrides });
|
||||
},
|
||||
input(data: string, overrides: Record<string, unknown> = {}) {
|
||||
textarea.fire('input', inputEvent(data, overrides));
|
||||
},
|
||||
flushTimers() {
|
||||
for (const [id, callback] of [...timers]) {
|
||||
timers.delete(id);
|
||||
callback();
|
||||
}
|
||||
},
|
||||
pendingTimers: () => timers.size,
|
||||
};
|
||||
}
|
||||
|
||||
/** terminal-ui.js's exported predicates, loaded the same way as in test/mobile-shell-keyboard.test.ts. */
|
||||
function loadTerminalInput() {
|
||||
const source = readFileSync(new URL('../src/web/public/terminal-ui.js', import.meta.url), 'utf8');
|
||||
const win: Record<string, any> = {
|
||||
addEventListener() {},
|
||||
matchMedia: () => ({ matches: false, addEventListener() {} }),
|
||||
};
|
||||
const sandbox: Record<string, any> = {
|
||||
window: win,
|
||||
globalThis: win,
|
||||
document: { addEventListener() {} },
|
||||
CodemanApp: class {},
|
||||
};
|
||||
win.CodemanApp = sandbox.CodemanApp;
|
||||
vm.runInNewContext(source, sandbox, { filename: 'terminal-ui.js' });
|
||||
return win.CodemanTerminalInput as {
|
||||
shouldSuppressTerminalQueryResponse(data: string): boolean;
|
||||
isTerminalFocusOrMouseReport(data: string): boolean;
|
||||
};
|
||||
}
|
||||
|
||||
describe('orphaned terminal input recovery', () => {
|
||||
it('forwards the committed text when xterm stayed silent', () => {
|
||||
const h = harness();
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
expect(h.emitted).toEqual([]);
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual(['x']);
|
||||
});
|
||||
|
||||
it('forwards nothing when xterm emitted canonical data after the keydown', () => {
|
||||
// The "xterm handled it" case is decided by the COUNTER, never by assuming
|
||||
// the input event does not reach us. On capture it always does (xterm's
|
||||
// cancel() only stops later BUBBLE listeners), so this test dispatches the
|
||||
// real input event AND has xterm emit canonical data for that keystroke.
|
||||
const h = harness();
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
h.controller.notifyCanonicalData();
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it('registers the input listener in the CAPTURE phase', () => {
|
||||
// Measured in jsdom and headless chromium: a capture-phase listener on the
|
||||
// TARGET calling stopPropagation() (which is what xterm's cancel() does in
|
||||
// the branch where it handled the input) stops later BUBBLE listeners on
|
||||
// that same target, because the target is visited twice in the event path.
|
||||
//
|
||||
// capture-then-BUBBLE, stopPropagation: ours NEVER fires
|
||||
// capture-then-CAPTURE, stopPropagation: ours still fires
|
||||
//
|
||||
// So this must not be "tidied" to bubble: on bubble we would silently stop
|
||||
// seeing exactly the events xterm handled, and whether we saw them at all
|
||||
// would depend on xterm's `options.cancelEvents`, which Codeman never sets.
|
||||
const h = harness();
|
||||
const input = h.textarea.registrations().filter((entry) => entry.type === 'input');
|
||||
expect(input).toHaveLength(1);
|
||||
expect(input[0].capture).toBe(true);
|
||||
for (const entry of h.textarea.registrations()) expect(entry.capture).toBe(true);
|
||||
});
|
||||
|
||||
it('forwards nothing on the keypress path, where canonical data precedes the input event', () => {
|
||||
// xterm's _keyPress calls triggerDataEvent() and sets _keyPressHandled
|
||||
// BEFORE the input event fires. The "did xterm speak?" snapshot therefore
|
||||
// has to be taken at keydown; taken at input time it would already include
|
||||
// this emission and the character would be delivered twice.
|
||||
const h = harness();
|
||||
h.keydown();
|
||||
h.controller.notifyCanonicalData();
|
||||
h.input('x');
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not let a stale candidate swallow a later identical keystroke (defect 1)', () => {
|
||||
const h = harness();
|
||||
|
||||
// First keystroke: orphaned, recovered.
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual(['x']);
|
||||
|
||||
// Second identical keystroke, handled by xterm itself.
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
h.controller.notifyCanonicalData();
|
||||
h.flushTimers();
|
||||
|
||||
// Exactly one recovery total, and the second keystroke's canonical byte was
|
||||
// never claimed or suppressed by the first one.
|
||||
expect(h.emitted).toEqual(['x']);
|
||||
});
|
||||
|
||||
it('forwards committed text that no keydown key could describe, exactly once (defect 2)', () => {
|
||||
const h = harness();
|
||||
h.keydown({ key: 'Enter' });
|
||||
h.input('a longer commit');
|
||||
h.flushTimers();
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual(['a longer commit']);
|
||||
});
|
||||
|
||||
it('recovers a GBoard keydown and never reads key or keyCode (defect 3)', () => {
|
||||
const h = harness();
|
||||
const reads: string[] = [];
|
||||
h.controller.handleKeyEvent({
|
||||
type: 'keydown',
|
||||
get key() {
|
||||
reads.push('key');
|
||||
return 'Unidentified';
|
||||
},
|
||||
get keyCode() {
|
||||
reads.push('keyCode');
|
||||
return 229;
|
||||
},
|
||||
get which() {
|
||||
reads.push('which');
|
||||
return 229;
|
||||
},
|
||||
});
|
||||
h.input('x');
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual(['x']);
|
||||
expect(reads).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores input events that are not committed text', () => {
|
||||
const h = harness();
|
||||
for (const inputType of ['insertCompositionText', 'deleteContentBackward', 'insertLineBreak', 'insertFromPaste']) {
|
||||
h.keydown();
|
||||
h.input('x', { inputType });
|
||||
}
|
||||
h.keydown();
|
||||
h.input('');
|
||||
h.keydown();
|
||||
h.textarea.fire('input', { data: null, inputType: 'insertText' });
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores composition and cancels pending candidates on compositionstart', () => {
|
||||
const composing = harness();
|
||||
composing.keydown();
|
||||
composing.input('x', { isComposing: true });
|
||||
composing.flushTimers();
|
||||
expect(composing.emitted).toEqual([]);
|
||||
|
||||
const lifecycle = harness();
|
||||
lifecycle.textarea.fire('compositionstart');
|
||||
lifecycle.keydown();
|
||||
lifecycle.input('中');
|
||||
lifecycle.flushTimers();
|
||||
expect(lifecycle.emitted).toEqual([]);
|
||||
|
||||
// compositionstart arriving after a candidate is queued must cancel it.
|
||||
const cancelled = harness();
|
||||
cancelled.keydown();
|
||||
cancelled.input('x');
|
||||
cancelled.textarea.fire('compositionstart');
|
||||
cancelled.flushTimers();
|
||||
expect(cancelled.emitted).toEqual([]);
|
||||
|
||||
// compositionend releases the gate again.
|
||||
cancelled.textarea.fire('compositionend');
|
||||
cancelled.keydown();
|
||||
cancelled.input('y');
|
||||
cancelled.flushTimers();
|
||||
expect(cancelled.emitted).toEqual(['y']);
|
||||
});
|
||||
|
||||
it('stays out of the way in screen reader mode', () => {
|
||||
const h = harness({ screenReader: true });
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it('recovers an input event that arrives with no preceding keydown', () => {
|
||||
const h = harness();
|
||||
h.input('x');
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual(['x']);
|
||||
});
|
||||
|
||||
it('clears timers and listeners on destroy', () => {
|
||||
const h = harness();
|
||||
expect(h.textarea.listenerCount()).toBeGreaterThan(0);
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
expect(h.pendingTimers()).toBe(1);
|
||||
|
||||
h.controller.destroy();
|
||||
expect(h.pendingTimers()).toBe(0);
|
||||
expect(h.textarea.listenerCount()).toBe(0);
|
||||
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual([]);
|
||||
|
||||
// Nothing fires after destroy, even if a stray event is delivered.
|
||||
h.textarea.fire('input', inputEvent('y'));
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the first input event of a page load, with no keydown before it', () => {
|
||||
it('stands down when xterm already delivered it, instead of duplicating the text', () => {
|
||||
// Dictation (Android voice typing, desktop dictation, any `insertText` with
|
||||
// no key held) reaches xterm with `_keyDownSeen` false, so xterm's OWN capture
|
||||
// listener forwards it and bumps the canonical counter before this controller's
|
||||
// listener runs. The snapshot baseline has to predate that bump, or the
|
||||
// candidate reads "xterm stayed silent" and emits the text a second time.
|
||||
const h = harness();
|
||||
h.controller.notifyCanonicalData(); // xterm delivered it first
|
||||
h.input('hello');
|
||||
h.flushTimers();
|
||||
expect(h.emitted, 'xterm already delivered this text').toEqual([]);
|
||||
});
|
||||
|
||||
it('still recovers one that xterm genuinely dropped', () => {
|
||||
const h = harness();
|
||||
h.input('hello'); // nothing from xterm for it
|
||||
h.flushTimers();
|
||||
expect(h.emitted).toEqual(['hello']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('terminal-ui wiring: what counts as "xterm spoke for this keystroke"', () => {
|
||||
const terminalSource = readFileSync(new URL('../src/web/public/terminal-ui.js', import.meta.url), 'utf8');
|
||||
|
||||
it('gates notifyCanonicalData on the two predicates this file already owns', () => {
|
||||
// onData does NOT only carry keystrokes: xterm answers DA/DSR/CPR/OSC
|
||||
// queries through it during Ink redraws, and emits SGR mouse and focus
|
||||
// reports on its own initiative. Counting one of those as canonical data
|
||||
// for the pending keystroke stands the recovery down and leaves the
|
||||
// character dropped, worst on a busy agent pane, which is the case this
|
||||
// exists for. Same gate, same two predicates, as the one-shot Ctrl
|
||||
// modifier uses for the same question (test/mobile-shell-keyboard.test.ts).
|
||||
const notify = terminalSource.indexOf('_keyCode229Recovery?.notifyCanonicalData?.()');
|
||||
expect(notify).toBeGreaterThan(0);
|
||||
|
||||
const gate = terminalSource.lastIndexOf(
|
||||
'!input?.shouldSuppressTerminalQueryResponse(data) && !input?.isTerminalFocusOrMouseReport(data)',
|
||||
notify
|
||||
);
|
||||
expect(gate).toBeGreaterThan(0);
|
||||
expect(gate).toBeLessThan(notify);
|
||||
|
||||
// ⚠️ The predicates live inside the module IIFE that ends long before this
|
||||
// call site, so they are reachable ONLY through the global. Bare references
|
||||
// would throw a ReferenceError straight into the surrounding try/catch,
|
||||
// which swallows it, and notifyCanonicalData would then NEVER run: the
|
||||
// recovery would re-emit a character xterm already delivered.
|
||||
expect(terminalSource.slice(gate - 120, notify)).toContain('window.CodemanTerminalInput');
|
||||
});
|
||||
|
||||
it('stands down for a real keystroke, but not for a mouse report or a query reply', () => {
|
||||
// The gate as terminal-ui.js writes it. The wiring test above pins the real
|
||||
// source; this proves the behaviour it buys.
|
||||
const input = loadTerminalInput();
|
||||
const onData = (h: ReturnType<typeof harness>, data: string) => {
|
||||
if (!input.shouldSuppressTerminalQueryResponse(data) && !input.isTerminalFocusOrMouseReport(data)) {
|
||||
h.controller.notifyCanonicalData();
|
||||
}
|
||||
};
|
||||
|
||||
for (const noise of ['\x1b[<0;10;5M', '\x1b[I', '\x1b[?1;2c']) {
|
||||
const h = harness();
|
||||
h.keydown();
|
||||
h.input('x');
|
||||
onData(h, noise);
|
||||
h.flushTimers();
|
||||
expect(h.emitted, `${JSON.stringify(noise)} must not stand the recovery down`).toEqual(['x']);
|
||||
}
|
||||
|
||||
const typed = harness();
|
||||
typed.keydown();
|
||||
typed.input('x');
|
||||
onData(typed, 'x');
|
||||
typed.flushTimers();
|
||||
expect(typed.emitted, 'xterm really did deliver this one').toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -11,11 +11,15 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatCursorRestore, 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');
|
||||
const methodStart = source.indexOf('capturePaneBuffer(muxName: string');
|
||||
const methodBody = source.slice(methodStart, methodStart + 4000);
|
||||
// Bounded at the next method so `methodBody` really is one method: the
|
||||
// ordering assertions below would otherwise be satisfiable by a neighbour.
|
||||
const methodEnd = source.indexOf('captureActivePaneBuffer(muxName: string', methodStart);
|
||||
const methodBody = source.slice(methodStart, methodEnd);
|
||||
|
||||
it('capturePaneBuffer accepts pane-capture options with a fullHistory flag', () => {
|
||||
expect(methodStart).toBeGreaterThan(-1);
|
||||
@@ -42,13 +46,37 @@ describe('tmux full-history pane capture (COD-47)', () => {
|
||||
});
|
||||
|
||||
it('returns full-history capture as raw scrollback (skips the single-screen repaint)', () => {
|
||||
// When fullHistory, return the raw buffer BEFORE the formatPaneSnapshot
|
||||
// repaint (which is single-screen and would clip a multi-screen history).
|
||||
const earlyReturn = methodBody.indexOf('return normalizeScrollbackEol(buffer);');
|
||||
// The fullHistory branch returns before the formatPaneSnapshot repaint,
|
||||
// which is single-screen and would clip a multi-screen history.
|
||||
const branch = methodBody.indexOf('if (fullHistory) {\n // Without geometry');
|
||||
const snapshot = methodBody.indexOf('formatPaneSnapshot(');
|
||||
expect(earlyReturn).toBeGreaterThan(-1);
|
||||
expect(branch).toBeGreaterThan(-1);
|
||||
expect(snapshot).toBeGreaterThan(-1);
|
||||
expect(earlyReturn).toBeLessThan(snapshot);
|
||||
expect(branch).toBeLessThan(snapshot);
|
||||
// …and what it returns is normalized linear scrollback, not a repaint.
|
||||
expect(methodBody.slice(branch, snapshot)).toContain('normalizeScrollbackEol(');
|
||||
});
|
||||
|
||||
it('appends the pane cursor to the full-history capture', () => {
|
||||
// A linear replay leaves the caret wherever the last character landed — the
|
||||
// status line, for an agent CLI — and every cursor-relative update the CLI
|
||||
// sends afterwards is then measured from the wrong row.
|
||||
const restore = methodBody.indexOf('formatCursorRestore(geometry)');
|
||||
const snapshot = methodBody.indexOf('formatPaneSnapshot(');
|
||||
expect(restore).toBeGreaterThan(-1);
|
||||
expect(restore).toBeLessThan(snapshot);
|
||||
});
|
||||
|
||||
it('keeps the trailing rows only when a cursor move will follow', () => {
|
||||
// Trailing blank rows are the bottom of the screen and the cursor move counts
|
||||
// up from them, so the two decisions travel together: no geometry, no move,
|
||||
// and the old trim applies instead.
|
||||
expect(methodBody).toContain("rawCapture.replace(/\\n$/, '')");
|
||||
expect(methodBody).toContain("if (!geometry) return normalizeScrollbackEol(rawCapture.replace(/\\n+$/g, ''))");
|
||||
});
|
||||
|
||||
it('defers to the byte history when the pane holds nothing visible', () => {
|
||||
expect(methodBody).toContain("if (!hasVisibleContent(trimmed)) return ''");
|
||||
});
|
||||
|
||||
it('captureActivePaneBuffer forwards the capture options', () => {
|
||||
@@ -59,3 +87,37 @@ describe('tmux full-history pane capture (COD-47)', () => {
|
||||
expect(body).toContain('this.capturePaneBuffer(muxName, target, opts)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('full-history cursor restore', () => {
|
||||
it('counts up from the last replayed row rather than down from the top', () => {
|
||||
// Relative, not `CUP`: absolute row addressing is only correct while the
|
||||
// browser's row count equals the pane's, and resizeWindow does not wait for
|
||||
// tmux, so a capture can be taken before a requested resize has applied.
|
||||
expect(formatCursorRestore({ cols: 80, rows: 24, cursorX: 2, cursorY: 20 })).toBe('\x1b[3A\r\x1b[2C');
|
||||
});
|
||||
|
||||
it('emits no row move when the caret is already on the last row', () => {
|
||||
expect(formatCursorRestore({ cols: 80, rows: 24, cursorX: 5, cursorY: 23 })).toBe('\r\x1b[5C');
|
||||
});
|
||||
|
||||
it('emits no column move for column zero', () => {
|
||||
expect(formatCursorRestore({ cols: 80, rows: 10, cursorX: 0, cursorY: 0 })).toBe('\x1b[9A\r');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasVisibleContent', () => {
|
||||
it('is false for a pane of blank rows', () => {
|
||||
expect(hasVisibleContent('\n'.repeat(23))).toBe(false);
|
||||
});
|
||||
|
||||
it('is false for blank rows carrying only SGR attributes', () => {
|
||||
// `capture-pane -e` styles every row, so an all-blank pane is not an empty
|
||||
// string. Treating it as content would replace the byte history with a
|
||||
// blank screen.
|
||||
expect(hasVisibleContent('\x1b[m \x1b[0m\n\x1b[m \x1b[0m')).toBe(false);
|
||||
});
|
||||
|
||||
it('is true as soon as one row carries a character', () => {
|
||||
expect(hasVisibleContent('\x1b[m \x1b[0m\n\x1b[m x \x1b[0m')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -172,6 +172,43 @@ describe('TmuxManager (unit)', () => {
|
||||
expect(command).toContain('exec "${SHELL:-/bin/sh}" -i -l -c');
|
||||
expect(command).toContain('claude --dangerously-skip-permissions');
|
||||
});
|
||||
|
||||
it('pins SSH-remote claude to the Codeman session id so a respawn resumes the same conversation', () => {
|
||||
// Regression (2026-08-29): remote claude was launched as a bare `claude …`,
|
||||
// so every reattach/respawn after a pane death (user ctrl-d or ctrl-c exit)
|
||||
// started a NEW conversation. The launch now mirrors the docker-claude shape:
|
||||
// `--session-id <id>` to create, with a `|| --resume <id>` fallback so the
|
||||
// idempotent re-run resumes instead of erroring ("already in use").
|
||||
const command = buildRemoteLaunchCommand({
|
||||
mode: 'claude',
|
||||
remote: { hostId: 'gpu-box', label: 'GPU Box', host: '10.0.0.42', username: 'ubuntu', remotePath: '/w' },
|
||||
sessionId: 'abc123def456',
|
||||
});
|
||||
expect(command).toContain('claude --dangerously-skip-permissions --session-id abc123def456');
|
||||
expect(command).toContain('claude --dangerously-skip-permissions --resume abc123def456');
|
||||
});
|
||||
|
||||
it('resumes an explicit resumeSessionId distinct from sessionId (mirrors claudeDockerPaneCommand)', () => {
|
||||
// The docker-claude builder (claudeDockerPaneCommand) has always handled a
|
||||
// resumeId that differs from sessionId — e.g. a resume-from-history launch —
|
||||
// by leading with `--resume <rid> || --session-id <sessionId>`. The remote
|
||||
// claude branch used to only mirror the SAME-id fallback shape and silently
|
||||
// dropped a distinct resumeSessionId, so a remote resume-from-history claude
|
||||
// launch created a brand-new conversation instead of resuming the named one.
|
||||
const command = buildRemoteLaunchCommand({
|
||||
mode: 'claude',
|
||||
remote: { hostId: 'gpu-box', label: 'GPU Box', host: '10.0.0.42', username: 'ubuntu', remotePath: '/w' },
|
||||
sessionId: 'abc123def456',
|
||||
resumeSessionId: 'old-conversation-uuid',
|
||||
});
|
||||
expect(command).toContain('claude --dangerously-skip-permissions --resume old-conversation-uuid');
|
||||
expect(command).toContain('claude --dangerously-skip-permissions --session-id abc123def456');
|
||||
// The resume attempt must lead — session-id is the fallback here, reversed
|
||||
// from the same-id case.
|
||||
const resumeIdx = command.indexOf('--resume old-conversation-uuid');
|
||||
const sessionIdIdx = command.indexOf('--session-id abc123def456');
|
||||
expect(resumeIdx).toBeLessThan(sessionIdIdx);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remote kill command builder', () => {
|
||||
@@ -258,6 +295,13 @@ describe('TmuxManager (unit)', () => {
|
||||
expect(callBuildEnvExports('opencode')).toContain('unset COLORTERM');
|
||||
});
|
||||
|
||||
// Claude renders its themed backgrounds as RGB. Without this the pane inherits
|
||||
// tmux's TERM=screen, supports-color reads 16 colors, and every dark background
|
||||
// quantizes to ESC[40m — the terminal's own black — so the block goes invisible.
|
||||
it('exports truecolor for Claude sessions', () => {
|
||||
expect(callBuildEnvExports('claude')).toContain('export COLORTERM=truecolor');
|
||||
});
|
||||
|
||||
it('exports the server-stamped CODEMAN_API_URL verbatim', () => {
|
||||
const original = process.env.CODEMAN_API_URL;
|
||||
process.env.CODEMAN_API_URL = 'https://127.0.0.1:3199';
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* @fileoverview Loopback links open through a proxied web tab (webview-tabs.js).
|
||||
*
|
||||
* An agent prints `http://localhost:5173/` and the user taps it on a phone. The
|
||||
* browser there can never reach the Codeman box's loopback, so the link was a
|
||||
* guaranteed connection error — while the web-tab proxy fetches from the server,
|
||||
* where it works. Pinned here:
|
||||
*
|
||||
* 1. The decision: only http(s) on a loopback host, and only when the page
|
||||
* itself is not on that host. A LAN/tailnet address stays a direct open.
|
||||
* 2. A saved proxied dashboard on the same origin is reused, with the deep
|
||||
* path appended to the minted proxy prefix; a mounted frame is navigated,
|
||||
* not torn down.
|
||||
* 3. An unknown origin is saved under its host:port and opened.
|
||||
* 4. The terminal link provider and the response viewer consult the hook
|
||||
* before their own opening path.
|
||||
*
|
||||
* Same in-test JSDOM boot as webview-menu-rows.test.ts (no per-file env).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
const CONSTANTS = readFileSync(new URL('../src/web/public/constants.js', import.meta.url), 'utf-8');
|
||||
const WEBVIEW_TABS = readFileSync(new URL('../src/web/public/webview-tabs.js', import.meta.url), 'utf-8');
|
||||
const TERMINAL_UI = readFileSync(new URL('../src/web/public/terminal-ui.js', import.meta.url), 'utf-8');
|
||||
const APP_JS = readFileSync(new URL('../src/web/public/app.js', import.meta.url), 'utf-8');
|
||||
|
||||
type Webview = { id: string; name: string; url: string; embedMode?: string; managed?: string };
|
||||
|
||||
interface AppLike {
|
||||
webviews: Map<string, Webview>;
|
||||
webviewOrder: string[];
|
||||
activeWebviewId: string | null;
|
||||
renderSessionTabs(): void;
|
||||
refreshWebviews(): Promise<void>;
|
||||
openLinkThroughWebTabIfLoopback(url: string): boolean;
|
||||
openUrlInWebTab(url: string): Promise<void>;
|
||||
openWebview(id: string, options?: { path?: string }): Promise<void>;
|
||||
_apiJson(path: string, opts?: { method?: string; body?: unknown }): Promise<unknown>;
|
||||
_updateActiveWebviewTab(): void;
|
||||
showToast?: (msg: string, kind: string) => void;
|
||||
}
|
||||
|
||||
function boot(pageUrl = 'http://192.168.1.135:8095/') {
|
||||
const dom = new JSDOM(
|
||||
`<!doctype html><body><div class="main"></div><div id="sessionTabs"></div><div id="webviewLayer"></div></body>`,
|
||||
{ url: pageUrl, runScripts: 'outside-only' }
|
||||
);
|
||||
const win = dom.window as unknown as Window &
|
||||
typeof globalThis & { app: AppLike; CodemanApp: new () => AppLike; CodemanWebviewLinks: WebviewLinks };
|
||||
(win as unknown as { eval: (s: string) => void }).eval(
|
||||
[
|
||||
'window.CodemanApp = class CodemanApp {};',
|
||||
'window.CodemanBase = { url: (p) => p };',
|
||||
'if (!window.CSS) window.CSS = { escape: (s) => s };',
|
||||
'window.requestAnimationFrame = (fn) => { fn(); return 1; };',
|
||||
CONSTANTS,
|
||||
WEBVIEW_TABS,
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
const calls: Array<{ path: string; method: string; body?: unknown }> = [];
|
||||
const app = new win.CodemanApp();
|
||||
app.webviews = new Map([
|
||||
['dev', { id: 'dev', name: 'localhost:5173', url: 'http://localhost:5173/' }],
|
||||
['direct', { id: 'direct', name: 'Direct', url: 'https://localhost:9443/', embedMode: 'direct' }],
|
||||
]);
|
||||
app.webviewOrder = [];
|
||||
app.activeWebviewId = null;
|
||||
app.renderSessionTabs = () => {};
|
||||
app._updateActiveWebviewTab = () => {};
|
||||
app.refreshWebviews = async () => {};
|
||||
app._apiJson = async (path: string, opts: { method?: string; body?: unknown } = {}) => {
|
||||
calls.push({ path, method: opts.method || 'GET', body: opts.body });
|
||||
if (path === '/api/webviews' && opts.method === 'POST') {
|
||||
const body = opts.body as { name: string; url: string };
|
||||
const created = { id: 'new-id', name: body.name, url: body.url, embedMode: 'proxy' };
|
||||
app.webviews.set(created.id, created);
|
||||
return created;
|
||||
}
|
||||
const open = /^\/api\/webviews\/([^/]+)\/open$/.exec(path);
|
||||
if (open) {
|
||||
const id = decodeURIComponent(open[1]);
|
||||
const webview = app.webviews.get(id);
|
||||
if (!webview) return null;
|
||||
return webview.embedMode === 'direct' ? { webview } : { webview, embedUrl: `/webview/cap-${id}/` };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
win.app = app;
|
||||
return { win, app, calls };
|
||||
}
|
||||
|
||||
interface WebviewLinks {
|
||||
isLoopbackHostname(host: string): boolean;
|
||||
isOnBoxHostname(host: string): boolean;
|
||||
webTabOriginKey(url: URL): string;
|
||||
linkNeedsWebTabProxy(url: string, pageHostname: string): boolean;
|
||||
}
|
||||
|
||||
const frameSrc = (win: Window, id: string) =>
|
||||
(
|
||||
win.document.querySelector(`.webview-frame[data-webview-id="${id}"] iframe`) as HTMLIFrameElement | null
|
||||
)?.getAttribute('src');
|
||||
|
||||
describe('loopback link decision', () => {
|
||||
const { win } = boot();
|
||||
const links = win.CodemanWebviewLinks;
|
||||
|
||||
it('recognises every loopback spelling and nothing else', () => {
|
||||
for (const host of ['localhost', 'LOCALHOST', '127.0.0.1', '127.1.2.3', '0.0.0.0', '[::1]', '::1']) {
|
||||
expect(links.isLoopbackHostname(host), host).toBe(true);
|
||||
}
|
||||
for (const host of [
|
||||
'192.168.1.135',
|
||||
'10.9.0.4',
|
||||
'172.16.0.2',
|
||||
'box.ts.net',
|
||||
'128.0.0.1',
|
||||
'',
|
||||
'localhost.example.com',
|
||||
]) {
|
||||
expect(links.isLoopbackHostname(host), host).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps *.localhost OUT of the auto-route set, because it is a DNS name an attacker can steer', () => {
|
||||
// Every other member of the set is an address literal that can only mean
|
||||
// this box. `evil.localhost` is not: on a resolver that does not synthesise
|
||||
// *.localhost locally and has a search domain configured, it NXDOMAINs as
|
||||
// absolute and is retried as `evil.localhost.<search domain>`. The link
|
||||
// source is agent-written terminal output, so this set is the whole
|
||||
// confinement on a tap that makes Codeman fetch a URL and persist it.
|
||||
expect(links.isLoopbackHostname('app.localhost')).toBe(false);
|
||||
expect(links.isLoopbackHostname('evil.localhost')).toBe(false);
|
||||
expect(links.linkNeedsWebTabProxy('http://evil.localhost/', '192.168.1.135')).toBe(false);
|
||||
|
||||
// The PAGE-side test stays broader: a false positive there only ever
|
||||
// DECLINES to proxy, leaving the caller's own direct open untouched.
|
||||
expect(links.isOnBoxHostname('app.localhost')).toBe(true);
|
||||
expect(links.linkNeedsWebTabProxy('http://localhost:5173/', 'app.localhost')).toBe(false);
|
||||
});
|
||||
|
||||
it('keys a dashboard per dev server, not per host spelling', () => {
|
||||
const key = (u: string) => links.webTabOriginKey(new URL(u));
|
||||
expect(key('http://localhost:5173/')).toBe(key('http://127.0.0.1:5173/'));
|
||||
expect(key('http://localhost:5173/')).not.toBe(key('http://localhost:5174/'));
|
||||
expect(key('http://localhost:5173/')).not.toBe(key('https://localhost:5173/'));
|
||||
expect(key('http://box.ts.net:3000/')).toBe('http://box.ts.net:3000');
|
||||
});
|
||||
|
||||
it('proxies a loopback http(s) link only when the page is not on that box', () => {
|
||||
expect(links.linkNeedsWebTabProxy('http://localhost:5173/', '192.168.1.135')).toBe(true);
|
||||
expect(links.linkNeedsWebTabProxy('https://127.0.0.1:8443/x?y=1', 'box.ts.net')).toBe(true);
|
||||
// On the box itself the browser reaches localhost directly.
|
||||
expect(links.linkNeedsWebTabProxy('http://localhost:5173/', 'localhost')).toBe(false);
|
||||
expect(links.linkNeedsWebTabProxy('http://localhost:5173/', '127.0.0.1')).toBe(false);
|
||||
// A LAN address may be reachable from the device; leave it direct.
|
||||
expect(links.linkNeedsWebTabProxy('http://192.168.1.135:3000/', '192.168.1.135')).toBe(false);
|
||||
expect(links.linkNeedsWebTabProxy('http://10.9.0.4:8095/', '192.168.1.135')).toBe(false);
|
||||
// Not a web URL at all.
|
||||
expect(links.linkNeedsWebTabProxy('ftp://localhost/', '192.168.1.135')).toBe(false);
|
||||
expect(links.linkNeedsWebTabProxy('not a url', '192.168.1.135')).toBe(false);
|
||||
expect(links.linkNeedsWebTabProxy('', '192.168.1.135')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('openLinkThroughWebTabIfLoopback', () => {
|
||||
it('reuses the saved proxied dashboard on that origin and opens the deep path', async () => {
|
||||
const { win, app, calls } = boot();
|
||||
expect(app.openLinkThroughWebTabIfLoopback('http://localhost:5173/pages/report?tab=2#top')).toBe(true);
|
||||
await vi.waitFor(() => expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/pages/report?tab=2#top'));
|
||||
expect(calls.some((c) => c.path === '/api/webviews' && c.method === 'POST')).toBe(false);
|
||||
expect(app.activeWebviewId).toBe('dev');
|
||||
expect(app.webviewOrder).toEqual(['dev']);
|
||||
});
|
||||
|
||||
it('navigates an already-mounted frame instead of remounting it', async () => {
|
||||
const { win, app } = boot();
|
||||
await app.openWebview('dev');
|
||||
const first = win.document.querySelector('.webview-frame[data-webview-id="dev"] iframe');
|
||||
expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/');
|
||||
|
||||
await app.openUrlInWebTab('http://localhost:5173/other');
|
||||
expect(win.document.querySelector('.webview-frame[data-webview-id="dev"] iframe')).toBe(first);
|
||||
expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/other');
|
||||
expect(win.document.querySelectorAll('.webview-frame').length).toBe(1);
|
||||
});
|
||||
|
||||
it('navigates an already-mounted frame back to the origin ROOT, which used to do nothing', async () => {
|
||||
// openUrlInWebTab used to flatten '/' to '', and openWebview reads an empty
|
||||
// path as "no deep link", so it mounted with navigate:false and an open
|
||||
// frame stayed on whatever page it was showing. Deep links navigated; a tap
|
||||
// on the bare origin silently did not.
|
||||
const { win, app } = boot();
|
||||
await app.openUrlInWebTab('http://localhost:5173/deep/page?a=1');
|
||||
expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/deep/page?a=1');
|
||||
|
||||
await app.openUrlInWebTab('http://localhost:5173/');
|
||||
expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/');
|
||||
expect(win.document.querySelectorAll('.webview-frame').length).toBe(1);
|
||||
});
|
||||
|
||||
it('reuses one dashboard across host spellings of the same dev server', async () => {
|
||||
const { win, app, calls } = boot();
|
||||
// The saved dashboard is http://localhost:5173/; a 127.0.0.1 link to the
|
||||
// same port is the same server and must not mint a second tab.
|
||||
await app.openUrlInWebTab('http://127.0.0.1:5173/status');
|
||||
expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/status');
|
||||
expect(calls.find((c) => c.method === 'POST' && c.path === '/api/webviews')).toBeUndefined();
|
||||
expect(win.document.querySelectorAll('.webview-frame').length).toBe(1);
|
||||
});
|
||||
|
||||
it('waits for an in-flight webview load instead of POSTing a duplicate record', async () => {
|
||||
// initWebviews() assigns a truthy EMPTY map synchronously and only then
|
||||
// awaits GET /api/webviews, so "is this.webviews set" answered "is it
|
||||
// loaded" wrongly: a tap inside that round trip found nothing to reuse and
|
||||
// saved a second dashboard for an origin that already existed server-side.
|
||||
const { win, app, calls } = boot();
|
||||
const loaded = app.webviews;
|
||||
app.webviews = new Map();
|
||||
let release: () => void = () => {};
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
(app as unknown as { _webviewsRefresh: Promise<void> })._webviewsRefresh = gate.then(() => {
|
||||
app.webviews = loaded;
|
||||
});
|
||||
|
||||
const tap = app.openUrlInWebTab('http://localhost:5173/late');
|
||||
release();
|
||||
await tap;
|
||||
|
||||
expect(calls.find((c) => c.method === 'POST' && c.path === '/api/webviews')).toBeUndefined();
|
||||
expect(frameSrc(win, 'dev')).toBe('/webview/cap-dev/late');
|
||||
});
|
||||
|
||||
it('saves an unknown origin under its host:port, then opens it', async () => {
|
||||
const { win, app, calls } = boot();
|
||||
expect(app.openLinkThroughWebTabIfLoopback('http://127.0.0.1:3000/')).toBe(true);
|
||||
await vi.waitFor(() => expect(frameSrc(win, 'new-id')).toBe('/webview/cap-new-id/'));
|
||||
const post = calls.find((c) => c.path === '/api/webviews' && c.method === 'POST');
|
||||
expect(post?.body).toEqual({
|
||||
name: '127.0.0.1:3000',
|
||||
url: 'http://127.0.0.1:3000/',
|
||||
embedMode: 'proxy',
|
||||
trusted: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reuse a TRUSTED dashboard, whose frame runs on Codeman's own origin", async () => {
|
||||
// A trusted webview is mounted with `allow-same-origin`. The link being
|
||||
// followed came from agent output, so auto-reusing that frame would let an
|
||||
// agent-chosen path be opened inside a privileged origin on one tap. A fresh
|
||||
// sandboxed record is saved instead.
|
||||
const { win, app, calls } = boot();
|
||||
app.webviews.set('trusted-dev', {
|
||||
id: 'trusted-dev',
|
||||
name: 'trusted',
|
||||
url: 'http://localhost:5173/',
|
||||
embedMode: 'proxy',
|
||||
trusted: true,
|
||||
} as never);
|
||||
app.webviews.delete('dev');
|
||||
|
||||
await app.openUrlInWebTab('http://localhost:5173/admin');
|
||||
|
||||
const post = calls.find((c) => c.method === 'POST' && c.path === '/api/webviews');
|
||||
expect(post, 'a trusted dashboard must not be reused for a tapped link').toBeTruthy();
|
||||
expect(post?.body).toMatchObject({ url: 'http://localhost:5173/', trusted: false });
|
||||
expect(frameSrc(win, 'trusted-dev')).toBeFalsy();
|
||||
});
|
||||
|
||||
it('does not reuse a direct-mode dashboard, which cannot show a loopback page from elsewhere', async () => {
|
||||
const { win, app, calls } = boot();
|
||||
expect(app.openLinkThroughWebTabIfLoopback('https://localhost:9443/admin')).toBe(true);
|
||||
await vi.waitFor(() => expect(frameSrc(win, 'new-id')).toBe('/webview/cap-new-id/admin'));
|
||||
expect(calls.find((c) => c.method === 'POST' && c.path === '/api/webviews')?.body).toMatchObject({
|
||||
url: 'https://localhost:9443/',
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves a reachable link alone so the caller opens it directly', () => {
|
||||
const { app, calls } = boot();
|
||||
expect(app.openLinkThroughWebTabIfLoopback('http://192.168.1.135:3000/')).toBe(false);
|
||||
expect(app.openLinkThroughWebTabIfLoopback('https://example.com/')).toBe(false);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('opens loopback links directly when the page itself is on the box', () => {
|
||||
const { app, calls } = boot('http://localhost:8095/');
|
||||
expect(app.openLinkThroughWebTabIfLoopback('http://localhost:5173/')).toBe(false);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('callers consult the hook first', () => {
|
||||
it('terminal URL links try the web tab before window.open', () => {
|
||||
const activate = TERMINAL_UI.indexOf('activate(_event, text) {');
|
||||
expect(activate).toBeGreaterThan(-1);
|
||||
const body = TERMINAL_UI.slice(activate, TERMINAL_UI.indexOf('},', activate));
|
||||
expect(body.indexOf('openLinkThroughWebTabIfLoopback?.(text)')).toBeGreaterThan(-1);
|
||||
expect(body.indexOf('openLinkThroughWebTabIfLoopback?.(text)')).toBeLessThan(body.indexOf('window.open('));
|
||||
});
|
||||
|
||||
it('response viewer links route through the hook and keep the file-path handler first', () => {
|
||||
const bind = APP_JS.indexOf('_bindResponseViewerInteractions(body) {');
|
||||
const section = APP_JS.slice(bind, bind + 2500);
|
||||
const pathHandler = section.indexOf("closest('a.rv-path')");
|
||||
const urlHandler = section.indexOf("closest('a[href]')");
|
||||
expect(pathHandler).toBeGreaterThan(-1);
|
||||
expect(urlHandler).toBeGreaterThan(pathHandler);
|
||||
expect(section.indexOf('openLinkThroughWebTabIfLoopback?.(urlLink.href)')).toBeGreaterThan(urlHandler);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user