Compare commits

...
Author SHA1 Message Date
Codeman maintainer 5548c17c4a chore: version packages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:46:20 +01:00
Codeman maintainer 1d33220493 chore: the changeset for the next release
One changeset for everything since 1.51.0: the eleven PRs merged on this
branch, #803's MLX row and #812 already on master, the dead-code cleanup and
the fixes applied while landing. It replaces the eight PR changesets. Patch
until the owner says otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:10:15 +01:00
Codeman maintainer baf9d6a6a4 chore(web): two constants got their own comments back
Removing THROTTLE_DELAY_MS and STATS_POLLING_INTERVAL_MS in 6fb8b277 left
each neighbour carrying the deleted line's comment, so the toast maximum read
as a throttle delay and the terminal sync wait as stats polling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:07:43 +01:00
Codeman maintainer d00a8d6cbf test(discord): the review items of #832 that go on top
A test pins the symlink and non-file branch of the reply store (a planted
link or a folder at the metadata path is never replaced, and replies are
still accepted), the @fileoverview names the file, its bounds, where the
bridge claims and the four rules a reader has to keep, and a comment left
from the #793 journal approach says store file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:06:03 +01:00
Codeman maintainer a9ed3f55c3 Merge #832: a replayed Discord reply is typed once, and a store failure never costs a reply
Each allowed Discord reply is claimed by its message id in a small private store (discord-reply-dedupe.json, 0600) before the rate-limit and exited-agent checks; when the store fails the bridge falls back to memory and still types the reply.
2026-11-20 04:05:22 +01:00
Codeman maintainer acd90efe73 fix(webview): the review items of #825
The owner of a managed dsh tab is compared with the server's starter only in
multi-user mode: a record created there keeps its owner, while a single-user
start records none, so that tab would never get its cookie again (new route
test). CLAUDE.md and the invariants doc name the cookie rules. The third item,
Codeman's session cookie filtered on the WebSocket leg whether or not the dsh
cookie is injected, came in with the merge itself, where it met #827.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:04:58 +01:00
Codeman maintainer 9d0f29fb22 fix(header): the two review items of #824
The format check passes again (Prettier breaks the createCpuUsageMeter call
one argument per line), and the load-average fallback answers 0 instead of
dividing by a core count of 0 on the platform it exists for, where cpus()
is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:03:46 +01:00
Codeman maintainer 6a5b818f65 chore(docker): the two review items of #822
A comment says why the wait after the kill keeps its 2>/dev/null (bash 3.2
prints a Terminated job line there, bash 5.2 does not, so CI would not
notice its removal), and the two probe tests use the file's own imports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:03:18 +01:00
Codeman maintainer 507116f019 docs(tmux): name the tmux releases a one-binding list-keys answer is blank on (#821)
The blank list-keys -T answer is not a development-build quirk: tmux commit
09bd686327 sent a one-binding listing to a status message instead of stdout,
and it shipped in 3.7, 3.7a, 3.7b and 3.7c until 7ec94fda08 fixed it for 3.8.
The comments, the tests and the invariants doc now say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:02:36 +01:00
Codeman maintainer 8202e07286 fix(watchers): the two review items of #818
The fs.watch failure tests skip on macOS, where chokidar 3 never calls
fs.watch for these watchers (fsevents, or polling without it), so the stub
never fired and the waits timed out. TeamWatcher.stop() clears its outage
set, so a stop() and start() on the same instance warns again about a
watcher that still fails; a new test pins it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:02:07 +01:00
Codeman maintainer 6222444e82 Merge #820: Send on Enter for the pinned CJK input field
A per-device mode for the pinned CJK field on phones: a typed answer stays in the field while the terminal scrolls and goes out only on Enter.
2026-11-20 04:00:05 +01:00
Codeman maintainer 1207c316c0 Merge #834: codeman tui attaches by session name
codeman tui <name> attaches by an exact session name as well as by list number.
2026-11-20 04:00:05 +01:00
Codeman maintainer 923db64a10 Merge #831: the wheel is forwarded for any CLI whose registry entry asks for it
The wheel gate reads each CLI's wheelForward rule from the registry (window.__codemanWheelForward) instead of a list of ids, so a custom full-screen CLI in clis.json can opt in.
2026-11-20 04:00:05 +01:00
Codeman maintainer 756d8d875e Merge #818: a chokidar watcher whose fs.watch fails is closed instead of retrying forever
A persistent:false watcher closes on its first error (closeWatcherOnError), so a failing fs.watch costs one warning instead of an endless climb to /, and TeamWatcher re-creates a stopped watcher from its 30 s poll.
2026-11-20 04:00:05 +01:00
Codeman maintainer f25e94141f Merge #825: proxied dashboards render in a web tab (dsh token, relative base, dynamic imports)
The DeepSeek Harness web tab trades the dsh web launch token for its session cookie, a relative <base href> resolves against the document's own directory, and root-absolute import("/...") inside scripts is rewritten onto the proxy prefix.

# Conflicts:
#	src/web/routes/webview-routes.ts
#	test/routes/webview-routes.test.ts
2026-11-20 04:00:05 +01:00
Codeman maintainer c31e4fc716 Merge #824: the header CPU reading shows CPU use, not the load average per core
Busy time across all cores, sampled over a window of at least a second (#823).
2026-11-20 03:59:10 +01:00
Codeman maintainer 99a69a87cf Merge #822: Start-Codeman.sh gives each port probe about a second
A dropped 127.0.0.1 connect (seen on WSL) no longer stalls the first run on the kernel's connect timeout.
2026-11-20 03:59:10 +01:00
Codeman maintainer 5df5628518 Merge #821: a key table reduced to one binding is read from the full listing
tmux 3.7 to 3.7c print a one-binding list-keys -T answer as a status message instead of stdout; Codeman now falls back to the full list-keys listing.
2026-11-20 03:59:10 +01:00
Codeman maintainer 4344ce8c11 Merge #827: a trusted web tab's WebSocket leg no longer forwards Codeman's session cookie
The WebSocket upgrade filters codeman_session out of the Cookie header the same way the HTTP leg already did.
2026-11-20 03:59:10 +01:00
Codeman maintainer b732cec36d Merge #826: a password-protected Codeman can be installed as an app
The manifest link fetches manifest.json with the session cookie (crossorigin=use-credentials), so the browser no longer gets a 401 for it.
2026-11-20 03:59:10 +01:00
JD c7b6e1cb4e fix(watchers): re-arm a stopped TeamWatcher watcher from the poll
chokidar 3 reports a one-off ENOENT race (a new file gone between its
stat and its watch) through the same TypeError as a lasting EMFILE, so a
watcher that stayed closed ended live team and task updates until a
restart. Each poll tick now re-creates a stopped watcher, as
WorkflowRunWatcher already does, and an outage warns once rather than
once per attempt. Also imports getErrorMessage from the types barrel.
2026-11-19 02:52:40 -05:00
JD b5a356dadf docs(cli-registry): say a version-gated wheel rule needs gates to forward
A version-gated rule reads the session's cliVersion, which the server
probes only for an entry that declares capabilities.gates, so a custom
entry with version-gated and no gates never forwards. Also brings the
claude and copilot comments in line with the code that now reads them.
2026-11-19 02:39:47 -05:00
Kamil KaliszandClaude Opus 5.5 d7b195a783 fix(tui): the not-found hint no longer says --list shows the names
The --list column is rowLabel() cut to 48 characters: an unnamed session
shows its folder, a long name ends in an ellipsis, and neither resolves as
a name. Point at attaching by number instead. Review on #834.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:21:22 +01:00
Kamil KaliszandClaude Opus 5.5 d9ded95b95 docs(readme): attach by name in the zh-CN tui example
Review on #834.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:12:51 +01:00
Kamil KaliszandClaude Opus 5.5 8b809da466 docs(tui): keep docs/tui.md hand-formatted, show attach by name
Review on #834: drop the Prettier reflow of docs/tui.md and keep only the
new example line and paragraph, put "two" back in the fast-paths
sentence, list <n|name> in the tui-app.ts fileoverview, and add a
codeman tui <name> line to the README and the Remote Access wiki page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:56:04 +01:00
Saqeb Akhter ce899f59cc docs(discord): document reply replay guard in agent guide (#218) 2026-11-18 11:07:32 +04:00
Saqeb Akhter 44459a12dd fix(discord): claim refused replies before rate limiting (#218) 2026-11-18 11:04:02 +04:00
Kamil KaliszandClaude Opus 5.5 974b85493c test(cli): the tui operand is now [session]
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:52:17 +01:00
Kamil KaliszandClaude Opus 5.5 a36b875363 feat(tui): attach by session name, codeman tui <name>
codeman tui <session> takes a list number or a session name. Digits only
stay a number; anything else matches the session name exactly
(case-sensitive, never a prefix, folder or prompt). Names are not unique,
so two live matches refuse and print their numbers; a name only a RECENT
row carries says the session has finished. The target is resolved before
the TTY check, so scripts get these answers without a terminal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:23:56 +01:00
Saqeb Akhter 7343274d5f fix(discord): heal invalid reply metadata after upstream review (#218, #258) 2026-11-18 00:38:59 +04:00
Saqeb Akhter ba4a1c16e2 fix(discord): tolerate reply dedupe storage failures (#218, #258) 2026-11-17 23:25:43 +04:00
Kamil KaliszandClaude Opus 5.5 c639b38c1a fix(mobile): case sheet lift on a partial pan, live placeholder language
- The phone case sheet (#mobileCasePickerModal) is inside .app, so once
  .app follows a pan it takes the same insideLift as the bars. The layout
  gap on top lifted it twice (186px above the keyboard at offsetTop 100).
  Comment, architecture-invariants and a test case updated.
- setHoldUntilEnter() writes the placeholder before the unchanged-mode
  early return, only when the text differs, so a live language switch
  shows up without touching the rest of the field.
- Settings-Reference: Shift+Enter needs a hardware keyboard.
- styles.css: the #cjkInput cap is a backstop now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:08:26 +01:00
Kamil KaliszandClaude Opus 5.5 e85bb83353 fix(mobile): pinned field on phones: swipes, focus scroll, viewport pan, iOS lift
Found on a real Android phone (Chrome) and iPhone (Safari) with Send on Enter:

- A swipe that started on the live screen closed the keyboard: the content
  touchstart blurred the focused input before the gesture was known to be a
  tap or a scroll. It now skips the visible #cjkInput
  (_contentTouchStartBlurs()); a real tap still closes it (inert content, a
  link, a long press).
- Focusing the field scrolled the terminal off screen: KeyboardHandler's
  focusin scrollIntoView({ block: 'center' }) centred the fixed field in its
  ancestors. isInputElement() skips #cjkInput like xterm's inputs.
- Android pans the visual viewport to reveal the field (offsetTop 285 in a
  458/744 viewport), leaving only the terminal's last line visible. On phones
  .app now follows visualViewport.offsetTop while the keyboard is up, and the
  fixed bars inside .app are lifted from .app's bottom, so a partial pan does
  not lift them twice. Non-phone branches and resetLayout() clear the shift.
- On iOS the first keyboard open reported innerHeight as the visual height
  (323 vs 640), zeroing the bars' lift; the layout height is now the larger of
  innerHeight and documentElement.clientHeight.

Tests in test/keyboard-handler-pinned-field.test.ts and
test/terminal-touch-tap.test.ts; docs in architecture-invariants and
src/web/CLAUDE.md; changeset sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:45:20 +01:00
JD 3ef4900e60 fix(web): forward the wheel for any CLI whose registry entry asks for it
The browser's wheel gate named copilot, pi, claude and codex by id, so a custom clis.json entry that launches pi could not get the forwarding #771 gave stock pi: after every tab switch or reload its wheel scrolled an empty local buffer. Copying pi's altScreen value into such an entry made it worse, since the mouse DECSETs were then stripped while nothing forwarded the wheel.

The server now publishes every CLI's wheelForward rule as window.__codemanWheelForward, disabled entries included because disabling a CLI leaves its sessions running, and _shouldForwardWheelToApp reads that map instead of an id list. Stock CLIs keep their behaviour, and a minVersion that is not MAJOR.MINOR.PATCH refuses forwarding instead of comparing as passing.
2026-11-17 00:43:09 -05:00
Kamil KaliszandClaude Opus 5.5 3c5b7e2199 fix(mobile): Send on Enter placeholder i18n, one-line field on desktop
- input-cjk.js translates its placeholder with CodemanI18n.t(), like the
  prompt composer, since i18n.js skips <textarea> subtrees; the zh-CN
  entries now show.
- The field only grows on touch devices, where it is position: fixed.
  On a desktop it sits under the terminal, so growing would shrink the
  terminal box and resize the PTY on every line; it stays one line and
  scrolls there.
- Input And Voice: a line break needs a hardware keyboard (no Shift+Enter
  on a phone keyboard, and the extended bar's newline key goes to the CLI).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:42:37 +01:00
Kamil KaliszandClaude Opus 5.5 57fdb52f7c fix(mobile): turning Send on Enter off drops the held draft
setHoldUntilEnter going from on to off clears the stashed drafts and
resets the field, so live mode's next flush sends only the new key, not
a held multi-line draft. The invariants doc and the _handleCjkInput
comment name _sendCjkPrompt as the path a held answer takes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:37:01 +01:00
Kamil KaliszandClaude Opus 5.5 387cb830f4 fix(mobile): the clear-line key discards a Send on Enter draft
clear({ discard: true }) skips the owner stash, drops any older stash of
the owner and keeps the owner; clearTerminalInput() (the keyboard bar's
clear-line key) uses it, so a cleared draft does not come back on a
same-tab reload or a switch back. @fileoverview gains a Send on Enter
section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:37:16 +01:00
Kamil KaliszandClaude Opus 5.5 673a656538 fix(mobile): Send on Enter keeps drafts on every path, Ctrl stays in a held field
- CjkInput remembers which session the field's text belongs to (set by
  restoreDraft) and clear() stashes a held draft under it, so the paths
  that drop the active session before the next cleanup (goHome,
  _replaceTileGrid, _onTileAdoptedElsewhere) keep the answer.
  discardDraft() drops the owner of a removed session.
- Tile focus no longer stashes again for a tile closed from this tab.
- With a draft in the field, Ctrl shortcuts (undo, select all, copy) are
  the field's; they reach the CLI only while it is empty, like Backspace
  and the arrows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:25:02 +01:00
Kamil KaliszandClaude Opus 5.5 b5ad7afebe fix(mobile): Send on Enter fourth review fixes
- selectSession restores the CJK draft after _activateFileBrowserSession,
  which test/file-browser-search.test.ts pins right after the
  activeSessionId assignment.
- A lone digit while the session has a pending permission_prompt or
  elicitation_dialog goes out without the delayed Enter: the dialog acts
  on the digit, and the Enter would confirm whatever comes next. Same
  rule as the Approvals Inbox and the Discord bridge.
- Changeset mentions the toolbar Enter sending the CJK field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:53:27 +01:00
Kamil KaliszandClaude Opus 5.5 80d719df5f fix(mobile): keep the Send on Enter draft when going Home
goHome() nulled activeSessionId without stashing the field, so picking the
session again cleared the draft. Stash it first.

Docs: src/web/CLAUDE.md lists cjkInputHoldUntilEnter among the per-device
keys the strict schema does not declare, and notes the sendEnterKey()
exception for the visible CJK field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:38:20 +01:00
Kamil KaliszandClaude Opus 5.5 64ee504247 fix(mobile): Send on Enter second review fixes
- Never send a held answer as text + CR in one write: Codex folds an Enter
  in the same burst into a paste. A single character is typed, then CR
  ~120 ms later to the session captured at Enter; anything longer goes
  through _sendComposedPrompt. Drops HELD_DIRECT_MAX. No session keeps the
  text in the field.
- Cap #cjkInput at 68px on every device, not only touch.
- _autoGrow adds the border height and skips a hidden field.
- setHoldUntilEnter returns early when the mode is unchanged.
- Per-session held drafts: stashed on switch and tile focus, restored on
  return, dropped when the session is removed.
- Toolbar Enter presses Enter in the visible CJK field (commits an active
  composition first).
- Blank-only field sends a bare Enter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:39:22 +01:00
Kamil KaliszandClaude Opus 5.5 95fb147e9c fix(mobile): Send on Enter review fixes
- A long single line (over 64 characters) or several lines now go through
  the composer's _sendComposedPrompt: one bracketed paste, then Enter as a
  separate delayed write to the session captured at Enter. Claude Code took
  a long `<text>\r` burst as a paste and left it unsent, and the old delayed
  Enter followed a tab switch. A refused prompt keeps the text in the field.
- Deleting held text no longer sends Backspace to the PTY. It goes out only
  when the field was already empty (the phantom itself deleted), so
  select-all + delete is covered too.
- With the one-shot Ctrl armed, the next single typed character skips the
  hold and reaches _handleCjkInput, which turns it into the control byte;
  any other change spends the modifier, as in live mode.
- A reload of the session already shown (tapping its tab, the geometry
  retry) keeps a held draft.
- With the keyboard down the field stays one line tall, so it no longer
  covers the terminal's last rows.
- zh-CN strings for both field placeholders, and a test pinning
  cjkInputHoldUntilEnter as per-device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:18:18 +01:00
Kamil KaliszandClaude Opus 5.5 14dccd462f fix(pwa): fetch the manifest with credentials so password installs can be installed
Browsers fetch the web app manifest without cookies unless the link sets
crossorigin="use-credentials". With a password set, manifest.json needs
the codeman_session cookie, so it answered 401 and Chrome refused to
install Codeman as an app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:51:27 +01:00
ArizeSky 677e393fc3 fix(webview): stop forwarding the session cookie on the websocket leg
The WebSocket leg sent the browser's whole Cookie header to a trusted dashboard, including Codeman's own codeman_session, which the dashboard could then replay against the API. Filter it through filterCookieHeader like the HTTP leg, and omit the header when nothing remains.
2026-11-16 16:46:10 +08:00
ArizeSky 2a3496b7b3 fix(webview): keep the browser's cookies on the websocket leg
The HTTP leg puts the server-held dsh credential in front of the browser's own
cookies; the upgrade leg replaced them with it. A managed dsh tab is trusted, so
its other cookies must survive there too. Filter the request the way the HTTP
leg does and merge the credential in front.

Order is the point: a `Cookie` header can name the same cookie twice, and the
first value is the one parsers keep, so appending the credential let a stale
browser copy of the same dsh cookie shadow the one the running process minted -
the tab would come back to the 401 this path exists to prevent. Both legs now
lead with it, and a route-level test asserts the bytes the upstream sees on the
upgrade, not only on the HTTP request.
2026-11-16 16:30:25 +08:00
ArizeSky 44a10cff39 fix(deepseek): skip a tokenless banner line while scanning
The scanner now takes the first `dsh web:` line that parses as an http(s)
URL AND carries a token, as the boot contract describes, instead of
settling on an earlier plain URL and reporting no launch URL. The
tokenless line is still what identifies an older, ungated dsh in the wait
loop.
2026-11-16 16:14:45 +08:00
ArizeSky 06100a5506 fix(webview): rewrite dynamic imports only inside script bodies
The root-absolute import("/...") rewrite ran over the whole document, so
visible text such as <pre>import("/x")</pre> was rewritten too. Run the
specifier rewrite per <script> body and leave markup text untouched.
2026-11-16 16:12:53 +08:00
ArizeSky cc413afdd1 fix(webview): resolve a relative base against the document directory
rebaseRelativeBase resolved a relative <base> against the proxy root, so
a document served from a subdirectory of its dashboard (for example
/webview/<cap>/app/page.html with <base href="./">) pointed at
/webview/<cap>/ and loaded its assets one level too high. Pass the
request's wildcard path into rewriteHtml and resolve the base against
the document URL, which keeps the proxy root for the landing page.
2026-11-16 16:11:58 +08:00
ArizeSky 238853f96a fix(webview): keep dashboard cookies alongside the injected one
The managed DeepSeek tab is trusted, so the browser's own cookies for the
dashboard are forwarded. The injected dsh credential replaced that header
instead of joining it, dropping any other cookie dsh had set. Append the
pair to the filtered browser cookies and leave the rest untouched.
2026-11-16 16:10:51 +08:00
ArizeSky 7f729ee87b fix(deepseek): only exchange a banner for the spawned loopback port
The launch URL comes from the child's output but fetching it is a request
made by the Codeman server, so a banner naming another host or another
local service could aim it. Require 127.0.0.1 and the port just spawned
before the exchange runs, and mark the server as unusable for reuse if
the check fails.
2026-11-16 16:10:10 +08:00
ArizeSky b1bcd1e3af fix(deepseek): restart a server whose token exchange failed
Reuse returned the running server whenever it answered HTTP and matched
the authority, including one whose launch token could not be exchanged
for a cookie. That server answered 401 forever, so the restart the
warning asks for could never happen. Track the failed exchange and skip
reuse, which makes the next start request stop and respawn it.
2026-11-16 16:09:16 +08:00
ArizeSky 4ce9abde7d fix(deepseek): scan every dsh web line for the launch URL
The banner parser and the boot wait each took the FIRST `dsh web:` match,
so a diagnostic such as `dsh web: loading profiles` printed before the
banner made parsing return null on every poll and boot gave up after four
seconds. Scan every line and take the first payload that parses as an
http(s) URL, and only scan complete lines in the wait loop so a banner
split across two output chunks is waited for instead of being parsed
truncated.
2026-11-16 16:08:19 +08:00
ArizeSky 6e3d6ebad9 test(webview): cover the managed dsh cookie at the route level
Drive the real proxy route against loopback listeners and assert the
Cookie header dsh would receive: the minted port gets it, another port,
an unmanaged tab and a multi-user owner without the grant get none, and
a granted multi-user owner still gets it.
2026-11-16 16:06:34 +08:00
ArizeSky 28ed4016bd fix(webview): require the owner's privilege grant for the dsh cookie
`managed` is accepted from the client on POST/PATCH /api/webviews and
GET /api/deepseek/web publishes the live port, so a saved managed record
pointing at that port was enough to receive the dsh-auth cookie. Gate it
on the same privileged-commands grant POST /api/deepseek/web requires,
fail closed for an ownerless record in multi-user mode, and record the
user whose request started the process so the supervisor only hands its
cookie to that identity. A request from another owner restarts the server
rather than reusing a cookie that is not theirs.
2026-11-16 16:05:22 +08:00
ArizeSky 0ea97d62ec chore(webview): name a root-absolute request that escapes the proxy
When a web tab's boot module (or any asset it builds at runtime) escapes the
`/webview/<cap>/` prefix, the request reaches Codeman's 404 with nothing to relay
to: the frame's document URL is masked, so its `Referer` carries no capability
and the existing fallback declines. The tab then shows a blank page or a spinner
that never resolves, and the log says nothing — the failure mode that made the
DeepSeek Harness tab un-diagnosable twice.

Classify that shape conservatively on the 404 path (asset-shaped
`Sec-Fetch-Dest`, same-origin `Referer` at the masked landing path, not `/api`,
not one of Codeman's own files) and log the path once per five minutes. Nothing
is relayed or rewritten: this only turns a silent blank tab into one grep.

Also document the boundary in `docs/web-tabs.md` — the root-absolute URLs the
proxy never sees (runtime-built `import()`, imports inside external `.js`, static
imports in inline scripts, service-worker registration, `url()` in external
stylesheets) — so the next occurrence starts from the list instead of from zero.
2026-11-16 10:09:37 +08:00
ArizeSky 0b3087918f fix(deepseek): make the Harness web tab render, not just authenticate
`dsh web` gates its own index behind a per-process launch token it prints on
boot, and only that URL mints the `dsh-auth-*` cookie every later request needs.
The managed tab stores the clean URL, so nothing on the browser side could
present the token: the iframe rendered dsh's 401 text, a blank tab.

Read the token out of the captured boot output, trade it for the cookie once at
startup (`redirect: 'manual'`, since the 303 is what carries Set-Cookie), and
let the proxy present it on both the HTTP and WebSocket legs. Scoped to the
exact loopback authority the cookie was minted for; a token-less banner (an
older dsh) keeps the previous behaviour untouched. The banner is scanned on its
own 256 KB budget rather than the 16 KB error-tail buffer: a chatty profile can
fill that cap before the banner prints.

Authentication alone was not enough. dsh ships `<base href="./">`, which a
browser resolves against the DOCUMENT url — and the proxy's runtime shim
rewrites that url to strip the `/webview/<cap>/` prefix. The base therefore
landed on Codeman's root: every module script 404'd and the page painted its
inline `#151517` background with nothing on it (the black screen that replaced
the white one). `rewriteHtml` now resolves a relative base against the proxy
prefix before the mask can run, leaving a cross-origin base exactly as written.

Verified against dsh 0.2.1-rc.5 and a live Codeman build: bare GET 401, captured
cookie 200, proxied `/api` WebSocket 101, and a headless-Chrome load of the
proxied tab boots the full Harness UI with no console errors.
2026-11-16 09:47:23 +08:00
Ludo FourrageandClaude Opus 5.5 9304f98efb fix(header): the CPU reading shows CPU use, not the load average per core
The header's CPU figure was the 1-minute load average divided by the core
count, capped at 100. Load counts runnable tasks, not busy time, so a host
with bursty processes, or a VM whose vCPU threads count as runnable, read
100% while most cores were idle. It is now busy time across all cores
since the previous reading, from os.cpus(), with a one-second minimum
window on the monotonic clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:56:33 -08:00
Aamer Akhter 0e913eedf2 fix(docker): bound Start-Codeman.sh's port probe to about a second
port_in_use() connected with bash's /dev/tcp and waited for the answer.
A listening port answers at once and a closed one is normally refused
at once, but on WSL a connect to a closed 127.0.0.1 port is dropped
and only fails at the kernel's connect timeout, minutes later
(measured: still waiting after 10 s; ::1 is refused at once). The
first-run port search tries up to 100 ports from 3000 and the start
path checks the chosen port again, so a first run on WSL stalled.

Each connect now runs in a background subshell that port_answers()
waits on for at most 20 x 50 ms, then kills; no answer in time reads
as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`.

Test: a python3 listener with a full accept queue (Linux drops further
SYNs, the same no-answer a WSL closed port gives) must be given up on
within 3 s; a listening port and a closed one still answer at once.
With the old unbounded connect the first test fails at its 10 s cap.
2026-11-15 15:09:20 -05:00
Aamer Akhter c497869ee5 fix(tmux): read a one-binding key table from the full listing
A tmux built from master (`tmux -V`: next-3.7) prints nothing, exit 0,
for `list-keys -T <table>` when the table holds exactly one binding.
tmux 3.4 prints the line. One binding is the shape
restrictTmuxPrefixTable leaves behind (`<prefix> send-prefix`), so on
that tmux the reduced table read as needing a reset and every session
create reset it again. `codeman tui` read its prefix table the same
way, so readPrefixBinding called a bound key free and readDetachKey
found no detach key.

A blank answer is now read from the full `list-keys` listing, keeping
only that table's lines. The parsers already match on `-T <table>`.

Tests: recorded-command cases for the blank answer (reduced table kept,
stray binding still reset) and TuiClient cases for both reads. The
real-tmux helper reads tables through the same fallback, and the
escaped `C-\` check accepts the unescaped form the full listing prints.
2026-11-15 15:06:07 -05:00
Kamil KaliszandClaude Opus 5.5 b8a4466643 docs(mobile): zh-CN strings and Input And Voice section for Send on Enter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:42:59 +01:00
Kamil KaliszandClaude Opus 5.5 e0e2f689cf feat(mobile): Send on Enter for the pinned CJK input field
A per-device setting next to CJK Input keeps typed text in the pinned
field until Enter instead of streaming it to the PTY, so a phone user can
scroll the terminal and edit an answer before sending (Termux-style).
One line goes as text + CR, several lines as one bracketed paste with a
delayed Enter, like the prompt composer. Shift+Enter is a newline,
Escape clears, Backspace on an empty field still reaches the PTY, and
autocorrect is on in this mode. The field grows with its text and the
keyboard layout reserves its real height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:38:25 +01:00
JD 10e443a309 fix(watchers): stop a chokidar watcher whose fs.watch fails instead of retrying forever
chokidar 3 with `persistent: false` has no guard for an `fs.watch` that throws (EMFILE once the inotify instance limit is used up, ENOSPC once the watch limit is). It emits the error, then a TypeError, then retries on the parent directory, and ends up re-adding `/` forever. TeamWatcher only logged its `'error'` events, so one failed watch became an endless stream of stack traces. WorkflowRunWatcher already closed its watcher on error, but `close()` removes every listener, so the TypeError from the same pass became an unhandled rejection, one per 10 s poll, and the server exits after five of those in a minute.

`closeWatcherOnError()` closes the watcher on its first error, keeps a no-op listener on it, and turns its `add()` into a no-op, since a callback chokidar still has in flight can otherwise re-add a path and reopen it. TeamWatcher logs one line per watcher and relies on its 30 s poll; WorkflowRunWatcher still drops the watcher and re-arms it on the next poll.
2026-11-14 15:14:35 -05:00
73 changed files with 5217 additions and 177 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@
"name": "codeman",
"source": "./plugins/codeman",
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
"version": "1.51.0",
"version": "1.51.1",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+38
View File
@@ -1,5 +1,43 @@
# aicodeman
## 1.51.1
### Patch Changes
- 1d33220: ### Thanks
- @kkalisz for Send on Enter in the phone's input field (#820), `codeman tui <name>` (#834), and a password-protected Codeman that installs as an app (#826).
- @ArizeSky for web tabs that render the DeepSeek Harness web UI and Vite dashboards (#825), and for closing a session-cookie leak on the web tab's WebSocket leg (#827).
- @JDProfresh for tracking a 174 GiB log flood down to a chokidar retry loop and fixing it (#818), and for wheel forwarding that any CLI entry can ask for (#831).
- @aakhter for the tmux 3.7 key-table fix (#821) and for Start-Codeman.sh on WSL (#822).
- @ludovicfourrage for the report and the fix that makes the header's CPU reading real CPU use (#823, #824).
- @johoja12 for Discord replies that are typed once, however often the gateway replays them (#832).
- @shenlvkang-collab for the report in #701 that led to answers on a relocated Claude config folder (#812).
**Phone: Send on Enter for the input field (#820).** A new per-device setting next to CJK Input, Input Field: Send on Enter. With both on, the field above the keyboard works like a chat box: your text stays there while you scroll the terminal to reread a question, Enter sends it, Shift+Enter adds a line and Esc clears it. The phone keyboard layout is sturdier for everyone too: a swipe on the live screen no longer closes the field's keyboard, and on iOS the bars sit on the keyboard the first time it opens.
**The terminal dashboard attaches by session name (#834).** `codeman tui <name>` attaches to a live session by its exact name as well as by its list number, so getting back into the same session over SSH no longer depends on where it sits in the list.
**Web tabs render the DeepSeek Harness web UI and Vite dashboards (#825).** The DeepSeek Harness web tab opened on a blank 401 page since `dsh web` started asking for a one-time launch token. Codeman now trades that token for dsh's session cookie and presents it only to that tab. Dashboards that ship a relative `<base href>` (what Vite and SvelteKit builds emit) and ones that load modules with `import("/...")` render through the web tab proxy too.
**Local model: Muse Glimmer 30B as its MLX build (#803).** On a Mac with 48 GB or more, Run a model on this Mac offers the MLX build of Muse Glimmer 30B. On an M5 Pro with 48 GB it wrote twice as many tokens a second as the GGUF build on the same request, and finished an OpenCode turn the GGUF build never answered. Macs with 32 or 36 GB keep the GGUF row as it was.
**Fixes.**
- **A failing file watcher no longer floods the log (#818).** When Linux ran out of inotify instances, a watcher whose `fs.watch` failed retried on each parent folder up to `/` and then forever, writing about 112,000 log lines a second until the disk filled. It now logs one warning and keeps working by polling, and the agent-teams watcher switches its live watcher back on once watching works again.
- **A password-protected Codeman installs as an app (#826).** The browser fetched the app manifest without the login cookie and got a 401, so Chrome's Install app refused. The manifest request now carries the cookie.
- **A trusted web tab's WebSocket no longer sends Codeman's session cookie to the dashboard (#827).** The HTTP leg already stripped it.
- **Answers come back for a session on its own Claude config folder (#701, #812).** A session started with `CLAUDE_CONFIG_DIR` (a second Claude account) showed "No response yet" in the response viewer, and `codeman agent read` and the Discord bridge's last message came back empty. They now read the transcript from that session's own folder.
- **tmux 3.7 to 3.7c: the prefix table and `codeman tui` keys read right (#821).** Those releases print nothing for a key table with exactly one binding, so Codeman reset its already reduced prefix table on every new session and `codeman tui` took a bound key for a free one.
- **`docker/Start-Codeman.sh` no longer hangs on WSL (#822).** Each free-port check gives up after about a second instead of waiting out the kernel's connect timeout.
- **The header CPU reading is CPU use (#823, #824).** It showed the load average per core, which read 100% on a host whose cores were mostly idle. Behaviour change: on such a host the figure is now much lower.
- **Discord: a replayed reply is typed once (#832).** A gateway replay, also after a restart, could type the same reply into a session twice. If the small store that prevents it fails, the reply is still typed.
- **A custom full-screen CLI can get the mouse wheel (#831).** The wheel went only to a fixed list of CLIs. It now follows each entry's `wheelForward` rule, so a `clis.json` entry can ask for it; stock CLIs behave as before.
**Fixes applied while landing.** The web tab proxy filters Codeman's session cookie off the WebSocket leg whether or not the dsh cookie is added, and a dsh tab created in multi-user mode still gets its cookie after a switch back to single-user mode (#825, #827). The CPU fallback no longer divides by a core count of 0 (#824). A watcher that a restart finds still failing warns again, and the watcher tests skip on macOS, where chokidar never calls `fs.watch` (#818). The Discord reply store has a test for a planted symlink at its path (#832).
**Docs and tests.** The docs name the tmux releases with the blank key-table answer, the DeepSeek web cookie rules and how a custom full-screen CLI asks for the wheel.
About 8,900 lines of code nothing reached are gone, among them the Ralph plan wizard that no button opened any more and the Agent Teams terminal windows; no route, setting or SSE event was removed. `npm run check:frontend-dead` lists frontend code nothing references.
## 1.51.0
### Minor Changes
+8 -6
View File
@@ -52,7 +52,7 @@ Uses [Semantic Versioning](https://semver.org/) (`MAJOR.MINOR.PATCH`) via `@chan
When the user says **COM** (`COM` = patch, `COM minor`, `COM major`): **Read [`docs/releasing.md`](docs/releasing.md) and follow every step in order**; never improvise a release from memory. It covers the changeset, `npm run version-packages`, the `**Version**` line below, the branch check and explicit-path commit, deploy, the getcodeman.com badge, watching BOTH CI workflows, the MCP registry publish, and the Discussions announcement.
**Version**: 1.51.0 (must match `package.json`)
**Version**: 1.51.1 (must match `package.json`)
## Project Overview
@@ -64,7 +64,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Requirements**: Node.js 22+, Claude CLI, tmux
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` to attach).
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` or `codeman tui <name>` to attach).
## Additional Commands
@@ -134,7 +134,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Agent CLI (`codeman agent …`, `src/cli-agent.ts`)**: the command-line client for the wait primitives and the session verbs, for agents the skill does not reach (pi, shell, no `jq`; `seedAgentSessionPreamble` covers every local session whose CLI takes the skill, `capabilities.agentSkillDir`; every pane still exports `CODEMAN_MUX`/`CODEMAN_SESSION_ID`/`CODEMAN_API_URL`). It is an HTTP CLIENT: inspection and guarded stage/submit use the ownership-checked `agent-session-routes.ts` module (experimental, behind `agentCoordinationEnabled`, SYNCED, default OFF: all three routes answer `403 FORBIDDEN` naming it while off, and the CLI shows that verbatim); the other verbs reuse existing routes, with no second transport (the plan's "Socket API" non-goal stands), every call carries `X-Codeman-Parent-Session`, only `spawn`'s quick-start carries `X-Codeman-Agent-Origin` (pinned in test/cli-agent.test.ts), while `spawn` without a case (cwd or `--working-dir`) is `POST /api/v1/sessions` plus `/interactive` or `/shell` without that header, so no agent-case marker, and refuses (exit 4, before any request) an empty `--working-dir` and a bare spawn from a HOME cwd, since it always sends an explicit `workingDir` and the server's no-`workingDir` hooks skip cannot apply (test/cli-agent-project-spawn.test.ts), auth (`src/codeman-credentials.ts`, shared with `codeman attach` and the TUI) from `CODEMAN_PASSWORD` or the data dir's `.env` (the same reader `codeman attach` uses — `readCodemanEnvFile`). Verbs return exit codes (`0` ok / `1` error / `2` timeout / `3` exited / `4` refused) instead of calling `process.exit`, so `test/cli-agent.test.ts` drives every verb against a recording fake transport plus the real `httpRequest` against a local server. ⚠️ Three guards live in code, not prose, and the tests pin them: refuse without `CODEMAN_MUX=1`+`CODEMAN_API_URL` (never guess a URL); `send` transmits printable text + `\r` only (`inputRefusal`: any byte < 0x20 or DEL refuses BEFORE the transport — opencode's `Ctrl+C` is `app_exit`), ESC exists solely as `interrupt` with no `\r`; `rm` fails closed (`deleteRefusal`: empty id, self shorter than 8, prefix match in EITHER direction, re-checked on the resolved id). ⚠️ The routes accept FULL ids only — an 8-char prefix is a 404 (measured live) — while `ls` prints prefixes, so `resolveSessionId` maps a short id through `GET /api/v1/sessions` and refuses an ambiguous one. It also refuses any id under 8 characters (exit 4, on every verb, before any request), the same floor as the server's `PARENT_SESSION_ID_MIN_PREFIX`, so `rm 9` can never pick an arbitrary session. ⚠️ A 400 for `--until stop` on a hook-less mode is passed through verbatim, never papered over: the marker path is the answer there. `spawn` on a readiness timeout exits 2 and LEAVES the session for inspection (the skill's `spawn_worker` deletes it; the CLI's caller is often a human); its stdout is the id ALONE (prose on stderr) so `SID=$(…)` works. ⚠️ Two server answers that look like success and are not: `delivered:false` without `duplicate` (the bytes went into a dead pane — the field exists so a client says "restart" instead of "wait longer") and `wait.ended:true, signal:null` (the worker died during a `stop`/`idle` wait: the registry satisfies only waiters that listed `exit`, then cancels the rest) — both exit 3, checked BEFORE the happy paths in `waitExitCode`. → README "`codeman agent`", `docs/api-reference.md`
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments or typing; a store failure never costs a reply. A file that could not be read is never overwritten. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
**MCP server (`codeman mcp`, `src/mcp-server.ts`)**: a Model Context Protocol server on stdio for any MCP client, a CLIENT of the HTTP API like `codeman agent` (reuses its `httpRequest`, `inputRefusal`, `buildSendBody`; the MCP server adds no routes). Seven tools: `list_sessions`, `start_session`, `send_prompt`, `wait_for_session`, `read_output`, `interrupt_session`, `delete_session`. ⚠️ Dual-era: answers the legacy `initialize` handshake (2024-11-05 to 2025-11-25) AND the 2026-07-28 revision (per-request `_meta` with `protocolVersion` + `clientCapabilities`, `server/discover`, `resultType: "complete"` on every modern result); a modern `tools/list`/`server/discover` MUST carry `ttlMs` + `cacheScope` (Claude Code 2.1.296 drops every tool without them: measured). ⚠️ stdout is protocol only; logs go to stderr. ⚠️ The URL comes from `--url`/`CODEMAN_API_URL`, never a guess, and unconfigured it still lists tools (registries introspect) while every call answers how to configure it. ⚠️ Prompt/interrupt/delete only sessions the PROCESS started (in-memory allowlist, so a restart fails closed) or, inside a pane, the calling session's own children, unless `--allow-any-session`; never its own session. ⚠️ `read_output` returns text ONLY, no `structuredContent` (a client that prefers it showed the model metadata instead of the output: measured). Waits default 45 s (Codex's MCP tool timeout is 60 s). Registry manifest `config/mcp-registry/server.json` (`mcpName` in package.json, version kept by `scripts/sync-plugin.mjs`). Tests: `test/mcp-server.test.ts`.
@@ -160,6 +160,8 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
**Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit)
**Auto-compact and auto-clear** (opt-in per session, Respawn tab; `session-auto-ops.ts`, pure decision `decideAutoThreshold()`): for a Claude session the size compared with the threshold is the context Claude Code reports on its statusline (`context_window.total_input_tokens`, cache reads included, handed over by `POST /api/status-telemetry` through `Session.noteContextReport()`); the session's token counter never sees the cached context and is only the fallback for a launch without the exporter. Thresholds go up to the reported window (`contextWindowSize`, 1M while unknown). ⚠️ After a `/compact` or `/clear` the report from before the command is ignored by VALUE, never for a length of time (a 601k compact took 39 s). ⚠️ The decision is made AGAIN when the command goes out (`_decideAtSend()`): a report fires the trigger in the middle of a turn, and the wait for that turn to end can outlast a compaction by Claude Code itself, so a `/clear` sent on the old answer would wipe a conversation that is small again. A skipped command stamps nothing. ⚠️ Nothing is sent into a usage-limit pause (`_heldByLimit()`, until auto-resume's `continue` went out), or that `continue` is typed into an empty conversation. → [architecture-invariants#auto-compact-and-auto-clear-thresholds](docs/architecture-invariants.md#auto-compact-and-auto-clear-thresholds)
@@ -188,7 +190,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All ten **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. ⚠️ **Copilot**: `allowAll` (`--yolo`) is a `privilegedParam` and `COPILOT_HOME`/`COPILOT_ALLOW_ALL`/`COPILOT_PROVIDER_*`/`COPILOT_MODEL` are privileged env keys, and so is every other `COPILOT_*` variable the CLI reads that switches approvals, runs code with no approval row or sends its sign-in token elsewhere (the 1.0.98 list is in `stock.ts`; the prefix admits whatever a later release adds, so re-read the bundle whenever the measured version moves); the resume id must start with a letter or digit (`path-segment`), since `--resume`'s value is optional and `--resume --yolo` would otherwise make `--yolo` its own flag; `--name` is dropped next to `--resume`/`--continue` (Copilot refuses the pair); its mouse DECSETs are stripped (`strip-mux-and-mouse`) so a drag selects and the wheel is forwarded by `_shouldForwardWheelToApp` while `cliMouseTracking` is on; `composerReadyMark` is the footer hint `/ commands · ? help`, NOT `❯` (the folder-trust dialog draws `❯ 1. Yes`); `last-response` reads the pane's visible screen (`transcriptNeedsScreenCapture`) through a per-CLI `PANE_DIALECTS` row, because its stream is cursor moves, not lines (a prompt row scrolled off by a tall answer reads as the answer's tail unless a banner/trust dialog is on screen, and typed composer text is not a prompt); Docker seeds no Copilot credential (`config.json` holds a plain-text token without a keyring). ⚠️ **jcode**: every pane is a client of ONE shared per-user daemon and the tools run in the daemon with ITS env, so jcode gets no agent skill and no `JCODE_*` envOverrides prefix (a per-session value would act as another session or reach every one); `last-response` is an honest empty (external + `transcript: 'none'`, never the segmenter or the Claude scan); ⚠️ that daemon is a descendant of whichever pane started it, so `capabilities.sharedDaemon` makes `killSession` spare descendants outside the pane's process group (`descendantsInPaneGroup()`, `proc-tree.ts`), or closing that one tab cuts every other jcode session off; it resolves through the generic registry resolver, with no per-CLI resolver module (`docs/jcode-integration.md`). → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp)
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it, but only for the same starter and while its cookie works), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). ⚠️ The launch token is traded for dsh's session cookie once at startup, and the web-tab proxy presents it on both legs only to the `managed: 'deepseek-web'` tab on the `127.0.0.1` port it was minted for (in multi-user mode, only to a granted owner who started it). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `<claude config>/projects/<old>` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`.
@@ -228,7 +230,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Which CLIs forward is the registry's `wheelForward`, published as `window.__codemanWheelForward` and never an id list in the gate, so a custom `clis.json` entry opts in with it plus `altScreen: 'strip-mux-and-mouse'` (`docs/cli-registry.md`). Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
**Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install)
**Self-update** (App Settings → System → Updates): in-app updater for git-clone installs under a supervisor (`systemd`, `launchd`, `launchd-daemon`, `docker-compose`, else `none`). The work runs in a DETACHED `scripts/self-update.sh` writing `update-status.json`, polled across the restart; pure helpers in `src/web/self-update.ts`. ⚠️ Compose: the restart kills the script, so nothing may be appended after the `restarting` marker; the repo must stay a host bind mount over `/opt/codeman` and the image must keep devDependencies + toolchain. ⚠️ `evaluateEnvironmentGate()` refuses releases that change `server.Dockerfile`/`docker-compose.yaml` or add `.env.example` keys, re-evaluated on `POST /api/system/update`; unknowns fail OPEN, but the exit-to-restart needs `--restart-by-exit 1` (`CODEMAN_RESTART_BY_EXIT=1` only in the Compose file). ⚠️ An install with no git checkout (`install.sh` on a machine without a working git leaves the marker `.install-source`) is kind `archive`: it cannot update in place, and both the check and the UI tell it to re-run the installer, never the npm line. ⚠️ Keep the agent CLIs in `server.Dockerfile` pinned. → [docs/docker-self-update.md](docs/docker-self-update.md), [architecture-invariants#self-update](docs/architecture-invariants.md#self-update)
@@ -334,7 +336,7 @@ One module per domain in `src/web/routes/` (plus a barrel; `ls src/web/routes/`
## State Files
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id) + `discord-reply-dedupe.json` (replayed-reply guard: at most 2,048 Discord message IDs with timestamps, kept 7 days, mode 0600; a file that could not be read is never overwritten), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
**Generated top-level dirs** (all gitignored — don't edit or commit): `dist/` (esbuild output), `out/`, `coverage/`, `test-results/`, `tmp/`, `screenshots-echo-diag/`. The committed gesture bundle (`src/web/public/gesture/gesture-codeman.js`) IS tracked, but its runtime wasm/model assets (`src/web/public/gesture/wasm/`, `*.task`) are fetched and gitignored.
+1
View File
@@ -744,6 +744,7 @@ A full-screen dashboard for your sessions, in the terminal. Same states as the w
codeman tui # the dashboard
codeman tui --list # numbered session list, then exit (scriptable)
codeman tui 2 # attach straight to session 2 of that list
codeman tui api-docs # attach straight to the live session named api-docs
```
Sessions are grouped **NEEDS YOU → WORKING → IDLE → RECENT**, longest-waiting first. `↑↓`/`j`/`k` select, `1`-`9` and `[`/`]` switch between sessions, `Enter` attaches into the tmux pane (**`F1`** to come back). Inside a pane the bar across the top keeps the session strip visible and `Alt+1`-`Alt+9` switch without leaving. `y`/`n`/digit answer a pending permission dialog right from the list, `p` sends a one-line prompt, `n` starts a session and opens straight into it, `x` kills one (`y` confirms), `/` searches, `g` shows the away digest, `?` is help, `q` quits. Below 72 columns it drops the preview pane and becomes a single-column list, so it stays usable in Termius on a phone. With no server running it still starts in attach-only degraded mode.
+1
View File
@@ -741,6 +741,7 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
codeman tui # 仪表盘
codeman tui --list # 带编号的会话列表,随即退出(可用于脚本)
codeman tui 2 # 直接附着到列表里的第 2 个会话
codeman tui api-docs # 直接附着到名为 api-docs 的活动会话
```
会话按 **NEEDS YOU → WORKING → IDLE → RECENT** 分组,等得最久的排最前。`↑↓`/`j`/`k` 选择,`1`-`9` 与 `[`/`]` 切换会话,`Enter` 附着进 tmux 面板(按 **`F1`** 回来)。在面板里,顶部的横条会一直显示会话条,`Alt+1`-`Alt+9` 不用离开就能切换。`y`/`n`/数字可以直接在列表里回答待处理的权限对话框,`p` 发送一行提示,`n` 新建会话并直接进入,`x` 杀掉一个(`y` 确认),`/` 搜索,`g` 显示离开摘要,`?` 是帮助,`q` 退出。窄于 72 列时它会去掉预览面板、变成单列列表,所以在手机上的 Termius 里依然好用。没有服务器在跑时,它仍会以仅附着的降级模式启动。
+2 -2
View File
@@ -3,7 +3,7 @@
"name": "io.github.Ark0N/codeman",
"title": "Codeman",
"description": "Start, prompt and read AI coding agent sessions (Claude Code, Codex, Gemini CLI and more) in Codeman",
"version": "1.51.0",
"version": "1.51.1",
"websiteUrl": "https://getcodeman.com",
"repository": {
"url": "https://github.com/Ark0N/Codeman",
@@ -13,7 +13,7 @@
{
"registryType": "npm",
"identifier": "aicodeman",
"version": "1.51.0",
"version": "1.51.1",
"transport": {
"type": "stdio"
},
+24 -1
View File
@@ -156,10 +156,33 @@ ask() {
fi
}
# True when host $1 accepts a connection on port $2 within about a second.
# A listening port answers at once and a closed one is normally refused at
# once, but on WSL a connect to a closed 127.0.0.1 port is dropped and only
# fails at the kernel's connect timeout, minutes later. No answer in time
# reads as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`.
port_answers() {
local pid tries=0
(exec 3<>"/dev/tcp/$1/$2") 2>/dev/null &
pid=$!
while kill -0 "$pid" 2>/dev/null; do
if ((tries >= 20)); then
kill "$pid" 2>/dev/null
# The 2>/dev/null keeps bash 3.2 from printing a "Terminated" job line on
# the first-run path; bash 5.2 prints nothing without it, so CI won't notice.
wait "$pid" 2>/dev/null
return 1
fi
tries=$((tries + 1))
sleep 0.05
done
wait "$pid"
}
# True when something on this host already accepts connections on the port.
# bash's /dev/tcp needs no extra tool on Linux or macOS.
port_in_use() {
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null || (exec 3<>"/dev/tcp/::1/$1") 2>/dev/null
port_answers 127.0.0.1 "$1" || port_answers ::1 "$1"
}
first_free_port() {
+15 -5
View File
@@ -18,7 +18,7 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough
### The prefix table on Codeman's socket holds only send-prefix
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`.
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T <table>` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client),Line truncated
### Reverse-proxy base path
@@ -135,7 +135,7 @@ Further detail: ⚠️ An ADOPTED container may back SEVERAL cases at different
⚠️ **`param` is TWO namespaces.** `launch.params` keys, `env.configSetenv[].fromParam` and `capabilities.privilegedParams[].param` all name a LAUNCH PARAM; the legacy `<Mode>Config` wire field is a separate namespace, bridged only by `launch.legacyConfigAliases`. Getting `privilegedParams[].param` wrong is SILENT — it is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a wrong name clamps nothing with no load error and no failing test — so `schema.ts` rejects an entry naming a param it never declared. Codex is the entry where the two names differ (`bypassApprovals` vs `dangerouslyBypassApprovals`) and therefore the one that catches a regression.
⚠️ Five fields are DECLARED-FOR-LATER and read by nothing (`accent`, `capabilities.echo`/`wheelForward`/`keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured (except `accent`, measured against styles.css on 2026-09-21), so re-measure before wiring one up; the list is pinned so it cannot quietly grow. (`shortBadge` left the list when the Settings CLI management list started showing it.)
⚠️ Four fields are DECLARED-FOR-LATER and read by nothing (`accent`, `capabilities.echo`/`keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured (except `accent`, measured against styles.css on 2026-09-21), so re-measure before wiring one up; the list is pinned so it cannot quietly grow. (`shortBadge` left the list when the Settings CLI management list started showing it, and `wheelForward` when the browser's wheel gate started reading it.)
Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.test.ts`, remote/docker pane commands in `test/location-overlay-commands.test.ts`. ⚠️ That second golden no longer covers **remote claude or remote omp**: both now have their own arm in `buildRemoteLaunchCommand` (a `--session-id || --resume` pair, and `--continue`, so a respawn continues the same conversation) and never reach `defaultRemoteCommandForMode`, which is what that test asserts. Their real pins are `toContain` substrings in `test/tmux-manager.test.ts` and `test/remote-shared-sessions.test.ts`; changing either arm will NOT fail the golden.
@@ -267,7 +267,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
⚠️ **What a mouse-DECSET strip (full or mouse) removes, it must REMEMBER.** Stripping the mouse DECSETs means xterm's `modes.mouseTrackingMode` is permanently `'none'` for those modes, so the browser hand-encodes click reports to compensate (`_sendSyntheticSgrTap`). With no state to consult it did that on EVERY click, which delivered mouse reports to programs that never asked for them: the same pane runs a plain shell whenever the CLI has exited or a `shell` was started inside a claude-mode session, and a shell prints the report as literal text (`[<0;88;20M`), garbling the next line typed. `_recordStrippedMouseMode()` therefore records each stripped sequence as it goes and publishes `cliMouseTracking` through `toState()`, and `_shouldReportMouseToCli()` requires it. ⚠️ Only the TRACKING modes count (1000/1001/1002/1003): 1005/1006 select an ENCODING and 1007 is alt-scroll, and counting those would put the stray reports straight back. ⚠️ The change broadcasts IMMEDIATELY rather than through `broadcastSessionStateDebounced`, because the flag flips when a dialog opens and the user can click that dialog inside the 500ms debounce window. Measured on a live claude 2.x: the CLI holds a tracking mode on continuously in fullscreen (so clicks keep being reported exactly as before; the default inline renderer holds none, measured on 2.1.283 even with `/model` open), while a bash prompt in the same stripped mode reports nothing. Fails toward silence: after a server restart the flag is false until the CLI re-emits, which tmux does at client attach.
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. A stale/false flag after startup cannot authorize forwarding. ⚠️ A strip mode alone is not evidence that a CLI consumes SGR reports. Verify with a real `\x1b[<64;c;rM` write into a live pane before adding a mode here. Hand-encoded SGR taps remain independently gated by `_shouldReportMouseToCli()`; the older #325 no-op measurement describes untracked inline Codex and must not be generalized to newer tracked fullscreen renderers. Shift/local-history opt-outs and xterm's native mouse/alternate-screen handling remain intact.
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. That field is the gate's only per-CLI rule: `renderIndexHtml` publishes every CLI's `wheelForward` (disabled ones included, since their sessions keep running; `never` left out) as `window.__codemanWheelForward`, so a custom `clis.json` entry forwards under its own id, and a `minVersion` that is not `MAJOR.MINOR.PATCH` refuses forwarding. A stale/false flag after startup cannot authorize forwarding. ⚠️ A strip mode alone is not evidence that a CLI consumes SGR reports. Verify with a real `\x1b[<64;c;rM` write into a live pane before adding a mode here. Hand-encoded SGR taps remain independently gated by `_shouldReportMouseToCli()`; the older #325 no-op measurement describes untracked inline Codex and must not be generalized to newer tracked fullscreen renderers. Shift/local-history opt-outs and xterm's native mouse/alternate-screen handling remain intact.
**Copilot also receives forwarded reports** (1.0.95 measured in tmux: alt screen, `mouse_any_flag=1`): its mouse DECSETs are stripped so a drag selects, which also stops xterm encoding the wheel for it, so `_shouldForwardWheelToApp` sends the same SGR reports by hand while `cliMouseTracking` is true; six `\x1b[<64;…M` reports moved its transcript 18 lines, a phone swipe takes the same gate, and there is NO version gate.
@@ -682,6 +682,8 @@ Adding the header changed the preamble, so `CODEMAN_PREAMBLE` was bumped (1.22.0
⚠️ Both `POST` and `DELETE` sit at the **same privilege bar as the profile installer** (`canUsernameRunPrivilegedCommands`) even though the action reads as "open a page": booting a dsh profile executes the plugin code in it, and the server is a single shared instance, so stopping it in multi-user mode takes it out from under other users' tabs.
⚠️ dsh's browser-auth gate answers only a request carrying the one-time launch token from its boot banner, so the supervisor trades that token for dsh's `dsh-auth-*` session cookie once at startup (`getDeepSeekWebCookie()`), and the web-tab proxy presents the cookie on BOTH legs, HTTP and WebSocket, only to a `managed: 'deepseek-web'` tab whose upstream is `127.0.0.1` on the port it was minted for. Reuse therefore needs the same starter AND a working cookie: a server whose exchange failed, or one another owner started, is restarted rather than reused. The owner check applies only in multi-user mode (a record keeps the owner it was created under, while a single-user start has none), and the browser's own `codeman_session` cookie is filtered out of both legs whether or not the dsh cookie is injected. Details: `docs/deepseek-integration.md`.
### Custom Model Endpoint Profiles
**Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`, design doc `docs/custom-model-endpoints-plan.md`; full stack — settings-panel CRUD + the Run-menu picker, on top of the backend below): points a session at a user-configured custom OpenAI-compatible endpoint — local (llama.cpp, DGX Spark, Strix Halo) or cloud (Azure AI Foundry, OpenRouter) — instead of its harness's native cloud backend. Endpoints are a read/write-array store (`custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`) discovered via `GET <baseUrl>/v1/models`; `CustomModelHost.authStyle` is `'bearer'` (default, `Authorization: Bearer`) or `'api-key'` (Azure's convention) — **never both**, live-tested against a real server: sending both headers on one request reliably hangs it indefinitely, reproduced 3×.
@@ -1139,7 +1141,9 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
**A fold is not a keyboard.** `KeyboardHandler.handleViewportResize()` (mobile-handlers.js) used to read any visual-viewport height drop over 150px as the keyboard appearing. A virtual keyboard only ever takes HEIGHT, so a resize that changes the WIDTH is the device changing shape (a rotation, or a foldable opening or closing) and is skipped by both detection branches. Closing an iPhone Duo (626→466pt wide, 890→678pt tall) otherwise latched `keyboardVisible` with no keyboard on screen: the accessory bar appeared, `main` grew 84px of dead padding, and `updateAppHeight()`, which bails while the keyboard is up, stopped refreshing `--app-height`. The latch was sticky because clearing it needed the height back within 100px of a baseline belonging to a display the user was no longer looking at. The shape branch re-baselines instead, which is also what lets a keyboard opened after the fold be detected, and `init()` seeds `lastViewportWidth` so the first resize of the page is not itself read as a shape change.
**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both.
**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact, but measures that height as the larger of `innerHeight` and `documentElement.clientHeight`: on a first keyboard open iOS Safari briefly reported `innerHeight` as the shrunk visual height, 323 against a 640 layout viewport, which zeroed the bars' lift). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both.
**A pan of the visual viewport moves `.app` with it.** In resizes-visual mode a focused field that starts behind the keyboard makes Android pan the visual viewport down to reveal it: the pinned `#cjkInput` sits at the bottom of the layout viewport, and Chrome panned 285px with a 458px visual viewport in a 744px layout one. `.app` is sized to the visual viewport (`--app-height`) but laid out at the top of the layout viewport, so that pan left only the terminal's last line on screen. On phones `updateLayoutForKeyboard()` therefore sets `.app`'s `translateY` to `visualViewport.offsetTop` while the keyboard is up, whatever has focus (no pan, the usual case, moves nothing), and clears it on every other branch and in `resetLayout()`. ⚠️ The transform makes `.app` the box its `position: fixed` children are placed against (header, `.toolbar`, the accessory bar, which is inserted before the toolbar, `#cjkInput`, and the phone case sheet, `#mobileCasePickerModal`), so their lift is measured from `.app`'s bottom (`insideLift`), not the layout viewport's: lifting them by the layout gap as well floated them above the keyboard on a partial pan. Separately, `KeyboardHandler.isInputElement()` skips `#cjkInput` like xterm's inputs, because the focusin `scrollIntoView({ block: 'center' })` centred the fixed field in its ancestors and pushed the terminal off screen. Pinned by `test/keyboard-handler-pinned-field.test.ts`.
**The hinge is a reserved region, and the CSS is inert by construction.** The CSS Viewport Segments media features report two segments only while a foldable is actually bent; `--fold-inline-end` / `--fold-block-end` (end of styles.css) measure the strip to keep clear from the LEADING segment (`env(viewport-segment-right 0 0)` and `env(viewport-segment-bottom 0 0)`, physical sides in every text direction) and are `0px` on everything else. The seven centred overlays are all `position: fixed; inset: 0` flex boxes; each shrinks its CONTENT box with padding rather than the box itself, so the backdrop still covers the far side of the fold and still swallows taps there. The cascade traps, each measured in headless Chromium against styles.css + mobile.css in index.html link order: (1) a later `padding-right` longhand beats the earlier `padding` shorthand it composes with, so each fold rule re-states the overlay's own gutter; (2) a base gutter that a LATER `@media` block overrides needs its own fold restatement in that block on a ZERO base, since the unconditional rules at the end of the file otherwise put the gutter back (the phone path picker and path preview drop to `padding: 0` under 600px and came back at 16px and 18px on every phone); (3) a compound rule written to outrank a mobile.css shorthand must be scoped to the band where that shorthand applies, because outside it there is no gutter to compose with (the palette's `.modal.command-palette-modal` added 0.75rem at 393, 900 and 1400px and pushed the shell 6px off centre, and inside the band it lost its bottom gutter to the shorthand until it restated that side too); (4) mobile.css loads AFTER styles.css, so a same-specificity rule there wins under its own breakpoint (the response viewer's `max-height: 92dvh` under 600px beat the tabletop cap, which now has a twin at the end of mobile.css). `test/foldable-layout.test.ts` DERIVES the overlay list from the stylesheet, simulates the cascade across both files at every breakpoint with and without the fold rules, and requires the two results to differ by exactly the fold strip, so each of the four fails there instead of on hardware nobody has.
@@ -1269,7 +1273,7 @@ The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTime
⚠️ It must disarm on ALL of: use, second tap, any other accessory key, session switch, keyboard dismissal, and a layout swap; a modifier left armed turns the next innocent keystroke into a control byte.
⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY, so one call covers typed characters, IME flushes, Enter, backspace and arrows. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke.
⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY in live mode, so one call covers typed characters, IME flushes, Enter, backspace and arrows; in Send on Enter a held answer leaves through `_sendCjkPrompt()` instead, which spends the modifier, while an armed next character still goes through `_handleCjkInput()`. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke.
Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Space=NUL / Ctrl+?=DEL); characters with no control equivalent pass through unchanged, like a hardware keyboard.
@@ -1299,6 +1303,8 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
**(2)** In `_handleMobileTerminalTap`, a second tap on **inert `content`** (`startedWithTerminalFocus`) blurs instead of re-focusing. ⚠️ Scoped to `content` on purpose: the prompt row (`input`) keeps focus-then-position so a second tap still places the caret, and actionable rows blur earlier via `_isActionableMobileTerminalTap`.
⚠️ **The pinned CJK field keeps its focus through a swipe.** `initTerminal`'s touchstart blurs the focused input on `content` before the gesture is known to be a tap or a scroll. For xterm's helper textarea that blur, with the `preventDefault` beside it, is what keeps the compatibility click from opening the keyboard. The visible `#cjkInput` owns the keyboard instead, so `_contentTouchStartBlurs()` leaves it focused; blurring it closed the keyboard on every swipe that started on the live screen. A real tap still closes it: inert content through (2), a link in `_handleMobileTerminalTap`'s link branch (which blurs because touchstart did not), a long press in `_beginTouchSelection`. A sideways session swipe keeps it open, since the field's draft is per session. Pinned by `test/terminal-touch-tap.test.ts`.
⚠️ **A scroll ends in `touchend` too** — dismissing there closes the keyboard and drops the composer mid-read, so travel is tracked from `touchstart` and multi-touch is never a tap. Both classifiers MUST share one threshold: `initTerminal`'s `TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`, since a gesture the terminal calls a scroll and the dismiss handler calls a tap is exactly that bug.
⚠️ **An accessory key that keeps the keyboard up must not take focus on the press.** The keys that act on the terminal and leave the keyboard open (`ACCESSORY_REFOCUS_ACTIONS` in keyboard-accessory.js: scroll, arrows, Tab, Shift+Tab, Ctrl, Esc, clear input and the rest) cancel the `mousedown` default, the same pattern as the Attach input, so the hidden textarea keeps focus through the press; the `terminal.focus()` in the click handler stays as the fallback. Letting the tap blur the terminal and refocusing it afterwards made every such key start a keyboard dismissal, a blur/focus pair per tap that shifted the toolbar each time. A first tap on clear/compact only arms the confirm and is treated the same; the confirming tap, and keys that open a dialog or dismiss the keyboard on purpose, keep the default. Pinned against the real module by `test/accessory-keeps-terminal-focus.test.ts`.
@@ -1549,3 +1555,7 @@ updates `lastSubmitAt` just like any other Enter.
- **Files.** Received files come only from Discord's HTTPS hosts into `<tab folder>/.codeman-discord/` (bounded probe, refused if a symlink, self-ignoring). A sent file's real path must lie inside the tab's folder; both the folder and the file are probed with the bounded probe first.
- **The whole last message.** A finished turn or an error posts the CLI's whole last message, not the screen: `WebServer.lastResponseFor` is the response viewer's reader (the body of `GET /api/sessions/:id/last-response`, registered on the route context by `registerSessionRoutes`), so the source is the same per-CLI transcript, or the pane split into turns where a CLI keeps none; a dialog and a shell keep the screen tail (its composer row and the status lines under it cut, never a `❯ 1.` option row). The read is bounded to 4 s and any failure or empty read falls back to the screen. It is split into at most 8 posts of 1,900 characters, a cut code fence closed and reopened, and Markdown tables become aligned code blocks (the separator test strips whitespace first: a regex over a run of spaces is quadratic, and the text is steerable by whatever the agent read). The repeat check is keyed on the text plus the turn it came from (the transcript stamp, else the last submit) and is recorded only after the first post succeeds, so a failed post is sent again and a later turn ending on the same words is not dropped. Only some CLIs raise a turn end (`/api/hook-event`: Claude's `stop` and `idle_prompt`, DeepSeek's `stop`), so the others reach this path through errors, a blocked respawn or a crash loop.
- **Cost guards.** The alert tail is a function called only once a post will happen (no tmux exec while off), and `discord-notify` is a per-session token bucket (6 a minute, `429 RATE_LIMITED`).
### Discord reply replay metadata
`discord-reply-dedupe.json` is a private 0600 data-directory file containing at most 2,048 reply IDs and timestamps retained for seven days. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments, or terminal input. Store failures log once and fall back to memory; they never cost a reply. An unreadable or unsafe file is never overwritten, and reads retry later. Invalid or oversized regular-file ID-only content warns and heals on the next write. Recovery keeps older disk rows before newer outage claims so bounded eviction drops the oldest IDs first. Ambiguous terminal input is never replayed automatically.
+5 -1
View File
@@ -300,7 +300,7 @@ This matters because it is invisible when it is wrong. `capabilities.privilegedP
## Fields declared for later
`accent`, `capabilities.echo`, `capabilities.wheelForward`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
`accent`, `capabilities.echo`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it, and `capabilities.wheelForward` until the browser's wheel gate started reading it, see below.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
Treat those values as **transcribed, not authoritative** — nothing enforces that `echo.policy` matches `_updateLocalEchoState`'s fallthrough, so re-measure before wiring one up. `accent` is the one exception: it was measured against styles.css on 2026-09-21 (method in the comment above `CLAUDE` in `stock.ts`), though nothing keeps it in step with the CSS either. A field that is both wrong and unread is worse than an absent one, because the next reader trusts it; `test/cli-registry-no-id-branching.test.ts` pins the list so it cannot quietly grow, and wiring one up makes its line there fail, which is the direction you want.
@@ -308,6 +308,10 @@ Treat those values as **transcribed, not authoritative** — nothing enforces th
Everything else in the interface is live, including `overlays.remote` / `overlays.docker`, which back `defaultRemoteCommandForMode()` and `defaultDockerCommandForMode()` directly. Those two used to be hardcoded `Record<…CommandMode, string>` tables duplicating the registry with nothing keeping the two in step; `test/location-overlay-commands.test.ts` pins every resulting command as a literal string.
### Wheel forwarding for a custom full-screen CLI
`capabilities.wheelForward` reaches the browser as `window.__codemanWheelForward` (id to rule, every CLI whose mode is not `never`, disabled ones included, since disabling a CLI leaves its running sessions open), and `_shouldForwardWheelToApp` in terminal-ui.js reads only that map, so a custom entry gets the same wheel as a stock one under its own id. A full-screen TUI that turns mouse tracking on itself (a wrapper around pi, for example) needs two values in its `clis.json` entry, the ones stock pi carries: `"altScreen": "strip-mux-and-mouse"` (the server strips its mouse DECSETs and publishes `cliMouseTracking`, and a drag selects locally) and `"wheelForward": { "mode": "always" }` (the wheel goes to the CLI as SGR reports while that flag is on). With the custom-entry defaults (`strip-mux-only`, `never`) the DECSETs reach xterm, which handles the wheel only until a tab switch or reload replays the pane without them; from then on the wheel scrolls an empty local buffer. Use `always` rather than `version-gated` for such an entry: a `version-gated` rule forwards only when the session has a `cliVersion`, and the server probes one only for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe` in `session.ts`), so a custom entry with `version-gated` and no gates never forwards, and nothing says why. ⚠️ Saving the entry from the Settings form rebuilds its capabilities from those defaults, so both values have to be set again in the file after an edit there.
## Consumers outside the server
Two things need the catalogue but cannot import TypeScript, so `npm run generate:cli-catalog`
+33
View File
@@ -288,6 +288,39 @@ dsh fences its `/api` behind a browser-trust check on the request authority, and
Codeman web tab reaches it through Codeman's own origin via the webview proxy, not
directly. Without it the page renders and every API call fails.
Since dsh's browser-auth gate, the index is not public either: boot prints
`dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
carrying that token is answered with the `dsh-auth-*` cookie that authorizes
everything after it. The saved tab deliberately keeps the clean URL, so the
browser can never present that token, and the tab used to open on dsh's 401 page.
`src/deepseek-web-server.ts` now reads the token out of the captured boot output,
trades it for the cookie once at startup, and `webview-routes.ts` presents that
cookie on both the HTTP and WebSocket legs — scoped to the exact loopback
authority it was minted for, so a repointed or stale tab cannot carry it
elsewhere. The reader scans every `dsh web:` line (dsh prints diagnostics such as
`dsh web: loading profiles` under the same prefix before the banner) and only
complete lines, so a banner split across two output chunks is waited for rather
than parsed truncated. Before the token URL is fetched it must name `127.0.0.1`
on the port the supervisor just spawned, so a banner cannot aim the server-side
request at another host or local service. A dsh without the gate prints a
token-less banner and keeps working unchanged. If a token is printed but the
exchange still fails, the server keeps running (its page serves, just 401) and is
marked unusable for reuse: the next start request stops and respawns it, which is
the "restart `dsh web`" the warning asks the user to perform.
The cookie is also bound to a person, not to a URL. `managed` is accepted from the
client on `POST/PATCH /api/webviews` and `GET /api/deepseek/web` publishes the live
port, so a saved record pointing at that port is not an entitlement by itself: the
proxy presents the cookie only when the tab's owner holds the same
privileged-commands grant `POST /api/deepseek/web` requires, and in multi-user mode
only to the owner whose request started that process. A different owner's start
request restarts the server rather than reusing a cookie that is not theirs, which
is why the shared instance is effectively single-user at a time. On a trusted
managed tab the cookie is sent ahead of whatever cookies dsh itself set in the
browser, rather than replacing them; leading matters because a `Cookie` header can
name the same cookie twice and the first value is the one the dashboard parses, so
a stale browser copy must not shadow the one the running process minted.
## 7. Docker and remote cases
Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui`
+6
View File
@@ -135,3 +135,9 @@ The text explains `codeman notify "message" --urgent`. `codeman` is on the PATH
| Posts arrive but replies do nothing | Message Content Intent is off, or your user ID is not in the allowlist |
| Thread is not deleted | The bot lacks Manage Threads on the parent channel |
| Nothing arrives on the phone | Check the Discord app's notification setting for the server |
## Reply replay protection
The bridge remembers up to 2,048 recent Discord reply IDs for seven days in the private `discord-reply-dedupe.json` metadata file. It claims an allowed reply before rate-limit or exited-agent checks, downloading attachments, or typing into its session, so a gateway replay normally cannot type it twice, including after a restart. The file contains IDs and timestamps only, with mode 0600.
This is best-effort replay protection, not an exactly-once guarantee. A full disk, unreadable file, or invalid metadata logs one content-free warning and falls back to in-memory checks. Invalid or oversized regular-file ID metadata is replaced on the next write. Files that could not be read are left untouched. Reads and writes retry on later replies; a restart during a metadata outage can lose those checks. At capacity the oldest entries are evicted, so capacity never blocks new replies. Notifications retain their existing delivery and retry behavior; this store never suppresses an outbound alert or replays terminal input.
+10
View File
@@ -18,6 +18,7 @@ tmux rather than proxying bytes.
codeman tui # the dashboard
codeman tui --list # print the numbered session list and exit
codeman tui 2 # attach straight to session 2 of that list
codeman tui api-docs # attach straight to the live session named api-docs
```
The two fast paths are the scriptable ones.
@@ -84,6 +85,15 @@ The same world through `--list`:
The numbers are the same on both surfaces, so `codeman tui --list` then
`codeman tui 4` is one thought.
A number moves as sessions change state; a name does not. `codeman tui <name>`
attaches to the live session whose name is exactly `<name>` (case-sensitive,
never a prefix, never the folder), so the same line gets you back into the same
session from any folder or a fresh SSH login. Digits only always mean a list
number. Session names are not unique in Codeman, so when two live sessions share
the name it refuses and prints their numbers instead of guessing; a name only a
RECENT row carries says the session has finished. Both refusals are printed
before the terminal check, so a script can tell them apart without a TTY.
## The four groups
Groups are always in this order, and a session is in exactly one of them:
+24 -2
View File
@@ -144,9 +144,21 @@ per-device (`localStorage`), since that is workspace layout rather than config.
Worth knowing, because it is where this feature does its least obvious work. Three
layers cooperate so a dashboard talking to its own backend just works:
1. `<base href>` handles relative URLs in the markup.
1. `<base href>` handles relative URLs in the markup. A page that ships its own
**relative** base (`<base href="./">`, what a Vite build emits) has it resolved
against the document's own directory inside the proxy prefix first, so a
document at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/` rather
than the proxy root: the page's URL is masked a few paragraphs below, a base is
resolved against that URL, so `./` would otherwise point at Codeman's root and
404 every module script behind an otherwise-painted page.
2. Attribute rewriting handles root-absolute `src`/`href`/`action` in the page the
proxy serves.
proxy serves — and root-absolute dynamic `import("/...")` specifiers inside
`<script>` bodies. The import is the one URL no other layer can reach: `<base>`
does not apply to a `/`-rooted specifier and it is not a `fetch()`. SvelteKit's
inline bootstrap is exactly this shape; without the rewrite the module loads
from Codeman's root, 404s, and the app sits on its own loading spinner forever.
Visible text is left alone: a `<pre>import("/x")</pre>` example is not a
loader and is not rewritten.
3. A small injected script rebases URLs built at **runtime**, which the first two
cannot see: `fetch('/api/data')` and `new WebSocket('/live')`, but equally
`card.innerHTML = '<img src="/api/hero">'`, `img.src = '/api/slide'`, and
@@ -190,6 +202,16 @@ then every API call fails, which looks like the dashboard being broken.
EventSource, normal markup, the DOM sinks a page uses to build markup at runtime,
and `url()` inside stylesheets. Something that constructs requests by an unusual
route can still slip through. Symptom: the page renders but a panel stays empty.
- **Root-absolute URLs the proxy never sees.** Only the HTML is rewritten, and only
literal `/`-rooted specifiers in it. Still escape: an `import()` built at runtime
(`import('/' + name)`), an import written inside an external `.js`, a static
`import x from "/x"` in an inline script, `navigator.serviceWorker.register("/sw.js")`,
and `url(/img.png)` inside an external stylesheet. They cannot be relayed either —
the masked frame's `Referer` carries no capability — so the failure is quiet: a
blank page, or a spinner that never resolves. Codeman now logs
`[Webview] <path> escaped the proxy` (once per path per five minutes) when such a
request reaches its 404, which is the fastest way to tell this class apart from a
dashboard that is genuinely broken.
- **A root-absolute `url()` inside an inline `<style>` is not rescued.** Masking the
page's URL (layer 5) trades away the `Referer` safety net of layer 4 for
requests the shim cannot see, and only HTML is rewritten server-side. An
+16
View File
@@ -67,6 +67,22 @@ below the terminal that owns composition, then delivers the composed text to the
Ctrl- and Alt-modified navigation keys typed through it reach the CLI as the modified
sequences, so word jumps and history keys keep working.
On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box:
typed text stays in it until Enter, so you can scroll the terminal back to a question and edit
your answer before sending. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen
keyboard has no Shift+Enter, and the extended bar's newline key goes to the CLI, not the field),
Esc clears the field, and autocorrect is on. Enter always goes out as its own write, a moment
after the text, to the session the answer was typed for: a single character is typed, so CLI menus
that take a digit still work, and anything longer goes like the prompt composer's Send, as one
paste. The one exception is a lone digit while a permission or question dialog is waiting: the
digit answers the dialog by itself, so no Enter follows it, which would otherwise confirm whatever
the CLI shows next. The toolbar's Enter button sends the field too. With the keyboard bar's
one-shot Ctrl armed, the next key you type goes out as a control key (Ctrl, then `c` is Ctrl+C)
instead of being held. With a hardware keyboard, Ctrl shortcuts (undo, select all, copy) act on
the field while it holds a draft and reach the CLI only when it is empty. With the keyboard down
the field stays one line tall. A draft stays with its session: switching tabs and coming back
brings it back.
## Voice dictation
`Ctrl+Shift+V`, or the microphone button. There are three providers and the default is
+1
View File
@@ -255,6 +255,7 @@ works well in SSH clients like Termius or Blink:
```bash
codeman tui # the dashboard
codeman tui 2 # attach straight to session 2
codeman tui api-docs # attach to the live session named api-docs
codeman tui --list # numbered list, then exit
```
+1
View File
@@ -48,6 +48,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
| Local Echo | On for touch devices | Paints keystrokes locally and flushes on Enter. See [Input And Voice](Input-And-Voice). |
| Keep Size Under Keyboard | On | For local Claude sessions, the on-screen keyboard no longer resizes the session: the terminal keeps its rows and the view scrolls so the prompt sits just above the keyboard. Resizing made Claude reprint its screen and drop transcript lines from history. Codex, Claude's fullscreen mode, remote and Docker sessions resize as before. See [Mobile Guide](Mobile-Guide). |
| CJK Input | Off | IME composition through a dedicated text field. |
| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. |
| Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. |
| Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. |
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.51.0",
"version": "1.51.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.51.0",
"version": "1.51.1",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.51.0",
"version": "1.51.1",
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
"mcpName": "io.github.Ark0N/codeman",
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "codeman",
"description": "Drive Codeman, the self-hosted session manager for AI coding agents, from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
"version": "1.51.0",
"version": "1.51.1",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+11 -1
View File
@@ -927,7 +927,7 @@ program
program
.command('tui')
.argument('[n]', 'attach straight to the nth session of `codeman tui --list`')
.argument('[session]', 'attach straight to a session: its number in `codeman tui --list`, or its exact session name')
.description('Terminal dashboard for your sessions (the web UI remains the primary surface)')
.option('-l, --list', 'Print the numbered session list and exit, instead of opening the dashboard')
.action(async (position: string | undefined, options: { list?: boolean }) => {
@@ -940,6 +940,16 @@ program
return;
}
if (position !== undefined) {
// Digits only is a list number, as it always was; anything else is a session name.
if (!/^\d+$/.test(position)) {
if (position.trim() === '') {
console.error(palette.err('An empty session name matches nothing.'));
process.exitCode = 1;
return;
}
process.exitCode = await runTuiAttach(position);
return;
}
const n = Number.parseInt(position, 10);
if (!Number.isSafeInteger(n) || n < 1) {
console.error(palette.err(`"${position}" is not a session number.`));
+4 -4
View File
@@ -303,8 +303,8 @@ const CLAUDE: CliEntry = {
transcript: 'claude-jsonl',
altScreen: 'strip-full',
echo: { policy: 'buffer', anchor: { kind: 'glyph', glyph: '❯', offset: 2 } },
// Declared-for-later: the live rule (`_shouldForwardWheelToApp`, terminal-ui.js) is this version
// AND the server-published `cliMouseTracking` flag (#498), so wiring this field up needs both.
// Read by `_shouldForwardWheelToApp` (terminal-ui.js) through `window.__codemanWheelForward`;
// forwarding also needs the server-published `cliMouseTracking` flag (#498).
wheelForward: { mode: 'version-gated', minVersion: '2.1.187' },
// A repaint-mode Claude pane keeps no local history, so when the wheel is not
// forwarded (older CLI, inline renderer, the local-scrollback opt-out) a scroll is
@@ -1926,8 +1926,8 @@ const COPILOT: CliEntry = {
// (`cliMouseTracking`). Same shape and reason as opencode. The wheel keeps working because
// `_shouldForwardWheelToApp` forwards it as SGR reports while the CLI is tracking.
altScreen: 'strip-mux-and-mouse',
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version
// (`_shouldForwardWheelToApp` in terminal-ui.js has no version check for copilot).
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version:
// `always` is what keeps `_shouldForwardWheelToApp` (terminal-ui.js) from checking one.
wheelForward: { mode: 'always' },
// Pages its own transcript on PageUp/PageDown (1.0.95, measured in tmux: three PageUp moved
// lines 109-140 to 010-042 and PageDown returned). This is the fallback when the
+15 -6
View File
@@ -596,10 +596,18 @@ export interface CliCapabilities {
* Forwarding the wheel to the CLI's own transcript. 'never' keeps local scrollback;
* 'version-gated' forwards from `minVersion` on; 'always' forwards at any version. Either
* forwarding mode applies only while the CLI has mouse tracking on (`cliMouseTracking`).
* Read by the browser's gate (`_shouldForwardWheelToApp` in terminal-ui.js) through
* `window.__codemanWheelForward`, which the server builds from this field for every CLI
* whose mode is not `never`, disabled ones included (their running sessions stay open).
*
* ⚠️ Declared only: nothing reads this field yet (see DECLARED-FOR-LATER below). The browser's
* gate is `_shouldForwardWheelToApp` in terminal-ui.js, which keeps its own hand-written
* per-CLI rules, so changing a value here changes nothing until that gate is changed too.
* ⚠️ 'version-gated' needs the session's `cliVersion`, and the server probes a version only
* for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe`, session.ts). An
* entry without gates never forwards under 'version-gated', silently, so it uses 'always'.
*
* ⚠️ `cliMouseTracking` is only ever set for a CLI whose mouse DECSETs the server strips
* (`altScreen: 'strip-full'` or `'strip-mux-and-mouse'`), so a forwarding mode on any other
* `altScreen` never forwards: xterm keeps the DECSETs and encodes the wheel itself, until a
* replay drops its mouse mode.
*/
wheelForward: { mode: 'never' | 'version-gated' | 'always'; minVersion?: string };
/**
@@ -1009,14 +1017,15 @@ export interface CliOverlays {
/**
* ⚠️ DECLARED-FOR-LATER: fields no code reads yet.
*
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.wheelForward`,
* `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` all describe FRONTEND
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.keyboardAccessory` and
* `capabilities.maxFrameBytes` all describe FRONTEND
* behaviour, and most of the frontend is deliberately untouched by the change that introduced
* this registry — `app.js`, `terminal-ui.js`, `styles.css` and friends keep their own
* hand-authored per-CLI rules, and moving them is its own piece of work with its own way of
* being verified (a mobile/browser suite the CI gate cannot see). `shortBadge` graduated out of
* this list (docs/cli-enable-disable-plan.md, Phase 2): `GET /api/clis` reads it for the
* CLI-management Settings list.
* CLI-management Settings list, and so did `capabilities.wheelForward`, which the browser's wheel
* gate reads through `window.__codemanWheelForward`.
*
* They are declared now because each entry should describe its CLI completely, and because
* transcribing them while the hand-written source is still on screen is when the values are
+52
View File
@@ -0,0 +1,52 @@
/**
* @fileoverview The header CPU reading: CPU use over all cores since the previous reading, from each core's
* busy and idle time as `os.cpus()` reports it (the kernel's per-core counters on Linux, macOS and Windows).
*
* It replaces the 1-minute load average divided by the core count. Load counts runnable tasks, not busy time,
* so a host with bursty short-lived processes, or a VM whose vCPU threads count as runnable, read 100% while
* most of its cores were idle.
*/
import type { CpuInfo } from 'node:os';
/** Readings closer together than this reuse the last value, so several open browsers never shrink the window. */
export const CPU_USAGE_MIN_WINDOW_MS = 1000;
interface CpuTimes {
busy: number;
total: number;
at: number;
}
/**
* A meter that answers the CPU use, 0 to 100, between this reading and the previous one. Without usable core
* times (none reported, or counters that went backwards, as when a core goes offline) it answers the last
* reading, else `fallback()`. The first reading covers the time since the meter was created.
*/
export function createCpuUsageMeter(
readCores: () => Pick<CpuInfo, 'times'>[],
clock: () => number,
fallback: () => number
): () => number {
const sample = (): CpuTimes => {
let busy = 0;
let total = 0;
for (const { times } of readCores()) {
const all = times.user + times.nice + times.sys + times.idle + times.irq;
total += all;
busy += all - times.idle;
}
return { busy, total, at: clock() };
};
let base = sample();
let last: number | undefined;
return () => {
const now = sample();
if (last !== undefined && now.at - base.at < CPU_USAGE_MIN_WINDOW_MS) return last;
const busy = now.busy - base.busy;
const total = now.total - base.total;
base = now;
if (!(total > 0) || busy < 0) return last ?? fallback();
last = Math.min(100, Math.max(0, Math.round((busy / total) * 100)));
return last;
};
}
+263 -10
View File
@@ -27,6 +27,11 @@
* - **Failures reported, not swallowed.** The shell tab used to be where the
* stack trace landed. With no tab, the spawn's own output is captured and
* handed back to the caller instead.
* - **The launch token traded, not forwarded.** `dsh web` gates its own index
* behind a one-time token it prints on stdout and exchanges for a browser
* cookie. The tab stores a clean URL, so nothing on the browser side could
* ever present that token and every load answered 401. This module trades it
* here, once, and hands the cookie to the proxy (`getDeepSeekWebCookie`).
*/
import { spawn, type ChildProcess } from 'node:child_process';
@@ -53,6 +58,23 @@ const READY_POLL_MS = 400;
const KILL_GRACE_MS = 3_000;
/** Bound on captured child output, so a chatty boot cannot grow without limit. */
const OUTPUT_CAP = 16_384;
/**
* Bound on the boot-output window searched for the launch banner.
*
* Deliberately larger and separate from {@link OUTPUT_CAP}: that one only has to
* keep an error tail, while this one must survive a chatty plugin tree's boot
* logs long enough to see a banner printed after them. 256 KB of one-line output
* is far beyond anything a real boot prints, and a bound still exists because a
* wedged child can print forever.
*/
const BANNER_SCAN_CAP = 262_144;
/** How long boot waits for `dsh web` to print the launch URL it gates itself on. */
const LAUNCH_URL_WAIT_MS = 4_000;
/** Bound on the one-shot token→cookie exchange (loopback, so this is generous). */
const TOKEN_EXCHANGE_TIMEOUT_MS = 5_000;
/** Cookie name `dsh web` mints for a browser session that presented the token. */
const DSH_AUTH_COOKIE_PREFIX = 'dsh-auth-';
export interface DeepSeekWebStatus {
running: boolean;
@@ -66,7 +88,33 @@ interface RunningServer {
child: ChildProcess;
port: number;
authority: string;
/**
* Username of the Codeman user whose request started this server. Undefined in
* single-user mode, where no owner exists. The cookie bought with the launch
* token belongs to that identity and is presented to nobody else (see
* `getDeepSeekWebCookie`).
*/
starter: string | undefined;
output: () => string;
/**
* Boot output scanned for the launch banner, on its own (larger) budget than
* `output`. Read through this rather than `output` so a banner printed after
* the error-tail cap filled is still found.
*/
banner: () => string;
/**
* The `dsh-auth-*` cookie bought with this process's launch token, once the
* exchange succeeded. Null on a dsh old enough to serve its index without a
* token, which is why "no cookie" is not a startup failure.
*/
cookie: string | null;
/**
* True when a token-bearing banner was found but the exchange produced no
* cookie. Such a server cannot authenticate its tab and must not be reused: the
* warning tells the user to restart `dsh web`, and the next start request is
* what performs that restart.
*/
cookieFailed: boolean;
}
let current: RunningServer | null = null;
@@ -105,6 +153,158 @@ async function answersHttp(port: number): Promise<boolean> {
}
}
/**
* Remove SGR sequences so a coloured banner still parses.
*
* A coloured banner would otherwise hide the URL behind escape codes and turn a
* perfectly working server into a 401.
*/
function stripSgr(output: string): string {
// Built from the code point rather than written as `\x1b` so the linter's
// no-control-regex rule does not read it as an accidental control character.
return output.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'), '');
}
/**
* The first `dsh web:` payload that parses as an absolute http(s) URL.
*
* Lines whose payload is not a URL are skipped, which is what makes a
* `dsh web: loading profiles` diagnostic harmless. `requireToken` skips an
* http(s) URL that carries no `token` as well, so a diagnostic that happens to
* contain a plain link cannot shadow the real banner. Null when no line qualifies.
*/
function firstLaunchBannerUrl(output: string, requireToken = false): string | null {
// Fresh per call: a module-level /g pattern carries lastIndex between calls.
const line = /dsh web:\s*(\S+)/g;
for (const match of stripSgr(output).matchAll(line)) {
let url: URL;
try {
url = new URL(match[1]);
} catch {
continue;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') continue;
if (requireToken && !url.searchParams.get('token')) continue;
return url.href;
}
return null;
}
/**
* The authenticated URL `dsh web` prints once it is up.
*
* Its browser-auth gate made the index private: boot writes
* `dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
* carrying that token is answered with the cookie that authorizes everything
* after it. The token is per process, so it can be neither guessed nor carried
* across restarts — it has to be read out of the boot output.
*
* Scans EVERY `dsh web:` line and returns the first one that is a usable URL
* carrying a token, because dsh also prints diagnostics under the same prefix
* before the banner.
*
* Null for output without one, which is the older-dsh case and stays working.
*
* @param output - captured stdout+stderr so far.
* @returns absolute http(s) URL carrying a `token`, or null.
*/
export function parseLaunchUrl(output: string): string | null {
return firstLaunchBannerUrl(output, true);
}
/**
* Whether a launch URL names the loopback port this supervisor just spawned.
*
* The URL is read from the child's output, but fetching it is a request made by
* the SERVER. A banner naming another host, or another local service's port, must
* not turn that exchange into an SSRF primitive, so the target is required to be
* the exact origin the token was minted for.
*/
export function launchUrlTargetsServer(launchUrl: string, port: number): boolean {
try {
const url = new URL(launchUrl);
const effectivePort = Number(url.port || (url.protocol === 'https:' ? 443 : 80));
return url.hostname === '127.0.0.1' && effectivePort === port;
} catch {
return false;
}
}
/**
* Trade the launch URL for the `dsh-auth-*` cookie the proxy will present.
*
* `redirect: 'manual'` is load-bearing: the 303 is the response that carries
* `Set-Cookie`, and following it would burn the token on a redirect to `./`
* while dropping the only credential the exchange produces.
*
* @param launchUrl - token-bearing URL from {@link parseLaunchUrl}.
* @returns `name=value` pair ready for a Cookie header, or null.
*/
async function exchangeLaunchToken(launchUrl: string): Promise<string | null> {
try {
const response = await fetch(launchUrl, {
redirect: 'manual',
signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS),
});
for (const header of response.headers.getSetCookie()) {
const pair = header.split(';', 1)[0]?.trim();
if (pair?.startsWith(DSH_AUTH_COOKIE_PREFIX)) return pair;
}
return null;
} catch {
return null;
}
}
/**
* Wait for the banner, then exchange it.
*
* Never fails startup: a dsh without the gate prints a token-less banner, which
* is answered as "nothing to exchange" immediately rather than after the whole
* wait, and a gate that changes shape must not turn a serving UI into a boot
* failure.
*
* @param running - the just-started server, read for its captured output.
* @returns the cookie to hand the proxy (null when there is none) and whether a
* token was printed but could not be exchanged.
*/
async function captureSessionCookie(running: RunningServer): Promise<{ cookie: string | null; failed: boolean }> {
const deadline = Date.now() + LAUNCH_URL_WAIT_MS;
while (Date.now() < deadline) {
// Only COMPLETE lines: a chunk boundary can cut the token in half, and
// exchanging a truncated one would burn the token on a request that cannot
// authenticate. The next poll picks up the rest of the line.
const banner = running.banner();
const complete = banner.slice(0, banner.lastIndexOf('\n') + 1);
const launchUrl = parseLaunchUrl(complete);
if (launchUrl) {
if (!launchUrlTargetsServer(launchUrl, running.port)) {
console.warn(
'[DeepSeek web] the printed launch URL does not name the loopback port this server was started on; ' +
'not fetching it'
);
return { cookie: null, failed: true };
}
const cookie = await exchangeLaunchToken(launchUrl);
// The URL is a credential: never log it, only the fact that it did not work.
if (!cookie) {
console.warn(
'[DeepSeek web] the launch token was printed but could not be exchanged for a session cookie; ' +
'the next start request will restart `dsh web` so it can retry'
);
return { cookie: null, failed: true };
}
return { cookie, failed: false };
}
// Only a printed http(s) URL settles this: it is the older dsh, which needs
// no cookie. Any other line carrying the prefix (a diagnostic, a truncated
// write) is not a banner, so the wait continues instead of giving up early.
if (firstLaunchBannerUrl(complete)) return { cookie: null, failed: false };
await new Promise((resolve) => setTimeout(resolve, 100));
}
return { cookie: null, failed: false };
}
/**
* Signal the whole process group.
*
@@ -134,6 +334,25 @@ export function getDeepSeekWebStatus(): DeepSeekWebStatus {
};
}
/**
* The cookie this server's launch token bought, for the proxy to present.
*
* Keyed by `port` because the cookie is signed for the authority it was minted
* under (`127.0.0.1:<port>`): handing it to a web tab pointed at some other
* server would neither authenticate nor be that server's to receive. Null also
* covers a dsh old enough to need no cookie at all.
*
* @param port - loopback port the upstream request is bound for.
* @param owner - identity asking for it; must be the user who started the server.
* Both sides are undefined in single-user mode, where there is no owner.
* @returns `name=value` cookie pair, or null.
*/
export function getDeepSeekWebCookie(port: number, owner?: string): string | null {
if (!current || current.port !== port) return null;
if (current.starter !== owner) return null;
return current.cookie;
}
/** Stop the background server, if one is running. Safe to call when none is. */
export async function stopDeepSeekWeb(): Promise<void> {
const running = current;
@@ -174,11 +393,12 @@ let startLock: Promise<unknown> = Promise.resolve();
*
* @param dshDir directory holding the resolved `dsh` binary.
* @param authority browser authority to pass as `--trusted-host`.
* @param starter user whose request is starting it (undefined in single-user).
*/
export function startDeepSeekWeb(dshDir: string, authority: string): Promise<StartResult> {
export function startDeepSeekWeb(dshDir: string, authority: string, starter?: string): Promise<StartResult> {
const run = startLock.then(
() => startDeepSeekWebLocked(dshDir, authority),
() => startDeepSeekWebLocked(dshDir, authority)
() => startDeepSeekWebLocked(dshDir, authority, starter),
() => startDeepSeekWebLocked(dshDir, authority, starter)
);
startLock = run.then(
() => undefined,
@@ -187,13 +407,24 @@ export function startDeepSeekWeb(dshDir: string, authority: string): Promise<Sta
return run;
}
async function startDeepSeekWebLocked(dshDir: string, authority: string): Promise<StartResult> {
async function startDeepSeekWebLocked(
dshDir: string,
authority: string,
starter: string | undefined
): Promise<StartResult> {
// Reuse only when the running server is BOTH healthy and fenced for the
// authority now asking. A server trusting the other origin renders a page
// whose every API call 403s, which looks like a broken dashboard rather than
// a misconfigured one.
// authority now asking, it was started by this identity, and its credential
// works: the launch cookie is per process and per user, so handing a previous
// starter's server to another user would leave that user's tab on dsh's 401
// page, and a server whose token exchange failed would keep answering 401
// forever because reuse never gave anyone a chance to restart it.
if (current) {
if (current.authority === authority && (await answersHttp(current.port))) {
if (
!current.cookieFailed &&
current.authority === authority &&
current.starter === starter &&
(await answersHttp(current.port))
) {
return { ok: true, port: current.port, url: `http://127.0.0.1:${current.port}`, reused: true };
}
await stopDeepSeekWeb();
@@ -223,8 +454,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
// The pipes must be drained whether or not anyone reads them: a full pipe
// blocks the child. Storage is capped; draining is not.
let output = '';
// Scanned for the launch banner separately from `output`. That cap exists to
// bound the error tail, and a chatty profile can fill it before the banner is
// printed — losing the banner there produces exactly the 401 tab this module
// exists to prevent, so the two buffers must not share a limit.
let banner = '';
const capture = (chunk: Buffer) => {
if (output.length < OUTPUT_CAP) output += chunk.toString('utf-8');
const text = chunk.toString('utf-8');
if (output.length < OUTPUT_CAP) output += text;
if (banner.length < BANNER_SCAN_CAP) banner += text;
};
child.stdout?.on('data', capture);
child.stderr?.on('data', capture);
@@ -241,7 +479,16 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
if (current?.child === child) current = null;
});
const running: RunningServer = { child, port, authority, output: () => output };
const running: RunningServer = {
child,
port,
authority,
starter,
output: () => output,
banner: () => banner,
cookie: null,
cookieFailed: false,
};
current = running;
const deadline = Date.now() + READY_TIMEOUT_MS;
@@ -255,6 +502,12 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
return { ok: false, error: tail ? `dsh web exited during startup: ${tail}` : 'dsh web exited during startup' };
}
if (await answersHttp(port)) {
// Bought before this call resolves, so the first proxied page load
// already carries a credential — a tab opened a moment earlier would
// otherwise get the 401 this whole module exists to prevent.
const captured = await captureSessionCookie(running);
running.cookie = captured.cookie;
running.cookieFailed = captured.failed;
return { ok: true, port, url: `http://127.0.0.1:${port}`, reused: false };
}
await new Promise((r) => setTimeout(r, READY_POLL_MS));
+8 -1
View File
@@ -4,7 +4,10 @@
* Split like webhook-notify.ts, so the parts that matter are testable without a network:
* - pure: `sanitiseReply`, `threadNameFor`, `buildPost`, `discordConfigProblem`, `maskToken`
* - store: `~/.codeman/discord.json` (bot token, 0600 via tmp+rename) and
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret)
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret) and
* `~/.codeman/discord-reply-dedupe.json` (bounded reply IDs/timestamps, private).
* Allowed replies are claimed before attachments or typing; store failures never cost a reply.
* An unreadable file is never overwritten; invalid readable ID metadata can heal.
* - IO: `DiscordApi` (REST, injected fetch), `DiscordGateway` (inbound WebSocket, injected
* socket factory) and `DiscordBridge` (the rules that tie them to sessions)
*
@@ -27,6 +30,7 @@ import { join } from 'node:path';
import { probePathKind } from './utils/bounded-path-probe.js';
import { DISCORD_RECEIVED_DIR } from './web/paste-image-gc.js';
import WebSocket from 'ws';
import { DiscordReplyDedupe } from './discord-reply-dedupe.js';
import { WEBHOOK_SCOPES, type WebhookUrgency } from './types/push.js';
import {
DISCORD_ON_DELETE,
@@ -824,6 +828,7 @@ export interface DiscordBridgeDeps {
}
export class DiscordBridge {
private readonly replies: DiscordReplyDedupe;
private cfg: DiscordConfig = { ...DEFAULT_DISCORD_CONFIG };
private threads: Record<string, string> = {};
private loaded = false;
@@ -857,6 +862,7 @@ export class DiscordBridge {
constructor(private readonly deps: DiscordBridgeDeps) {
this.now = deps.now ?? Date.now;
this.replies = new DiscordReplyDedupe(deps.configDir, this.now);
this.api = new DiscordApi(() => this.cfg.token, deps.fetchImpl, deps.sleep);
}
@@ -1301,6 +1307,7 @@ export class DiscordBridge {
if (!this.cfg.allowedUserIds.includes(m.author?.id)) return;
const sessionId = Object.keys(this.threads).find((k) => this.threads[k] === m.channel_id);
if (!sessionId) return;
if (!(await this.replies.claim(m.guild_id, m.channel_id, m.id))) return;
const t = this.now();
const prev = this.lastReply.get(sessionId);
if (prev !== undefined && t - prev < REPLY_MIN_INTERVAL_MS) {
+111
View File
@@ -0,0 +1,111 @@
/**
* @fileoverview Best-effort replay protection for Discord replies.
*
* Owns `<data dir>/discord-reply-dedupe.json`: at most 2,048 `guild:channel:message`
* ids with the time each was claimed, kept for 7 days, written 0600 through a temp
* file and a rename. It holds ids only, never message content.
*
* `DiscordBridge.handleMessage()` calls `claim()` once per allowed message, after the
* guild, allowlist and thread gates and before the rate limit, the exited-agent check,
* any download and any typing, so a gateway replay of a message that was refused is
* refused again rather than typed.
*
* Rules a reader has to keep:
* - A store failure never costs a reply: the claim falls back to memory, warns once
* per outage and the reply is still typed.
* - A file that could not be read (an errno failure, a symlink, anything but a regular
* file) is never overwritten.
* - Readable but invalid content (bad JSON, bad rows, oversized) is replaced.
* - Rows read from disk go first, so claims made while the file was unreadable are
* the ones the 2,048 bound keeps.
*/
import fs from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
const LIMIT = 2048;
const RETENTION_MS = 7 * 24 * 60 * 60_000;
export class DiscordReplyDedupe {
private seen = new Map<string, number>();
private loaded = false;
private dirty = false;
private warned = false;
private chain: Promise<unknown> = Promise.resolve();
constructor(
private readonly dir: string,
private readonly now: () => number = Date.now,
private readonly warn: () => void = () =>
console.warn('Discord reply metadata unavailable (discord-reply-dedupe.json); using in-memory deduplication')
) {}
claim(guild: string, channel: string, message: string): Promise<boolean> {
const run = this.chain.then(() => this.take(guild, channel, message));
this.chain = run.catch(() => undefined);
return run;
}
private async take(guild: string, channel: string, message: string): Promise<boolean> {
// Restored legacy configurations and malformed gateway IDs must not poison the store.
if (![guild, channel, message].every((id) => /^\d{15,25}$/.test(id))) return true;
const path = join(this.dir, 'discord-reply-dedupe.json');
const cutoff = this.now() - RETENTION_MS;
if (!this.loaded) {
let contentRead = false;
try {
const st = await fs.lstat(path);
if (!st.isFile() || st.isSymbolicLink()) throw Object.assign(new Error('Unsafe metadata'), { code: 'EINVAL' });
if (st.size > 512 * 1024) {
contentRead = true; // A known oversized regular file is invalid metadata, not an IO failure.
throw new Error('Oversized metadata');
}
const text = await fs.readFile(path, 'utf8');
contentRead = true;
const rows: unknown = JSON.parse(text);
if (!Array.isArray(rows) || rows.length > LIMIT) throw new Error('Invalid metadata');
const recovered = new Map<string, number>();
for (const row of rows) {
if (!Array.isArray(row) || !/^\d{15,25}:\d{15,25}:\d{15,25}$/.test(row[0]) || !Number.isFinite(row[1]))
throw new Error('Invalid metadata');
if (row[1] >= cutoff) recovered.set(row[0], row[1]);
}
// Older disk rows precede newer claims made while reads were unavailable.
this.seen = new Map([...recovered, ...this.seen]);
this.loaded = true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') this.loaded = true;
else {
this.report();
// Invalid content is recoverable ID-only metadata; unreadable/unsafe files stay untouched.
if (contentRead && !(err as NodeJS.ErrnoException).code) {
this.loaded = true;
this.dirty = true;
}
}
}
}
for (const [key, at] of this.seen) if (at < cutoff) this.seen.delete(key);
const key = `${guild}:${channel}:${message}`;
const fresh = !this.seen.has(key);
if (fresh) {
this.seen.set(key, this.now());
this.dirty = true;
} // Before awaiting IO or typing, including during an outage.
while (this.seen.size > LIMIT) this.seen.delete(this.seen.keys().next().value!);
if (!this.loaded || !this.dirty) return fresh; // Never overwrite a store file we could not read.
const tmp = `${path}.${randomUUID()}.tmp`;
try {
await fs.mkdir(this.dir, { recursive: true });
await fs.writeFile(tmp, JSON.stringify([...this.seen]), { mode: 0o600, flag: 'wx' });
await fs.rename(tmp, path);
this.warned = false;
this.dirty = false;
} catch {
this.report();
} finally {
await fs.rm(tmp, { force: true }).catch(() => undefined);
}
return fresh;
}
private report(): void {
if (!this.warned) this.warn();
this.warned = true;
}
}
+33 -8
View File
@@ -15,7 +15,8 @@ import { join } from 'node:path';
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
import type { TeamConfig, TeamTask, InboxMessage } from './types.js';
import { getErrorMessage, type TeamConfig, type TeamTask, type InboxMessage } from './types.js';
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
import { LRUMap } from './utils/lru-map.js';
import { TEAM_POLL_INTERVAL_MS, MAX_CACHED_TEAMS, MAX_CACHED_TASKS } from './config/team-config.js';
@@ -36,6 +37,8 @@ export class TeamWatcher extends EventEmitter {
private sessionToTeam: Map<string, string> = new Map();
private teamsWatcher: ChokidarWatcher | null = null;
private tasksWatcher: ChokidarWatcher | null = null;
// Watchers stopped by an error and not yet back for a whole poll: one warning per outage.
private watchersDown = new Set<'teams' | 'tasks'>();
constructor(teamsDir?: string, tasksDir?: string) {
super();
@@ -47,11 +50,28 @@ export class TeamWatcher extends EventEmitter {
start(): void {
if (this.pollTimer) return;
this.poll();
this.pollTimer = setInterval(() => this.poll(), TEAM_POLL_INTERVAL_MS);
this.pollTimer = setInterval(() => {
this.setupFsWatchers(); // re-creates a watcher an error stopped
this.poll();
}, TEAM_POLL_INTERVAL_MS);
this.setupFsWatchers();
}
private watcherStopped(name: 'teams' | 'tasks', err: unknown): void {
if (this.watchersDown.has(name)) return;
this.watchersDown.add(name);
console.warn(`[TeamWatcher] ${name} watcher stopped, relying on polling: ${getErrorMessage(err)}`);
}
/** Creates each watcher that is not running; one still running since the last call ends its outage. */
private setupFsWatchers(): void {
if (this.teamsWatcher) this.watchersDown.delete('teams');
else this.setupTeamsWatcher();
if (this.tasksWatcher) this.watchersDown.delete('tasks');
else this.setupTasksWatcher();
}
private setupTeamsWatcher(): void {
try {
this.teamsWatcher = chokidarWatch(this.teamsDir, {
depth: 2,
@@ -66,13 +86,16 @@ export class TeamWatcher extends EventEmitter {
this.teamsWatcher.on('change', teamsHandler);
this.teamsWatcher.on('unlink', teamsHandler);
this.teamsWatcher.on('unlinkDir', teamsHandler);
this.teamsWatcher.on('error', (err) => {
console.warn('[TeamWatcher] chokidar teams watcher error:', err);
closeWatcherOnError(this.teamsWatcher, (err) => {
this.teamsWatcher = null;
this.watcherStopped('teams', err);
});
} catch (err) {
console.warn('[TeamWatcher] Failed to set up teams chokidar watcher, relying on polling:', err);
this.watcherStopped('teams', err);
}
}
private setupTasksWatcher(): void {
try {
this.tasksWatcher = chokidarWatch(this.tasksDir, {
depth: 1,
@@ -84,11 +107,12 @@ export class TeamWatcher extends EventEmitter {
this.tasksWatcher.on('add', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry
this.tasksWatcher.on('change', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry
this.tasksWatcher.on('error', (err) => {
console.warn('[TeamWatcher] chokidar tasks watcher error:', err);
closeWatcherOnError(this.tasksWatcher, (err) => {
this.tasksWatcher = null;
this.watcherStopped('tasks', err);
});
} catch (err) {
console.warn('[TeamWatcher] Failed to set up tasks chokidar watcher, relying on polling:', err);
this.watcherStopped('tasks', err);
}
}
@@ -113,6 +137,7 @@ export class TeamWatcher extends EventEmitter {
this.taskMtimes.clear();
this.inboxMtimes.clear();
this.sessionToTeam.clear();
this.watchersDown.clear();
}
/** Get all discovered teams */
+10
View File
@@ -153,6 +153,16 @@ export function restrictTmuxPrefixTable(tmux: string, run: TmuxRunner = defaultR
let listing: string | null;
try {
listing = run(`${tmux} list-keys -T prefix`);
// ⚠️ tmux 3.7 through 3.7c (fixed in 3.8) print NOTHING on stdout for
// `list-keys -T prefix` when the table holds exactly one binding (the line goes
// to a status message instead), which is the shape this function leaves behind: read blank as "ask the full listing" and keep
// only its prefix-table lines, or every call would reset an already-reduced table.
if (!listing.trim()) {
listing = run(`${tmux} list-keys`)
.split('\n')
.filter((line) => PREFIX_LINE.test(line.trim()))
.join('\n');
}
} catch {
listing = null; // an empty table makes list-keys fail on some tmux builds
}
+72 -14
View File
@@ -1,6 +1,6 @@
/**
* @fileoverview `codeman tui`: the full-screen dashboard plus the two
* non-interactive fast paths (`--list`, `<n>`).
* non-interactive fast paths (`--list`, `<n|name>`).
*
* This is the IO half of `src/tui/`: it owns the terminal, the timers, stdin
* and the tmux handoff. Every decision it makes that can be stated as a
@@ -2643,7 +2643,7 @@ export async function runTui(options: TuiRunOptions = {}): Promise<number> {
if (!stdout.isTTY || !stdin.isTTY) {
process.stderr.write(
`${palette.err('codeman tui needs an interactive terminal.')}\n` +
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n>')} to attach.\n`
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n|name>')} to attach.\n`
);
return 1;
}
@@ -2689,17 +2689,72 @@ export async function runTuiList(options: TuiRunOptions = {}): Promise<number> {
}
}
/** What `codeman tui <session>` points at, resolved against one snapshot of the list. */
export type TuiAttachTarget =
| { kind: 'row'; row: TuiRow }
/** A number with no row, or a name nothing in the list carries. */
| { kind: 'none' }
/** Several LIVE sessions carry the name; `positions` are their `--list` numbers. */
| { kind: 'ambiguous'; positions: number[] }
/** Only a finished (RECENT) row carries the name: nothing to attach to. */
| { kind: 'finished' };
/**
* `codeman tui <n>`: attach straight to the nth row of `--list`. No screen setup
* at all, so it is as fast as the API call it makes.
* Resolve `codeman tui <session>` against the rows `--list` prints.
*
* Digits only is a position, exactly as before names were accepted. Anything else
* is a session name, matched exactly (case-sensitive) and only against the
* session's name, never its folder or a prompt. Session names are not unique in
* Codeman, so more than one LIVE match refuses rather than guessing; a RECENT row
* is history with no pane, so it never counts as a live match.
*/
export async function runTuiAttach(position: number, options: TuiRunOptions = {}): Promise<number> {
export function resolveAttachTarget(rows: readonly TuiRow[], target: number | string): TuiAttachTarget {
if (typeof target === 'number' || /^\d+$/.test(target)) {
const row = rows[Math.trunc(Number(target)) - 1];
return row ? { kind: 'row', row } : { kind: 'none' };
}
const positions: number[] = [];
let finished = false;
rows.forEach((row, index) => {
if (row.session.name !== target) return;
if (row.group === 'recent') finished = true;
else positions.push(index + 1);
});
if (positions.length === 1) return { kind: 'row', row: rows[positions[0] - 1] };
if (positions.length > 1) return { kind: 'ambiguous', positions };
return finished ? { kind: 'finished' } : { kind: 'none' };
}
/** The stderr text for a target that resolved to no row, ending in a newline. */
export function attachTargetError(
resolved: Exclude<TuiAttachTarget, { kind: 'row' }>,
target: number | string
): string {
const list = palette.info('codeman tui --list');
switch (resolved.kind) {
case 'ambiguous':
return (
`${palette.err(`${resolved.positions.length} live sessions are named ${target} (${resolved.positions.join(', ')} in the list)`)}\n` +
`Attach by number instead: ${palette.info(`codeman tui ${resolved.positions[0]}`)}, or run ${list}.\n`
);
case 'finished':
return `${palette.err(`there is no live session named ${target}, only a finished one`)}\nRun ${list} to see the live ones.\n`;
case 'none':
return typeof target === 'number' || /^\d+$/.test(target)
? `${palette.err(`there is no session ${target}`)}\nRun ${list} to see the numbers.\n`
: `${palette.err(`there is no session named ${target}`)}\nNames match exactly. Run ${list} and attach by number instead.\n`;
}
}
/**
* `codeman tui <session>`: attach straight to a row of `--list`, by its number or
* by its session name. No screen setup at all, so it is as fast as the API call
* it makes. The target is resolved before the terminal check, so a script learns
* that a name does not exist (or is ambiguous) without needing a TTY.
*/
export async function runTuiAttach(target: number | string, options: TuiRunOptions = {}): Promise<number> {
const stdin = options.stdin ?? process.stdin;
const stdout = options.stdout ?? process.stdout;
if (!stdout.isTTY || !stdin.isTTY) {
process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`);
return 1;
}
const env = options.env ?? process.env;
const client = options.client ?? new TuiClient();
try {
@@ -2712,11 +2767,14 @@ export async function runTuiAttach(position: number, options: TuiRunOptions = {}
process.stderr.write(authHint());
return 1;
}
const row = state.rows[Math.trunc(position) - 1];
if (!row) {
process.stderr.write(
`${palette.err(`there is no session ${position}`)}\nRun ${palette.info('codeman tui --list')} to see the numbers.\n`
);
const resolved = resolveAttachTarget(state.rows, target);
if (resolved.kind !== 'row') {
process.stderr.write(attachTargetError(resolved, target));
return 1;
}
const row = resolved.row;
if (!stdout.isTTY || !stdin.isTTY) {
process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`);
return 1;
}
const plan = planAttach(row.session.muxName, {
+15 -4
View File
@@ -991,6 +991,19 @@ export class TuiClient {
return null;
}
/**
* One key table as `list-keys` prints it. ⚠️ tmux 3.7 through 3.7c (fixed in 3.8)
* print NOTHING on stdout for `list-keys -T <table>` when the table holds exactly
* one binding (the line goes to a status message instead), which is the shape Codeman reduces the prefix table to. So a
* blank answer is retried as the full listing: every line there names its table,
* and both parsers already filter on it.
*/
private async listKeyTable(table: TuiKeyTable): Promise<string> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
if (stdout.trim()) return stdout;
return (await this.exec('tmux', ['-L', this.socket, 'list-keys'])).stdout;
}
/**
* The key that detaches, straight from tmux's own key table. Key tables are
* server-global, so unlike the prefix this takes no session. A failure is
@@ -998,8 +1011,7 @@ export class TuiClient {
*/
async readDetachKey(): Promise<string | null> {
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', 'prefix']);
return parseDetachKey(stdout);
return parseDetachKey(await this.listKeyTable('prefix'));
} catch {
return null;
}
@@ -1012,8 +1024,7 @@ export class TuiClient {
*/
async readPrefixBinding(key: string, table: TuiKeyTable = 'prefix'): Promise<string | null> {
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
return parsePrefixBinding(stdout, key, table);
return parsePrefixBinding(await this.listKeyTable(table), key, table);
} catch {
return null;
}
+39
View File
@@ -0,0 +1,39 @@
/**
* @fileoverview Close a chokidar watcher on its first error, safely.
*
* chokidar 3 with `persistent: false` has no guard for an `fs.watch` that
* throws (EMFILE once the inotify instance limit is used up, ENOSPC once the
* watch limit is): it emits the error, then a TypeError from closing the
* watcher it never got, then retries on the parent directory, one level per
* pass, and re-adds `/` forever, since the parent of `/` is `/`. Only a closed
* watcher ends that loop, so a watcher whose `'error'` handler just logs logs
* forever.
*
* Closing from the handler is not enough on its own:
* - `close()` removes every listener, and the TypeError of the same pass is
* emitted after it. With no `'error'` listener EventEmitter throws it, and it
* reaches the process as an unhandled rejection. So a no-op listener stays
* on the closed watcher.
* - callbacks chokidar already has in flight can still call `add()` (a deleted
* file's `_remove()` re-adds the file when chokidar thinks it was the only
* watched path), and `add()` sets `closed = false`, which starts the climb
* again, silently now. So `add()` becomes a no-op on the closed watcher.
*
* @module utils/close-watcher-on-error
*/
import type { FSWatcher } from 'chokidar';
/**
* Close `watcher` on its first `'error'` and pass that error to `onClosed`,
* once. The caller's polling has to cover what the watcher watched and create it
* again later: chokidar 3 reports a one-off ENOENT race through the same error.
*/
export function closeWatcherOnError(watcher: FSWatcher, onClosed: (err: unknown) => void): void {
watcher.once('error', (err: unknown) => {
watcher.close().catch(() => {}); // best-effort, like the stop() paths
watcher.on('error', () => {}); // see the fileoverview
watcher.add = () => watcher; // likewise
onClosed(err);
});
}
+3 -3
View File
@@ -56,7 +56,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry)
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
@@ -82,11 +82,11 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**WebSocket output-gap reconcile** (`_wsOutputGapSession`, app.js): output frames carry no sequence number, so an unintentional WS close while SSE stays up marks the session and the next open reconciles. ⚠️ The marker is cleared only once a repaint actually happened (`_markTerminalBufferReconciled()`, never in a `finally`). → [architecture-invariants#websocket-output-gap-reconcile](../../docs/architecture-invariants.md#websocket-output-gap-reconcile)
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ The content touchstart blur skips the visible `#cjkInput` (`_contentTouchStartBlurs()`), or every swipe on the live screen closed its keyboard; a tap still closes it (inert content, a link, a long press). On phones `updateLayoutForKeyboard()` also moves `.app` by `visualViewport.offsetTop` while the keyboard is up, and lifts the fixed bars inside it from `.app`'s bottom (architecture-invariants, Folding devices section). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) and then Enter.
⚠️ **Skin overrides outrank plain class rules.** `styles.css` nests its skin block inside `html:not([data-skin="og"]) { … }`, so a bare `.btn-toolbar` rule in there resolves to specificity **(0,2,1)** and beats a `.btn-toolbar.btn-x` rule **(0,2,0)** in `mobile.css` regardless of load order. Toolbar-button colors set from mobile.css therefore need `!important`: that is why mobile.css leans on it so heavily. Symptom: only your `!important` properties land and everything else silently renders in generic toolbar grey. Press feedback on the phone bars sidesteps this: the `:active` rules for `.btn-toolbar`, the mobile icon buttons and `.accessory-btn` (mobile.css) use `transform` and `filter` only, which nothing on these buttons sets at a higher specificity, so one rule reads the same on every skin; a background `:active` lost to the skin block on all but og, and an inset `box-shadow` lost to the skin hover rules, which is why neither is used. The light skins darken instead of brightening, and `prefers-reduced-motion` drops the scale.
+29 -3
View File
@@ -4929,6 +4929,11 @@ class CodemanApp {
document.body.classList.toggle('cjk-input-visible', !!showCjk);
cjkEl.style.display = showCjk ? 'block' : 'none';
cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true');
if (typeof CjkInput !== 'undefined') {
CjkInput.setHoldUntilEnter?.(
!!(settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false)
);
}
if (!showCjk) window.cjkActive = false;
if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard();
}
@@ -9379,7 +9384,7 @@ class CodemanApp {
// `skipSnapshot`: the tile grid opening on the session it parks
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
_cleanupPreviousSession(newSessionId, { skipSnapshot = false } = {}) {
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
// exact view on switch-back rather than replaying codex's byte stream, which
@@ -9432,8 +9437,16 @@ class CodemanApp {
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
// A held Send on Enter draft survives a reload of the same session: nothing
// switched, and the answer would be gone. On a real switch it is stashed for
// the session being left (selectSession restores it on the way back), so a
// stray swipe does not lose it. Live mode still clears, since a pending
// debounced flush could fire mid-reconnect.
if (typeof CjkInput !== 'undefined') {
CjkInput.clear();
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
@@ -9973,11 +9986,19 @@ class CodemanApp {
if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options);
if (options?.auto === true && !options?.leaveTiles) return;
this.closeTileGrid({ keepStored: true, reselect: false });
// The focused tile's Send on Enter draft: the null below hides that
// session from _cleanupPreviousSession, which would clear it unstashed.
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
// The parked terminal still holds what it showed before the grid opened;
// with no active id, the switch below snapshots none of it.
this.activeSessionId = null;
}
// A reload of the session already shown (tapping its own tab, the geometry
// retry) is not a switch: _cleanupPreviousSession keeps a Send on Enter
// draft for it, which it cannot tell on its own once activeSessionId is null.
let reloadingSameSession = false;
if (this.activeSessionId === sessionId && forceReload) {
reloadingSameSession = true;
this.terminalBufferCache?.delete(sessionId);
this._xtermSnapshots?.delete(sessionId);
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
@@ -10024,9 +10045,10 @@ class CodemanApp {
// A session tab takes the stage back from any active web tab.
this._hideWebviewLayer?.();
this._cleanupPreviousSession(sessionId);
this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });
this.activeSessionId = sessionId;
this._activateFileBrowserSession?.(sessionId);
if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);
// A keyboard row hold belongs to the session it was taken for: release it here
// if this one resizes instead (the geometry work below then fits it).
this._reconcileKeyboardHold?.({ resize: false });
@@ -10823,6 +10845,7 @@ class CodemanApp {
this._flushedOffsets?.delete(sessionId);
this._flushedTexts?.delete(sessionId);
if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.discardComposerDraft?.(sessionId);
if (typeof CjkInput !== 'undefined') CjkInput.discardDraft?.(sessionId);
// Drop any durably-queued input for a session that's actually gone (deleted/
// exited). Not a lost prompt — the target no longer exists. Only reached on
// real session removal, never on a tab switch.
@@ -11104,6 +11127,9 @@ class CodemanApp {
this._retireUrlSession();
// Home is a choice to leave the grid too; it is remembered for Tiles.
this.closeTileGrid?.({ keepStored: true, reselect: false });
// A Send on Enter draft goes with its session: the null below hides that
// session from the next _cleanupPreviousSession, which would clear it unstashed.
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
// Deselect active session and show welcome screen
this.activeSessionId = null;
try { localStorage.removeItem('codeman-active-session'); } catch {}
+2 -2
View File
@@ -112,7 +112,7 @@ const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send whi
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
const DEFAULT_TOAST_DURATION_MS = 3000; // How long a corner toast stays by default
const MIN_NOTIFICATION_DURATION_MS = 1000; // Shortest configurable toast / browser-notification time
const MAX_NOTIFICATION_DURATION_MS = 300000; // General UI throttle delay
const MAX_NOTIFICATION_DURATION_MS = 300000; // Longest configurable toast / browser-notification time
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more scrollback on tab switch)
// A shell's automatic loads (tab select, drop recovery, a tile's load) read
@@ -130,7 +130,7 @@ const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more s
const SHELL_LOAD_HISTORY_LINES = 10000;
const SHELL_LOAD_BASE_QUERY = `full=1&tail=${TERMINAL_TAIL_SIZE}&alt=recording`;
const SHELL_LOAD_QUERY = `${SHELL_LOAD_BASE_QUERY}&lines=${SHELL_LOAD_HISTORY_LINES}`;
const SYNC_WAIT_TIMEOUT_MS = 50; // System stats polling
const SYNC_WAIT_TIMEOUT_MS = 50; // Wait timeout for terminal sync
const TUI_REDRAW_SETTLE_MS = 400; // Grace for a TUI to redraw after a real resize, before fetching its buffer
// Z-index base values for layered floating windows
+5
View File
@@ -743,6 +743,11 @@
"For local Claude sessions, opening the on-screen keyboard keeps the session's size and scrolls the view instead, so Claude does not reprint its screen and lose transcript lines. Full-screen interfaces (Codex, Claude's fullscreen mode) are resized as before.":
'对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。',
'CJK Input': '中日韩输入',
'Input Field: Send on Enter': '输入框:按 Enter 发送',
'CJK input (Enter = send, Esc = clear)': '中日韩输入(Enter 发送,Esc 清除)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)': '输入文字,按 Enter 发送(Shift+Enter 换行,Esc 清除)',
'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.':
'开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。',
'Extended Keyboard Bar': '扩展键盘栏',
'Gesture Control (beta)': '手势控制(测试版)',
'Wheel Scrolls Local History': '滚轮滚动本地历史',
+9 -1
View File
@@ -13,7 +13,8 @@
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="apple-touch-icon" href="icon-192.png">
<link rel="manifest" href="manifest.json">
<!-- use-credentials: the manifest fetch otherwise omits the session cookie, so a password-protected install answers 401 and the browser refuses to install the app. -->
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<title>Codeman</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%2360a5fa'/%3E%3Cstop offset='100%25' stop-color='%233b82f6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='32' height='32' rx='6' fill='%230a0a0a'/%3E%3Cpath d='M18 4L8 18h6l-2 10 10-14h-6z' fill='url(%23g)'/%3E%3C/svg%3E">
<link rel="stylesheet" href="styles.css">
@@ -2064,6 +2065,13 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="cjk input send on enter hold draft pinned prompt field phone">
<div class="set-row-text">
<span class="set-row-label">Input Field: Send on Enter</span>
<span class="set-row-desc">With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkHoldUntilEnter"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="extended keyboard bar tab esc arrows phone">
<div class="set-row-text">
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
+321 -13
View File
@@ -7,6 +7,21 @@
* While this textarea has focus, window.cjkActive = true blocks xterm's onData.
* Arrow keys and function keys are forwarded to PTY directly.
*
* ## Send on Enter (setting cjkInputHoldUntilEnter)
*
* The live mode above streams typed text to the PTY after a short debounce.
* With Send on Enter on, the field is a chat box instead: _flush() holds the
* text, and only Enter sends it, through the sendPrompt callback
* (terminal-ui.js _sendCjkPrompt: a single character is typed, anything longer
* goes as the composer's bracketed paste, Enter is always its own later write,
* and a lone digit at a pending dialog goes without it). Shift+Enter is a
* newline, Esc clears, Backspace and the arrows reach the PTY only from an
* empty field, and so do the Ctrl shortcuts. Autocorrect is on. A held draft
* belongs to one session (_owner): clear() stashes it under that session and
* restoreDraft() brings it back when the session is shown again, except a
* clear({ discard: true }) (the keyboard bar's clear-line key), which throws
* it away.
*
* ## Android IME challenge
*
* Android virtual keyboards (WeChat, Sogou, Gboard in Chinese mode) use
@@ -57,6 +72,27 @@ const CjkInput = (() => {
let _dictationActive = false;
let _dictationDecayTimer = null;
let _printableKeydownAt = null;
// Send-on-Enter mode (setting cjkInputHoldUntilEnter): typed text stays in the
// field until Enter, like a chat box, instead of streaming to the PTY as it is
// typed. Lets a phone user scroll the terminal and edit an answer before sending.
let _hold = false;
// Send-on-Enter: the held text as of the last settled input event (phantom
// stripped). Tells a deletion that emptied the field from a Backspace on a field
// that was already empty, and finds the one character an armed Ctrl applies to.
let _heldBase = '';
// Send-on-Enter: delivers a held answer, text first and Enter as a separate
// delayed write, to the session it was typed for (terminal-ui.js).
let _sendPrompt = null;
// Send-on-Enter: whether setHoldUntilEnter() has applied the current mode to
// the field yet, so a repeat call with the same mode leaves the field alone.
let _holdApplied = false;
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
const _drafts = new Map();
// Send-on-Enter: the session the field's text belongs to (the one last shown,
// set by restoreDraft). clear() stashes a held draft under it, so every path
// that drops the active session before the next cleanup (goHome, the tile
// grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer.
let _owner = null;
const _listeners = {};
const PHANTOM = '​';
@@ -160,6 +196,7 @@ const CjkInput = (() => {
}
function _resetToPhantom() {
_heldBase = '';
// Skip redundant writes: every programmatic value/selection mutation can
// desync an Android IME's input session (InputConnection) — after which
// the keyboard composes in its own UI but NO events ever reach the page.
@@ -189,6 +226,13 @@ const CjkInput = (() => {
_t('flush SKIP composing');
return;
}
// Send-on-Enter: nothing leaves the field until Enter (keydown handler).
if (_hold) {
_t('flush SKIP hold');
_holdSettle();
_autoGrow();
return;
}
const val = _strip(_textarea.value);
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
if (val) {
@@ -197,6 +241,133 @@ const CjkInput = (() => {
_resetToPhantom();
}
/** Send-on-Enter: grow the field with its content (up to the CSS max-height)
* and let the keyboard layout re-read its height. */
function _autoGrow() {
if (!_textarea) return;
// A hidden field (no session shown yet) measures 0: leave the CSS height,
// or it stays a sliver until the next keystroke.
if (_textarea.getClientRects && !_textarea.getClientRects().length) {
_textarea.style.height = '';
return;
}
// Only a touch device grows the field: there it is position: fixed above the
// keyboard. On a desktop it sits in the flex column under the terminal, so
// every line it gained would shrink the terminal box, refit and resize the
// session's PTY (a CLI repaint each time). It stays one line there and
// scrolls inside instead.
if (!document.body?.classList?.contains('touch-device')) {
_textarea.style.height = '';
return;
}
const before = _textarea.style.height;
_textarea.style.height = 'auto';
// border-box: scrollHeight leaves the borders out, offsetHeight - clientHeight adds them back.
_textarea.style.height = `${_textarea.scrollHeight + _textarea.offsetHeight - _textarea.clientHeight}px`;
if (_textarea.style.height !== before && typeof KeyboardHandler !== 'undefined') {
KeyboardHandler.updateLayoutForKeyboard?.();
}
}
/** Send-on-Enter: deliver the held text, then Enter, through `_sendPrompt`
* (terminal-ui.js _sendCjkPrompt). Enter is never part of the text's write:
* Codex takes characters arriving in one burst as a paste and folds an Enter
* inside it into the paste, and Claude Code does the same for a long burst, so
* even `1\r` in one write sits unsent. Returns false when the text was refused
* (too long, no session), so the field keeps it. */
function _sendHeld(val) {
if (!_sendPrompt) {
_t('hold send DROP no-prompt-path');
return false;
}
return _sendPrompt(val) !== false;
}
/** Enter: send what the field holds (or a bare Enter when it is empty) and
* reset it. Returns false when a held answer was refused, which keeps it. */
function _submit() {
_composing = false;
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
let val = _strip(_textarea.value);
// Only blank lines held (Shift+Enter, then Enter): a bare Enter, not a
// newline typed into the CLI.
if (_hold && !val.trim()) val = '';
if (_hold && val) {
// Refused (too long, no session): keep the text so nothing is lost.
if (!_sendHeld(val)) return false;
} else if (val) {
_send(val + '\r');
} else {
_send('\r');
}
_resetToPhantom();
if (_hold) _autoGrow();
return true;
}
function _ctrlArmed() {
return typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() === true;
}
/** Index of the one character `after` adds to `before`, or -1 when the change
* is anything else (several characters, a deletion, a rewrite). */
function _singleInsertionAt(before, after) {
if (after.length !== before.length + 1) return -1;
let i = 0;
while (i < before.length && before[i] === after[i]) i++;
return after.slice(i + 1) === before.slice(i) ? i : -1;
}
/** Send-on-Enter: settle the field after an input event. With the shell bar's
* one-shot Ctrl armed, a single typed character is not held: it leaves the
* field and goes to the PTY, where _handleCjkInput turns it into the control
* byte (`c` → Ctrl+C). Any other change spends the modifier, the same rule
* live mode follows for a multi-character chunk. */
function _holdSettle() {
const before = _heldBase;
const now = _strip(_textarea.value);
_heldBase = now;
if (now === before || !_ctrlArmed()) return;
const at = _singleInsertionAt(before, now);
if (at < 0 || now[at] === '\n') {
KeyboardAccessoryBar.clearCtrl?.();
return;
}
_t('hold ctrl key');
_textarea.value = PHANTOM + before;
_textarea.setSelectionRange(1 + at, 1 + at);
_heldBase = before;
_send(now[at]);
}
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
* A deletion forwards Backspace to the PTY only when the field was ALREADY
* empty, i.e. the phantom itself was deleted. Deleting the last held
* character (or select-all + delete) must not also delete a character from
* the CLI's own composer, which Attach, image paste, Path and the mic fill. */
function _holdInput(e) {
if (_composing) return; // composed text settles at compositionend (_flush)
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
const wasEmpty = !_heldBase;
_heldBase = _strip(_textarea.value);
if (!_heldBase) {
if (wasEmpty) _send('\x7f');
_resetToPhantom();
} else if (!_textarea.value.startsWith(PHANTOM)) {
// Backspace at the very start of the text deleted the phantom: put it
// back with the caret where it was, at the start of the text.
_textarea.value = PHANTOM + _textarea.value;
_textarea.setSelectionRange(1, 1);
}
_autoGrow();
return;
}
_holdSettle();
_autoGrow();
}
/** Cancel any pending debounced flush */
function _cancelDebouncedFlush() {
if (_flushTimer) {
@@ -226,14 +397,16 @@ const CjkInput = (() => {
}
return {
init({ send }) {
init({ send, sendPrompt = null }) {
if (_initialized) this.destroy();
_send = send;
_sendPrompt = sendPrompt;
_composing = false;
_printableKeydownAt = null;
_flushTimer = null;
_textarea = document.getElementById('cjkInput');
_holdApplied = false; // a new field has not had the mode applied
if (!_textarea) return this;
_resetToPhantom();
@@ -316,16 +489,14 @@ const CjkInput = (() => {
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
_printableKeydownAt = null;
if (e.key === 'Enter') {
e.preventDefault();
_composing = false;
_cancelDebouncedFlush();
const val = _strip(_textarea.value);
if (val) {
_send(val + '\r');
} else {
_send('\r');
// Send-on-Enter: Shift+Enter (or an IME still composing) is a newline
// in the field, never a send.
if (_hold && (e.shiftKey || e.isComposing || e.keyCode === 229)) {
setTimeout(_autoGrow, 0);
return;
}
_resetToPhantom();
e.preventDefault();
_submit();
return;
}
@@ -334,10 +505,15 @@ const CjkInput = (() => {
_composing = false;
_cancelDebouncedFlush();
_resetToPhantom();
if (_hold) _autoGrow();
return;
}
if (e.ctrlKey && CTRL_KEYS[e.key]) {
// Send-on-Enter with a draft in the field: Ctrl shortcuts are the
// field's (Ctrl+Z undo, Ctrl+A select all, Ctrl+C copy a selection), so
// they reach the CLI only while the field is empty, the rule Backspace
// and the arrows already follow.
if (e.ctrlKey && CTRL_KEYS[e.key] && (!_hold || _isEffectivelyEmpty())) {
e.preventDefault();
_send(CTRL_KEYS[e.key]);
return;
@@ -405,6 +581,11 @@ const CjkInput = (() => {
_composing = false;
}
if (_hold) {
_holdInput(e);
return;
}
// ── Backspace / delete detection ──
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
if (_composing) return;
@@ -464,9 +645,24 @@ const CjkInput = (() => {
* can't flush into the wrong session). Restores the phantom so backspace
* forwarding keeps working — unlike a raw `textarea.value = ''`.
*/
clear() {
clear({ discard = false } = {}) {
if (!_initialized || !_textarea) return;
_t('clear (external)');
_t(`clear (external)${discard ? ' discard' : ''}`);
if (discard) {
// The user threw the text away (the keyboard bar's clear-line key):
// nothing is stashed, any older stash of this session goes too, and the
// field keeps its owner, since the session shown has not changed.
if (_owner) _drafts.delete(_owner);
} else {
// Send-on-Enter: a held draft is stashed for the session it was typed
// for, whichever path got here. discardDraft() drops the owner of a
// removed session, so its text is not stashed again.
if (_hold && _owner) {
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(_owner, draft);
}
_owner = null;
}
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
@@ -475,6 +671,118 @@ const CjkInput = (() => {
_resetToPhantom();
},
/**
* Send-on-Enter mode on or off (setting cjkInputHoldUntilEnter). On: text
* stays in the field until Enter and the browser's autocorrect is allowed,
* since nothing typed has reached the PTY yet. Off: the original live mode.
*/
setHoldUntilEnter(on) {
// The placeholder first, before the early return: App Settings applies a
// language switch live and then calls this with the mode unchanged. It is
// written only when the text differs, so a field mid-composition is not
// touched. i18n.js skips <textarea> subtrees (what is typed there is user
// content), so it is translated here, like the prompt composer's.
if (_textarea) {
const source = !!on
? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)'
: 'CJK input (Enter = send, Esc = clear)';
const i18n = typeof window !== 'undefined' ? window.CodemanI18n : undefined;
const placeholder = typeof i18n?.t === 'function' ? i18n.t(source) : source;
if (_textarea.placeholder !== placeholder) _textarea.placeholder = placeholder;
}
// Called on every session select and SSE reconnect: with the mode
// unchanged, leave the rest of the field alone, since rewriting its
// attributes while it has focus can disturb a composition in progress.
if (_holdApplied && _textarea && _hold === !!on) return;
const wasHolding = _hold;
_hold = !!on;
if (!_textarea) return;
_holdApplied = true;
// Turning the mode off: live mode's next flush would send everything in
// the field, a held multi-line draft included (its newline runs the first
// line in a shell), and stashed drafts would come back if the mode is
// switched on again. Drop them all.
if (wasHolding && !_hold) {
_drafts.clear();
_resetToPhantom();
}
_heldBase = _strip(_textarea.value);
const v = _hold ? 'on' : 'off';
_textarea.setAttribute('autocorrect', v);
_textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off');
_textarea.setAttribute('spellcheck', _hold ? 'true' : 'false');
if (_hold) {
_cancelDebouncedFlush();
_autoGrow();
} else {
_textarea.style.height = '';
}
_t(`hold ${v}`);
},
get holdUntilEnter() { return _hold; },
/**
* Enter from outside the field (the phone toolbar's Enter button, which
* xterm's onData would swallow while the field is visible). Same as Enter
* in the field. Returns false when nothing was done (not initialized) or a
* held answer was refused.
*/
submit() {
if (!_initialized || !_textarea) return false;
_t(`submit (external) c=${_composing}`);
if (_composing) {
// An IME still composing (Gboard holds the current word, iOS the
// unconverted pinyin): reading and resetting the field under it can
// desync the keyboard. Blur commits the composition, focus keeps the
// keyboard up (still inside the tap's gesture), then send what landed.
_textarea.blur();
_textarea.focus();
}
return _submit();
},
/**
* Send-on-Enter: keep the held draft of the session being left, so a
* switch (a stray sideways swipe) does not lose an answer. Call before
* clear(); restoreDraft() puts it back when that session is shown again.
*/
stashDraft(sessionId) {
if (!_initialized || !_textarea || !_hold || !sessionId) return;
// An empty field leaves any stash alone: a draft only sits in the map
// while its session is not shown (restoreDraft takes it out), and the
// tile grid may stash an id whose draft is already put away.
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(sessionId, draft);
},
/** Send-on-Enter: show the draft stashed for this session, if any, unless
* the field already holds text. */
restoreDraft(sessionId) {
if (!_initialized || !_textarea) return;
// The field now belongs to this session, draft or not (see _owner),
// unless it still holds another session's text (no clear() in between).
if (!_owner || !_strip(_textarea.value)) _owner = sessionId || null;
if (!_hold || !_drafts.has(sessionId)) return;
if (_strip(_textarea.value)) return;
const draft = _drafts.get(sessionId);
_drafts.delete(sessionId);
_t(`restore draft len=${draft.length}`);
_textarea.value = PHANTOM + draft;
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
_heldBase = draft;
_autoGrow();
},
/** Forget a stashed draft when its session no longer exists. */
discardDraft(sessionId) {
_drafts.delete(sessionId);
if (_owner === sessionId) _owner = null;
},
/** Diagnostic/test: the session the field's text belongs to. */
get draftOwner() { return _owner; },
/** Diagnostic: recent IME event trace (ring buffer). */
getTrace() {
return _trace.slice();
+47 -13
View File
@@ -435,27 +435,55 @@ const KeyboardHandler = {
// BEHIND the keyboard with its own search box out of sight.
const caseSheet = document.querySelector('.mobile-case-picker.active .mobile-case-picker-sheet');
// A focused field that starts behind the keyboard (the pinned CJK / Send on
// Enter field) makes Android pan the visual viewport down to reveal it (measured
// on Chrome: offsetTop 285px with a 458px visual viewport in a 744px layout one).
// The app is sized to the visual viewport but laid out at the top of the layout
// viewport, so that pan left only the terminal's last line on screen. On phones,
// follow the pan while the keyboard is up, whatever has focus: without a pan
// (offsetTop 0, the usual case) nothing moves, and a focus change that keeps the
// pan cannot drop the shift. Every other branch clears it.
// ⚠️ The transform makes .app the box its position:fixed children (header,
// toolbar, accessory bar, the field) are placed against, so their keyboard lift
// below is measured from .app's bottom, not the layout viewport's, or they would
// be lifted twice on a partial pan. The case sheet (#mobileCasePickerModal) is
// inside .app too and takes the same lift.
const appEl = document.querySelector('.app');
const pan = isSmallMedium ? Math.round(window.visualViewport.offsetTop || 0) : 0;
if (appEl) appEl.style.transform = pan > 0 ? `translateY(${pan}px)` : '';
// The layout viewport's height, which position:fixed bottoms are measured from.
// ⚠️ Not window.innerHeight alone: on the first keyboard open after focusing the
// pinned field, iOS Safari reported innerHeight as the shrunk visual height (323)
// while the layout viewport stayed 640 (documentElement.clientHeight), so the lift
// came out 0 and the bars stayed behind the keyboard. Earlier a delayed
// scrollIntoView re-ran this pass once innerHeight had caught up; without it the
// stale value stuck. The larger of the two cannot be stale in that direction.
const layoutHeight = Math.max(window.innerHeight, document.documentElement?.clientHeight || 0);
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
const insideLift = pan > 0 && appEl ? Math.max(0, pan + appEl.offsetHeight - visualBottom) : keyboardOffset;
if (isSmallMedium) {
// Phones/small tablets: toolbar and accessory bar are position:fixed
// via CSS. Use translateY to lift them above the keyboard.
const toolbar = document.querySelector('.toolbar');
const main = document.querySelector('.main');
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
if (toolbar) {
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
toolbar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (accessoryBar) {
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
accessoryBar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (caseSheet) {
caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
caseSheet.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (main && keyboardHeight > 0) {
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0;
// The field grows with its text in Send-on-Enter mode, so reserve its
// real height (44 = the one-line field plus its border, the old constant).
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible')
? Math.max(44, cjkInput.offsetHeight + 10)
: 0;
main.style.paddingBottom = `${84 + cjkInputHeight}px`;
}
} else if (keyboardHeight > 0) {
@@ -472,11 +500,8 @@ const KeyboardHandler = {
// CJK textarea positioning (always position:fixed on touch devices).
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
if (isSmallMedium) {
// Phones: use translateY like toolbar/accessory bar.
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
// Phones: use translateY like toolbar/accessory bar (it sits inside .app too).
cjkInput.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
cjkInput.style.bottom = '';
} else {
// iPad: direct bottom = keyboard + accessory bar height.
@@ -499,7 +524,11 @@ const KeyboardHandler = {
// keyboard was still up must still have its inline offset cleared, or the
// next open slides in already displaced.
const caseSheet = document.querySelector('.mobile-case-picker-sheet');
const appEl = document.querySelector('.app');
if (appEl) {
appEl.style.transform = '';
}
if (toolbar) {
toolbar.style.transform = '';
}
@@ -729,6 +758,11 @@ const KeyboardHandler = {
if (el.closest('.xterm') || el.closest('.terminal-container')) {
return false;
}
// The pinned CJK / Send on Enter field is position:fixed and lifted above the
// keyboard by updateLayoutForKeyboard(). Scrolling it into view centred it in its
// scrollable ancestors instead, which pushed the terminal off screen whenever the
// field took focus.
if (el.id === 'cjkInput') return false;
const tagName = el.tagName?.toLowerCase();
// Exclude type=range, type=checkbox, type=radio (don't trigger keyboard)
+10
View File
@@ -2082,6 +2082,16 @@ Object.assign(CodemanApp.prototype, {
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
sendEnterKey() {
if (!this.activeSessionId) return;
// While the CJK field is visible, onData drops everything (cjkActive), this
// Enter included. Press Enter in the field instead: it sends what the field
// holds (a Send on Enter answer, or live text not yet flushed), then Enter.
if (
typeof CjkInput !== 'undefined' &&
document.getElementById('cjkInput')?.classList.contains('cjk-input-visible')
) {
CjkInput.submit?.();
return;
}
const coreService = this.terminal?._core?.coreService;
if (coreService && typeof coreService.triggerDataEvent === 'function') {
coreService.triggerDataEvent('\r', true);
+6 -1
View File
@@ -649,6 +649,8 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsTerminalWheelLocal').checked =
settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false;
document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false;
document.getElementById('appSettingsCjkHoldUntilEnter').checked =
settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false;
document.getElementById('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false;
document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false;
document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings);
@@ -3195,6 +3197,7 @@ Object.assign(CodemanApp.prototype, {
),
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
@@ -3440,6 +3443,7 @@ Object.assign(CodemanApp.prototype, {
// SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT.
keyboardHoldsRows: _khr,
cjkInputEnabled: _cjk,
cjkInputHoldUntilEnter: _cjkHold,
extendedKeyboardBar: _ekb,
skin: _skin,
language: _language,
@@ -4478,6 +4482,7 @@ Object.assign(CodemanApp.prototype, {
sessionListLayout: 'header',
sessionSidebarFontSize: 12,
cjkInputEnabled: false,
cjkInputHoldUntilEnter: false,
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
webglRendererEnabled: false, // mobile always uses the DOM renderer
skin: 'daylight-blue',
@@ -5206,7 +5211,7 @@ Object.assign(CodemanApp.prototype, {
'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost',
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'extendedKeyboardBar',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'cjkInputHoldUntilEnter', 'extendedKeyboardBar',
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
'language',
+13
View File
@@ -14199,6 +14199,12 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
resize: none;
line-height: 1.4;
box-sizing: border-box;
/* A backstop: Send on Enter grows the field with its text only on touch devices
(input-cjk.js _autoGrow), where the .touch-device rule caps it too. On desktop
it keeps its one-line height, so this cap only guards against anything else
setting a taller one, which would push the terminal (and its PTY) down. */
max-height: 68px;
overflow-y: auto;
}
#cjkInput:focus {
@@ -14235,6 +14241,13 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
bottom: calc(var(--safe-area-bottom) + 84px);
}
/* Send on Enter grows the field with its text, but with the keyboard down .main
reserves a fixed 84px (below), so a grown field would cover the terminal's
last rows. Keep it one line tall there; the text scrolls inside. */
.touch-device:not(.keyboard-visible) #cjkInput.cjk-input-visible {
max-height: 34px;
}
body.touch-device.cjk-input-visible .main {
padding-bottom: calc(84px + var(--safe-area-bottom));
}
+100 -27
View File
@@ -1083,6 +1083,10 @@ Object.assign(CodemanApp.prototype, {
send: (text) => {
this._handleCjkInput(text);
},
// Send on Enter: a long or multi-line held answer goes out like the
// mobile prompt composer's Send (one bracketed paste, then Enter as a
// separate delayed write), bound to the session it was typed for.
sendPrompt: (text) => this._sendCjkPrompt(text),
});
}
@@ -1374,7 +1378,7 @@ Object.assign(CodemanApp.prototype, {
// selectSession() ends with scrollToLastNonEmptyLine(), that made
// the keyboard unreachable after every tab switch.
ev.preventDefault();
this._blurMobileTerminalInput();
if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
}
// Hold still and this press becomes a text selection. Cancelled by any
// travel past the shared tap slop below, so a scroll can never become one.
@@ -4551,8 +4555,10 @@ Object.assign(CodemanApp.prototype, {
// after every key. So the onData hook never sees these keystrokes, and an
// armed modifier could neither fire NOR be spent: it survived until a
// session switch and then turned an innocent keystroke into a control byte.
// This is the module's single choke point to the PTY, so applying it here
// covers typed characters, IME flushes, Enter, backspace and arrows at once.
// This is the module's single choke point to the PTY in live mode, so applying
// it here covers typed characters, IME flushes, Enter, backspace and arrows at
// once. In Send on Enter a held answer leaves through _sendCjkPrompt instead,
// which spends the modifier; an armed next character still comes here.
// Same policy as the onData hook: the next single character is modified,
// anything longer merely spends the modifier.
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
@@ -4564,6 +4570,49 @@ Object.assign(CodemanApp.prototype, {
this._sendInputAsync(this.activeSessionId, text);
},
/**
* Send on Enter (CjkInput, setting cjkInputHoldUntilEnter): deliver a held
* answer, then Enter as its own write ~120 ms later. Never `<text>\r` in one
* write: Codex reads characters arriving in one burst as a paste and folds an
* Enter inside it into the paste (even `1\r` stays unsent), and Claude Code
* does the same for a long burst. Same split as TmuxManager.sendInput: a
* single character is typed (a selection dialog ignores a pasted `3`, then
* Enter confirms the highlighted option), anything else goes through the
* composer's path as one bracketed paste. The session is captured now, so the
* delayed Enter cannot follow a tab switch. A lone digit while the session
* shows a permission or question dialog goes out without the Enter: the
* dialog acts on the digit itself, and a later Enter would confirm whatever
* the CLI shows next (a second permission prompt, unseen). Same rule as the
* Approvals Inbox and the Discord bridge (server.ts awaitingChoice). Returns
* false when nothing was sent (no session, too long), so the field keeps the
* text.
*/
_sendCjkPrompt(text) {
const sessionId = this.activeSessionId;
if (!sessionId || typeof KeyboardAccessoryBar === 'undefined') {
_crashDiag.log(`CJK prompt DROP no-session len=${text.length}`);
return false;
}
// A held answer is never what an armed one-shot Ctrl applies to (CjkInput
// sends the next typed character straight away as the control key), so
// Enter spends it, the same rule _handleCjkInput has for a longer chunk.
KeyboardAccessoryBar.clearCtrl?.();
_crashDiag.log(`CJK prompt→${sessionId.slice(0, 8)} len=${text.length}`);
if ([...text].length === 1) {
if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions();
this._sendInputAsync(sessionId, text);
const hooks = this.pendingHooks?.get(sessionId);
const awaitingChoice = !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog'));
if (/^\d$/.test(text) && awaitingChoice) {
_crashDiag.log(`CJK prompt digit answers a dialog, no Enter`);
return true;
}
setTimeout(() => this._sendInputAsync(sessionId, '\r', { useMux: true }), 120);
return true;
}
return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text);
},
/**
* Re-assert a history anchor captured before a terminal write (#358).
*
@@ -5087,7 +5136,9 @@ Object.assign(CodemanApp.prototype, {
clearTerminalInput() {
if (!this.activeSessionId) return;
if (typeof CjkInput !== 'undefined') CjkInput.clear();
// discard: the line is thrown away, so a Send on Enter draft must not be
// stashed and come back on the next visit to this session.
if (typeof CjkInput !== 'undefined') CjkInput.clear({ discard: true });
// A tile or Pane B holds the keyboard: its TUI owns the editable buffer
// (no local-echo overlay there), so kill the line in that pane's session,
// never in the parked main pane's.
@@ -5650,6 +5701,19 @@ Object.assign(CodemanApp.prototype, {
return 'content';
},
/**
* Whether a touchstart on transcript content should blur the focused terminal input.
* It does for xterm's helper textarea: that blur, with the preventDefault beside it,
* keeps the compatibility click from opening the keyboard. It must NOT for the pinned
* CJK field: at touchstart the gesture may still be a scroll, and that field owns the
* keyboard while it is visible, so blurring it closed the keyboard on every swipe that
* started on the live screen. A real tap on inert transcript still closes the keyboard
* at touchend (the startedWithTerminalFocus branch), so a tap keeps its meaning.
*/
_contentTouchStartBlurs() {
return document.activeElement?.id !== 'cjkInput';
},
_blurMobileTerminalInput() {
const active = document.activeElement;
if (
@@ -5848,6 +5912,9 @@ Object.assign(CodemanApp.prototype, {
) {
// No focus change: a 'content' tap was already blurred by touchstart, and
// popping the keyboard behind a tab that is about to take over is noise.
// The pinned CJK field is the exception touchstart leaves focused (a swipe must
// not close its keyboard), so a tap that opens a link closes it here instead.
if (!this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
return 'link';
}
@@ -6016,12 +6083,16 @@ Object.assign(CodemanApp.prototype, {
// True when a parsed CLI version string ('2.1.187' — banner-parsed on the
// server, delivered via session:cliInfo / SessionState.cliVersion) is known
// AND >= the minimum. Unknown or unparseable versions return false so
// callers keep the conservative behavior.
// callers keep the conservative behavior, and so does an unparseable
// minimum: it can come from a user's clis.json (`wheelForward.minVersion`).
_cliVersionAtLeast(version, minimum) {
if (typeof version !== 'string') return false;
const parts = version.trim().replace(/^v/, '').split('.').map(Number);
if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) return false;
const min = minimum.split('.').map(Number);
const parse = (v) => {
const m = typeof v === 'string' ? /^v?(\d+)\.(\d+)\.(\d+)$/.exec(v.trim()) : null;
return m ? m.slice(1).map(Number) : null;
};
const parts = parse(version);
const min = parse(minimum);
if (!parts || !min) return false;
for (let i = 0; i < 3; i++) {
if (parts[i] !== min[i]) return parts[i] > min[i];
}
@@ -6081,24 +6152,26 @@ Object.assign(CodemanApp.prototype, {
if (mode && mode !== 'none') return false;
const session = this.sessions?.get(target.sessionId || this.activeSessionId);
const sessionMode = session?.mode || 'claude';
// GitHub Copilot CLI (and pi, fullscreen by default) scrolls its own transcript on SGR wheel
// reports (checked with xterm encoding them natively). Their mouse DECSETs are stripped
// server-side so a drag selects locally (strip-mux-and-mouse), which also means xterm no longer
// encodes the wheel: send the same reports by hand, but only while the CLI is actually tracking
// the mouse. Not gated on a version. On Copilot a stale-false flag falls through to the
// PageUp/PageDown fallback like claude's; pi has none on purpose (the `transcriptPageKeys` note
// in stock.ts), so there the wheel does nothing until the flag is back.
if (sessionMode === 'copilot' || sessionMode === 'pi') return session?.cliMouseTracking === true;
if (sessionMode !== 'claude' && sessionMode !== 'codex') return false;
if (sessionMode === 'claude' && !this._cliVersionAtLeast(session?.cliVersion, '2.1.187')) return false;
// Only while Claude or Codex is actually listening for the mouse. Claude's
// inline renderer (2.1.280 measured: alternate_on=0, mouse_any_flag=0), like
// older inline Codex, keeps its transcript in real scrollback; SGR reports are
// ignored, so forwarding made every swipe and wheel tick dead. Fullscreen
// (CLAUDE_CODE_NO_FLICKER=1, or "tui": "fullscreen" in ~/.claude/settings.json)
// turns on alt-screen + mode 1003/1006, which the server records as
// cliMouseTracking. A stale-false flag after a server restart falls through
// to _maybePageCliTranscript, so it never goes dead.
// Which CLIs scroll their own transcript on SGR wheel reports is the registry's
// `wheelForward` rule, published by renderIndexHtml as `window.__codemanWheelForward`
// (id -> rule, `never` left out; a page rendered without the map forwards nothing), so a
// custom clis.json entry shaped like pi forwards under its own id. Stock: claude from
// 2.1.187 (older versions take the wheel as menu navigation), codex, copilot and pi always.
// Their mouse DECSETs are stripped server-side (a drag selects locally), so xterm never
// encodes the wheel for them and the reports are sent by hand.
const rule = window.__codemanWheelForward?.[sessionMode];
if (!rule || (rule.mode !== 'always' && rule.mode !== 'version-gated')) return false;
if (rule.mode === 'version-gated' && !this._cliVersionAtLeast(session?.cliVersion, rule.minVersion)) return false;
// Only while the CLI is actually listening for the mouse. Claude's inline renderer
// (2.1.280 measured: alternate_on=0, mouse_any_flag=0), like older inline Codex and pi's
// `tuiMode: regular`, keeps its transcript in real scrollback; SGR reports are ignored, so
// forwarding made every swipe and wheel tick dead. Fullscreen (CLAUDE_CODE_NO_FLICKER=1, or
// "tui": "fullscreen" in ~/.claude/settings.json; pi's default since 1.0.0) turns on
// alt-screen + mouse tracking, which the server records as cliMouseTracking. That flag is
// what survives a tab switch or reload, where xterm's own mouse mode does not. A stale-false
// flag falls through to _maybePageCliTranscript (PageUp/PageDown for a CLI declaring
// `transcriptPageKeys`); pi declares none on purpose (the note in stock.ts), so there the
// wheel does nothing until the flag is back.
if (session?.cliMouseTracking !== true) return false;
// Deliberately NOT gated on _terminalViewportAtBottom(). It used to be, so
// that leaving the bottom handed the wheel back to local scrollback and both
+14
View File
@@ -2651,6 +2651,20 @@ Object.assign(CodemanApp.prototype, {
// Aborts any in-flight normal select at its next _isStaleSelect check.
const selectGen = ++this._selectGeneration;
this._hideWebviewLayer?.();
// The one CJK field follows tile focus, and Enter sends to the session
// active at that moment: a Send on Enter draft typed for one tile must not
// go to the next. Stash it for the tile left, show the one focused (also
// the draft openTileGrid's cleanup stashed for the session it parked).
if (typeof CjkInput !== 'undefined') {
if (this.activeSessionId && this.activeSessionId !== sessionId) {
// A tile closed from this tab is already gone from this.sessions and
// its draft discarded: stashing it again would leave it in the map
// until the page reloads.
if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
CjkInput.restoreDraft?.(sessionId);
}
this.activeSessionId = sessionId;
grid.focusedId = sessionId;
// Moving focus off a zoomed tile restores the grid, as selecting another
+9 -9
View File
@@ -1,13 +1,13 @@
{
"version": "1.51.0",
"version": "1.51.1",
"highlights": [
"Local models: a library, more models, and the coding agent you choose (#803, #804, #806, #807, #808)",
"Mac app: With the Lid Closed no longer asks for a password",
"Auto-compact and auto-clear see the whole context (#777)",
"jcode as a run mode (#650)",
"The File Viewer edits `.env` files (#796, #797)",
"Response viewer: a Copy Markdown button (#810)",
"Firefox no longer pastes twice on Ctrl+V (#799)",
"An omp pane that asks for a tool approval alerts (#798)"
"Phone: Send on Enter for the input field (#820)",
"The terminal dashboard attaches by session name (#834)",
"Web tabs render the DeepSeek Harness web UI and Vite dashboards (#825)",
"Local model: Muse Glimmer 30B as its MLX build (#803)",
"A failing file watcher no longer floods the log (#818)",
"A password-protected Codeman installs as an app (#826)",
"A trusted web tab's WebSocket no longer sends Codeman's session cookie to the dashboard (#827)",
"Answers come back for a session on its own Claude config folder (#701, #812)"
]
}
+16 -5
View File
@@ -14,11 +14,12 @@ import { execSync, spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { dataPath } from '../../config/instance.js';
import { readHostSensors } from '../../host-sensors.js';
import { createCpuUsageMeter } from '../../cpu-usage.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } from '../../types.js';
import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions } from '../route-helpers.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions, ownerFor } from '../route-helpers.js';
import {
ConfigUpdateSchema,
SettingsUpdateSchema,
@@ -93,6 +94,15 @@ const SCREENSHOTS_DIR = dataPath('screenshots');
/** Cached CPU count — doesn't change at runtime */
const CPU_COUNT = cpus().length;
/** Header CPU use; the 1-minute load average per core only when the platform reports no core times. */
const cpuUsagePercent = createCpuUsageMeter(
cpus,
() => performance.now(),
() =>
// That is also the platform where cpus() is empty, so CPU_COUNT can be 0 here.
CPU_COUNT > 0 ? Math.min(100, Math.round((loadavg()[0] / CPU_COUNT) * 100)) : 0
);
function parseOptionalNumber(value: string | undefined): number | undefined {
if (value === undefined || value.trim() === '') return undefined;
const parsed = Number(value);
@@ -125,9 +135,7 @@ function getSystemStats(): {
usedMem = totalMem - freemem();
}
// CPU load average (1 min) as percentage (rough approximation)
const load = loadavg()[0];
const cpuPercent = Math.min(100, Math.round((load / CPU_COUNT) * 100));
const cpuPercent = cpuUsagePercent();
return {
cpu: cpuPercent,
@@ -659,7 +667,10 @@ export function registerSystemRoutes(
if (!dir) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getDeepSeekNotFoundMessage());
const { startDeepSeekWeb } = await import('../../deepseek-web-server.js');
const result = await startDeepSeekWeb(dir, authority);
// The launch cookie is bound to the identity whose request started the
// process, so `ownerFor` (undefined in single-user) is recorded here rather
// than the synthetic admin `getAuthUser` would report.
const result = await startDeepSeekWeb(dir, authority, ownerFor(req));
if (!result.ok) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, result.error);
return { success: true, data: { port: result.port, url: result.url, reused: result.reused } };
});
+66 -2
View File
@@ -36,6 +36,7 @@ import { WebSocket as WsClient } from 'ws';
import type { ClientOptions as WsClientOptions, WebSocket } from 'ws';
import type { Response as UndiciResponse } from 'undici';
import { getDataDir } from '../../config/instance.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import {
MAX_LIVE_WEBVIEW_FRAMES,
MAX_WEBVIEWS,
@@ -47,9 +48,11 @@ import {
WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
} from '../../config/webview-limits.js';
import { readWebviews, writeWebviews } from '../../webview-store.js';
import { canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js';
import { blockedWebviewHostReason } from '../webview-egress-policy.js';
import { getDeepSeekWebCookie } from '../../deepseek-web-server.js';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import type { Webview, WebviewOpenData, WebviewProbe } from '../../types.js';
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
@@ -64,8 +67,10 @@ import {
buildUpstreamRequestHeaders,
capabilityFromReferer,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
isHtmlContentType,
mergeCookieHeader,
parseWebviewUrl,
proxyPrefixFor,
resolveUpstreamUrl,
@@ -426,6 +431,51 @@ function proxyHttp(
return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '', basePath);
}
/**
* The credential a Codeman-managed dashboard needs on every upstream request.
*
* `dsh web` now gates its index and `/api` behind a cookie minted for the
* authority it was started on, and only the URL it prints on boot carries the
* token that buys it. The managed DeepSeek tab deliberately stores the clean
* URL, so the browser can never hold that cookie: `deepseek-web-server.ts`
* exchanges the token at startup, and this is where the supervisor's result
* reaches the request.
*
* Strictly scoped to the exact loopback origin the cookie was minted for. A
* web tab the user repointed at another host, or a stale tab still naming a
* previous port, must not be handed a credential that is not its own.
*
* ⚠️ `managed` is accepted from the client on POST/PATCH /api/webviews, and the
* live port is published by GET /api/deepseek/web, so "this record is managed and
* points at the port" is NOT an entitlement: without the check below, any signed-in
* user could save `{ url: "http://127.0.0.1:<port>", managed: "deepseek-web" }` and
* be handed the cookie bought by the user allowed to start the server. The gate
* needs the owner's privileged-commands grant, which is the same bar
* `POST /api/deepseek/web` applies before it starts a server.
*
* @param webview - the saved tab being proxied.
* @param upstream - resolved upstream URL for this request.
* @returns `name=value` cookie pair, or undefined when none applies.
*/
async function managedDashboardCookie(webview: Webview, upstream: URL): Promise<string | undefined> {
if (webview.managed !== 'deepseek-web') return undefined;
if (upstream.hostname !== '127.0.0.1') return undefined;
if (isMultiUserMode()) {
// Fail closed on an ownerless legacy record: `canUsernameRunPrivilegedCommands`
// treats an absent username as privileged (right for a cron job with no owner,
// wrong here), so the owner must be present before it is asked.
if (!webview.owner) return undefined;
if (!(await canUsernameRunPrivilegedCommands(webview.owner))) return undefined;
}
const port = Number(upstream.port || (upstream.protocol === 'https:' ? 443 : 80));
// The second identity check is the supervisor's: even an entitled owner gets
// nothing from a process another user started (POST restarts it for a new
// starter, so that tab simply reopens with its own cookie). Only in multi-user
// mode: a record created there keeps its owner, while a single-user start has
// no starter, so comparing that owner would refuse the tab for good.
return getDeepSeekWebCookie(port, isMultiUserMode() ? webview.owner : undefined) ?? undefined;
}
/**
* Proxy one request to the dashboard behind `cap`, serving `wildcard` as the
* upstream path. Split out from the route handler so the 404 fallback (which has
@@ -468,12 +518,14 @@ async function proxyRequest(
}
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
const injectedCookie = await managedDashboardCookie(webview, upstream);
const headers = buildUpstreamRequestHeaders(req.headers, upstream, {
forwardCookies: webview.trusted,
sessionCookieName: AUTH_COOKIE_NAME,
refererPath:
typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap, basePath) : undefined,
relayBodyLength: hasBody && req.body !== undefined,
...(injectedCookie ? { injectedCookie } : {}),
});
// #237: the timeout bounds TIME-TO-HEADERS only. A plain AbortSignal.timeout on
@@ -595,7 +647,9 @@ async function proxyRequest(
// Buffer only HTML, only under the cap: `<base>` injection needs the whole
// document, and buffering an unbounded upstream body is a memory hazard.
const html = await response.text();
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath) : html);
return reply.send(
html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath, wildcard) : html
);
}
return reply.send(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]));
@@ -707,13 +761,23 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa
};
const protocols = req.headers['sec-websocket-protocol'];
// The same credential the HTTP leg presents. A managed dashboard's realtime
// channel is gated exactly like its index, so without this the page loads
// and then sits there silently disconnected. Trusted dashboards get the
// browser's other cookies too, but never Codeman's own session cookie,
// with or without an injected one: the HTTP leg strips it the same way.
const injectedCookie = await managedDashboardCookie(webview, upstream);
const browserCookie = webview.trusted
? filterCookieHeader(req.headers.cookie ? String(req.headers.cookie) : undefined, [AUTH_COOKIE_NAME])
: undefined;
const cookie = injectedCookie ? mergeCookieHeader(browserCookie, injectedCookie) : browserCookie;
// `lookup` is absent from ws's ClientOptions typings but flows through
// http.request to net.connect untouched, which is where the resolved
// address is judged (see webview-egress.ts).
const upstreamOptions: WsClientOptions & { lookup: EgressLookup } = {
headers: {
origin: upstream.origin,
...(webview.trusted && req.headers.cookie ? { cookie: String(req.headers.cookie) } : {}),
...(cookie ? { cookie } : {}),
},
handshakeTimeout: WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
lookup: webviewEgressLookup,
+51 -1
View File
@@ -269,7 +269,7 @@ import {
registerCliRegistryRoutes,
registerLocalModelRoutes,
} from './routes/index.js';
import { isLostWebviewFrameNavigation } from './webview-proxy.js';
import { escapedWebviewAssetPath, isLostWebviewFrameNavigation } from './webview-proxy.js';
import { CronService } from '../cron/cron-service.js';
import { caseSessionSettled } from '../case-rename.js';
@@ -361,6 +361,38 @@ function getOrCreateSelfSignedCert(): { key: string; cert: string } {
};
}
/**
* One warn per escaped path per few minutes.
*
* A page whose boot module 404s retries in a loop, so an undeduped warn would
* bury the log it is meant to explain. Capped so a page emitting unbounded
* unique paths cannot grow the map without limit.
*/
const escapedWebviewWarnedAt = new Map<string, number>();
const ESCAPED_WEBVIEW_WARN_TTL_MS = 5 * 60_000;
/**
* Name a root-absolute request that escaped a web tab's proxy prefix.
*
* Nothing is retried or rewritten here — the request genuinely has no capability
* to relay to. This exists because that failure is otherwise silent: the tab
* shows a blank page or a spinner that never resolves, and the log says nothing.
*
* @param path - request path already judged as that shape.
*/
function warnEscapedWebviewAsset(path: string): void {
const now = Date.now();
const last = escapedWebviewWarnedAt.get(path);
if (last !== undefined && now - last < ESCAPED_WEBVIEW_WARN_TTL_MS) return;
if (escapedWebviewWarnedAt.size >= 200) escapedWebviewWarnedAt.clear();
escapedWebviewWarnedAt.set(path, now);
console.warn(
`[Webview] ${path} escaped the proxy: a web tab asked for a root-absolute URL that no Codeman route serves. ` +
`Its URL is masked, so the Referer cannot identify the dashboard. Usual cause: a URL built at runtime ` +
`(dynamic import(), worker, service worker) or an import inside an external script. The tab will look blank or stuck.`
);
}
export class WebServer extends EventEmitter {
private app: FastifyInstance;
private sessions: Map<string, Session> = new Map();
@@ -1294,6 +1326,11 @@ export class WebServer extends EventEmitter {
// and the relay declines unless the Referer carries a live capability, so
// genuinely unknown `/api` paths still get the envelope below.
if (await tryWebviewRefererFallback(req, reply, this.basePath)) return reply;
// No capability in the Referer, so this cannot be relayed — but if it has
// the shape of a dashboard asset, say so once. Silent 404s here are what
// turned a boot-module failure into a "blank tab" mystery more than once.
const escaped = escapedWebviewAssetPath({ method: req.method, url: req.url, headers: req.headers });
if (escaped) warnEscapedWebviewAsset(escaped);
// An authenticated web-tab frame (Basic auth, or trusted mode with a cookie)
// that navigated itself off its proxy prefix: the runtime shim masks the
// prefix so the page's router sees its own path, and a reload of that page
@@ -2133,6 +2170,19 @@ export class WebServer extends EventEmitter {
'</head>',
() => `<script>window.__codemanKeyboardHoldModes=${JSON.stringify(keyboardHoldClis)};</script>\n</head>`
);
// Which run modes take the wheel as SGR reports while they track the mouse
// (`_shouldForwardWheelToApp`), keyed by id with the `wheelForward` rule itself, so a
// custom clis.json entry shaped like pi forwards under its own id. `never` is left out.
// Disabled entries are kept (`listClis`, not `enabledClis`): disabling a CLI never ends
// its running sessions, and their wheel must keep working across a reload.
// `minVersion` is a free string a user's clis.json sets, hence the script escaper.
const wheelForwardClis = Object.fromEntries(
listClis()
.filter((entry) => entry.capabilities.wheelForward.mode !== 'never')
.map((entry) => [entry.id, entry.capabilities.wheelForward])
);
const wheelForwardJson = escapeScriptJson(JSON.stringify(wheelForwardClis));
html = html.replace('</head>', () => `<script>window.__codemanWheelForward=${wheelForwardJson};</script>\n</head>`);
if (!soloSessionId && process.env.CODEMAN_GESTURE === '1') {
html = html.replace('</head>', () => `<script>window.__codemanGestureAvailable=true;</script>\n</head>`);
if (settings.gestureControlEnabled === true) {
+194 -5
View File
@@ -207,6 +207,73 @@ export function capabilityFromReferer(referer: string | undefined, basePath = ''
}
}
/** `Sec-Fetch-Dest` values that describe a page fetching for itself, not navigating. */
const ASSET_FETCH_DESTS = new Set([
'script',
'style',
'image',
'font',
'manifest',
'worker',
'sharedworker',
'audio',
'video',
'track',
'embed',
'object',
'empty',
]);
/** Codeman's own missing files: a 404 here says nothing about a web tab. */
const CODEMAN_OWN_404 =
/^\/(?:favicon\.ico|manifest\.json|manifest\.webmanifest|robots\.txt|apple-touch-icon[\w.-]*)$/i;
/**
* Whether a 404 looks like a proxied dashboard's root-absolute request that
* escaped the prefix.
*
* This decides NOTHING about the response — the request cannot be relayed (a
* masked frame's `Referer` carries no capability, which is exactly why the
* Referer fallback above declined). It exists so the failure is diagnosable:
* the symptom of an escaped URL is a blank page or a spinner that never
* resolves, with nothing in the log to say why. Naming the path turns that into
* one grep.
*
* Deliberately conservative — a masked landing frame (`Referer` path `/`), an
* asset-shaped `Sec-Fetch-Dest`, same origin, not the API, not one of Codeman's
* own files. A false positive is a log line, never a behaviour change.
*
* @param input - method, request URL and headers of the 404.
* @returns the escaped path (no query), or null when it is not that shape.
*/
export function escapedWebviewAssetPath(input: {
method: string;
url: string;
headers: Record<string, string | string[] | undefined>;
}): string | null {
if (input.method !== 'GET' && input.method !== 'HEAD') return null;
const path = input.url.split('?')[0] ?? '';
if (path.startsWith('/api') || CODEMAN_OWN_404.test(path)) return null;
const single = (value: string | string[] | undefined): string | undefined =>
Array.isArray(value) ? value[0] : value;
const dest = single(input.headers['sec-fetch-dest']);
if (!dest || !ASSET_FETCH_DESTS.has(dest.toLowerCase())) return null;
const host = single(input.headers.host);
const referer = single(input.headers.referer);
if (!host || !referer) return null;
try {
const from = new URL(referer);
// Same origin, and the masked landing path: a real Codeman page's assets all
// resolve, so a 404 from one is not this shape.
if (from.host !== host || from.pathname !== '/') return null;
} catch {
return null;
}
return path;
}
/** Remove the `frame-ancestors` directive from a CSP, preserving the rest. */
export function stripFrameAncestors(csp: string): string {
return csp
@@ -296,6 +363,20 @@ export function rewriteSetCookie(cookie: string, capability: string, secureConte
return out.join('; ');
}
/**
* Put a server-held credential in front of the cookies the browser sent.
*
* Order matters: a `Cookie` header can name the same cookie twice, and parsers
* that collapse it into a map keep the FIRST value (RFC 6265 §5.4 leaves the
* choice open; the common Node parsers take the first). The browser may still
* hold a stale copy of the same dsh cookie from an earlier proxied response, so
* the credential minted by the running process must lead, with everything else
* preserved behind it.
*/
export function mergeCookieHeader(browserCookie: string | undefined, injectedCookie: string): string {
return browserCookie ? `${injectedCookie}; ${browserCookie}` : injectedCookie;
}
/** Drop named cookies from a `Cookie` request header, returning undefined if none remain. */
export function filterCookieHeader(cookie: string | undefined, drop: string[]): string | undefined {
if (!cookie) return undefined;
@@ -311,7 +392,21 @@ export function filterCookieHeader(cookie: string | undefined, drop: string[]):
export function buildUpstreamRequestHeaders(
incoming: Record<string, string | string[] | undefined>,
upstream: URL,
opts: { forwardCookies: boolean; sessionCookieName: string; refererPath?: string; relayBodyLength?: boolean }
opts: {
forwardCookies: boolean;
sessionCookieName: string;
refererPath?: string;
relayBodyLength?: boolean;
/**
* A credential the SERVER holds for this dashboard, put in front of whatever
* browser cookies were forwarded (see `mergeCookieHeader` for why the order
* matters). `dsh web` mints its session cookie for a loopback authority the
* browser never visits, so the proxy is the only party that can present it
* (see `deepseek-web-server.ts`); the managed tab is trusted, which means the
* browser may also carry other cookies dsh set, and those must survive.
*/
injectedCookie?: string;
}
): Record<string, string> {
const headers: Record<string, string> = {};
@@ -343,6 +438,14 @@ export function buildUpstreamRequestHeaders(
if (cookie) headers['cookie'] = cookie;
}
// In front of the relayed cookies rather than after them, so a stale browser
// copy of the same cookie cannot shadow the one minted by the running process
// (the parser keeps the first value). Other cookies are kept: a managed dsh tab
// is trusted, so dsh's own non-auth cookies may legitimately be there.
if (opts.injectedCookie) {
headers['cookie'] = mergeCookieHeader(headers['cookie'], opts.injectedCookie);
}
// Present as if the browser were talking to the dashboard directly. Apps that
// check Origin on writes (CSRF defenses) need this to match their own origin.
headers['origin'] = upstream.origin;
@@ -646,6 +749,79 @@ try{
}catch(e){}})();</script>`;
}
/**
* Make a page's own RELATIVE `<base href>` absolute under the proxy prefix.
*
* A base element is resolved against the document's URL, and {@link runtimeUrlShim}
* deliberately rewrites that URL to strip the proxy prefix. So a page shipping
* `<base href="./">` — which is what a Vite build does, DeepSeek Harness among
* them — has its base re-resolved to Codeman's ROOT the moment the shim runs:
* every module script, stylesheet and `fetch('./api')` then asks the Codeman
* origin instead of the dashboard. The visible symptom is not an error page but
* a blank one: the markup and inline `<style>` paint (dsh paints a dark
* `#151517`), the module 404s, and nothing else ever renders.
*
* Resolving it here, while the prefix is still known, keeps the author's target
* (the document as it existed before masking) and is idempotent: an
* already-absolute path resolves to itself. Cross-origin bases are the author
* pointing at a CDN and are left exactly as written.
*
* The document path matters: a base in `/webview/<cap>/app/page.html` is
* relative to `/webview/<cap>/app/`, not to the proxy root, or a page served
* from a subdirectory would resolve its assets one level too high.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix the document was served from.
* @param documentPath - upstream path of the document, without the leading slash.
* @returns the document with a relative base href made absolute.
*/
function rebaseRelativeBase(html: string, prefix: string, documentPath: string): string {
const documentUrl = `http://codeman.invalid${prefix}${documentPath.replace(/^\/+/, '')}`;
return html.replace(
/(<base\b[^>]*?\bhref\s*=\s*)(["'])([^"']*)\2/i,
(match: string, head: string, quote: string, href: string) => {
let resolved: URL;
try {
// A stand-in origin: only the path is kept, and a different origin here
// is exactly the "absolute base" case this must not touch.
resolved = new URL(href, documentUrl);
} catch {
return match;
}
if (resolved.origin !== 'http://codeman.invalid') return match;
return `${head}${quote}${resolved.pathname}${resolved.search}${resolved.hash}${quote}`;
}
);
}
/**
* Rewrite root-absolute specifiers of dynamic `import()` calls in `<script>`
* bodies.
*
* A dynamic import is the one URL no other layer can reach: it is not an
* attribute, so `<base>` does not apply to it; it is not `fetch()`, so the runtime
* shim cannot rewrite it; and the browser resolves it against the ORIGIN root, not
* the document. SvelteKit's inline bootstrap is exactly this shape
* (`import("/_app/…")`), and the failure mode is silent: the module 404s against
* Codeman and the app's own loading spinner never resolves.
*
* ⚠️ Scoped to script bodies on purpose. Running the same regex over the whole
* document also rewrote visible text — `<pre>import("/x")</pre>` became a broken
* example — which is a rendering bug, not a loader the browser was going to run.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix to put in front of a `/`-rooted specifier.
*/
function rewriteScriptImports(html: string, prefix: string): string {
return html.replace(
/(<script\b[^>]*>)([^]*?)(<\/script>)/gi,
(_match: string, open: string, body: string, close: string) =>
open +
body.replace(/\bimport\s*\(\s*(["'])\/(?!\/)/g, (_import: string, quote: string) => `import(${quote}${prefix}`) +
close
);
}
/**
* Inject `<base href="/webview/<cap>/">` plus the runtime URL shim, and rebase
* root-absolute `src`/`href`/`action` attributes, which `<base>` alone does not
@@ -654,14 +830,27 @@ try{
* Three layers, because no single one is sufficient: `<base>` for parser-resolved
* relative URLs, attribute rewriting for root-absolute markup, and the shim for
* URLs built at runtime.
*
* @param html - the upstream document.
* @param capability - capability the document is being served under.
* @param basePath - reverse-proxy mount prefix (`''` at root).
* @param documentPath - upstream path of the document, without the leading slash.
* Used to resolve the page's own relative `<base>` against its directory.
*/
export function rewriteHtml(html: string, capability: string, basePath = ''): string {
export function rewriteHtml(html: string, capability: string, basePath = '', documentPath = ''): string {
const prefix = proxyPrefixFor(capability, basePath);
// Fresh regexes per call: module-level /g patterns carry `lastIndex` between calls.
const rebased = html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`);
const rebased = rebaseRelativeBase(
rewriteScriptImports(
html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`),
prefix
),
prefix,
documentPath
);
// A page that ships its own <base> keeps it (overriding it would break the
// author's intent), but it STILL needs the shim, which is the layer that
+3 -4
View File
@@ -40,6 +40,7 @@ import { join } from 'node:path';
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
import type { WorkflowRunInfo, WorkflowRunSummary, WorkflowAgentInfo, WorkflowRunPhase } from './types/workflow-run.js';
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
import { LRUMap } from './utils/lru-map.js';
import {
WORKFLOW_RUN_POLL_INTERVAL_MS,
@@ -865,10 +866,8 @@ export class WorkflowRunWatcher extends EventEmitter {
// subagents/workflows/ children are wf_<id>/ DIRS — catch their add/remove too.
watcher.on('addDir', handler);
watcher.on('unlinkDir', handler);
watcher.on('error', () => {
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
this.removeDirWatcher(workflowsDir);
});
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
closeWatcherOnError(watcher, () => this.dirWatchers.delete(workflowsDir));
this.dirWatchers.set(workflowsDir, watcher);
} catch {
// Watch setup failed — periodic poll still discovers changes.
+201
View File
@@ -0,0 +1,201 @@
// test/cjk-hold-per-device-setting.test.ts
// Port: none (static analysis + vm, runs in CI, no browser/server).
//
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
// merge policy, stripped out of the object saveAppSettings() PUTs
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
// never declared in the schema. Plus the pieces around the mode: a held draft
// surviving a reload of the same session, the field staying one line tall with
// the keyboard down, and zh-CN strings for its placeholders.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'cjkInputHoldUntilEnter'");
});
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
});
it('is never declared in the .strict() SettingsUpdateSchema', () => {
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
});
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
});
it('is loaded into and saved from its App Settings switch', () => {
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
expect(settingsUi).toContain(
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
);
});
});
describe('a held draft survives a reload of the same session', () => {
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
// activeSessionId before calling it on a same-session forceReload (tapping the
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) {
const clear = vi.fn();
const stashDraft = vi.fn();
const context = vm.createContext({
console,
setTimeout,
clearTimeout,
setInterval: vi.fn(),
clearInterval: vi.fn(),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
fetch: vi.fn(),
URLSearchParams,
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => 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: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
CjkInput: { holdUntilEnter: hold, clear, stashDraft },
});
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.create(CodemanApp.prototype) as Record<string, unknown> & {
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
};
app.activeSessionId = outgoing;
app.sessions = new Map();
app._clearTimer = vi.fn();
app._disconnectWs = vi.fn();
app._xtermSnapshots = new Map();
app.pendingWrites = [];
app._cleanupPreviousSession('s1', { keepCjkDraft });
return Object.assign(clear, { stashDraft });
}
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
expect(cleanup(true, true)).not.toHaveBeenCalled();
});
it('still clears on a real switch', () => {
expect(cleanup(true, false)).toHaveBeenCalled();
});
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
expect(cleanup(false, true)).toHaveBeenCalled();
});
it('stashes the held draft of the session being left before clearing', () => {
const clear = cleanup(true, false, 's0');
expect(clear.stashDraft).toHaveBeenCalledWith('s0');
expect(clear.stashDraft.mock.invocationCallOrder[0]).toBeLessThan(clear.mock.invocationCallOrder[0]);
});
it('selectSession restores the draft of the session it lands on', () => {
// After _activateFileBrowserSession: test/file-browser-search.test.ts pins
// that call as the line right after the activeSessionId assignment.
expect(read('app.js')).toContain(
"this.activeSessionId = sessionId;\n this._activateFileBrowserSession?.(sessionId);\n if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);"
);
});
it('leaving the tile grid for another session stashes the focused tile draft', () => {
// selectSession nulls activeSessionId there, which hides the tile from
// _cleanupPreviousSession.
expect(read('app.js')).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\n(?:\s*\/\/.*\n)*\s*this\.activeSessionId = null;/
);
});
it('tile focus does not stash again for a tile closed from this tab', () => {
// removeSession discards the closed session's draft first; a stash after
// that would keep it in the map until the page reloads.
expect(read('tile-grid.js')).toContain(
'if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);'
);
});
it('tile focus stashes the draft of the tile left and restores the focused one', () => {
const tiles = read('tile-grid.js');
const start = tiles.indexOf(' _selectTiledSession(sessionId, options = {}) {');
const body = tiles.slice(start, tiles.indexOf('grid.focusedId = sessionId;', start));
expect(body).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\s*CjkInput\.clear\(\);\s*\}\s*CjkInput\.restoreDraft\?\.\(sessionId\);\s*\}\s*this\.activeSessionId = sessionId;/
);
});
it('going Home stashes the draft of the session it leaves', () => {
const appJs = read('app.js');
const start = appJs.indexOf(' goHome() {');
const body = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(body).toContain('CjkInput.stashDraft?.(this.activeSessionId);');
});
it('a removed session drops its stashed draft', () => {
expect(read('app.js')).toMatch(
/discardComposerDraft\?\.\(sessionId\);\n\s*if \(typeof CjkInput !== 'undefined'\) CjkInput\.discardDraft\?\.\(sessionId\);/
);
});
it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => {
const appJs = read('app.js');
expect(appJs).toMatch(
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
});
});
describe('Send on Enter field layout and strings', () => {
it('keeps the field one line tall while the keyboard is down', () => {
// .main reserves a fixed 84px there; a grown field would cover the terminal.
expect(read('styles.css')).toMatch(
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
);
});
it('caps the field on every device, not only in the .touch-device rule', () => {
// The setting is not limited to phones; on desktop an uncapped field grew to
// 502px at 25 lines and resized the PTY on every step.
const css = read('styles.css');
const base = css.slice(css.indexOf('#cjkInput {'), css.indexOf('}', css.indexOf('#cjkInput {')));
expect(base).toContain('max-height: 68px;');
expect(base).toContain('overflow-y: auto;');
});
it('the phone toolbar Enter presses Enter in the visible CJK field', () => {
// onData drops everything while cjkActive, so the xterm path does nothing.
const sessionUi = read('session-ui.js');
const start = sessionUi.indexOf(' sendEnterKey() {');
const body = sessionUi.slice(start, sessionUi.indexOf('triggerDataEvent', start));
expect(body).toContain("classList.contains('cjk-input-visible')");
expect(body).toContain('CjkInput.submit?.();');
});
it('has zh-CN strings for both field placeholders', () => {
const i18n = read('i18n.js');
const cjk = read('input-cjk.js');
for (const placeholder of [
'CJK input (Enter = send, Esc = clear)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
]) {
expect(cjk).toContain(`'${placeholder}'`);
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
}
});
});
+1 -1
View File
@@ -172,7 +172,7 @@ describe('registered arguments', () => {
['attach', ['path']],
['start', []],
// Optional: bare `codeman tui` opens the dashboard.
['tui', ['n']],
['tui', ['session']],
])('declares the operands of `%s`', (name, expected) => {
const args = find(program, name)!.registeredArguments.map((arg) => arg.name());
expect(args).toEqual(expected);
@@ -435,7 +435,6 @@ describe('declared-for-later fields', () => {
const DECLARED_FOR_LATER = [
'accent',
'capabilities.echo',
'capabilities.wheelForward',
'capabilities.keyboardAccessory',
'capabilities.maxFrameBytes',
// The Docker credential-seeding path still reads its own CRED_STORES table: this shape
+77
View File
@@ -0,0 +1,77 @@
/**
* @fileoverview The header CPU reading's meter: busy time over all cores between readings, the minimum window
* that keeps several browsers from shrinking it, and the fallback when no usable core times exist.
*/
import { describe, expect, it } from 'vitest';
import { createCpuUsageMeter } from '../src/cpu-usage.js';
const core = (busy: number, idle: number) => ({ times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } });
function meterOver(samples: ReturnType<typeof core>[][], fallback = () => 999) {
let at = 0;
let index = 0;
const meter = createCpuUsageMeter(
() => samples[Math.min(index, samples.length - 1)],
() => at,
fallback
);
return (ms: number) => {
at += ms;
index += 1;
return meter();
};
}
describe('createCpuUsageMeter', () => {
it('reports busy time over all cores between readings', () => {
const next = meterOver([
[core(0, 0), core(0, 0)],
[core(50, 50), core(50, 50)],
[core(150, 50), core(50, 150)],
]);
expect(next(2000)).toBe(50);
expect(next(2000)).toBe(50);
});
it('counts nice, system and interrupt time as busy', () => {
const times = (user: number, nice: number, sys: number, irq: number, idle: number) => ({
times: { user, nice, sys, idle, irq },
});
const meter = createCpuUsageMeter(
(() => {
let calls = 0;
return () => [calls++ === 0 ? times(0, 0, 0, 0, 0) : times(10, 20, 30, 15, 25)];
})(),
(() => {
let at = 0;
return () => (at += 2000);
})(),
() => 999
);
expect(meter()).toBe(75);
});
it('reads idle cores as idle however long the run queue is', () => {
expect(meterOver([[core(0, 0)], [core(40, 60)]])(5000)).toBe(40);
});
it('reuses the last value for readings under a second apart and keeps the baseline', () => {
const next = meterOver([[core(0, 0)], [core(30, 70)], [core(30, 170)], [core(130, 170)]]);
expect(next(2000)).toBe(30);
expect(next(200)).toBe(30);
expect(next(2000)).toBe(50);
});
it('falls back without a bogus reading when there are no core times or the counters go backwards', () => {
expect(meterOver([[], []], () => 7)(2000)).toBe(7);
const next = meterOver([[core(100, 100)], [core(10, 10)], [core(60, 60)]], () => 7);
expect(next(2000)).toBe(7);
expect(next(2000)).toBe(50);
});
it('answers a whole number from 0 to 100', () => {
expect(meterOver([[core(0, 0)], [core(2, 1)]])(2000)).toBe(67);
expect(meterOver([[core(0, 0)], [core(0, 9)]])(2000)).toBe(0);
expect(meterOver([[core(0, 0)], [core(9, 0)]])(2000)).toBe(100);
});
});
+362 -2
View File
@@ -12,10 +12,25 @@
* 2. The supervisor tracks at most ONE server. The status accessor is what every
* caller reads to decide whether to start another, so "no server" must report
* as absent rather than as a half-populated record.
* 3. `dsh web` now gates its index behind a launch token it prints on boot. The
* supervisor is the only party that can trade it, and the cookie it produces
* is authority-bound: getting that wrong is a blank tab, not a visible error.
*/
import { describe, expect, it, beforeEach } from 'vitest';
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import http from 'node:http';
import { DeepSeekWebStartSchema } from '../src/web/schemas.js';
import { getDeepSeekWebStatus, resetDeepSeekWebForTest, stopDeepSeekWeb } from '../src/deepseek-web-server.js';
import {
getDeepSeekWebCookie,
getDeepSeekWebStatus,
launchUrlTargetsServer,
parseLaunchUrl,
resetDeepSeekWebForTest,
startDeepSeekWeb,
stopDeepSeekWeb,
} from '../src/deepseek-web-server.js';
describe('DeepSeekWebStartSchema: the authority reaching --trusted-host', () => {
it('accepts the authority shapes a browser can actually report', () => {
@@ -71,3 +86,348 @@ describe('DeepSeek web supervisor: status', () => {
expect(getDeepSeekWebStatus().running).toBe(false);
});
});
describe('parseLaunchUrl: the one-time token dsh prints on boot', () => {
it('pulls the URL out of the banner a real boot writes', () => {
const output = ['dsh web: http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc', 'ready'].join('\n');
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc');
});
it('sees through SGR colouring, which would otherwise hide the token', () => {
const output = '\u001b[36mdsh web:\u001b[0m \u001b[4mhttp://127.0.0.1:3080/?token=abc123\u001b[0m\n';
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=abc123');
});
// dsh prints diagnostics under the same prefix before the banner. Taking the
// FIRST match made the real URL invisible and boot gave up 4 seconds later.
it('skips a diagnostic line and keeps scanning for the URL', () => {
expect(parseLaunchUrl('dsh web: loading profiles\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('skips a URL without a token and keeps scanning for the token one', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('returns null for a token-less banner, which is the older dsh', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\n')).toBeNull();
});
it('refuses anything that is not an http(s) URL carrying a token', () => {
expect(parseLaunchUrl('')).toBeNull();
expect(parseLaunchUrl('booting...')).toBeNull();
expect(parseLaunchUrl('dsh web: javascript:alert(1)?token=x')).toBeNull();
expect(parseLaunchUrl('dsh web: not a url?token=x')).toBeNull();
});
});
describe('launchUrlTargetsServer: the exchange must hit the spawned port', () => {
it('accepts only 127.0.0.1 on the port that was just spawned', () => {
expect(launchUrlTargetsServer('http://127.0.0.1:3080/?token=x', 3080)).toBe(true);
expect(launchUrlTargetsServer('http://127.0.0.1:3081/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://localhost:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://evil.example:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('not a url', 3080)).toBe(false);
});
});
describe('DeepSeek web supervisor: the launch-token cookie', () => {
let dir: string;
beforeEach(() => {
resetDeepSeekWebForTest();
dir = mkdtempSync(join(tmpdir(), 'codeman-dsh-web-'));
});
afterEach(async () => {
await stopDeepSeekWeb();
rmSync(dir, { recursive: true, force: true });
});
/**
* A stand-in for `dsh web` with the browser-auth gate: prints the banner,
* refuses `/` without a cookie, and trades the token for one 303.
*/
const FAKE_DSH = `#!/usr/bin/env node
const http = require('node:http');
const portArg = process.argv.indexOf('--port');
const port = Number(process.argv[portArg + 1]);
const token = 'test-launch-token';
const cookie = 'dsh-auth-test=v1.payload.sig';
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.pathname === '/' && url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/; HttpOnly' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<!doctype html><title>harness</title>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`;
it('trades the boot token for the cookie, scoped to its own port', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
// Before the exchange this page is exactly the blank tab being fixed: 401.
expect((await fetch(`http://127.0.0.1:${result.port}/`)).status).toBe(401);
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-test=v1.payload.sig');
// A credential minted for this authority must never travel to another port.
expect(getDeepSeekWebCookie(result.port + 1)).toBeNull();
const authed = await fetch(`http://127.0.0.1:${result.port}/`, {
headers: { cookie: getDeepSeekWebCookie(result.port) as string },
});
expect(authed.status).toBe(200);
}, 20_000);
// `managed` is a client-supplied field and the port is published by
// GET /api/deepseek/web, so the supervisor additionally binds the cookie to the
// identity whose request started the process: another user's tab must not be
// handed it, and their POST must not reuse bob's server either.
it('hands the cookie only to the identity that started the server', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const bob = await startDeepSeekWeb(dir, 'localhost:3000', 'bob');
expect(bob.ok).toBe(true);
if (!bob.ok) return;
expect(getDeepSeekWebCookie(bob.port, 'bob')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(bob.port)).toBeNull();
expect(getDeepSeekWebCookie(bob.port, 'alice')).toBeNull();
// A different owner restarts rather than reusing bob's cookie.
const alice = await startDeepSeekWeb(dir, 'localhost:3000', 'alice');
expect(alice.ok).toBe(true);
if (!alice.ok) return;
expect(alice.reused).toBe(false);
expect(getDeepSeekWebCookie(alice.port, 'alice')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(alice.port, 'bob')).toBeNull();
}, 20_000);
// A failed exchange leaves a server that answers 401 to everything. Reuse used
// to hand that same server back on every POST, so the restart the warning asks
// for could never happen. The next start request must perform it.
it('restarts rather than reusing a server whose exchange failed', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'retry-token';
const cookie = 'dsh-auth-retry=v1.sig';
const marker = path.join(__dirname, '.exchange-failed');
const failedBefore = fs.existsSync(marker);
if (!failedBefore) fs.writeFileSync(marker, '1');
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
if (!failedBefore) {
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('temporary failure');
return;
}
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const first = await startDeepSeekWeb(dir, 'localhost:3000');
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(getDeepSeekWebCookie(first.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be exchanged'));
} finally {
warn.mockRestore();
}
const second = await startDeepSeekWeb(dir, 'localhost:3000');
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(second.reused).toBe(false);
expect(getDeepSeekWebCookie(second.port)).toBe('dsh-auth-retry=v1.sig');
// The recovered server is healthy again, so ordinary reuse resumes.
const third = await startDeepSeekWeb(dir, 'localhost:3000');
expect(third.ok).toBe(true);
if (!third.ok) return;
expect(third.reused).toBe(true);
}, 20_000);
// The exchange is a request made by the SERVER. A banner naming another local
// port would let captured child output aim it, so the URL is judged before it
// is fetched at all.
it('does not fetch a banner naming another port', async () => {
const hits: string[] = [];
const target = http.createServer((req, res) => {
hits.push(req.url ?? '');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('should never be reached');
});
await new Promise<void>((resolve) => target.listen(0, '127.0.0.1', resolve));
const address = target.address();
if (!address || typeof address === 'string') throw new Error('target has no address');
try {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
process.stdout.write('dsh web: http://127.0.0.1:${address.port}/?token=stolen\\n');
http
.createServer((_req, res) => {
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('not fetching it'));
} finally {
warn.mockRestore();
}
expect(hits).toEqual([]);
} finally {
await new Promise<void>((resolve) => target.close(() => resolve()));
}
}, 20_000);
it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync(
join(dir, 'dsh'),
'#!/usr/bin/env node\nconst http = require("node:http");\nconst port = Number(process.argv[process.argv.indexOf("--port") + 1]);\nprocess.stdout.write("dsh web: http://127.0.0.1:" + port + "/\\n");\nhttp.createServer((_q, s) => s.end("ok")).listen(port, "127.0.0.1");\n',
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
}, 20_000);
// The error-tail buffer is capped at 16 KB, and a chatty plugin tree can fill
// it before dsh prints its banner. Scanning that buffer alone lost the token
// and put the tab back on the 401 page, so the banner is matched on its own
// (larger) budget.
// The banner can arrive in two stdout writes: `capture()` sees two chunks and
// neither is a complete line. Scanning the raw buffer either missed it or, with
// a partial URL that happened to parse, exchanged a truncated token.
it('waits for a banner split across two output chunks', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'split-token';
const cookie = 'dsh-auth-split=v1.sig';
process.stdout.write('dsh web: loading profiles\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1', () => {
const line = 'dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n';
process.stdout.write(line.slice(0, 30));
setTimeout(() => process.stdout.write(line.slice(30)), 150);
});
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-split=v1.sig');
}, 20_000);
it('still finds a banner printed after more than the error-tail cap', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'late-banner-token';
const cookie = 'dsh-auth-late=v1.sig';
process.stdout.write('warn: plugin noise '.repeat(1100) + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
setTimeout(() => process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n'), 300);
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-late=v1.sig');
}, 20_000);
});
+69 -3
View File
@@ -448,6 +448,72 @@ describe('DiscordBridge', () => {
return b;
}
it('deduplicates replayed real gateway IDs across restart while new replies still work', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
b.stop();
t += 10_000;
const next = await ready();
await next.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555556', content: 'continue' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('claims rate-limited snowflake replies so replays remain refused across restart', async () => {
const b = await ready();
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
t += 200;
const refused = reply({ id: '555555555555555556', content: 'too soon' });
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(true);
t += 5_000;
const count = posts.length;
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts).toHaveLength(count);
b.stop();
const next = await ready();
await next.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555557', content: 'new attempt' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('ignores an immediate replay without adding an hourglass to a successful reply', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
t += 200;
await b.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.filter((p) => p.method === 'PUT')).toHaveLength(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(false);
b.stop();
});
it('delivers replies and alerts when metadata is corrupt and recovers without restarting', async () => {
const b = await ready();
writeFileSync(join(dir, 'discord-reply-dedupe.json'), '{');
const log = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
expect(sendInput).toHaveBeenCalledTimes(1);
t += 10_000;
expect((await b.notify(MSG))?.ok).toBe(true);
rmSync(join(dir, 'discord-reply-dedupe.json'));
await b.onGatewayMessage(reply({ id: '555555555555555556' }));
expect(sendInput).toHaveBeenCalledTimes(2);
expect(log).toHaveBeenCalledTimes(1);
} finally {
log.mockRestore();
b.stop();
}
});
it('types an allowed reply into the mapped session and ticks it', async () => {
const b = await ready();
await b.onGatewayMessage(reply());
@@ -1143,7 +1209,7 @@ describe('DiscordBridge files and startup hint', () => {
it('types a reply that waits on a download before a later text reply', async () => {
const b = await make();
const slow = b.onGatewayMessage(reply({ content: 'first' }));
await new Promise((r) => setTimeout(r, 0)); // the first reply is under way (gate passed) before the clock moves
await vi.waitFor(() => expect(downloads).toHaveLength(1)); // wait for the claim and rate-limit gate
t += 5_000;
const fast = b.onGatewayMessage(reply({ id: '555555555555555556', content: 'second', attachments: [] }));
await Promise.all([slow, fast]);
@@ -1157,11 +1223,11 @@ describe('DiscordBridge files and startup hint', () => {
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2');
t += 5_000;
await b.onGatewayMessage(reply({ content: 'yes', attachments: [] }));
await b.onGatewayMessage(reply({ id: '555555555555555556', content: 'yes', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('yes\r');
t += 5_000;
waiting = false;
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
await b.onGatewayMessage(reply({ id: '555555555555555557', content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2\r');
b.stop();
});
+151
View File
@@ -0,0 +1,151 @@
import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { DiscordReplyDedupe } from '../src/discord-reply-dedupe.js';
import fs from 'node:fs/promises';
let dir: string;
const guild = '111111111111111111',
channel = '222222222222222222',
message = '333333333333333333';
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'discord-replies-'));
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
it('claims once across concurrent events and restarts, without storing message content', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await Promise.all([store.claim(guild, channel, message), store.claim(guild, channel, message)])).toEqual([
true,
false,
]);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(join(dir, 'discord-reply-dedupe.json'))).mode & 0o777).toBe(0o600);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toEqual([
[`${guild}:${channel}:${message}`, expect.any(Number)],
]);
});
it('falls back on corrupt metadata, logs once, retries after recovery, and retains memory claims', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, '{');
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('does not poison metadata with incomplete restored configuration', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await store.claim('', channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('keeps accepting new replies during ENOSPC and persists memory claims when writes recover', async () => {
const warn = vi.fn();
const store = new DiscordReplyDedupe(dir, Date.now, warn);
const rename = vi.spyOn(fs, 'rename').mockRejectedValueOnce(Object.assign(new Error('full'), { code: 'ENOSPC' }));
try {
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
} finally {
rename.mockRestore();
}
});
it('evicts old records rather than refusing replies at capacity', async () => {
await writeFile(
join(dir, 'discord-reply-dedupe.json'),
JSON.stringify(
Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${String(100000000000000000n + BigInt(i))}`,
Date.now(),
])
)
);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(true);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toHaveLength(2048);
});
it.each(['{', '{}', '[null]'])(
'heals readable invalid metadata %s and keeps the claim across restart',
async (invalid) => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, invalid);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
}
);
it('retains newer outage claims when disk recovery reaches capacity, without overwriting an unread file', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const rows = Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${100000000000000000n + BigInt(i)}`,
Date.now(),
]);
const original = JSON.stringify(rows);
await writeFile(path, original);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
const read = vi
.spyOn(fs, 'readFile')
.mockRejectedValueOnce(Object.assign(new Error('descriptor limit'), { code: 'EMFILE' }));
expect(await store.claim(guild, channel, message)).toBe(true);
read.mockRestore();
expect(await readFile(path, 'utf8')).toBe(original);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
const saved = JSON.parse(await readFile(path, 'utf8'));
expect(saved).toHaveLength(2048);
expect(saved.some((row: [string, number]) => row[0] === rows[0][0])).toBe(false);
});
it('heals an over-cap readable store rather than remaining memory-only until manual deletion', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(
path,
JSON.stringify(
Array.from({ length: 2049 }, (_, i) => [`${guild}:${channel}:${100000000000000000n + BigInt(i)}`, Date.now()])
)
);
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
});
it('heals oversized regular metadata and persists replay protection across restart', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, ' '.repeat(512 * 1024 + 1));
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(path)).size).toBeLessThan(512 * 1024);
expect(warn).toHaveBeenCalledTimes(1);
});
it('never replaces a symlink or a folder at the metadata path, and still accepts replies', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const target = join(dir, 'target');
await writeFile(target, 'keep');
await symlink(target, path);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect((await lstat(path)).isSymbolicLink()).toBe(true);
expect(await readFile(target, 'utf8')).toBe('keep');
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
await mkdir(path);
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect((await lstat(path)).isDirectory()).toBe(true);
});
+68 -1
View File
@@ -38,7 +38,7 @@ import {
symlinkSync,
readdirSync,
} from 'node:fs';
import { execFileSync, spawnSync } from 'node:child_process';
import { spawn, execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { diffRequiredEnvKeys, parseEnvKeys } from '../src/web/self-update.js';
@@ -639,3 +639,70 @@ describe('version_older_than', () => {
expect(out).toBe(older ? 'yes' : 'no');
});
});
/**
* A listener whose accept queue is full, so the kernel drops further SYNs and a
* connect to it gets no answer, the same thing a WSL host does for a CLOSED
* 127.0.0.1 port. Held by a python3 child, since Node accepts every connection
* as it arrives and so can never leave its own queue full.
*/
const HAS_PYTHON = spawnSync('python3', ['-c', 'pass']).status === 0;
const SILENT_LISTENER = [
'import socket, sys, time',
's = socket.socket(); s.bind(("127.0.0.1", 0)); s.listen(0)',
'port = s.getsockname()[1]; held = []',
'for _ in range(3):',
' c = socket.socket(); c.setblocking(False)',
' try: c.connect(("127.0.0.1", port))',
' except BlockingIOError: pass',
' held.append(c)',
'time.sleep(0.3); print(port, flush=True); time.sleep(60)',
].join('\n');
describe.skipIf(process.platform !== 'linux' || !HAS_PYTHON)('port_answers', () => {
/** Runs the script's own port_answers on host/port, returning its status and how long it took. */
function probe(host: string, port: number): { status: number | null; ms: number } {
const script = [
'set -euo pipefail',
`eval "$(sed -n '/^port_answers() {/,/^}/p' "$1")"`,
'if port_answers "$2" "$3"; then exit 0; else exit 1; fi',
].join('\n');
const started = Date.now();
const res = spawnSync('bash', ['-c', script, '_', join(ROOT, 'docker/Start-Codeman.sh'), host, String(port)], {
encoding: 'utf-8',
timeout: 10_000,
});
return { status: res.status, ms: Date.now() - started };
}
it('gives up on a connect that gets no answer within about a second, and reads it as free', async () => {
const child = spawn('python3', ['-I', '-c', SILENT_LISTENER], { stdio: ['ignore', 'pipe', 'ignore'] });
try {
const port = await new Promise<number>((resolve, reject) => {
child.stdout!.once('data', (chunk: Buffer) => resolve(Number(String(chunk).trim())));
child.once('exit', () => reject(new Error('listener exited')));
});
const { status, ms } = probe('127.0.0.1', port);
expect(status).toBe(1);
expect(ms).toBeLessThan(3000);
} finally {
child.kill();
}
});
it('still answers at once for a listening port and a closed one', async () => {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as { port: number }).port;
try {
const open = probe('127.0.0.1', port);
expect(open.status).toBe(0);
expect(open.ms).toBeLessThan(1000);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
const closed = probe('::1', port);
expect(closed.status).toBe(1);
expect(closed.ms).toBeLessThan(1000);
});
});
+617
View File
@@ -0,0 +1,617 @@
/**
* @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js,
* setting cjkInputHoldUntilEnter): typed text stays in the field until Enter,
* so a phone user can scroll the terminal and edit an answer before sending.
*
* Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also
* carries the attributes and style the mode touches.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const PHANTOM = '​';
function makeTextarea() {
const listeners = new Map<string, Array<(e?: unknown) => void>>();
const attrs: Record<string, string> = {};
return {
value: '',
placeholder: '',
style: { height: '' } as Record<string, string>,
scrollHeight: 34,
// border-box with a 1px border: offsetHeight - clientHeight is the borders.
offsetHeight: 36,
clientHeight: 34,
attrs,
blur: vi.fn(),
focus: vi.fn(),
getClientRects: (): unknown[] => [{}],
classList: { contains: (c: string) => c === 'cjk-input-visible' },
setSelectionRange: () => {},
setAttribute: vi.fn((k: string, v: string) => {
attrs[k] = v;
}),
addEventListener: (ev: string, fn: (e?: unknown) => void) => {
listeners.set(ev, [...(listeners.get(ev) ?? []), fn]);
},
removeEventListener: (ev: string, fn: (e?: unknown) => void) => {
listeners.set(
ev,
(listeners.get(ev) ?? []).filter((f) => f !== fn)
);
},
fire(ev: string, arg: Record<string, unknown> = {}) {
const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg };
for (const fn of listeners.get(ev) ?? []) fn(base);
},
};
}
function load({
hold = true,
promptResult = true,
touch = true,
translate,
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const prompts: string[] = [];
const layout = vi.fn();
// The shell bar's one-shot Ctrl, reduced to its armed flag.
const bar = {
armed: false,
isCtrlArmed() {
return this.armed;
},
clearCtrl() {
this.armed = false;
},
};
const context = vm.createContext({
window: translate ? { CodemanI18n: { t: translate } } : {},
document: {
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
activeElement: null,
body: { classList: { contains: (c: string) => touch && c === 'touch-device' } },
},
navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' },
KeyboardHandler: { updateLayoutForKeyboard: layout },
KeyboardAccessoryBar: bar,
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
performance: { now: () => performance.now() },
console,
});
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8');
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({
send: (t: string) => sent.push(t),
sendPrompt: (t: string) => {
prompts.push(t);
return promptResult;
},
});
CjkInput.setHoldUntilEnter(hold);
textarea.fire('focus');
return { CjkInput, textarea, sent, prompts, layout, bar };
}
function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
textarea.value = PHANTOM + text;
textarea.fire('input', { isComposing: false, inputType: 'insertText' });
}
function backspace(textarea: ReturnType<typeof makeTextarea>, valueAfter: string) {
textarea.value = valueAfter;
textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' });
}
const enter = (textarea: ReturnType<typeof makeTextarea>) =>
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
describe('CJK input: Send on Enter', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] });
});
afterEach(() => {
vi.useRealTimers();
});
it('keeps typed text in the field instead of streaming it', () => {
const { textarea, sent } = load();
type(textarea, 'use Postgres');
vi.advanceTimersByTime(5000);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'use Postgres');
});
it('keeps text after a physical keystroke (no zero-latency flush)', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false });
type(textarea, 'a');
vi.advanceTimersByTime(1000);
expect(sent).toEqual([]);
});
it('keeps text across a composition cycle and autocorrect rewrites', () => {
const { textarea, sent } = load();
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'teh';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
textarea.value = PHANTOM + 'the';
textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' });
vi.advanceTimersByTime(5000);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'the');
});
it('sends one line on Enter through the prompt path, then clears the field', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'yes, use Postgres');
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(prompts).toEqual(['yes, use Postgres']);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('never writes text and Enter together, whatever the length', () => {
// Codex takes characters arriving in one burst as a paste and folds an Enter
// inside it into the paste, so even `1\r` in one write stays unsent; Claude
// Code does the same for a long burst. terminal-ui.js _sendCjkPrompt types a
// single character and pastes anything longer, Enter always on its own.
const { textarea, sent, prompts } = load();
for (const answer of ['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]) {
type(textarea, answer);
enter(textarea);
}
expect(sent).toEqual([]);
expect(prompts).toEqual(['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]);
expect(textarea.value).toBe(PHANTOM);
});
it('keeps a short answer in the field when it is refused (no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'yes');
enter(textarea);
expect(prompts).toEqual(['yes']);
expect(textarea.value).toBe(PHANTOM + 'yes');
});
it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'line one\nline two');
enter(textarea);
vi.advanceTimersByTime(500);
expect(prompts).toEqual(['line one\nline two']);
expect(sent).toEqual([]);
});
it('keeps the text in the field when the prompt is refused (too long, no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'line one\nline two');
enter(textarea);
expect(prompts).toHaveLength(1);
expect(textarea.value).toBe(PHANTOM + 'line one\nline two');
});
it('treats Shift+Enter as a newline, never a send', () => {
const { textarea, sent } = load();
type(textarea, 'first');
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault });
vi.advanceTimersByTime(10);
expect(preventDefault).not.toHaveBeenCalled();
expect(sent).toEqual([]);
});
it('sends a bare Enter when the field is empty (accepting a default answer)', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
expect(sent).toEqual(['\r']);
});
it('still forwards Backspace on an empty field to the PTY', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'Backspace', keyCode: 8 });
expect(sent).toEqual(['\x7f']);
});
it('does not send Backspace when deleting the last held character', () => {
// The CLI's own composer may hold text (Attach, image paste, Path, mic):
// a stray DEL would eat its last character.
const { textarea, sent } = load();
type(textarea, 'a');
type(textarea, 'ab');
backspace(textarea, PHANTOM + 'a');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('sends Backspace once the field is empty and the phantom itself is deleted', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
backspace(textarea, '');
expect(sent).toEqual(['\x7f']);
expect(textarea.value).toBe(PHANTOM);
});
it('does not send Backspace for select-all + delete of held text', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, '');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('deletes held text right after typing it, before any debounce, without a DEL', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
vi.advanceTimersByTime(2000);
expect(sent).toEqual([]);
});
it('puts the phantom back when Backspace at the start of the text deleted it', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, 'abc');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'abc');
});
it('one-shot Ctrl: the next typed character goes out instead of being held', () => {
// _handleCjkInput turns the single character into the control byte.
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'c');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: held text stays and only the new character leaves the field', () => {
const { textarea, sent, bar } = load();
type(textarea, 'ab');
bar.armed = true;
type(textarea, 'abc');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM + 'ab');
});
it('one-shot Ctrl: a character committed by an IME composition also goes out', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'c';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
vi.advanceTimersByTime(10);
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'hello');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'hello');
expect(bar.armed).toBe(false);
});
it('Escape clears the held text without sending', () => {
const { textarea, sent } = load();
type(textarea, 'never mind');
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('turning the mode off drops the held draft and the stashes, so live mode sends only new keys', () => {
const { CjkInput, textarea, sent } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'rm -rf build\nsecond line');
CjkInput.stashDraft('session-b');
CjkInput.setHoldUntilEnter(false);
expect(textarea.value).toBe(PHANTOM);
type(textarea, 'x');
vi.advanceTimersByTime(1000);
expect(sent).toEqual(['x']);
CjkInput.setHoldUntilEnter(true);
CjkInput.clear();
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('stays one line on a desktop, where growing would resize the PTY', () => {
const { textarea, layout } = load({ touch: false });
layout.mockClear();
textarea.scrollHeight = 60;
type(textarea, 'a\nb\nc');
vi.advanceTimersByTime(1000);
expect(textarea.style.height).toBe('');
expect(layout).not.toHaveBeenCalled();
});
it('translates its placeholder itself, since i18n.js skips textareas', () => {
const { CjkInput, textarea } = load({ translate: (s) => `zh:${s}` });
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
CjkInput.setHoldUntilEnter(false);
expect(textarea.placeholder).toBe('zh:CJK input (Enter = send, Esc = clear)');
});
it('turns autocorrect on in the mode and back off without it', () => {
const { CjkInput, textarea } = load();
expect(textarea.attrs.autocorrect).toBe('on');
expect(textarea.attrs.spellcheck).toBe('true');
CjkInput.setHoldUntilEnter(false);
expect(textarea.attrs.autocorrect).toBe('off');
expect(textarea.attrs.spellcheck).toBe('false');
expect(CjkInput.holdUntilEnter).toBe(false);
});
it('grows the field with its text and re-runs the keyboard layout', () => {
const { textarea, layout } = load();
layout.mockClear();
textarea.scrollHeight = 60;
type(textarea, 'a\nb\nc');
vi.advanceTimersByTime(1000);
// scrollHeight + the 2px of border, so a two-line draft does not scroll inside.
expect(textarea.style.height).toBe('62px');
expect(layout).toHaveBeenCalled();
});
it('leaves the field alone when the mode is set again unchanged', () => {
// Runs on every session select and SSE reconnect, possibly mid-composition.
const { CjkInput, textarea } = load();
textarea.setAttribute.mockClear();
const placeholder = textarea.placeholder;
let writes = 0;
Object.defineProperty(textarea, 'placeholder', {
get: () => placeholder,
set: () => {
writes++;
},
});
CjkInput.setHoldUntilEnter(true);
expect(textarea.setAttribute).not.toHaveBeenCalled();
expect(writes).toBe(0);
CjkInput.setHoldUntilEnter(false);
expect(textarea.setAttribute).toHaveBeenCalled();
});
it('follows a live language switch with the mode unchanged', () => {
// App Settings runs applyLocalization(), then _updateCjkInputState(), which
// calls setHoldUntilEnter() with the same mode.
let lang = 'en';
const { CjkInput, textarea } = load({ translate: (s) => (lang === 'zh' ? `zh:${s}` : s) });
expect(textarea.placeholder).toBe('Type, Enter to send (Shift+Enter: new line, Esc: clear)');
textarea.setAttribute.mockClear();
lang = 'zh';
CjkInput.setHoldUntilEnter(true);
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
expect(textarea.setAttribute).not.toHaveBeenCalled();
});
it('submit() from outside the field (toolbar Enter) sends like Enter', () => {
const { CjkInput, textarea, prompts, sent } = load();
type(textarea, 'go ahead');
expect(CjkInput.submit()).toBe(true);
expect(prompts).toEqual(['go ahead']);
expect(textarea.value).toBe(PHANTOM);
expect(CjkInput.submit()).toBe(true);
expect(sent).toEqual(['\r']);
});
it('submit() keeps a refused answer and reports it', () => {
const { CjkInput, textarea } = load({ promptResult: false });
type(textarea, 'go ahead');
expect(CjkInput.submit()).toBe(false);
expect(textarea.value).toBe(PHANTOM + 'go ahead');
});
it('a draft stashed on a switch comes back for its own session only', () => {
const { CjkInput, textarea, sent, prompts } = load();
type(textarea, 'half an answer');
CjkInput.stashDraft('session-a');
CjkInput.clear();
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'half an answer');
// Restored once: the stash is consumed, so once the user empties the
// field (Esc here) a second visit does not bring it back. A draft still in
// the field when the session is left is stashed again by clear().
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
expect(sent).toEqual([]);
expect(prompts).toEqual([]);
});
it('a restored draft is held text: Backspace edits it without a DEL', () => {
const { CjkInput, textarea, sent } = load();
type(textarea, 'ok');
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
backspace(textarea, PHANTOM + 'o');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
});
it('an empty field stashes nothing, and a discarded draft is gone', () => {
const { CjkInput, textarea } = load();
type(textarea, 'draft');
CjkInput.stashDraft('session-a');
CjkInput.discardDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
CjkInput.stashDraft('session-b');
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('a switch with an empty field keeps the draft already stashed for that session', () => {
// The tile grid stashes the session it parks, then may stash it again from
// tile focus with the field already cleared.
const { CjkInput, textarea } = load();
type(textarea, 'keep me');
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.stashDraft('session-a');
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'keep me');
});
it('clear() stashes a held draft for the session it was typed for, with no stash call', () => {
// goHome(), _replaceTileGrid and _onTileAdoptedElsewhere drop the active
// session before the next cleanup, which then has no session to stash for.
const { CjkInput, textarea, sent } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'typed for a');
CjkInput.clear();
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'typed for a');
expect(sent).toEqual([]);
});
it('clear({ discard }) throws the draft away: a same-tab restore and a switch back stay empty', () => {
// The keyboard bar's clear-line key (terminal-ui.js clearTerminalInput).
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'thrown away');
CjkInput.clear({ discard: true });
expect(textarea.value).toBe(PHANTOM);
expect(CjkInput.draftOwner).toBe('session-a');
// Tapping the session's own tab: the field is kept, then restoreDraft runs.
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
// Switching away and back.
CjkInput.clear();
CjkInput.restoreDraft('session-b');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('clear({ discard }) also drops an older stash of the same session', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'old');
CjkInput.stashDraft('session-a');
CjkInput.clear({ discard: true });
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('a removed session loses its field text: discardDraft drops the owner', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'for a closed tile');
CjkInput.discardDraft('session-a');
expect(CjkInput.draftOwner).toBe(null);
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('a field still holding text keeps its owner when another session is shown', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'still for a');
CjkInput.restoreDraft('session-b');
expect(CjkInput.draftOwner).toBe('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'still for a');
});
it('Ctrl shortcuts stay in the field while it holds a draft', () => {
// Ctrl+Z is undo, Ctrl+A select all, Ctrl+C copy: never a control byte to
// the CLI while there is a draft to act on.
const { textarea, sent } = load();
type(textarea, 'draft');
for (const key of ['z', 'a', 'c']) {
const preventDefault = vi.fn();
textarea.fire('keydown', { key, keyCode: key.toUpperCase().charCodeAt(0), ctrlKey: true, preventDefault });
expect(preventDefault).not.toHaveBeenCalled();
}
expect(sent).toEqual([]);
});
it('Ctrl shortcuts reach the CLI from an empty field', () => {
const { textarea, sent } = load();
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true, preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(sent).toEqual(['\x03']);
});
it('live mode keeps sending Ctrl shortcuts with text in the field', () => {
const { textarea, sent } = load({ hold: false });
textarea.value = PHANTOM + 'x';
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true });
expect(sent).toEqual(['\x03']);
});
it('sends a bare Enter when the field holds only blank lines', () => {
const { textarea, sent, prompts } = load();
type(textarea, '\n');
enter(textarea);
expect(prompts).toEqual([]);
expect(sent).toEqual(['\r']);
});
it('submit() mid-composition commits it first (blur, focus) and sends what landed', () => {
const { CjkInput, textarea, prompts } = load();
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'yes';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
expect(CjkInput.submit()).toBe(true);
expect(textarea.blur).toHaveBeenCalled();
expect(textarea.focus).toHaveBeenCalled();
expect(prompts).toEqual(['yes']);
expect(textarea.value).toBe(PHANTOM);
});
it('a hidden field does not get a 0px height (no session shown yet)', () => {
const { CjkInput, textarea } = load({ hold: false });
textarea.getClientRects = () => [];
textarea.scrollHeight = 0;
textarea.style.height = '40px';
CjkInput.setHoldUntilEnter(true);
expect(textarea.style.height).toBe('');
});
it('live mode stashes no drafts', () => {
const { CjkInput, textarea } = load({ hold: false });
textarea.value = PHANTOM + 'abc';
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('live mode is unchanged: text streams after the debounce', () => {
const { textarea, sent } = load({ hold: false });
type(textarea, 'hi');
vi.advanceTimersByTime(1000);
expect(sent).toEqual(['hi']);
});
});
+174
View File
@@ -0,0 +1,174 @@
// Port: none (pure logic in a vm context — no browser, no server).
//
// KeyboardHandler scrolls a newly focused text field into view (scrollInputIntoView,
// `scrollIntoView({ block: 'center' })`) once the keyboard is up. The pinned CJK /
// Send on Enter field (#cjkInput) is position:fixed and already lifted above the
// keyboard by updateLayoutForKeyboard(), so scrolling it into view only centred it in
// its scrollable ancestors and pushed the terminal off screen. It must be skipped,
// like xterm's own inputs, while ordinary inputs keep the behaviour.
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/mobile-handlers.js'), 'utf8');
function loadHandler() {
const context = vm.createContext({
console,
navigator: { userAgent: 'test', maxTouchPoints: 1 },
window: { addEventListener: () => {}, matchMedia: () => ({ matches: false }), scrollTo: () => {} },
document: {
body: { classList: { add: () => {}, remove: () => {} } },
addEventListener: () => {},
getElementById: () => null,
querySelector: () => null,
},
setTimeout: () => 1,
clearTimeout: () => {},
});
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
return (context as { __KH: any }).__KH;
}
function element(tagName: string, { id = '', inside = '' }: { id?: string; inside?: string } = {}) {
return { tagName, id, type: '', isContentEditable: false, closest: (sel: string) => (sel === inside ? {} : null) };
}
describe('KeyboardHandler.isInputElement', () => {
it('skips the pinned CJK field, which the keyboard layout positions itself', () => {
expect(loadHandler().isInputElement(element('TEXTAREA', { id: 'cjkInput' }))).toBe(false);
});
it('still skips xterm inputs and still scrolls ordinary fields into view', () => {
const kh = loadHandler();
expect(kh.isInputElement(element('TEXTAREA', { inside: '.xterm' }))).toBe(false);
expect(kh.isInputElement(element('TEXTAREA', { id: 'someOtherField' }))).toBe(true);
expect(kh.isInputElement(element('INPUT'))).toBe(true);
});
});
function loadLayout({
focused = 'cjkInput',
offsetTop,
height = 458,
width = 390,
innerHeight = 744,
clientHeight = 744,
}: {
focused?: string;
offsetTop: number;
height?: number;
width?: number;
innerHeight?: number;
clientHeight?: number;
}) {
const el = (offsetHeight = 36) => ({
style: {} as Record<string, string>,
offsetHeight,
classList: { contains: () => true },
});
// .app is sized to the visual viewport (--app-height), which is what its fixed
// children are placed against once it carries a transform.
const nodes: Record<string, any> = {
'.app': el(height),
'.toolbar': el(),
'.main': el(),
'.keyboard-accessory-bar': el(),
'.mobile-case-picker.active .mobile-case-picker-sheet': el(300),
};
const cjk = { ...el(), id: 'cjkInput' };
const context = vm.createContext({
console,
navigator: { userAgent: 'test', maxTouchPoints: 1 },
window: {
addEventListener: () => {},
matchMedia: () => ({ matches: false }),
scrollTo: () => {},
innerHeight,
innerWidth: width, // MobileDetection (defined in the module) reads this
visualViewport: { offsetTop, height },
},
document: {
body: { classList: { add: () => {}, remove: () => {} } },
documentElement: { clientHeight },
addEventListener: () => {},
activeElement: focused === 'cjkInput' ? cjk : { id: focused },
getElementById: (id: string) => (id === 'cjkInput' ? cjk : null),
querySelector: (sel: string) => nodes[sel] || null,
},
setTimeout: () => 1,
clearTimeout: () => {},
});
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
const kh = (context as { __KH: any }).__KH;
kh.keyboardVisible = true;
kh.initialViewportHeight = 744;
return { kh, nodes, cjk };
}
describe('KeyboardHandler follows the visual-viewport pan on phones', () => {
it('moves the app down by the pan and lifts nothing more (measured Android case)', () => {
const { kh, nodes, cjk } = loadLayout({ offsetTop: 285 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
// .app bottom = 285 + 458 = 743, visual bottom = 743: the bars already sit on it.
expect(nodes['.toolbar'].style.transform).toBe('');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
expect(cjk.style.transform).toBe('');
});
it('does not lift the bars twice on a partial pan', () => {
// Mid-animation: offsetTop 100 in a 744 layout. Lifting by the layout gap (186px)
// inside the shifted .app would float the bars 186px above the keyboard.
const { kh, nodes, cjk } = loadLayout({ offsetTop: 100 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(100px)');
expect(nodes['.toolbar'].style.transform).toBe('');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
expect(cjk.style.transform).toBe('');
// The open case sheet is inside .app too (index.html #mobileCasePickerModal):
// the layout gap on top of the shift floated it 186px above the keyboard.
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('');
});
it('keeps the old lift when there is no pan', () => {
const { kh, nodes } = loadLayout({ offsetTop: 0 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('');
expect(nodes['.toolbar'].style.transform).toBe('translateY(-286px)');
// Without a pan insideLift is the layout gap, so the case sheet keeps its lift
// (test/mobile-case-sheet-keyboard-lift.test.ts).
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('translateY(-286px)');
});
it('follows a pan whatever has focus, so a focus change cannot drop the shift', () => {
const { kh, nodes } = loadLayout({ focused: 'someOtherField', offsetTop: 285 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
});
it('never shifts the app outside the phone layout (tablet landscape)', () => {
const { kh, nodes } = loadLayout({ offsetTop: 285, width: 1024 });
nodes['.app'].style.transform = 'translateY(285px)'; // left over from portrait
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('');
});
it('lifts the bars when iOS reports innerHeight as the shrunk visual height', () => {
// Measured on an iPhone, first keyboard open: innerHeight 323 = visual height,
// documentElement.clientHeight 640. Lifting by innerHeight - visual bottom gave 0.
const { kh, nodes, cjk } = loadLayout({ offsetTop: 0, height: 323, innerHeight: 323, clientHeight: 640 });
kh.updateLayoutForKeyboard();
expect(nodes['.toolbar'].style.transform).toBe('translateY(-317px)');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('translateY(-317px)');
expect(cjk.style.transform).toBe('translateY(-317px)');
});
it('clears the shift when the layout resets', () => {
const { kh, nodes } = loadLayout({ offsetTop: 285 });
kh.updateLayoutForKeyboard();
kh.resetLayout();
expect(nodes['.app'].style.transform).toBe('');
});
});
+138 -2
View File
@@ -41,8 +41,9 @@ function loadTerminalModule(): TerminalModule {
console,
setInterval: vi.fn(),
clearInterval: vi.fn(),
setTimeout,
clearTimeout,
// Looked up per call, so a test's vi.useFakeTimers() reaches the cached module.
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
@@ -547,6 +548,141 @@ describe('one-shot Ctrl through the CJK input field', () => {
});
});
describe('Send on Enter: a held answer goes out with Enter as its own write', () => {
// _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one
// character goes to the composer's _sendComposedPrompt with the session
// captured at Enter, so the delayed Enter cannot follow a tab switch.
function promptApp() {
const { CodemanApp, bar } = loadTerminalModule();
bar.clearCtrl();
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string | null;
_sendCjkPrompt(text: string): boolean;
};
app.activeSessionId = 'session-a';
const composed = vi
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
.mockReturnValue(true);
return { app, bar, composed };
}
it('sends through the composer path, bound to the session active at Enter', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
app.activeSessionId = 'session-b';
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
composed.mockRestore();
});
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
const { app, bar, composed } = promptApp();
bar.toggleCtrl();
app._sendCjkPrompt('x'.repeat(100));
expect(bar.isCtrlArmed()).toBe(false);
composed.mockRestore();
});
it('types a single character, then Enter ~120 ms later to the same session', () => {
// Codex folds an Enter that arrives in the same burst as the text into a
// paste, even for `1\r`; a selection dialog ignores a pasted digit. Same
// split as TmuxManager.sendInput (submitsAsKeys).
vi.useFakeTimers();
try {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) =>
writes.push([id, input, opts]);
expect(app._sendCjkPrompt('1')).toBe(true);
expect(writes).toEqual([['session-a', '1', undefined]]);
app.activeSessionId = 'session-b';
vi.advanceTimersByTime(119);
expect(writes).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]);
expect(composed).not.toHaveBeenCalled();
composed.mockRestore();
} finally {
vi.useRealTimers();
}
});
it('sends a lone digit without Enter while a permission or question dialog waits', () => {
// The dialog acts on the digit keypress itself; an Enter 120 ms later would
// confirm whatever the CLI shows next (a second permission prompt, unseen).
// Same rule as the Approvals Inbox and the Discord bridge (awaitingChoice).
vi.useFakeTimers();
try {
for (const hook of ['permission_prompt', 'elicitation_dialog']) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt('2')).toBe(true);
vi.advanceTimersByTime(500);
expect(writes).toEqual([['session-a', '2', undefined]]);
composed.mockRestore();
}
} finally {
vi.useRealTimers();
}
});
it('keeps the delayed Enter for a digit when only an idle prompt is pending, or for a letter in a dialog', () => {
vi.useFakeTimers();
try {
const cases: Array<[string, string]> = [
['idle_prompt', '1'],
['permission_prompt', 'y'],
];
for (const [hook, text] of cases) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt(text)).toBe(true);
vi.advanceTimersByTime(120);
expect(writes).toEqual([
['session-a', text, undefined],
['session-a', '\r', { useMux: true }],
]);
composed.mockRestore();
}
} finally {
vi.useRealTimers();
}
});
it('pastes even a short word: only one character is typed', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('yes')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'yes');
composed.mockRestore();
});
it('reports a refusal so the field keeps the text', () => {
const { app, composed } = promptApp();
composed.mockReturnValue(false);
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
app.activeSessionId = null;
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('1')).toBe(false);
expect(composed).toHaveBeenCalledTimes(1);
composed.mockRestore();
});
});
describe('armed styling survives the light-skin overrides', () => {
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');
+18
View File
@@ -0,0 +1,18 @@
/**
* @fileoverview The manifest link must be fetched with credentials. Browsers fetch the web app
* manifest without cookies unless the link says `crossorigin="use-credentials"`, and every
* non-exempt path needs the `codeman_session` cookie when a password is set, so without the
* attribute the manifest answers 401 and the browser refuses to install Codeman as an app.
*/
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
const HTML = readFileSync(new URL('../src/web/public/index.html', import.meta.url), 'utf-8');
describe('PWA manifest link', () => {
it('requests the manifest with credentials so a password-protected install can be installed', () => {
const links = HTML.match(/<link\b[^>]*rel="manifest"[^>]*>/g) ?? [];
expect(links).toHaveLength(1);
expect(links[0]).toContain('crossorigin="use-credentials"');
});
});
+72
View File
@@ -181,6 +181,78 @@ describe('WebServer.renderIndexHtml', () => {
}
});
it('injects the wheelForward rules of every CLI that forwards, custom and disabled entries included', async () => {
// A custom clis.json entry shaped like pi (its mouse DECSETs stripped, wheel forwarded)
// must reach the browser's gate by its own id, and every `never` stays out. A DISABLED
// entry stays in: disabling a CLI never ends its running sessions, so a fullscreen copilot
// tab opened before the switch still needs its wheel after a reload (and an entry enabled
// after the page loaded already has its rule). A solo window scrolls a terminal too, so
// it gets the same map.
const path = dataPath('clis.json');
mkdirSync(dirname(path), { recursive: true });
const custom = {
label: 'PiD',
shortBadge: 'PL',
accent: '#6b7280',
enabled: true,
order: 120,
kind: 'agent',
discovery: { binaries: ['pi-locked'], searchDirs: [], install: { command: {} } },
launch: { params: {}, variants: [{ id: 'default', args: [{ lit: 'pi-locked' }] }] },
env: { exports: [], unset: [], tmuxSetenvKeys: [], dockerExecEnvNames: [], allowedPrefixes: [], allowedKeys: [] },
capabilities: {
external: true,
requiresMux: true,
hooks: 'none',
transcript: 'none',
altScreen: 'strip-mux-and-mouse',
echo: { policy: 'buffer', anchor: { kind: 'none' } },
wheelForward: { mode: 'always' },
keyboardAccessory: 'agent',
privilegedCommandGate: false,
startMode: 'interactive',
stripInkBloat: false,
ralph: false,
respawn: false,
effort: false,
agentSkillInjection: false,
statusLineTelemetry: false,
model: { source: 'none' },
privilegedParams: [],
privilegedEnvKeys: [],
gates: {},
customModelInjection: { kind: 'unsupported' },
},
overlays: {},
};
writeFileSync(
path,
JSON.stringify({ schemaVersion: 1, clis: { copilot: { enabled: false }, 'pi-locked': custom } }),
{
mode: 0o600,
}
);
reloadCliRegistry();
try {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer({});
const html = await render(server, solo);
const match = html.match(/window\.__codemanWheelForward=(\{[^<]*\});/);
expect(match, String(solo)).not.toBeNull();
expect(JSON.parse(match![1])).toEqual({
claude: { mode: 'version-gated', minVersion: '2.1.187' },
codex: { mode: 'always' },
pi: { mode: 'always' },
copilot: { mode: 'always' },
'pi-locked': { mode: 'always' },
});
}
} finally {
writeFileSync(path, JSON.stringify({ clis: {} }, null, 2), { mode: 0o600 });
reloadCliRegistry();
}
});
it('injects the keyboard-hold modes from the keyboardHold capability: inline Claude, never full-height codex', async () => {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer();
+339
View File
@@ -9,7 +9,11 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import fastifyWebsocket from '@fastify/websocket';
import WebSocket, { WebSocketServer } from 'ws';
import { once } from 'node:events';
import type { AddressInfo } from 'node:net';
import fs from 'node:fs/promises';
import http, { createServer, type IncomingHttpHeaders, type Server } from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { registerWebviewRoutes } from '../../src/web/routes/webview-routes.js';
@@ -17,12 +21,28 @@ import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { webviewCapabilities } from '../../src/webview-capabilities.js';
import { capabilityFromProxyPath } from '../../src/web/webview-proxy.js';
import { writeWebviews } from '../../src/webview-store.js';
import { readUsers } from '../../src/user-store.js';
import { TabLayoutService } from '../../src/tab-layout-service.js';
import type { TabLayout } from '../../src/tab-layout.js';
/**
* The supervisor is the one process-spawning piece in this path. Its own tests
* cover the launch-token exchange and the starter binding; here a stub stands in
* for "this port has a cookie" so the route-level question stays what the proxy
* actually puts on the upstream request.
*/
const { getDeepSeekWebCookie } = vi.hoisted(() => ({
getDeepSeekWebCookie: vi.fn((_port: number, _owner?: string): string | null => null),
}));
vi.mock('../../src/deepseek-web-server.js', () => ({ getDeepSeekWebCookie }));
let app: FastifyInstance;
let tmpDir: string;
let savedDataDir: string | undefined;
let savedMultiUser: string | undefined;
/** Stands in for what the auth middleware decorates on the request. */
let currentUser: { username: string; role: 'admin' | 'user' } | undefined;
const broadcasts: Array<{ event: string; data: unknown }> = [];
const webviewCreated = vi.fn(async () => {});
const webviewDeleted = vi.fn(async () => {});
@@ -30,15 +50,23 @@ const webviewDeleted = vi.fn(async () => {});
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'codeman-webviews-'));
savedDataDir = process.env.CODEMAN_DATA_DIR;
savedMultiUser = process.env.CODEMAN_MULTIUSER;
process.env.CODEMAN_DATA_DIR = tmpDir;
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
broadcasts.length = 0;
webviewCreated.mockClear();
webviewDeleted.mockClear();
getDeepSeekWebCookie.mockReset();
getDeepSeekWebCookie.mockReturnValue(null);
app = Fastify({ logger: false });
await app.register(fastifyCookie);
// The proxy route declares a wsHandler, so the plugin must be present.
await app.register(fastifyWebsocket);
app.addHook('onRequest', async (req) => {
if (currentUser) (req as unknown as { authUser: typeof currentUser }).authUser = currentUser;
});
registerWebviewRoutes(app, {
broadcast: (event: string, data: unknown) => broadcasts.push({ event, data }),
tabLayouts: { webviewCreated, webviewDeleted },
@@ -51,11 +79,22 @@ afterEach(async () => {
await app.close();
if (savedDataDir === undefined) delete process.env.CODEMAN_DATA_DIR;
else process.env.CODEMAN_DATA_DIR = savedDataDir;
if (savedMultiUser === undefined) delete process.env.CODEMAN_MULTIUSER;
else process.env.CODEMAN_MULTIUSER = savedMultiUser;
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
const create = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/webviews', payload });
/** Wait for something a relayed connection reports asynchronously. */
async function waitUntil(check: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!check()) {
if (Date.now() > deadline) throw new Error('condition not met in time');
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
describe('GET /api/webviews', () => {
it('starts empty and reports the frame budget the client must honour', async () => {
const res = await app.inject({ method: 'GET', url: '/api/webviews' });
@@ -268,6 +307,306 @@ describe('proxy route', () => {
});
});
describe('proxy route: WebSocket cookie forwarding', () => {
let upstream: Server;
let upstreamPort: number;
let wss: WebSocketServer;
let appPort: number;
let upgradeHeaders: Promise<IncomingHttpHeaders>;
let client: WebSocket | undefined;
beforeEach(async () => {
let resolveUpgrade!: (headers: IncomingHttpHeaders) => void;
upgradeHeaders = new Promise((resolve) => {
resolveUpgrade = resolve;
});
// A real loopback dashboard: its upgrade handler is what records the cookie
// the proxy put on the handshake.
upstream = createServer();
wss = new WebSocketServer({ noServer: true });
upstream.on('upgrade', (req, socket, head) => {
resolveUpgrade(req.headers);
wss.handleUpgrade(req, socket, head, (upstreamSocket) => {
wss.emit('connection', upstreamSocket, req);
});
});
await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));
upstreamPort = (upstream.address() as AddressInfo).port;
// WebSocket upgrades cannot go through inject(); this app needs a real port.
await app.listen({ port: 0, host: '127.0.0.1' });
appPort = (app.server.address() as AddressInfo).port;
});
afterEach(async () => {
client?.terminate();
client = undefined;
for (const socket of wss.clients) socket.terminate();
await new Promise<void>((resolve) => wss.close(() => resolve()));
await new Promise<void>((resolve) => upstream.close(() => resolve()));
await app.close();
});
/** Wait for a promise without letting a missing handshake hang the test until vitest's timeout. */
function within<T>(promise: Promise<T>, timeoutMs = 5000): Promise<T> {
let timer!: NodeJS.Timeout;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('timed out waiting for the upstream WebSocket handshake')), timeoutMs);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
/** Create a trusted tab, open it for a capability, and connect the browser leg with `cookie`. */
async function connectThroughProxy(cookie: string): Promise<void> {
const created = await create({
name: 'Trusted dashboard',
url: `http://127.0.0.1:${upstreamPort}/`,
trusted: true,
});
expect(created.statusCode).toBe(200);
const opened = await app.inject({ method: 'POST', url: `/api/webviews/${created.json().data.id}/open` });
const cap = capabilityFromProxyPath(opened.json().data.embedUrl)!;
client = await new Promise<WebSocket>((resolve, reject) => {
const socket = new WebSocket(`ws://127.0.0.1:${appPort}/webview/${cap}/ws`, { headers: { cookie } });
socket.once('open', () => resolve(socket));
socket.once('error', reject);
});
}
it('forwards only the dashboard cookie, never the Codeman session cookie', async () => {
await connectThroughProxy('codeman_session=SECRET; theme=dark');
const headers = await within(upgradeHeaders);
expect(headers.cookie).toBe('theme=dark');
expect(headers.cookie).not.toContain('codeman_session');
});
it('sends no cookie header when the browser only has the Codeman session cookie', async () => {
await connectThroughProxy('codeman_session=SECRET');
const headers = await within(upgradeHeaders);
expect(headers.cookie).toBeUndefined();
});
});
describe('managed DeepSeek web cookie', () => {
const COOKIE = 'dsh-auth-test=v1.payload.sig';
const upstreams: Array<{ port: number; cookies: Array<string | undefined>; close: () => Promise<void> }> = [];
/** A real loopback listener, so the assertion is on the bytes dsh would receive. */
async function startUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer((req, res) => {
cookies.push(req.headers.cookie);
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('ok');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
upstreams.push(upstream);
return upstream;
}
/** The stub answers for one port and one owner, like the supervisor's two checks. */
function mintCookieOn(port: number, owner: string | undefined): void {
getDeepSeekWebCookie.mockImplementation((askedPort, askedOwner) =>
askedPort === port && askedOwner === owner ? COOKIE : null
);
}
async function openManaged(url: string): Promise<string> {
const created = (await create({ name: 'DeepSeek Harness', url, managed: 'deepseek-web', trusted: true })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
return capabilityFromProxyPath(opened.embedUrl)!;
}
const getThrough = (cap: string) => app.inject({ method: 'GET', url: `/webview/${cap}/` });
async function writeUsersFixture(users: Array<{ username: string; role: string; canBypassPermissions: boolean }>) {
await fs.writeFile(
path.join(tmpDir, 'users.json'),
JSON.stringify({
version: 1,
users: users.map((user) => ({
...user,
password: { algo: 'scrypt', N: 1, r: 1, p: 1, salt: '00', hash: '00' },
createdAt: 1,
})),
})
);
// The store keeps a short cache; write through it instead of waiting for the TTL.
await readUsers(true);
}
afterEach(async () => {
await Promise.all(upstreams.splice(0).map((upstream) => upstream.close()));
});
it('presents it to a managed tab on 127.0.0.1 at the minted port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
it('presents nothing to a managed tab on another port', async () => {
const minted = await startUpstream();
const other = await startUpstream();
mintCookieOn(minted.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${other.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(other.cookies).toEqual([undefined]);
});
it('presents nothing to an unmanaged tab on the same port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const created = (await create({ name: 'Not managed', url: `http://127.0.0.1:${upstream.port}/` })).json().data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
// `managed` comes from the client and the port is public, so this is the case
// the gate exists for: a regular user must not receive the starter's cookie.
it('presents nothing in multi-user mode when the owner has no privileged grant', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'bob', role: 'user' };
await writeUsersFixture([{ username: 'bob', role: 'user', canBypassPermissions: false }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'bob');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
it('presents it in multi-user mode to a granted owner who started the server', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'carol');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, 'carol');
});
// A record keeps the owner it was created under. Back in single-user mode the
// server is started with no starter, so comparing that stale owner would leave
// the tab on dsh's 401 for good.
it('presents it in single-user mode to a managed tab created under multi-user mode', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
mintCookieOn(upstream.port, undefined);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
/**
* A loopback listener that completes the upgrade and records the cookie on the
* handshake. The realtime leg is a separate code path from `proxyRequest`, so
* the HTTP assertions above say nothing about what it puts on the wire.
*/
async function startWebSocketUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
cookies.push(req.headers.cookie);
wss.handleUpgrade(req, socket, head, (client) => client.close());
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('ws upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () =>
new Promise<void>((resolve) => {
wss.close();
server.close(() => resolve());
}),
};
upstreams.push(upstream);
return upstream;
}
it('presents it on the websocket leg too, ahead of the browser cookies', async () => {
const upstream = await startWebSocketUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
// Upgrades need a real listener: inject() cannot carry them.
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address() as AddressInfo;
const client = new WebSocket(`ws://127.0.0.1:${port}/webview/${cap}/ws`, {
headers: { cookie: 'codeman_session=SECRET; dsh-ui=dark' },
});
await once(client, 'open');
await waitUntil(() => upstream.cookies.length > 0);
// The credential leads so a stale browser copy cannot win, other dashboard
// cookies survive, and Codeman's own session cookie never goes upstream.
expect(upstream.cookies).toEqual([`${COOKIE}; dsh-ui=dark`]);
client.close();
});
});
describe('proxy HTML rewrite', () => {
// The request path is what the page's relative URLs are relative to. Proving
// it here (rather than only on rewriteHtml) pins that proxyRequest passes it.
it("resolves the document's relative base against its own directory", async () => {
const server = http.createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<html><head><base href="./"></head><body>app</body></html>');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
try {
const created = (await create({ name: 'App', url: `http://127.0.0.1:${address.port}/app/page.html` })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
const res = await app.inject({ method: 'GET', url: `/webview/${cap}/app/page.html` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain(`<base href="/webview/${cap}/app/">`);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
});
describe('POST /api/webviews/probe', () => {
it('reports an unreachable target as a normal answer, not a 500', async () => {
// Port 1 is reserved and refuses instantly.
+3 -1
View File
@@ -117,7 +117,9 @@ describe('WebServer index.html <title> templating (#82)', () => {
// Likewise the page-key mode list: an array, possibly empty, always injected.
.replace(/<script>window\.__codemanTranscriptPageKeys=\[.*?\];<\/script>\n/, '')
// And the keyboard-hold mode list, built the same way.
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '');
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '')
// And the wheel-forwarding rules: an object keyed by run mode, always injected.
.replace(/<script>window\.__codemanWheelForward=\{.*?\};<\/script>\n/, '');
const beforeTitle = rawTemplate.split('<title>Codeman</title>')[0];
const afterTitle = rawTemplate.split('<title>Codeman</title>')[1];
expect(html.startsWith(beforeTitle)).toBe(true);
+102 -1
View File
@@ -28,8 +28,19 @@ import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
*/
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
/**
* The run modes that take the wheel as SGR reports, read off the shipped registry the way
* the server builds `__codemanWheelForward` (every `wheelForward` other than `never`).
*/
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
function loadTerminalUiHarness(
windowGlobals: Record<string, unknown> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES }
windowGlobals: Record<string, unknown> = {
__codemanTranscriptPageKeys: PAGE_KEY_MODES,
__codemanWheelForward: WHEEL_FORWARD,
}
) {
const CodemanApp = function CodemanApp(this: any) {};
const logs: string[] = [];
@@ -927,6 +938,96 @@ describe('pi wheel forwarding (fullscreen by default since 1.0.0)', () => {
});
});
describe('wheel forwarding read from the injected wheelForward map, for any CLI id', () => {
// A custom CLI (clis.json, e.g. a pi wrapper under its own id) that strips its mouse
// DECSETs gets `cliMouseTracking` like pi, but the gate used to name copilot and pi by id,
// so its wheel hit an empty local buffer after every tab switch or reload.
function customApp(
map: Record<string, unknown> | undefined,
session: { mode: string; cliMouseTracking?: boolean; cliVersion?: string }
) {
const globals: Record<string, unknown> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES };
if (map) globals.__codemanWheelForward = map;
const { app } = loadTerminalUiHarness(globals);
app.activeSessionId = 'sess-1';
app.sessions = new Map([['sess-1', session]]);
app.terminal = {
rows: 36,
modes: { mouseTrackingMode: 'none' },
buffer: { active: { type: 'normal', viewportY: 0, baseY: 0, length: 36 } },
};
return app;
}
it('forwards a custom id the map lists as always, only while it tracks the mouse', () => {
const map = { 'pi-locked': { mode: 'always' } };
const tracking = customApp(map, { mode: 'pi-locked', cliMouseTracking: true });
expect(tracking._shouldForwardWheelToApp({ shiftKey: false })).toBe(true);
expect(tracking._shouldForwardWheelToApp({ shiftKey: true })).toBe(false);
expect(customApp(map, { mode: 'pi-locked', cliMouseTracking: false })._shouldForwardWheelToApp({})).toBe(false);
expect(customApp(map, { mode: 'pi-locked' })._shouldForwardWheelToApp({})).toBe(false);
});
it('applies a version-gated rule to a custom id: at or above minVersion only, unknown version never', () => {
const map = { 'my-cli': { mode: 'version-gated', minVersion: '2.0.0' } };
const at = (cliVersion?: string) =>
customApp(map, { mode: 'my-cli', cliMouseTracking: true, cliVersion })._shouldForwardWheelToApp({});
expect(at('1.9.9')).toBe(false);
expect(at('2.0.0')).toBe(true);
expect(at('2.0.1')).toBe(true);
expect(at(undefined)).toBe(false);
});
it('a version-gated rule whose minVersion is not three numbers forwards nothing, whatever the CLI version', () => {
// The schema takes any string up to 20 characters. A minimum that cannot be read as
// MAJOR.MINOR.PATCH must refuse, the conservative answer an unreadable session version gets.
for (const minVersion of ['', '0', '2.0', '1.2.3.4', '0.bad.999', 'x.y.z', '2..0', '+2.0.0', '0x1.0.0']) {
const app = customApp(
{ 'my-cli': { mode: 'version-gated', minVersion } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({}), JSON.stringify(minVersion)).toBe(false);
}
// A well-formed minimum keeps working, a leading `v` and surrounding spaces included.
for (const minVersion of ['9.9.9', 'v2.0.0', ' 2.0.0 ']) {
const app = customApp(
{ 'my-cli': { mode: 'version-gated', minVersion } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({}), JSON.stringify(minVersion)).toBe(true);
}
});
it('a version-gated rule with no minVersion (the schema allows it) forwards nothing and does not throw', () => {
const app = customApp(
{ 'my-cli': { mode: 'version-gated' } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({})).toBe(false);
});
it('never forwards an id the map leaves out, and nothing at all from a page rendered without the map', () => {
expect(
customApp(
{ 'pi-locked': { mode: 'always' } },
{ mode: 'other', cliMouseTracking: true }
)._shouldForwardWheelToApp({})
).toBe(false);
for (const mode of ['claude', 'codex', 'copilot', 'pi']) {
expect(
customApp(undefined, { mode, cliMouseTracking: true, cliVersion: '9.9.9' })._shouldForwardWheelToApp({}),
mode
).toBe(false);
}
});
it('a map entry of mode never forwards, even for a stock id', () => {
expect(
customApp({ pi: { mode: 'never' } }, { mode: 'pi', cliMouseTracking: true })._shouldForwardWheelToApp({})
).toBe(false);
});
});
describe('the paging gates asked for another pane (a TerminalTile)', () => {
it('exports the paging math, and the primary pane runs on it', () => {
const { app, sent, windowRef } = hollowApp();
+6
View File
@@ -49,6 +49,11 @@ const fetchMock = vi.fn();
*/
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
/** The wheel-forwarding rules, read off the registry as the server builds `window.__codemanWheelForward`. */
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
/**
* The clock both panes read gesture gaps from (`performance.now()`). Real time by
* default; a test that needs a pause or a burst moves it by hand.
@@ -62,6 +67,7 @@ function loadContext() {
removeEventListener: vi.fn(),
CodemanBase: { base: '' },
__codemanTranscriptPageKeys: PAGE_KEY_MODES,
__codemanWheelForward: WHEEL_FORWARD,
};
const context = vm.createContext({
console: { ...console, log: vi.fn(), debug: vi.fn() },
+48 -2
View File
@@ -2,6 +2,12 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
/** The wheel-forwarding rules, read off the registry as the server builds `window.__codemanWheelForward`. */
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
function loadTerminalUiHarness() {
const CodemanApp = function CodemanApp(this: any) {};
@@ -10,7 +16,7 @@ function loadTerminalUiHarness() {
let activeElement: unknown = null;
// The module hangs its constants off window (CodemanTerminalInput) and the URL branch of
// the link provider opens through window.open, so tests need a handle on the same object.
const windowRef: Record<string, any> = {};
const windowRef: Record<string, any> = { __codemanWheelForward: WHEEL_FORWARD };
const context = vm.createContext({
window: windowRef,
document: {
@@ -139,6 +145,28 @@ describe('terminal touch tap mouse guard', () => {
expect(app._isMobileTerminalInputFocused()).toBe(true);
});
it('a content touchstart blurs xterm input but leaves the pinned CJK field focused', () => {
const { app, setActiveElement } = loadTerminalUiHarness();
setActiveElement({ id: '', classList: { contains: (c: string) => c === 'xterm-helper-textarea' } });
expect(app._contentTouchStartBlurs()).toBe(true);
// A swipe that starts on the live screen must not close the keyboard the field owns.
setActiveElement({ id: 'cjkInput', classList: { contains: () => false } });
expect(app._contentTouchStartBlurs()).toBe(false);
setActiveElement(null);
expect(app._contentTouchStartBlurs()).toBe(true);
});
it('the content touchstart only blurs through _contentTouchStartBlurs()', () => {
// The touchstart listener lives in initTerminal, which this harness does not run,
// so pin its one line: an unconditional blur there closes the pinned field's
// keyboard on every swipe that starts on the live screen.
const code = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
const branch = code.slice(code.indexOf("if (touchStartIntent === 'content') {"));
const body = branch.slice(0, branch.indexOf('// Hold still and this press becomes a text selection.'));
expect(body).toContain('if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();');
expect(body.match(/_blurMobileTerminalInput\(\)/g)).toHaveLength(1);
});
it('routes a readback row to the TUI while keeping the prompt row as keyboard input', () => {
const { app } = loadTerminalUiHarness();
app.activeSessionId = 'sess-1';
@@ -967,9 +995,27 @@ describe('terminal link tap', () => {
app._isOutsideWorktreePath = () => false;
windowRef.open = vi.fn();
app.registerFilePathLinkProvider();
return { app, windowRef, sent };
return { app, windowRef, sent, setActiveElement: harness.setActiveElement };
}
it('a link tap closes the keyboard of the pinned CJK field, which touchstart left focused', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
const cjk = { id: 'cjkInput', classList: { contains: () => false }, blur: vi.fn() };
setActiveElement(cjk);
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
expect(cjk.blur).toHaveBeenCalled();
});
it('a link tap leaves focus alone otherwise (touchstart already blurred xterm input)', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
const other = { id: '', classList: { contains: () => false }, blur: vi.fn() };
setActiveElement(other);
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
expect(other.blur).not.toHaveBeenCalled();
});
it('opens a URL under the finger in a new tab', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, windowRef } = linkHarness([line, '', '❯ ']);
+48 -4
View File
@@ -115,6 +115,32 @@ describe('restrictTmuxPrefixTable (recorded commands)', () => {
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false);
expect(tmux.calls.filter((c) => c.includes('bind-key'))).toEqual([]);
});
it('reads a one-binding table from the full listing when `list-keys -T prefix` prints nothing', () => {
// tmux 3.7 through 3.7c list a table holding exactly one binding as nothing at
// all on stdout (fixed in 3.8). The reduced table must still read as reduced, or every call resets it.
const tmux = fakeTmux({
'show-options -gv prefix': 'C-b\n',
'list-keys -T prefix': '',
'list-keys':
'bind-key -T copy-mode C-a send-keys -X start-of-line\n' +
'bind-key -T prefix C-b send-prefix\n' +
'bind-key -T root F1 detach-client\n',
});
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false);
expect(tmux.calls).toContain(`tmux -L 'codeman' list-keys`);
expect(tmux.calls.filter((c) => c.includes('bind-key') || c.includes('unbind-key'))).toEqual([]);
});
it('still resets when the full listing shows a stock prefix binding', () => {
const tmux = fakeTmux({
'show-options -gv prefix': 'C-b\n',
'list-keys -T prefix': '',
'list-keys': 'bind-key -T prefix ) switch-client -n\n',
});
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(true);
expect(tmux.calls).toContain(`tmux -L 'codeman' unbind-key -a -T prefix`);
});
});
const hasTmux = (() => {
@@ -126,12 +152,29 @@ const hasTmux = (() => {
}
})();
/**
* One key table as `list-keys -T <table>` prints it. tmux 3.7 through 3.7c (fixed in
* 3.8) print NOTHING there when the table holds exactly one binding,
* which is the shape every reset in this file produces, so a blank answer is read from
* the full listing instead, its padding folded to the `-T <table>` form.
*/
function listKeyTable(base: string, table: string): string {
const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const direct = run(`${base} list-keys -T ${table}`);
if (direct.trim()) return direct;
return run(`${base} list-keys`)
.split('\n')
.filter((line) => new RegExp(`^bind-key\\s+(?:-\\S+\\s+)*?-T\\s+${table}\\s`).test(line.trim()))
.map((line) => line.trim().replace(/-T\s+(\S+)\s+/, '-T $1 '))
.join('\n');
}
describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private socket)', () => {
// Throwaway server, never Codeman's socket; -f /dev/null keeps the user's config out.
const socket = `codeman-prefix-test-${process.pid}`;
const tmux = `tmux -L ${socket} -f /dev/null`;
const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const keys = (table: string) => run(`${tmux} list-keys -T ${table}`);
const keys = (table: string) => listKeyTable(tmux, table);
let client: pty.IPty | null = null;
/** The session the attach client is looking at right now. */
@@ -275,7 +318,8 @@ describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private
run(`${tmux} set-option -g prefix 'C-\\'`);
try {
expect(restrictTmuxPrefixTable(tmux, run)).toBe(true);
expect(keys('prefix')).toMatch(/-T prefix C-\\\\\s+send-prefix/);
// `list-keys -T` escapes the key (`C-\\`); the full listing some builds fall back to does not.
expect(keys('prefix')).toMatch(/-T prefix C-\\(?:\\)?\s+send-prefix/);
expect(restrictTmuxPrefixTable(tmux, run)).toBe(false);
} finally {
run(`${tmux} set-option -g prefix C-b`);
@@ -345,7 +389,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke
it('after the nested reset, Ctrl+Q ), s and w leave the client, and Ctrl+Q Ctrl+Q reaches the pane', async () => {
for (const command of nestedPrefixTableResetCommands()) run(`${tmux} ${command}`);
const prefix = run(`${tmux} list-keys -T prefix`)
const prefix = listKeyTable(tmux, 'prefix')
.split('\n')
.filter((line) => line.trim());
expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]);
@@ -381,7 +425,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke
].join(' \\; ');
try {
run(`${base} -f ${config} ${chain}`);
const prefix = run(`${base} list-keys -T prefix`)
const prefix = listKeyTable(base, 'prefix')
.split('\n')
.filter((line) => line.trim());
expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]);
+57
View File
@@ -13,6 +13,7 @@ import { describe, it, expect } from 'vitest';
import {
applyLiveMetrics,
applyMuxNames,
attachTargetError,
beginAttachHandoff,
buildAttachBanner,
buildListLines,
@@ -30,6 +31,7 @@ import {
planResume,
previewIntervalMs,
previewNoteFor,
resolveAttachTarget,
resyncDelayMs,
sameFrame,
samePreview,
@@ -915,3 +917,58 @@ describe('planResume', () => {
});
});
});
describe('resolveAttachTarget (codeman tui <session>)', () => {
function named(name: string, group: TuiRow['group'], sessionId: string): TuiRow {
return {
session: { sessionId, sources: ['live'], name },
state: group === 'recent' ? 'recent' : 'idle',
group,
since: 0,
};
}
const rows: TuiRow[] = [
named('api', 'working', 'aaaaaaaa01'),
named('docs', 'idle', 'bbbbbbbb02'),
named('twin', 'idle', 'cccccccc03'),
named('twin', 'needs-you', 'dddddddd04'),
named('old', 'recent', 'eeeeeeee05'),
named('docs', 'recent', 'ffffffff06'),
];
it('keeps digits-only as a list position, as a number or as a string', () => {
expect(resolveAttachTarget(rows, 2)).toEqual({ kind: 'row', row: rows[1] });
expect(resolveAttachTarget(rows, '2')).toEqual({ kind: 'row', row: rows[1] });
expect(resolveAttachTarget(rows, '7')).toEqual({ kind: 'none' });
});
it('attaches the one live session with that exact name, ignoring a finished namesake', () => {
expect(resolveAttachTarget(rows, 'api')).toEqual({ kind: 'row', row: rows[0] });
expect(resolveAttachTarget(rows, 'docs')).toEqual({ kind: 'row', row: rows[1] });
});
it('matches case-sensitively and never by prefix', () => {
expect(resolveAttachTarget(rows, 'API')).toEqual({ kind: 'none' });
expect(resolveAttachTarget(rows, 'ap')).toEqual({ kind: 'none' });
});
it('refuses a name two live sessions share, naming their positions', () => {
expect(resolveAttachTarget(rows, 'twin')).toEqual({ kind: 'ambiguous', positions: [3, 4] });
});
it('says a name only history carries is finished, not missing', () => {
expect(resolveAttachTarget(rows, 'old')).toEqual({ kind: 'finished' });
expect(resolveAttachTarget(rows, 'nope')).toEqual({ kind: 'none' });
});
it('words each refusal for a human and points at --list', () => {
expect(attachTargetError({ kind: 'ambiguous', positions: [3, 4] }, 'twin')).toMatch(
/2 live sessions are named twin \(3, 4 in the list\)[\s\S]*codeman tui 3/
);
expect(attachTargetError({ kind: 'finished' }, 'old')).toContain('no live session named old');
expect(attachTargetError({ kind: 'none' }, 'nope')).toContain('there is no session named nope');
expect(attachTargetError({ kind: 'none' }, 9)).toContain('there is no session 9');
for (const kind of ['finished', 'none'] as const)
expect(attachTargetError({ kind }, 'x')).toContain('codeman tui --list');
});
});
+32
View File
@@ -1015,3 +1015,35 @@ describe('resumeSession', () => {
expect(recorded).toHaveLength(1);
});
});
describe('TuiClient key-table reads on a tmux that lists a one-binding table as nothing', () => {
// tmux 3.7 through 3.7c (fixed in 3.8) print nothing for `list-keys -T prefix` when
// the table holds exactly one binding, which is how Codeman leaves it. Reading that as "free"
// would let the TUI claim a key the user has bound.
const fullListing =
'bind-key -T copy-mode C-a send-keys -X start-of-line\n' +
'bind-key -T prefix C-b send-prefix\n' +
'bind-key -T root F1 detach-client\n';
function client(direct: string) {
const calls: string[][] = [];
const exec = async (_file: string, args: readonly string[]) => {
calls.push([...args]);
return { stdout: args.includes('-T') ? direct : fullListing, stderr: '' };
};
return { tui: new TuiClient({ socket: 'cod563', exec }), calls };
}
it('falls back to the full listing when the table answer is blank', async () => {
const { tui, calls } = client('');
expect(await tui.readPrefixBinding('C-b')).toBe('send-prefix');
expect(await tui.readPrefixBinding('F1', 'root')).toBe('detach-client');
expect(await tui.readPrefixBinding('x')).toBeNull();
expect(calls.some((args) => args.length === 3 && args[2] === 'list-keys')).toBe(true);
});
it('keeps the table answer when there is one, with no second call', async () => {
const { tui, calls } = client('bind-key -T prefix d detach-client\n');
expect(await tui.readDetachKey()).toBe('d');
expect(calls).toEqual([['-L', 'cod563', 'list-keys', '-T', 'prefix']]);
});
});
+41
View File
@@ -778,6 +778,47 @@ describe('codeman tui --list', () => {
}, 30_000);
});
describe('codeman tui <session name>', () => {
it('resolves an exact live name before asking for a terminal', async () => {
const result = await runPiped(['tui', 'w1-alpha']);
expect(result.code).toBe(1);
// Got past resolution: the only refusal left is the missing TTY.
expect(result.stderr).toContain('attaching needs an interactive terminal');
expect(result.stderr).not.toContain('no session');
}, 30_000);
it('says a name nothing carries is missing, and points at --list', async () => {
const result = await runPiped(['tui', 'w9-nope']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('there is no session named w9-nope');
expect(result.stderr).toContain('codeman tui --list');
}, 30_000);
it('says a name only history carries is finished', async () => {
const result = await runPiped(['tui', 'w3-gamma']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('no live session named w3-gamma, only a finished one');
}, 30_000);
it('refuses a name two live sessions share and names their numbers', async () => {
sessions.push({ ...sessions[1], sessionId: 'eeee5555-0000-0000-0000-000000000000' });
try {
const result = await runPiped(['tui', 'w1-alpha']);
expect(result.code).toBe(1);
expect(result.stderr).toMatch(/2 live sessions are named w1-alpha \(\d+, \d+ in the list\)/);
expect(result.stderr).toContain('Attach by number instead');
} finally {
resetSessions();
}
}, 30_000);
it('still reads digits as a list number', async () => {
const result = await runPiped(['tui', '42']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('there is no session 42');
}, 30_000);
});
describe('codeman tui without a terminal', () => {
it('refuses to open the dashboard and points at the fast paths', async () => {
const result = await runPiped(['tui']);
+695
View File
@@ -0,0 +1,695 @@
/**
* @fileoverview Pins bounded fs.watch failure handling and polling fallback after a production chokidar retry loop flooded logs and synchronous close caused unhandled rejections.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { TeamWatcher } from '../src/team-watcher.js';
import { WorkflowRunWatcher } from '../src/workflow-run-watcher.js';
import { TEAM_POLL_INTERVAL_MS } from '../src/config/team-config.js';
import { WORKFLOW_RUN_POLL_INTERVAL_MS } from '../src/config/workflow-config.js';
import type { TeamConfig } from '../src/types.js';
import type { WorkflowRunInfo } from '../src/types/workflow-run.js';
const FAILURES = [
{ code: 'EMFILE', errno: -24, text: 'too many open files' },
{ code: 'ENOSPC', errno: -28, text: 'no space left on device' },
] as const;
type WatchFailure = { code: string; errno: number; text: string };
// On macOS chokidar 3 never calls fs.watch for these watchers: it uses fsevents,
// or polling when fsevents is missing, so the retry loop these tests pin cannot
// happen there and the stubbed fs.watch never fires.
const describeLinuxWatch = describe.skipIf(process.platform === 'darwin');
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function waitUntil(predicate: () => boolean, message: string): Promise<void> {
const deadline = Date.now() + 1500;
while (!predicate()) {
if (Date.now() >= deadline) throw new Error(message);
await delay(10);
}
}
function watchError(failure: WatchFailure, path: string): NodeJS.ErrnoException {
return Object.assign(new Error(`${failure.code}: ${failure.text}, watch '${path}'`), {
code: failure.code,
errno: failure.errno,
syscall: 'watch',
path,
});
}
function failEveryWatch(failure: WatchFailure) {
return vi.spyOn(fs, 'watch').mockImplementation((path) => {
throw watchError(failure, String(path));
});
}
let tempDir: string;
let watcher: TeamWatcher | WorkflowRunWatcher | undefined;
let warn: ReturnType<typeof vi.spyOn<typeof console, 'warn'>>;
let error: ReturnType<typeof vi.spyOn<typeof console, 'error'>>;
let unhandled: unknown[];
let onUnhandled: (reason: unknown) => void;
beforeEach(async () => {
watcher = undefined;
tempDir = await mkdtemp(join(tmpdir(), 'codeman-watch-failure-'));
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
error = vi.spyOn(console, 'error').mockImplementation(() => {});
unhandled = [];
onUnhandled = (reason) => unhandled.push(reason);
process.on('unhandledRejection', onUnhandled);
});
afterEach(async () => {
try {
watcher?.stop();
// Keep mocks and the rejection listener installed while asynchronous close settles.
await delay(100);
await rm(tempDir, { recursive: true, force: true });
} finally {
process.off('unhandledRejection', onUnhandled);
vi.useRealTimers();
vi.restoreAllMocks();
}
});
function createTeamConfig(): TeamConfig {
return {
name: 'test-team',
createdAt: 1_700_000_000_000,
leadAgentId: 'team-lead@test-team',
leadSessionId: 'session-123',
members: [
{
agentId: 'team-lead@test-team',
name: 'team-lead',
agentType: 'team-lead',
joinedAt: 1_700_000_000_000,
},
],
};
}
async function writeTeam(teamsDir: string, config: TeamConfig): Promise<void> {
const dir = join(teamsDir, config.name);
await mkdir(dir);
await writeFile(join(dir, 'config.json'), JSON.stringify(config));
}
describeLinuxWatch('TeamWatcher fs.watch failure', () => {
let teamsDir: string;
let tasksDir: string;
let teamWatcher: TeamWatcher;
beforeEach(async () => {
teamsDir = join(tempDir, 'teams');
tasksDir = join(tempDir, 'tasks');
await mkdir(teamsDir);
await mkdir(tasksDir);
watcher = teamWatcher = new TeamWatcher(teamsDir, tasksDir);
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
});
function expectWarnings(messages: string[]): void {
// Check counts before arguments so a retry storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(messages.length);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
expect(warn.mock.calls.map((call) => [...call]).sort()).toEqual(messages.map((message) => [message]).sort());
}
it.each(FAILURES)('$code stops both watchers with two warnings and keeps polling', async (failure) => {
const watch = failEveryWatch(failure);
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
const attempts = watch.mock.calls.length;
await delay(500);
// Check counts before arguments so the unfixed log storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(2);
expect(error).toHaveBeenCalledTimes(0);
for (const call of warn.mock.calls) expect(call.length).toBe(1);
expect(warn.mock.calls.map(([message]) => message).sort()).toEqual(
[
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
].sort()
);
expect(watch.mock.calls.length).toBe(attempts);
expect(attempts).toBeGreaterThanOrEqual(2);
// Allow a handful of in-flight attempts, but never an ancestor retry loop.
expect(attempts).toBeLessThanOrEqual(6);
expect(unhandled.length).toBe(0);
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
for (const pollCount of [2, 3, 4]) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
// The same empty roots must cost the same bounded number of attempts on every tick.
expect(watch).toHaveBeenCalledTimes(attempts * pollCount);
expectWarnings(expectedWarnings);
expect(teamWatcher.getTeams()).toEqual([]);
await delay(200);
expect(watch).toHaveBeenCalledTimes(attempts * pollCount);
}
const config = createTeamConfig();
await writeTeam(teamsDir, config);
expect(teamWatcher.getTeams()).toEqual([]);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await waitUntil(() => teamWatcher.getTeams().length > 0, 'polling did not discover the new team');
expect(teamWatcher.getTeams()).toEqual([config]);
await delay(500);
const finalAttempts = watch.mock.calls.length;
expect(finalAttempts - attempts * 4).toBeGreaterThanOrEqual(2);
expect(finalAttempts - attempts * 4).toBeLessThanOrEqual(6);
expectWarnings(expectedWarnings);
expect(() => teamWatcher.stop()).not.toThrow();
expect(() => teamWatcher.stop()).not.toThrow();
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS * 3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(finalAttempts);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
}
});
it('warns again about a watcher that still fails after stop() and start() on the same instance', async () => {
const failure = FAILURES[0];
const watch = failEveryWatch(failure);
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
await delay(200);
expectWarnings(expectedWarnings);
teamWatcher.stop();
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 4, 'a restarted watcher stayed silent about the same outage');
await delay(200);
expectWarnings([...expectedWarnings, ...expectedWarnings]);
} finally {
teamWatcher.stop();
watch.mockRestore();
}
});
it('keeps a healthy watcher active and discovers a new team before the poll interval', async () => {
const watch = vi.spyOn(fs, 'watch');
try {
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'healthy watchers did not start');
await delay(200);
const attempts = watch.mock.calls.length;
for (let tick = 0; tick < 3; tick++) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(200);
expect(watch).toHaveBeenCalledTimes(attempts);
expect(teamWatcher.getTeams()).toEqual([]);
expectWarnings([]);
}
const config = createTeamConfig();
await writeTeam(teamsDir, config);
// No interval is advanced: discovery must come from the real filesystem watcher.
await waitUntil(() => teamWatcher.getTeams().length > 0, 'healthy watcher did not discover the new team');
expect(teamWatcher.getTeams()).toEqual([config]);
teamWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
teamWatcher.stop();
}
});
it.each(FAILURES)('$code resumes live discovery when both watchers recover on the next poll', async (failure) => {
const watch = failEveryWatch(failure);
const created = vi.fn();
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
try {
teamWatcher.on('teamCreated', created);
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
await delay(200);
expectWarnings(expectedWarnings);
watch.mockRestore();
const recoveredWatch = vi.spyOn(fs, 'watch');
await delay(200);
expect(recoveredWatch).toHaveBeenCalledTimes(0);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(recoveredWatch).toHaveBeenCalledTimes(2);
expect(recoveredWatch.mock.calls.map(([path]) => String(path)).sort()).toEqual([teamsDir, tasksDir].sort());
expect(teamWatcher.getTeams()).toEqual([]);
const config = createTeamConfig();
await writeTeam(teamsDir, config);
// No further interval tick: the recovered teams watcher must discover this team.
await waitUntil(() => created.mock.calls.length > 0, 'recovered watcher did not discover the new team');
expect(created).toHaveBeenCalledTimes(1);
expect(created.mock.calls).toEqual([[config]]);
expect(teamWatcher.getTeams()).toEqual([config]);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
teamWatcher.off('teamCreated', created);
}
});
it('re-arms after one new file throws ENOENT and resumes live discovery without another poll', async () => {
const realWatch = fs.watch;
const vanishedPath = join(teamsDir, 'vanished.json');
const failure = watchError({ code: 'ENOENT', errno: -2, text: 'no such file or directory' }, vanishedPath);
let failedCalls = 0;
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
if (String(args[0]) === vanishedPath && failedCalls === 0) {
failedCalls++;
throw failure;
}
return realWatch(...args);
});
const created = vi.fn();
let closeErrorMessage = '';
try {
(undefined as unknown as fs.FSWatcher).close();
} catch (error) {
closeErrorMessage = (error as TypeError).message;
}
const expectedWarnings = [`[TeamWatcher] teams watcher stopped, relying on polling: ${closeErrorMessage}`];
try {
teamWatcher.on('teamCreated', created);
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'healthy watchers did not start');
await delay(200);
await writeFile(vanishedPath, '{}');
await waitUntil(() => warn.mock.calls.length > 0, 'the transient failure did not stop the teams watcher');
await delay(200);
expect(failedCalls).toBe(1);
expectWarnings(expectedWarnings);
await rm(vanishedPath);
const stoppedAttempts = watch.mock.calls.length;
await delay(200);
expect(watch).toHaveBeenCalledTimes(stoppedAttempts);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(stoppedAttempts + 1);
expect(watch.mock.calls.slice(stoppedAttempts).map(([path]) => String(path))).toEqual([teamsDir]);
expect(teamWatcher.getTeams()).toEqual([]);
const config = createTeamConfig();
await writeTeam(teamsDir, config);
await waitUntil(() => created.mock.calls.length > 0, 're-armed watcher did not discover the new team');
expect(created).toHaveBeenCalledTimes(1);
expect(created.mock.calls).toEqual([[config]]);
expect(teamWatcher.getTeams()).toEqual([config]);
expect(failedCalls).toBe(1);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
teamWatcher.off('teamCreated', created);
}
});
it.each(FAILURES.flatMap((failure) => ['teams', 'tasks'].map((kind) => ({ ...failure, kind }))))(
'$code re-arms only the $kind watcher and warns again only after a healthy poll',
async ({ kind, ...failure }) => {
const root = kind === 'teams' ? teamsDir : tasksDir;
const healthyRoot = kind === 'teams' ? tasksDir : teamsDir;
const realWatch = fs.watch;
let failingPath: string | undefined = root;
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
if (String(args[0]) === failingPath) throw watchError(failure, failingPath);
return realWatch(...args);
});
const expectedWarnings = [
`[TeamWatcher] ${kind} watcher stopped, relying on polling: ${watchError(failure, root).message}`,
];
const attemptsAt = (path: string) =>
watch.mock.calls.filter(([watchedPath]) => String(watchedPath) === path).length;
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the failed watcher warning');
await delay(200);
expectWarnings(expectedWarnings);
expect(attemptsAt(root)).toBe(1);
expect(attemptsAt(healthyRoot)).toBe(1);
for (const expectedAttempts of [2, 3]) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(expectedAttempts + 1);
expect(attemptsAt(root)).toBe(expectedAttempts);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
await delay(200);
expect(watch).toHaveBeenCalledTimes(expectedAttempts + 1);
}
failingPath = undefined;
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(5);
expect(attemptsAt(root)).toBe(4);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
// A successful re-arm alone does not end the outage before the following poll.
failingPath = join(root, 'before-healthy-poll.json');
await writeFile(failingPath, '{}');
await waitUntil(() => attemptsAt(failingPath!) > 0, 'recreated watcher did not watch the first new file');
await delay(200);
expect(watch).toHaveBeenCalledTimes(6);
expectWarnings(expectedWarnings);
await rm(failingPath);
failingPath = undefined;
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(7);
expect(attemptsAt(root)).toBe(5);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(200);
expect(watch).toHaveBeenCalledTimes(7);
expectWarnings(expectedWarnings);
failingPath = join(root, 'after-healthy-poll.json');
await writeFile(failingPath, '{}');
await waitUntil(() => attemptsAt(failingPath!) > 0, 'healthy watcher did not watch the second new file');
await delay(200);
expect(watch).toHaveBeenCalledTimes(8);
expectWarnings([
...expectedWarnings,
`[TeamWatcher] ${kind} watcher stopped, relying on polling: ${watchError(failure, failingPath).message}`,
]);
expect(teamWatcher.getTeams()).toEqual([]);
} finally {
teamWatcher.stop();
}
}
);
it.each([{ code: 'healthy', failure: undefined }, ...FAILURES.map((failure) => ({ code: failure.code, failure }))])(
'$code stop closes both watchers and the interval and is idempotent',
async ({ failure }) => {
const watch = failure ? failEveryWatch(failure) : vi.spyOn(fs, 'watch');
const expectedWarnings = failure
? [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
]
: [];
try {
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'watchers did not attempt to start');
await delay(200);
expectWarnings(expectedWarnings);
const attempts = watch.mock.calls.length;
const closed: string[] = [];
if (!failure) {
expect(watch).toHaveBeenCalledTimes(2);
watch.mock.results.forEach((result, index) => {
expect(result.type).toBe('return');
(result.value as fs.FSWatcher).on('close', () => closed.push(String(watch.mock.calls[index][0])));
});
}
expect(() => teamWatcher.stop()).not.toThrow();
expect(() => teamWatcher.stop()).not.toThrow();
await delay(200);
if (!failure) expect(closed.sort()).toEqual([teamsDir, tasksDir].sort());
expect(vi.getTimerCount()).toBe(0);
await writeTeam(teamsDir, createTeamConfig());
await writeFile(join(tasksDir, 'after-stop.json'), '{}');
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS * 3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attempts);
expect(teamWatcher.getTeams()).toEqual([]);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
}
}
);
});
describeLinuxWatch('TeamWatcher in-flight fs.watch failure', () => {
it('stays stopped when file replacement and deletion race with ENOSPC', async () => {
const teamsDir = join(tempDir, 'teams');
const tasksDir = join(tempDir, 'tasks');
const teamDir = join(teamsDir, 't');
await mkdir(teamDir, { recursive: true });
await mkdir(tasksDir);
await writeFile(join(teamDir, 'a.json'), '{}');
await writeFile(join(teamDir, 'b.json'), '{}');
const teamWatcher = new TeamWatcher(teamsDir, tasksDir);
watcher = teamWatcher;
const realWatch = fs.watch;
const listeners = new Map<string, fs.WatchListener<string | Buffer>>();
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
const handle = realWatch(...args);
if (args[2]) listeners.set(String(args[0]), args[2]);
return handle;
});
let firstFailure: NodeJS.ErrnoException | undefined;
let failingCalls = 0;
try {
teamWatcher.start();
await waitUntil(
() => listeners.has(join(teamDir, 'a.json')) && listeners.has(join(teamDir, 'b.json')),
'timed out waiting for both file watches'
);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
watch.mockImplementation((...args) => {
// Bound the unfixed retry loop so it can recover and the test can finish.
if (failingCalls >= 2000) return realWatch(...args);
failingCalls++;
const failure = watchError(FAILURES[1], String(args[0]));
firstFailure ??= failure;
throw failure;
});
fs.writeFileSync(join(teamDir, 'b.json.tmp'), '{"replaced":true}');
fs.renameSync(join(teamDir, 'b.json.tmp'), join(teamDir, 'b.json'));
await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the teams watcher warning');
// Deliver the queued deletion callback only after the replacement failure stops the watcher.
fs.unlinkSync(join(teamDir, 'a.json'));
listeners.get(join(teamDir, 'a.json'))!('rename', 'a.json');
await delay(1000);
const attempts = watch.mock.calls.length;
const failures = failingCalls;
await delay(500);
const settledAttempts = watch.mock.calls.length;
const settledFailures = failingCalls;
const warnings = warn.mock.calls.length;
teamWatcher.stop();
await delay(500);
// Check counts before arguments so a retry storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(1);
expect(warnings).toBe(1);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
expect(watch.mock.calls.length).toBe(settledAttempts);
expect(failingCalls).toBe(settledFailures);
expect(settledAttempts).toBe(attempts);
expect(settledFailures).toBe(failures);
expect(failures).toBeGreaterThanOrEqual(1);
expect(failures).toBeLessThanOrEqual(6);
expect(firstFailure?.code).toBe('ENOSPC');
expect(firstFailure?.path?.startsWith(`${teamDir}/`)).toBe(true);
expect(warn.mock.calls).toEqual([
[`[TeamWatcher] teams watcher stopped, relying on polling: ${firstFailure?.message}`],
]);
} finally {
teamWatcher.stop();
}
});
});
const PROJECT_HASH = '-home-arkon-default-claudeman';
const SESSION_UUID = '388113c8-cd01-4e80-93a8-3be66ab1519b';
const RUN_ID = 'wf_test1234-abc';
const RUN_START = 1_700_000_000_000;
function sampleRunJson() {
return {
runId: RUN_ID,
timestamp: new Date(RUN_START).toISOString(),
workflowName: 'watch-failure-test',
summary: 'Discover a run despite exhausted filesystem watches',
status: 'completed',
startTime: RUN_START,
agentCount: 0,
durationMs: 1234,
totalTokens: 0,
totalToolCalls: 0,
phases: [],
workflowProgress: [],
};
}
const { workflowProgress: _progress, ...runFields } = sampleRunJson();
const EXPECTED_RUN: WorkflowRunInfo = {
...runFields,
agents: [],
projectHash: PROJECT_HASH,
sessionUuid: SESSION_UUID,
lastActivityAt: RUN_START,
};
describeLinuxWatch('WorkflowRunWatcher fs.watch failure', () => {
let runWatcher: WorkflowRunWatcher;
let workflowsDir: string;
beforeEach(async () => {
const projectsDir = join(tempDir, 'projects');
workflowsDir = join(projectsDir, PROJECT_HASH, SESSION_UUID, 'workflows');
await mkdir(workflowsDir, { recursive: true });
await writeFile(join(workflowsDir, `${RUN_ID}.json`), JSON.stringify(sampleRunJson()));
watcher = runWatcher = new WorkflowRunWatcher(projectsDir);
// Later interval polls run only when a test explicitly advances the clock.
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
});
function firstRun(): Promise<WorkflowRunInfo> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
runWatcher.off('run_discovered', onRun);
reject(new Error('timed out waiting for run_discovered'));
}, 1500);
function onRun(info: WorkflowRunInfo) {
clearTimeout(timer);
resolve(info);
}
runWatcher.once('run_discovered', onRun);
runWatcher.start();
});
}
it.each(FAILURES)('$code discovers the run without retries, logging, or unhandled rejections', async (failure) => {
const watch = failEveryWatch(failure);
try {
const discovered = await firstRun();
await delay(500);
const attempts = watch.mock.calls.length;
await delay(500);
expect(unhandled.length).toBe(0);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(watch.mock.calls.length).toBe(attempts);
expect(attempts).toBeGreaterThanOrEqual(1);
expect(attempts).toBeLessThanOrEqual(3);
expect(discovered).toEqual(EXPECTED_RUN);
expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
expect(runWatcher.isRunning()).toBe(true);
runWatcher.stop();
expect(runWatcher.isRunning()).toBe(false);
await delay(100);
expect(unhandled.length).toBe(0);
expect(watch.mock.calls.length).toBe(attempts);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
} finally {
runWatcher.stop();
}
});
it('retries a failed directory once per poll and resumes live discovery when fs.watch recovers', async () => {
const watch = failEveryWatch(FAILURES[0]);
const discovered = vi.fn();
try {
expect(await firstRun()).toEqual(EXPECTED_RUN);
await delay(500);
const attemptsPerPoll = watch.mock.calls.length;
expect(attemptsPerPoll).toBeGreaterThanOrEqual(1);
expect(attemptsPerPoll).toBeLessThanOrEqual(3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attemptsPerPoll);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
for (const pollCount of [2, 3]) {
vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS);
await waitUntil(
() => watch.mock.calls.length > attemptsPerPoll * (pollCount - 1),
'later poll did not retry the failed workflows directory'
);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attemptsPerPoll * pollCount);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
}
watch.mockRestore();
const recoveredWatch = vi.spyOn(fs, 'watch');
vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS);
await waitUntil(() => recoveredWatch.mock.calls.length > 0, 'recovery poll did not install a watcher');
// Let watcher setup and the recovery poll settle before creating the new completion file.
await delay(500);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
const otherId = 'wf_recovered5678-def';
runWatcher.on('run_discovered', discovered);
await writeFile(join(workflowsDir, `${otherId}.json`), JSON.stringify({ ...sampleRunJson(), runId: otherId }));
// Do not advance the interval again: only the recovered watcher can discover this file.
await waitUntil(() => discovered.mock.calls.length > 0, 'recovered watcher did not discover the new run');
expect(discovered).toHaveBeenCalledTimes(1);
const expectedRun = { ...EXPECTED_RUN, runId: otherId };
expect(discovered).toHaveBeenCalledWith(expectedRun);
expect(runWatcher.getRun(otherId)).toEqual(expectedRun);
runWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
runWatcher.stop();
runWatcher.off('run_discovered', discovered);
}
});
it('discovers a run with a healthy watcher without logging or unhandled rejections', async () => {
try {
const discovered = await firstRun();
await delay(1000);
expect(discovered).toEqual(EXPECTED_RUN);
expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
runWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
runWatcher.stop();
}
});
});
+177
View File
@@ -13,6 +13,7 @@ import {
buildUpstreamRequestHeaders,
capabilityFromProxyPath,
capabilityFromReferer,
escapedWebviewAssetPath,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
@@ -238,6 +239,56 @@ describe('buildUpstreamRequestHeaders', () => {
expect(headers.authorization).toBeUndefined();
});
// `dsh web` mints its session cookie for the loopback authority the proxy
// dials, which the browser has never visited and cannot store anything for.
// The supervisor holds it instead. The managed tab is trusted, so the browser's
// other dsh cookies are still present and must be kept alongside it.
it('puts the server-held credential ahead of the filtered browser cookies', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; dash=1' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dash=1');
});
it('keeps every non-Codeman browser cookie when injecting the server credential', () => {
const headers = buildUpstreamRequestHeaders(
{ cookie: 'dsh-ui=dark; codeman_session=SECRET; dsh-settings=z' },
upstream,
{
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
}
);
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dsh-ui=dark; dsh-settings=z');
});
// A `Cookie` header may name the same cookie twice, and the first value is the
// one parsers keep. The browser can still hold a dsh cookie from an earlier
// proxied response, so the server's fresh copy has to lead or the stale one wins
// and the tab goes back to the 401 this whole path exists to prevent.
it('keeps the server credential in front of a stale browser copy of the same name', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'dsh-auth-p=STALE; dsh-ui=dark' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=FRESH',
});
// The stale copy is still forwarded behind it (dropping it would need its own
// name parsing), but the parser sees FRESH first, which is what authenticates.
expect(headers.cookie).toBe('dsh-auth-p=FRESH; dsh-auth-p=STALE; dsh-ui=dark');
});
it('sends the server-held credential even when browser cookies are not forwarded', () => {
const headers = buildUpstreamRequestHeaders({}, upstream, {
forwardCookies: false,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig');
});
it('presents Origin/Referer as if the browser talked to the dashboard directly', () => {
const headers = buildUpstreamRequestHeaders({ origin: 'https://codeman.local' }, upstream, {
forwardCookies: false,
@@ -345,6 +396,38 @@ describe('rewriteHtml', () => {
expect(out.match(/<base/g)).toHaveLength(1);
});
// A Vite build ships `<base href="./">`, and the runtime shim rewrites the
// document URL to strip the prefix — so "./" would resolve to Codeman's root
// and every module script would 404 behind an otherwise-painted page.
it('resolves a page-relative <base> against the prefix before the shim masks the URL', () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP);
expect(out).toContain(`<base href="${PREFIX}">`);
expect(out.match(/<base/g)).toHaveLength(1);
});
it('keeps a sub-path in a relative <base> inside the proxy prefix', () => {
const out = rewriteHtml('<html><head><base target="_blank" href="./sub/"></head></html>', CAP);
expect(out).toContain(`<base target="_blank" href="${PREFIX}sub/">`);
});
// A document served from a subdirectory resolves its relative base against
// ITS directory, not the proxy root: `/webview/<cap>/app/page.html` with
// `<base href="./">` must point at `/webview/<cap>/app/`.
it("resolves a relative <base> against the document's own directory", () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP, '', 'app/page.html');
expect(out).toContain(`<base href="${PREFIX}app/">`);
});
it('resolves a ../ base from the document directory', () => {
const out = rewriteHtml('<html><head><base href="../assets/"></head></html>', CAP, '', 'app/sub/page.html');
expect(out).toContain(`<base href="${PREFIX}app/assets/">`);
});
it('leaves a cross-origin <base> exactly as the author wrote it', () => {
const out = rewriteHtml('<html><head><base href="https://cdn.example/x/"></head></html>', CAP);
expect(out).toContain('<base href="https://cdn.example/x/">');
});
it('still injects the runtime shim when the page ships its own <base>', () => {
// The shim is the only layer that catches runtime-built URLs, so an early
// return on an existing <base> would silently break those pages.
@@ -358,6 +441,48 @@ describe('rewriteHtml', () => {
expect(rewriteHtml('just text', CAP)).toContain('<script>');
});
// SvelteKit's inline bootstrap does `import("/_app/…")`. A dynamic import is
// neither an attribute nor a fetch(), so `<base>` and the runtime shim both
// miss it and the module loads from Codeman's root — the app then sits on its
// own spinner forever.
it('rewrites root-absolute dynamic import() specifiers', () => {
const dq = rewriteHtml('<head><script>import("/_app/entry.js")</script></head>', CAP);
expect(dq).toContain(`import("${PREFIX}_app/entry.js")`);
const sq = rewriteHtml("<head><script>import( '/x.js' )</script></head>", CAP);
expect(sq).toContain(`import('${PREFIX}x.js' )`);
});
it('leaves relative and cross-origin import() specifiers alone', () => {
const out = rewriteHtml(
`<head><script>import("./a.js");import("//cdn.example/b.js");import("https://cdn.example/c.js")</script></head>`,
CAP
);
expect(out).toContain('import("./a.js")');
expect(out).toContain('import("//cdn.example/b.js")');
expect(out).toContain('import("https://cdn.example/c.js")');
});
// The rewrite is for specifiers a loader will execute, not for the word
// appearing in the page a reader sees.
it('leaves import() in visible text alone', () => {
const out = rewriteHtml(
`<html><body><pre>import("/example.js")</pre><code>import('/other.js')</code></body></html>`,
CAP
);
expect(out).toContain('<pre>import("/example.js")</pre>');
expect(out).toContain("<code>import('/other.js')</code>");
expect(out).not.toContain(`${PREFIX}example.js`);
});
it('rewrites imports in every script body, including one with attributes', () => {
const out = rewriteHtml(
`<head><script type="module">import("/_app/a.js")</script><script defer>import('/b.js')</script></head>`,
CAP
);
expect(out).toContain(`import("${PREFIX}_app/a.js")`);
expect(out).toContain(`import('${PREFIX}b.js')`);
});
it('rebases root-absolute src/href/action, which <base> cannot fix', () => {
const out = rewriteHtml(
`<head></head><body><script src="/static/app.js"></script><link href='/s.css'><form action="/login"></form></body>`,
@@ -858,3 +983,55 @@ describe('lost-frame recovery', () => {
expect(has({ authorization: 'Basic YWRtaW46eA==' })).toBe(true);
});
});
describe('escapedWebviewAssetPath: naming a 404 a web tab caused', () => {
const req = (over: Record<string, unknown> = {}) => ({
method: 'GET',
url: '/_app/immutable/entry/start.js',
...over,
headers: {
host: 'codeman.example:3001',
referer: 'http://codeman.example:3001/',
'sec-fetch-dest': 'script',
...((over.headers as Record<string, string | string[] | undefined> | undefined) ?? {}),
},
});
it('recognises a root-absolute module a masked frame asked for', () => {
expect(escapedWebviewAssetPath(req())).toBe('/_app/immutable/entry/start.js');
});
it('drops the query string, which carries no diagnostic value', () => {
expect(escapedWebviewAssetPath(req({ url: '/_app/x.js?v=17' }))).toBe('/_app/x.js');
});
it('ignores every shape that is not a dashboard asset', () => {
// A navigation is the lost-frame recovery's job, not this one's.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'document' } }))
).toBeNull();
// Codeman's own missing files say nothing about a web tab.
expect(
escapedWebviewAssetPath(
req({ url: '/favicon.ico', headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'image' } })
)
).toBeNull();
// A real Codeman page's assets resolve; only a masked landing (`/`) is this shape.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/settings', 'sec-fetch-dest': 'script' } }))
).toBeNull();
// Cross-origin referer, API paths, writes, and no referer at all.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://other/', 'sec-fetch-dest': 'script' } }))
).toBeNull();
expect(escapedWebviewAssetPath(req({ url: '/api/thing' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ method: 'POST' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ headers: { host: 'h' } }))).toBeNull();
});
it('accepts the array headers a proxy front end can produce', () => {
expect(
escapedWebviewAssetPath(req({ headers: { host: ['h'], referer: ['http://h/'], 'sec-fetch-dest': ['image'] } }))
).toBe('/_app/immutable/entry/start.js');
});
});