Compare commits

..
Author SHA1 Message Date
Codeman maintainer 2c55fe907e feat(tiles): move tiles by hand, and detach a tile into its own window
Gesture control now moves tiles: with the tile grid open, pinch anywhere
on a tile and carry it onto another tile (they swap) or an empty cell (it
moves there); a session tab carried onto the grid joins it there. The
overlay asks tile-grid.js what is under the hand (tileAtPoint,
tileDropTargetAt) and drops through the mouse drag's own paths
(dropSessionOnTile / dropSessionOnSlot, so _reorderTiles stays the one
move path).

Detach Tiles (App Settings > Appearance, per device, OFF by default,
desktop only):
- a tile's header let go outside the browser window opens the session as
  a pop-out (detachSession, which now takes an optional size and screen
  position), the tile's size, near the drop point, after a 120 ms settle;
- dropped on another Codeman window's tiles it moves there: that window
  docks it through the target's own drop and posts 'tile-adopted' on the
  window channel, and only the window it was dragged from lets go of its
  copy (a last tile goes to the welcome screen, never onto that session);
- a pop-out's title drags back onto any grid: the session is taken back,
  the pop-out is asked to close and is released (stops answering
  roll-calls; one a script cannot close says where the session went), and
  its stale 'detached' answers are ignored for 2 s;
- a tile's menu offers "Open in a new window", and a hand that lets a tile
  go outside the grid pops it out too.

With the setting off nothing changes. No server change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 07:17:26 +02:00
32 changed files with 1500 additions and 1999 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
---
'aicodeman': minor
---
Keep your laptop awake while Codeman runs. App Settings > System > Power has "Keep this computer awake" (off by default) and "Only on AC power" (on by default), with a live status line. On Linux it stops lid-close suspend while you are logged in to the desktop; on macOS it stops idle sleep, and lid-close sleep too with the optional root helper. The installer asks on laptops, and `install.sh keep-awake` turns it on for an existing install.
+5
View File
@@ -0,0 +1,5 @@
---
'aicodeman': minor
---
Tiles move by hand, and can leave the window. With gesture control on, pinch a tile and carry it onto another tile (they swap) or an empty cell (it moves there), or carry a tab onto the grid to tile it. A new **Detach Tiles** setting (App Settings → Appearance, per device, off by default) lets you drag a tile's header out of the browser to open it in its own window, drop it on another Codeman window's tiles to move it there, and drag a popped-out window's title back onto any grid. The tile's ⋯ menu gets "Open in a new window" too.
+1 -3
View File
@@ -280,7 +280,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same keyCode-229 soft-keyboard controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions)
**Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default ON on desktop and OFF on handhelds and touch-primary tablets (primary pointer coarse, `getDefaultSettings()`; a touchscreen laptop keeps ON), desktop-only at 1180px, per-device; tile-grid.js, design `docs/tile-grid-plan.md`): 1 to 6 live sessions side by side (the cap is ONE constant, `TILE_GRID_MAX` in constants.js, owner decision; the layout table still covers 7 to 9, unreachable), each a `TerminalTile` with a header (state dot, harness logo, name, model, menu, zoom, ×; no +, owner decision), laid out by count (`CodemanTileGrid`, constants.js) with draggable column/row dividers, zoom (tmux-style), an Attach overlay, and per-browser persistence (`codeman:tile-grid`, localStorage only: cells with `null` holes, `count`, focus, user zoom, divider fractions, never content; written on every change, kept by EVERY close, restored INSIDE `handleInit` in place of the single-view select, so the main terminal never loads on that page load). While the grid is open the main terminal is PARKED: `activeSessionId` is the focused tile's session, and every main-terminal path that would write, fetch, resize or reconnect stands aside through `_tilesOwnTerminal()` (the WebGL long-task observer included). ⚠️ Every capture a tile fetches (initial, reconnect refresh, `{t:'r'}`, history pull) goes through ONE `TileLoadQueue` (concurrency 1, a deadline covering the body), because each is a synchronous tmux call on the server. ⚠️ Only a USER-initiated pick of a non-tiled session (or `leaveTiles`, a followed link) leaves the grid; an `auto` selection never collapses it, and every app-driven fallback (close, delete, restore) picks a tile. A caller of `closeTileGrid({ reselect: false })` must null `activeSessionId` before any `_cleanupPreviousSession`, or the parked terminal's stale content is saved as a snapshot. ⚠️ The grid and the split are never open together. ⚠️ Tile chords go through `tileShortcutFor` and are swallowed in every xterm key handler BEFORE the Shift+Enter gate; the toggle follows `showTileGridButton` (owner decision: OFF makes the chord inert, it passes through like any unbound key). ⚠️ The Tiles button's click and Ctrl+Shift+G are ONE function, `toggleTileGrid` (owner decision): they open the grid AT ONCE on `tileGridOpenSet` (constants.js): the stored grid EXACTLY as the user left it (owner decision 11: `restoreTileGridCells`, never filled to the count nor trimmed to the window; a cell whose session is gone since is filled from the ranking, a hole the user made stays), else an open split's two, else the open sessions as `rankTileSessions` orders them (working first, keyed off `lastSubmitAt` ONLY, then needing input, then most recent; `_mobileOverviewState`'s states), the active one focused, filled to the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) by `tileGridSetForCount`, never a menu. ⚠️ `removeTile(..., { gone: true })` (a session deleted, popped out or refused) keeps the stored `count` so the next open refills that cell; a removal by hand lowers it. Right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. SuchLine truncated
**Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default ON on desktop and OFF on handhelds and touch-primary tablets (primary pointer coarse, `getDefaultSettings()`; a touchscreen laptop keeps ON), desktop-only at 1180px, per-device; tile-grid.js, design `docs/tile-grid-plan.md`): 1 to 6 live sessions side by side (the cap is ONE constant, `TILE_GRID_MAX` in constants.js, owner decision; the layout table still covers 7 to 9, unreachable), each a `TerminalTile` with a header (state dot, harness logo, name, model, menu, zoom, ×; no +, owner decision), laid out by count (`CodemanTileGrid`, constants.js) with draggable column/row dividers, zoom (tmux-style), an Attach overlay, and per-browser persistence (`codeman:tile-grid`, localStorage only: cells with `null` holes, `count`, focus, user zoom, divider fractions, never content; written on every change, kept by EVERY close, restored INSIDE `handleInit` in place of the single-view select, so the main terminal never loads on that page load). While the grid is open the main terminal is PARKED: `activeSessionId` is the focused tile's session, and every main-terminal path that would write, fetch, resize or reconnect stands aside through `_tilesOwnTerminal()` (the WebGL long-task observer included). ⚠️ Every capture a tile fetches (initial, reconnect refresh, `{t:'r'}`, history pull) goes through ONE `TileLoadQueue` (concurrency 1, a deadline covering the body), because each is a synchronous tmux call on the server. ⚠️ Only a USER-initiated pick of a non-tiled session (or `leaveTiles`, a followed link) leaves the grid; an `auto` selection never collapses it, and every app-driven fallback (close, delete, restore) picks a tile. A caller of `closeTileGrid({ reselect: false })` must null `activeSessionId` before any `_cleanupPreviousSession`, or the parked terminal's stale content is saved as a snapshot. ⚠️ The grid and the split are never open together. ⚠️ Tile chords go through `tileShortcutFor` and are swallowed in every xterm key handler BEFORE the Shift+Enter gate; the toggle follows `showTileGridButton` (owner decision: OFF makes the chord inert, it passes through like any unbound key). ⚠️ The Tiles button's click and Ctrl+Shift+G are ONE function, `toggleTileGrid` (owner decision): they open the grid AT ONCE on `tileGridOpenSet` (constants.js): the stored grid EXACTLY as the user left it (owner decision 11: `restoreTileGridCells`, never filled to the count nor trimmed to the window; a cell whose session is gone since is filled from the ranking, a hole the user made stays), else an open split's two, else the open sessions as `rankTileSessions` orders them (working first, keyed off `lastSubmitAt` ONLY, then needing input, then most recent; `_mobileOverviewState`'s states), the active one focused, filled to the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) by `tileGridSetForCount`, never a menu. ⚠️ `removeTile(..., { gone: true })` (a session deleted, popped out or refused) keeps the stored `count` so the next open refills that cell; a removal by hand lowers it. Right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. SuchLine truncated
**Terminal touch gestures: link taps and text selection**: on touch devices xterm's linkifier and SelectionService never see the gesture, so both are driven explicitly (terminal-ui.js). ⚠️ A tap activates the link under it through the SAME provider as the hover linkifier (`_terminalLinkAtPoint`), synchronously inside `touchend` (keeps the user gesture `window.open` needs) and BEFORE any mouse report; the caret's logical line (`_tapIsOnCaretLine`) and TUI-owned rows (`_isActionableMobileTerminalTap`) keep their meaning. ⚠️ Gate on the caret line, never on tap intent (a shell calls every tap `'input'`). ⚠️ Long-press selects via xterm's public `select()`; keep the three guards: suppress the compat mouse pair after `touchend`, the bounded focus guard + `contextmenu` suppression for the platform long-press, and no closing `terminal.focus()` on phones. Tests: `test/terminal-touch-tap.test.ts`. → [architecture-invariants#terminal-touch-gestures-link-taps-and-text-selection](docs/architecture-invariants.md#terminal-touch-gestures-link-taps-and-text-selection)
@@ -293,8 +293,6 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Self-update** (App Settings → System → Updates): in-app updater for git-clone installs under a supervisor (`systemd`, `launchd`, `launchd-daemon`, `docker-compose`, else `none`). The work runs in a DETACHED `scripts/self-update.sh` writing `update-status.json`, polled across the restart; pure helpers in `src/web/self-update.ts`. ⚠️ Compose: the restart kills the script, so nothing may be appended after the `restarting` marker; the repo must stay a host bind mount over `/opt/codeman` and the image must keep devDependencies + toolchain. ⚠️ `evaluateEnvironmentGate()` refuses releases that change `server.Dockerfile`/`docker-compose.yaml` or add `.env.example` keys, re-evaluated on `POST /api/system/update`; unknowns fail OPEN, but the exit-to-restart needs `--restart-by-exit 1` (`CODEMAN_RESTART_BY_EXIT=1` only in the Compose file). ⚠️ Keep the agent CLIs in `server.Dockerfile` pinned. → [docs/docker-self-update.md](docs/docker-self-update.md), [architecture-invariants#self-update](docs/architecture-invariants.md#self-update)
**Keep awake** (`keepAwakeEnabled`, SYNCED, default OFF; `keepAwakeAcOnly` default ON; pure `src/keep-awake.ts` + IO `src/keep-awake-manager.ts`, status `GET /api/system/keep-awake`): holds an OS sleep lock while the server runs, so a closed laptop keeps its agents working. ⚠️ Linux needs the LOW-level `handle-lid-switch` lock (logind's default `LidSwitchIgnoreInhibited=yes` ignores a `sleep` lock for the lid, and a user's own `sleep` lock never blocks that user's desktop suspending), and polkit grants it only while someone is logged in to the desktop: `denied` is a retried state, never an error. ⚠️ The lock must die with the server: `systemd-inhibit` runs `cat` on a stdin pipe (the unit's `KillMode=process` would orphan a `sleep infinity` holding it forever), macOS runs `caffeinate -w <pid>`. ⚠️ macOS lid close needs `pmset -a disablesleep`, applied by the optional root helper `scripts/keep-awake-macos.sh`, which `install.sh` copies to a ROOT-OWNED path (never run it from the user-writable install dir); it follows a heartbeat request file it ignores after 2 minutes, and undoes only a disablesleep it set. Reconcile from `merged` in `PUT /api/settings`; a non-admin's value is dropped in multi-user mode. Tests: `test/keep-awake*.test.ts`, `test/routes/system-routes-keep-awake.test.ts`, `test/install-sh-keep-awake.test.ts`.
**Reverse-proxy base path** (`--base-url` / `CODEMAN_BASE_URL`, default `/`; pure single source `src/config/base-path.ts`, normalized to `''` or `/foo`): mounts Codeman under a sub-path behind a proxy that forwards the prefix unchanged. Few choke points: `stripBasePath()` in Fastify's `rewriteUrl` (routes stay prefix-agnostic; unprefixed requests still answer), one `onSend` hook rebasing `Location`, `renderIndexHtml` rewriting `<base href>` + injecting `window.__CODEMAN_BASE__`, and `CodemanBase.url()` (constants.js) for runtime URLs. ⚠️ Keep template asset refs RELATIVE, and route every root-absolute frontend URL (EventSource/WebSocket/`window.open`/src) through `CodemanBase.url()`. ⚠️ Web-tab proxy egress goes through `proxyPrefixFor(cap, basePath)`; ingress parsers stay base-agnostic. ⚠️ `--base-url` must ride `buildWebArgs` and `resolveServicePlan`. Tests: `test/base-path.test.ts`. → [architecture-invariants#reverse-proxy-base-path](docs/architecture-invariants.md#reverse-proxy-base-path)
**Attachments** (live external document references; all wiring in `file-routes.ts`): a **registry** maps a stable `attachmentId` to a realpath-resolved, extension-allowlisted absolute path, so browser requests never carry arbitrary absolute paths. ⚠️ The **magic-link scanner** (`codeman://attach?...` in terminal output) is **prompt-injectable**, so its scan path is force-confined to the session workspace; a hostile prompt could otherwise exfiltrate arbitrary host files over SSE. The security gate is an extension **allowlist**, not a blocklist. `document-conversion-limiter.ts` caps converter spawns globally: without it, N large docs detected at once fork N multi-minute processes, which is a resource-exhaustion vector. → [architecture-invariants#attachments](docs/architecture-invariants.md#attachments)
-4
View File
@@ -860,10 +860,6 @@ Delivery goes through the same egress guard as web tabs (refused on the resolved
`GET /api/doctor[?category=core|office|other]` returns the `codeman doctor --json` report (`platform`, `summary`, `tools[]` with `status` `ok` \| `missing` \| `outdated` \| `skipped` \| `error`, `version`, `path`, `installHint`). The probe engine is synchronous, so it runs in a child process of the same entry script, never on the server's event loop (30 s timeout). It names install paths and versions, so it is admin only in multi-user mode (`403`). `400` for an unknown category, `500` if the child produces no report.
## Keep awake
`GET /api/system/keep-awake` reports the sleep lock behind the `keepAwakeEnabled` setting (switched through `PUT /api/settings`, together with `keepAwakeAcOnly`): `{ enabled, acOnly, platform: linux|macos|unsupported, state, onAc, lidHelper, detail }`. `state` is `off` \| `paused-battery` \| `starting` \| `active` \| `denied` (Linux refused the lock because no one is logged in to a desktop; retried every minute) \| `unavailable` \| `failed` (retried). `onAc` is `null` when unknown or not read; `lidHelper` is `installed` \| `missing` on macOS and `null` elsewhere. In multi-user mode a non-admin's `keepAwake*` values in `PUT /api/settings` are dropped (the rest of the save goes through).
## Voice dictation
Browser dictation transcribed through this server's Claude Code login, i.e. the
+3 -1
View File
@@ -841,13 +841,15 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
⚠️ **Persistence and joining.** `codeman:tile-grid` (localStorage, per browser, never sent to the server) holds `{ v: 1, open, ids, count, focused, zoomed, colFr, rowFr }`, session ids and layout only, never content, written on every change (move, divider pointer-up, add, remove, count pick, focus, zoom); its `ids` are the CELLS, `null` for an empty one, and `sanitizeTileGridState` returns them as `cells` (a dropped id a hole, never a shift) beside the packed `ids` every list consumer wants, plus `freed` (cells whose session went away since) and `count`. ⚠️ `count` is how many tiles the user's own last change left: `removeTile(..., { gone: true })` (the `_onSessionDeleted` wrapper, `_reconcileTileGrid`, `_onTileExit`, and app.js `_markDetached` for a session popped out while the grid is open) does NOT lower it, so the next activation refills that cell, while a removal by hand does; it is derived (the sessions the cells name) for a value written before it, and the format stays `v: 1` so an older build still reads a newer value. A restore keeps the cells when their shape matches the current one, else `reformTileCells` (positions kept when all fit, else packed). ⚠️ Every close keeps the grid as `open: false` (`closeTileGrid({ keepStored: true })` from every caller: the toggle, a non-tiled pick, `leaveTiles`, Home, the width gate, the last tile leaving, "Open group as tiles", kill-all); `_closeStoredTileGrid` (a `#session=` link on load) flips `open` on the RAW stored value, so a gone id still frees its cell; `_openStoredTileGrid` holds `_persistTileGrid` (`_tilePersistHold`) until the grid is back, so `openTileGrid`'s packed intermediate layout is never written over it. Only when none of its sessions survive does activation rank from scratch. ⚠️ A RELOAD's fill (`_restoreTileGrid` inside `handleInit`) ranks on status and stamps only: pending approvals arrive later through the async `seedApprovals`, so needs-input cannot rank for that one fill, and a late seed never re-forms the restored grid (holding the fill back would open fewer tiles, possibly another shape, and move the user's tiles a moment after the reload; pinned in `test/tile-grid-restore.test.ts`). A solo window never reads or writes it, an automatic zoom is not stored. Sessions created by THIS tab's Run join the open grid (`_joinTileGridFromRun`, called from session-ui.js `_ensureCreatedSessionVisible`; a wrapper from tile-grid.js would be overwritten by session-ui.js's later `Object.assign`); sessions created elsewhere arrive only by `session:created` and never join. ⚠️ A tile that joins that way connects BEFORE Run starts its pane: its resize reaches a session with no PTY, which `Session.resize()` only records (`_lastDesktopDims`) while the spawn uses a fixed 120x40, and Run's own resize step measures the parked main terminal (`display: none`, so `proposeDimensions()` is NaN and the step is skipped). Measured live: a 97x17 tile over a 120x40 pane. So `_renderTileChrome` remembers each tile's last-seen pid and calls `tile.paneStarted()` when it appears or changes (keyed on the sessions map, so a `handleInit` after an SSE drop counts too); `paneStarted()` forgets the sent size and sends it, and a hidden tile (a zoomed neighbour) sends nothing but keeps the size forgotten, so its next `fit()` sends it. A plain `fit({ force: true })` would lose that case. Tests: `test/tile-grid-*.test.ts` over the shared vm harness `test/mocks/tile-grid-vm.ts`.
⚠️ **Detach Tiles** (`tileDetachEnabled`, per-device, default OFF: in `displayKeys`, stripped from the settings PUT, not in `SettingsUpdateSchema`; App Settings → Appearance, its row shown on desktop only). A tile leaves the grid for a window of its own, and comes back into any Codeman window's grid, by dragging, with nothing new on the server: a pop-out is another client of the same session (`detachSession`), and a tile is a `TerminalTile` in whichever window has it. (1) A header let go OUTSIDE the window opens it with `detachSession(id, placement)`, the tile's size (at least 480x320), its header near the drop point, after `TILE_TEAR_OFF_SETTLE_MS` (120 ms) that a claim from another window cancels. "Outside" is the dragend's own point off the viewport with `dropEffect: 'none'`; where a browser reports no point (0, 0) it is the page's record of a `dragleave` at the viewport's edge with nothing entered, cleared by any later `dragover`. A drop that any target took (`dropEffect: 'move'`, in this window or another) never opens one, a drop inside on nothing changes nothing, and with the setting on a lone or zoomed tile drags too (out only: no target here takes it). (2) A header dropped on ANOTHER Codeman window's tile or empty cell moves it there: that window's `_acceptTabDrops` takes a drag that is none of its own and carries `application/x-codeman-tile` (`_isForeignTileDrag`; the id is only readable on drop), docks it through the target's own drop (`_dockForeignTile` → `dropSessionOnTile` / `dropSessionOnSlot`, so `_reorderTiles` stays the one move path) and posts `tile-adopted` on the `codeman-windows` channel. Only the window the tile was dragged FROM acts on that (its drag still settling, or ended within `TILE_ADOPT_WINDOW_MS`): the tile goes with `focus: false`, and a last tile closes the grid onto the welcome screen, never onto that session, since two windows sizing one PTY garble it. (3) A pop-out's title (`#soloSessionTitle`, `_installSoloTileHandle`) carries the same type, so it drags back onto any grid: docking a popped-out session `_redock`s it first (a detached session never mounts), posts `close-request`, and ignores that pop-out's `detached` answers for `TILE_DOCK_GRACE_MS` (`_tileDockedRecently`), which would otherwise take the new tile straight back off. A pop-out that gets `close-request` is RELEASED (`_releaseSoloWindow`): it posts `redocked` at once, stops answering roll-calls, then closes; one a script may not close (opened by typing its URL) says where the session went instead of staying a pop-out every dashboard would mark detached again. A tile's ⋯ menu offers "Open in a new window" with the setting on (`detachTile`, placed over the tile): the keyboard's way to the drag. ⚠️ Chrome keeps a script-opened window on the opener's screen unless the page holds the Window Management permission, so a drop on another monitor opens at this screen's edge (drag the window across from there), and Wayland ignores the position. The gesture overlay reaches all of it through `tileAtPoint` / `canGrabTile` / `tileDropTargetAt` / `dropOnTileTarget` / `isOverTileGrid` / `detachTileAtPoint`, never move logic of its own; its pop-out has no click behind it, so a popup blocker refuses it unless the site's pop-ups are allowed (detachSession's toast says so, and the tile stays). Tests: `test/tile-grid-detach.test.ts`.
### Gesture control: the setting
**Gesture control** (the camera hand-tracking overlay) is **opt-in, default OFF**, under App Settings → Terminal & Input → Scrolling & rendering (`gestureControlEnabled`). `CODEMAN_GESTURE=1` makes the feature _available_ on the instance (CSP widening + `/gesture/` assets) and sets `window.__codemanGestureAvailable` (the Input section only shows when set); the overlay bundle is injected by `renderIndexHtml` **only when the setting is enabled**, so that method is `async` and reads `settings.json` via `readSettings(true)` — the `true` forces a **fresh** read (bypassing the 2s `_settingsCache`), because a post-save reload happens within that TTL and the cached value would otherwise render the pre-toggle state. Toggling the setting reloads the page (the bundle is render-injected).
### Gesture control: the source package
**Gesture-control source lives in-repo** at `packages/gesture-control/` (workspace package `codeman-gesture-control`, was the standalone `Ark0N/codeman-gesture-control` repo). The transport-agnostic core is `src/gesture/*` (MediaPipe GestureRecognizer → One-Euro-filtered cursor → pinch state machine); `src/codeman/entry.ts` is the Codeman _consumer_ that maps grab/drag/drop onto real `.session-tab`/toolbar buttons and is the bundle entry. **Edit there, then run `npm run build:gesture`** (`scripts/build-gesture-bundle.mjs` → esbuild bundles `entry.ts`, MediaPipe JS included, into `src/web/public/gesture/gesture-codeman.js`) and **commit the regenerated bundle** — the committed bundle is what dev/`tsx` serves (no bundler at runtime), and `scripts/build.mjs` reruns the same step so prod always reflects current source. The MediaPipe **wasm + model** are NOT bundled — loaded at runtime from same-origin `/gesture/wasm` + `/gesture/gesture_recognizer.task`, fetched by `scripts/fetch-gesture-assets.mjs` (gitignored, see Gotchas). `entry.ts` mounts `window.__codemanGesture = new GestureBridge()` idempotently at module-eval. A standalone vite playground (`npm run dev` in the package — fake tabs, no Codeman) lets you iterate on gesture _feel_ in isolation. ⚠️ Keep `MP_VERSION` in `fetch-gesture-assets.mjs` in sync with `@mediapipe/tasks-vision` in `packages/gesture-control/package.json`.
**Gesture-control source lives in-repo** at `packages/gesture-control/` (workspace package `codeman-gesture-control`, was the standalone `Ark0N/codeman-gesture-control` repo). The transport-agnostic core is `src/gesture/*` (MediaPipe GestureRecognizer → One-Euro-filtered cursor → pinch state machine); `src/codeman/entry.ts` is the Codeman _consumer_ that maps grab/drag/drop onto real `.session-tab`/toolbar buttons and is the bundle entry. **Edit there, then run `npm run build:gesture`** (`scripts/build-gesture-bundle.mjs` → esbuild bundles `entry.ts`, MediaPipe JS included, into `src/web/public/gesture/gesture-codeman.js`) and **commit the regenerated bundle** — the committed bundle is what dev/`tsx` serves (no bundler at runtime), and `scripts/build.mjs` reruns the same step so prod always reflects current source. The MediaPipe **wasm + model** are NOT bundled — loaded at runtime from same-origin `/gesture/wasm` + `/gesture/gesture_recognizer.task`, fetched by `scripts/fetch-gesture-assets.mjs` (gitignored, see Gotchas). `entry.ts` mounts `window.__codemanGesture = new GestureBridge()` idempotently at module-eval. A standalone vite playground (`npm run dev` in the package — fake tabs, no Codeman) lets you iterate on gesture _feel_ in isolation. ⚠️ Keep `MP_VERSION` in `fetch-gesture-assets.mjs` in sync with `@mediapipe/tasks-vision` in `packages/gesture-control/package.json`. The tile grid's verbs (a tile pinched anywhere on it and carried onto another tile or an empty cell; a tab carried onto the grid joins it there; with Detach Tiles a tile let go outside the grid pops out) ask tile-grid.js's gesture helpers (see Tile grid, Detach Tiles) and never move tiles themselves, so the hand and the mouse cannot disagree about a drop.
### Theme skins
-6
View File
@@ -57,11 +57,6 @@ unattended. You can leave while it builds. What it asks you:
4. **Whether to run Codeman in the background.** Enter installs a systemd user service or a
macOS LaunchAgent that starts on boot; answering no offers to start it in this terminal
instead, or not at all.
5. **On a laptop only: keep it awake while Codeman runs?** Closing the lid suspends the
machine, and every agent session freezes until it wakes. Yes turns on App Settings >
System > **Power** (only while plugged in). On a Mac it also offers a small root helper,
because macOS sleeps on lid close whatever an app asks; it needs your admin password
once. The default is no, and `--yes` never turns it on.
It ends on a screen with the URL (your tailnet, your network, or this machine), a QR code to
scan with your phone, and the two commands you need to manage the service.
@@ -80,7 +75,6 @@ install.sh uninstall # remove (offers to undo a rename it performed)
install.sh tailscale # retrofit Tailscale access onto an existing install
install.sh name [<n>] # rename this machine on your tailnet (default codeman-<hostname>)
install.sh cloudflared # install cloudflared for the in-app Cloudflare tunnel
install.sh keep-awake # keep this machine awake while Codeman runs (macOS: adds the lid helper)
```
**Flags** answer the questions from the command line and pipe through `bash -s --`:
+2 -8
View File
@@ -181,14 +181,8 @@ Rebinding for the shortcut registry. See [Keyboard Shortcuts](Keyboard-Shortcuts
`CLAUDE.md` template for new cases, default working directory, the image watcher, and
Cloudflare tunnel controls including the tunnel URL. The **Diagnostics** group runs
`codeman doctor` on the server and lists the agent CLIs, tmux, Node and the optional office
tools with their versions and install hints (admin only in multi-user mode). The **Power**
group keeps the machine Codeman runs on awake while Codeman runs (`keepAwakeEnabled`, off by
default; **Only on AC power**, `keepAwakeAcOnly`, on by default), and shows what the lock is
doing right now. On Linux it blocks lid-close suspend while someone is logged in to the
desktop (the desktop's own Automatic Suspend timer is separate). On macOS it blocks idle
sleep, and lid-close sleep too once the root helper from `install.sh keep-awake` is
installed. Admin only in multi-user mode. In multi-user mode, the **Users** administration
entry is injected here.
tools with their versions and install hints (admin only in multi-user mode). In multi-user
mode, the **Users** administration entry is injected here.
## Session Options
+28 -258
View File
@@ -7,9 +7,8 @@
#
# The flow: look at what is already on the machine, ask at most three
# questions (how the dashboard is reached, optionally what to call this
# machine on your tailnet, whether to run Codeman as a service; on a laptop,
# a follow-up on keeping it awake), then do all the work unattended and end on
# the URL, with a QR code for your phone.
# machine on your tailnet, whether to run Codeman as a service), then do all
# the work unattended and end on the URL, with a QR code for your phone.
#
# Flags (each has an environment-variable twin, listed below):
# --tailscale | --lan | --local How the dashboard is reached (question 1)
@@ -49,7 +48,6 @@
# install.sh name [<n>] - Rename this machine on your tailnet (default: codeman-<hostname>)
# install.sh status - Print the URLs, the QR code and how to manage the service
# install.sh cloudflared - Install cloudflared for the in-app Cloudflare tunnel
# install.sh keep-awake - Keep this machine awake while Codeman runs (macOS: adds the lid helper)
set -euo pipefail
@@ -131,18 +129,6 @@ SUBCOMMAND_ARG=""
# alone) | empty (no service manager here).
LAUNCH_CHOICE="3"
SERVICE_TYPE=""
# Follow-up to question 3, laptops only (choose_keep_awake): KEEP_AWAKE=1
# writes keepAwakeEnabled into settings.json, KEEP_AWAKE_LID_HELPER=1 installs
# the macOS root helper that covers lid-close sleep. Empty = leave as is.
KEEP_AWAKE=""
KEEP_AWAKE_LID_HELPER=""
# Where laptop detection looks. Variables only so the test harness can point
# them at a fake tree.
POWER_SUPPLY_ROOT="/sys/class/power_supply"
LID_BUTTON_ROOT="/proc/acpi/button/lid"
KEEP_AWAKE_HELPER_DIR="/Library/Application Support/Codeman"
KEEP_AWAKE_HELPER_PLIST="/Library/LaunchDaemons/com.codeman.keepawake.plist"
KEEP_AWAKE_HELPER_LABEL="com.codeman.keepawake"
# Everything the unattended steps print goes here; the terminal gets one line
# per step and the tail of this file on failure.
@@ -2719,200 +2705,6 @@ cloudflared_subcommand() {
# Wait briefly for codeman-web.service to report active. A bad node path or a
# busy port makes the unit crash within the first seconds (then sit in
# activating/auto-restart), so a blind "started!" message would be a lie.
# ----------------------------------------------------------------------------
# Keep awake (laptops): Codeman holds an OS sleep lock while it runs
# ----------------------------------------------------------------------------
# The server does the work (src/keep-awake-manager.ts: systemd-inhibit on
# Linux, caffeinate on macOS); the installer only asks, writes the setting and,
# on macOS, installs the root helper for the one thing caffeinate cannot do:
# keep a closed MacBook awake (scripts/keep-awake-macos.sh).
# True on a machine with its own battery or a lid. A peripheral's battery
# (scope=Device, e.g. a wireless mouse) does not make a desktop a laptop.
is_laptop() {
local os="$1" d t scope
if [[ "$os" == "macos" ]]; then
pmset -g batt 2>/dev/null | grep -q 'InternalBattery'
return
fi
if [[ -d "$LID_BUTTON_ROOT" ]] && [[ -n "$(ls -A "$LID_BUTTON_ROOT" 2>/dev/null)" ]]; then
return 0
fi
for d in "$POWER_SUPPLY_ROOT"/*; do
[[ -f "$d/type" ]] || continue
t=$(cat "$d/type" 2>/dev/null || true)
[[ "$t" == "Battery" ]] || continue
scope=$(cat "$d/scope" 2>/dev/null || true)
[[ "$scope" == "Device" ]] && continue
return 0
done
return 1
}
keep_awake_settings_file() {
printf '%s\n' "$HOME/.codeman/settings.json"
}
# The server writes settings.json with JSON.stringify(…, null, 2).
keep_awake_enabled_now() {
grep -q '"keepAwakeEnabled": *true' "$(keep_awake_settings_file)" 2>/dev/null
}
# Asked right after question 3, on laptops only ($2 = force skips that check,
# for `install.sh keep-awake`). The default is no, so --yes and headless runs
# never turn it on: keeping a machine awake is the owner's call.
choose_keep_awake() {
local os="$1" force="${2:-}"
KEEP_AWAKE=""
KEEP_AWAKE_LID_HELPER=""
if [[ "$force" != "force" ]]; then
is_laptop "$os" || return 0
fi
if keep_awake_enabled_now; then
info "Keep-awake is already on (App Settings > System > Power)."
else
echo -e " ${DIM}Closing the lid suspends the machine, and every agent session freezes until it wakes.${NC}" >&2
prompt_yes_no "Keep this machine awake while Codeman runs, even with the lid closed (only while plugged in)?" "n" || return 0
KEEP_AWAKE="1"
fi
# The helper needs sudo, so it is only ever offered to a person at a terminal.
if [[ "$os" == "macos" ]] && [[ ! -f "$KEEP_AWAKE_HELPER_PLIST" ]] &&
[[ "$NONINTERACTIVE" != "1" && "$ASSUME_YES" != "1" ]] && has_tty; then
echo -e " ${DIM}macOS sleeps on lid close whatever an app asks. A small root helper (pmset disablesleep) covers that, only while Codeman runs.${NC}" >&2
if prompt_yes_no "Install the lid helper? (asks for your admin password once)" "y"; then
KEEP_AWAKE_LID_HELPER="1"
sudo_session_start
fi
fi
return 0
}
# Turn the setting on before the service starts, so its first boot already
# holds the lock. node does the JSON; a settings file that does not parse is
# left untouched.
write_keep_awake_setting() {
local file
file=$(keep_awake_settings_file)
mkdir -p "$(dirname "$file")"
if node -e '
const fs = require("fs");
const p = process.argv[1];
let s = {};
try { s = JSON.parse(fs.readFileSync(p, "utf8")); }
catch (e) { if (e.code !== "ENOENT") process.exit(2); }
if (s === null || typeof s !== "object" || Array.isArray(s)) process.exit(2);
s.keepAwakeEnabled = true;
if (s.keepAwakeAcOnly === undefined) s.keepAwakeAcOnly = true;
fs.writeFileSync(p, JSON.stringify(s, null, 2));
' "$file" </dev/null; then
success "Keep-awake is on (only while plugged in; App Settings > System > Power)"
return 0
fi
warn "Could not turn keep-awake on: $file is not valid JSON. Use App Settings > System > Power instead."
return 1
}
# macOS: copy the helper to a ROOT-OWNED path (a root daemon must never run a
# file the user can edit, and the install dir is the user's) and load it as a
# LaunchDaemon that runs every 20 seconds. It only acts while the server keeps
# a fresh request file in the data dir.
install_keep_awake_lid_helper() {
local src="$INSTALL_DIR/scripts/keep-awake-macos.sh"
local script="$KEEP_AWAKE_HELPER_DIR/keep-awake-macos.sh"
local request="$HOME/.codeman/keep-awake-lid.pid"
local tmp
if [[ ! -f "$src" ]]; then
warn "Lid helper not found at $src; skipped."
return 1
fi
if ! { run_as_root mkdir -p "$KEEP_AWAKE_HELPER_DIR" &&
run_as_root chown root:wheel "$KEEP_AWAKE_HELPER_DIR" &&
run_as_root chmod 755 "$KEEP_AWAKE_HELPER_DIR" &&
run_as_root install -m 755 -o root -g wheel "$src" "$script"; }; then
warn "Could not install the lid helper (sudo refused?). Run later: install.sh keep-awake"
return 1
fi
tmp=$(mktemp)
cat > "$tmp" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>$KEEP_AWAKE_HELPER_LABEL</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>$(xml_escape "$script")</string>
<string>$(xml_escape "$request")</string>
</array>
<key>StartInterval</key>
<integer>20</integer>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOF
run_as_root launchctl unload "$KEEP_AWAKE_HELPER_PLIST" 2>/dev/null || true
if ! run_as_root install -m 644 -o root -g wheel "$tmp" "$KEEP_AWAKE_HELPER_PLIST"; then
rm -f "$tmp"
warn "Could not write $KEEP_AWAKE_HELPER_PLIST. Run later: install.sh keep-awake"
return 1
fi
rm -f "$tmp"
run_as_root launchctl load -w "$KEEP_AWAKE_HELPER_PLIST" 2>/dev/null || true
if run_as_root launchctl list "$KEEP_AWAKE_HELPER_LABEL" &>/dev/null; then
success "Lid helper installed (it only acts while Codeman asks it to)"
return 0
fi
warn "The lid helper did not load. Inspect: sudo launchctl list $KEEP_AWAKE_HELPER_LABEL"
return 1
}
# Uninstall: undo a disablesleep only the helper set (its .owned marker, never
# an administrator's own setting), then remove the daemon and its files.
remove_keep_awake_lid_helper() {
[[ -f "$KEEP_AWAKE_HELPER_PLIST" || -d "$KEEP_AWAKE_HELPER_DIR" ]] || return 0
run_as_root launchctl unload "$KEEP_AWAKE_HELPER_PLIST" 2>/dev/null || true
if [[ -f "$KEEP_AWAKE_HELPER_DIR/keep-awake.owned" ]]; then
run_as_root pmset -a disablesleep 0 2>/dev/null || true
fi
run_as_root rm -f "$KEEP_AWAKE_HELPER_PLIST" "$KEEP_AWAKE_HELPER_DIR/keep-awake-macos.sh" \
"$KEEP_AWAKE_HELPER_DIR/keep-awake.owned" 2>/dev/null || true
run_as_root rmdir "$KEEP_AWAKE_HELPER_DIR" 2>/dev/null || true
success "Removed the keep-awake lid helper"
}
# Work-phase half of choose_keep_awake. Both steps are optional extras: a
# failure warns and the install carries on.
apply_keep_awake() {
if [[ "$KEEP_AWAKE" == "1" ]]; then
write_keep_awake_setting || true
fi
if [[ "$KEEP_AWAKE_LID_HELPER" == "1" ]]; then
install_keep_awake_lid_helper || true
fi
return 0
}
# `install.sh keep-awake`: turn it on for an existing install (no laptop check:
# asking for it is the answer), add the macOS lid helper, then restart the
# service so the running server picks it up.
keep_awake_subcommand() {
print_banner
command -v node &>/dev/null || die "node is required. Install Codeman first (run the installer without arguments)."
local os
os=$(detect_os)
choose_keep_awake "$os" force
if [[ -z "$KEEP_AWAKE" && -z "$KEEP_AWAKE_LID_HELPER" ]]; then
info "Nothing changed."
return 0
fi
apply_keep_awake
echo ""
restart_running_service
}
verify_systemd_active() {
local attempt
for attempt in 1 2 3; do
@@ -3240,7 +3032,6 @@ main() {
choose_network_binding
echo ""
choose_launch_mode "$os"
choose_keep_awake "$os"
echo ""
# ========================================================================
@@ -3259,9 +3050,6 @@ main() {
# (symlinks, PATH, launch menu) instead of silently "updating".
date -u +%Y-%m-%dT%H:%M:%SZ > "$INSTALL_DIR/.install-complete"
# Before the service starts, so its first boot already reads the setting.
apply_keep_awake
local service_ok="true"
if [[ "$LAUNCH_CHOICE" == "2" ]]; then
if [[ "$SERVICE_TYPE" == "launchd" ]]; then
@@ -3705,36 +3493,6 @@ print_done_screen() {
return 0
}
# Restart Codeman under whatever supervises it, so a new build or a changed
# setting takes effect; otherwise say how. Shared by update and keep-awake.
restart_running_service() {
local agent_plist="$HOME/Library/LaunchAgents/com.codeman.web.plist"
if systemctl --user is-active codeman-web.service &>/dev/null 2>&1; then
info "Restarting codeman-web service..."
systemctl --user restart codeman-web.service 2>/dev/null || true
if verify_systemd_active; then
success "codeman-web service restarted"
else
warn "codeman-web.service did not come back up."
warn "Inspect: systemctl --user status codeman-web ; journalctl --user -u codeman-web -e"
fi
elif [[ -f "$agent_plist" ]]; then
info "Restarting LaunchAgent..."
launchctl unload "$agent_plist" 2>/dev/null || true
launchctl load "$agent_plist" 2>/dev/null || true
success "LaunchAgent restarted"
elif [[ -f "/Library/LaunchDaemons/com.codeman.web.plist" ]]; then
# Left alone on purpose (see setup_launchd_service); it keeps running
# the previous build until its owner restarts it.
info "A system LaunchDaemon supervises Codeman; restart it to apply:"
echo -e " ${CYAN}sudo launchctl kickstart -k system/com.codeman.web${NC}"
else
echo -e " ${DIM}Restart codeman web to apply:${NC}"
echo -e " ${CYAN}codeman web --stop; codeman web -d${NC}"
fi
echo ""
}
update() {
if [[ ! -d "$INSTALL_DIR/.git" ]]; then
die "Codeman is not installed at $INSTALL_DIR. Run the installer first."
@@ -3767,15 +3525,32 @@ update() {
success "Updated to $(node -e "console.log(require('./package.json').version)")"
echo ""
restart_running_service
# The lid helper runs from a root-owned copy, so an update never reaches it
# on its own (and must not: that would need sudo here). Say so when it drifted.
if [[ -f "$KEEP_AWAKE_HELPER_DIR/keep-awake-macos.sh" ]] &&
! cmp -s "$INSTALL_DIR/scripts/keep-awake-macos.sh" "$KEEP_AWAKE_HELPER_DIR/keep-awake-macos.sh"; then
info "The keep-awake lid helper has a newer version. Refresh it with: install.sh keep-awake"
echo ""
# Auto-restart service if running, otherwise tell the user
local agent_plist="$HOME/Library/LaunchAgents/com.codeman.web.plist"
if systemctl --user is-active codeman-web.service &>/dev/null 2>&1; then
info "Restarting codeman-web service..."
systemctl --user restart codeman-web.service 2>/dev/null || true
if verify_systemd_active; then
success "codeman-web service restarted"
else
warn "codeman-web.service did not come back up."
warn "Inspect: systemctl --user status codeman-web ; journalctl --user -u codeman-web -e"
fi
elif [[ -f "$agent_plist" ]]; then
info "Restarting LaunchAgent..."
launchctl unload "$agent_plist" 2>/dev/null || true
launchctl load "$agent_plist" 2>/dev/null || true
success "LaunchAgent restarted"
elif [[ -f "/Library/LaunchDaemons/com.codeman.web.plist" ]]; then
# Left alone on purpose (see setup_launchd_service); it keeps running
# the previous build until its owner restarts it.
info "A system LaunchDaemon supervises Codeman; restart it to run the new build:"
echo -e " ${CYAN}sudo launchctl kickstart -k system/com.codeman.web${NC}"
else
echo -e " ${DIM}Restart codeman web to use the new version:${NC}"
echo -e " ${CYAN}codeman web --stop; codeman web -d${NC}"
fi
echo ""
# Reflect the service's actual binding in the closing notice. Updates
# never rewrite the service files, so the existing choice is authoritative.
@@ -3828,9 +3603,6 @@ uninstall() {
rm -f "$agent_plist"
success "Removed LaunchAgent"
fi
if [[ "$(uname -s)" == "Darwin" ]]; then
remove_keep_awake_lid_helper
fi
if [[ -f "$daemon_plist" ]]; then
# This installer never writes a LaunchDaemon (setup_launchd_service
# leaves one alone), so this one is the user's own headless-Mac setup:
@@ -3949,7 +3721,6 @@ Subcommands
name [<n>] Rename this machine on your tailnet (default: codeman-<hostname>)
status Print the URLs, the QR code and how to manage the service
cloudflared Install cloudflared for the in-app Cloudflare tunnel
keep-awake Keep this machine awake while Codeman runs (macOS: adds the lid helper)
Environment: CODEMAN_NONINTERACTIVE=1, CODEMAN_INSTALL_DIR, CODEMAN_HOST,
CODEMAN_PASSWORD, CODEMAN_PORT, CODEMAN_TAILSCALE=1, CODEMAN_TAILSCALE_NAME,
@@ -3991,7 +3762,7 @@ parse_flags() {
CODEMAN_PORT="$1"; export CODEMAN_PORT; RECONFIGURE="1" ;;
--port=*) CODEMAN_PORT="${1#--port=}"; export CODEMAN_PORT; RECONFIGURE="1" ;;
--help|-h) usage; exit 0 ;;
update|uninstall|tailscale|name|status|cloudflared|keep-awake)
update|uninstall|tailscale|name|status|cloudflared)
[[ -z "$SUBCOMMAND" ]] || die "Only one subcommand at a time ($SUBCOMMAND and $1 given)."
SUBCOMMAND="$1" ;;
-*) die "Unknown option: $1 (see --help)" ;;
@@ -4024,7 +3795,6 @@ case "$SUBCOMMAND" in
name) setup_name_subcommand ;;
status) status_subcommand ;;
cloudflared) cloudflared_subcommand ;;
keep-awake) keep_awake_subcommand ;;
*)
# Only a COMPLETED install re-runs as a quiet update. A partial one
# (clone succeeded but build/menu never finished) lacks the marker and
+7
View File
@@ -133,6 +133,13 @@ its CSP for WebAssembly). Deploy = copy the bundle into Codeman's
drop point. Pinch the panel again to move it anywhere. It stays inside the
camera-owning page, so the hand keeps control (the old `window.app.detachSession`
`window.open` was a one-way trip). A small twitch-and-release cancels.
- **Tiles** (tile grid open): pinch anywhere on a tile and carry it onto
another tile (the two trade places) or an empty cell (it moves there). A
session tab carried onto a tile or an empty cell joins the grid there. With
**Detach Tiles** on (App Settings, per device, off by default) a tile let go
outside the grid opens as a window of its own, which needs the site's pop-ups
allowed (a hand is no click). The moves are tile-grid.js's own
(`tileDropTargetAt` / `dropOnTileTarget` / `detachTileAtPoint`).
- **Run / Run Shell** — pinch over the **Run** (`#runBtn`) or **Run Shell**
(`.btn-shell`) toolbar button and release in place to fire it; drifting too
far first cancels the tap. The button list is `CLICK_SELECTOR` in `entry.ts`.
+182 -6
View File
@@ -27,6 +27,14 @@
// • Button "tap" — pinch over a toolbar button (Run / Run Shell) and release
// in place → fires the button's real click handler. Drift too far first and
// it's treated as a stray move, not a tap.
// • Tile "grab-to-move": with the tile grid open, pinch anywhere on a tile
// and carry it onto another tile (the two trade places) or an empty cell
// (it moves there). With Detach Tiles on (App Settings, per device, off by
// default) a tile let go OUTSIDE the grid opens as a window of its own.
// A session TAB carried onto a tile or an empty cell joins the grid there,
// as a mouse-dragged tab does. Every move goes through app.js's own paths
// (tile-grid.js tileDropTargetAt / dropOnTileTarget / detachTileAtPoint), so
// the hand and the mouse can never disagree about what a drop does.
//
// Why in-page floats, not OS-window detach (decided 2026-06-08, see
// docs/MULTIMONITOR_DESIGN.md): the hand only exists in the one page that owns
@@ -52,11 +60,22 @@ declare global {
saveSubagentWindowStates?: () => void;
subagentWindowZIndex?: number;
ultracodeWindowZIndex?: number;
// The tile grid (tile-grid.js). All optional: an older dashboard without
// them simply has no tile verbs for the hand.
tileAtPoint?: (x: number, y: number) => string | null;
canGrabTile?: (id: string) => boolean;
tileDropTargetAt?: (x: number, y: number, draggedId: string) => TileTarget | null;
dropOnTileTarget?: (draggedId: string, target: TileTarget) => boolean;
isOverTileGrid?: (x: number, y: number) => boolean;
tileDetachEnabled?: () => boolean;
detachTileAtPoint?: (id: string, x: number, y: number, at?: { offsetX: number; offsetY: number }) => boolean;
};
}
}
const TAB_SELECTOR = '.session-tab';
/** A tile of the open tile grid (tile-grid.js), keyed by `data-session-id`. */
const TILE_SELECTOR = '#tileGrid .tile';
/** An in-page floating session panel this layer spawned — re-grabbable to move. */
const PANEL_SELECTOR = '.cg-float';
/** The dashboard's own floating agent windows (subagent runs + ultracode run and
@@ -81,11 +100,20 @@ const FLOAT_H = 420;
const DETACH_PULL_PX = 70;
/** If a button-pinch drifts more than this, it's a stray move, not a tap. */
const TAP_CANCEL_PX = 45;
/** How far (px) a grabbed tile must travel before it targets anything: a pinch
* that barely moves is a stray one, and the tile stays where it is. */
const TILE_MOVE_PX = 40;
/** The width (px) of the small copy of a grabbed tile that follows the hand. */
const TILE_GHOST_W = 280;
/** First letter colours: cyan left, violet right; green while pinching. */
const handColor = (handedness: string, pinching: boolean): string =>
pinching ? '#4ade80' : handedness === 'Right' ? '#a78bfa' : '#38bdf8';
/** Where a session carried by the hand would land in the tile grid: another
* tile, or an empty cell (tile-grid.js tileDropTargetAt). */
type TileTarget = { kind: 'tile'; id: string; el: HTMLElement } | { kind: 'cell'; cell: number; el: HTMLElement };
/** A floating in-page session panel (an iframe of `/session/:id`) the hand can
* place and re-grab. Stays in this page's DOM, so it never leaves hand reach. */
interface FloatingPanel {
@@ -107,6 +135,29 @@ type Grab =
oy: number;
/** Pulled past the float-out threshold at least once. */
armed: boolean;
/** With the tile grid open: the tile or empty cell it would join (highlighted). */
target: TileTarget | null;
}
| {
/** A tile of the open grid, carried to another cell or (Detach Tiles)
* out of the grid. The tile itself never moves until the drop: it dims
* (`tile--dragging`, the mouse drag's own class) and a small copy of
* it follows the hand. */
kind: 'tile';
id: string;
el: HTMLElement;
ghost: HTMLElement;
/** Where in the tile the hand closed, so a pop-out window lands under it. */
offsetX: number;
offsetY: number;
ox: number;
oy: number;
/** Travelled past TILE_MOVE_PX at least once. */
armed: boolean;
/** The tile or empty cell it would drop onto (highlighted). */
target: TileTarget | null;
/** Outside the grid with Detach Tiles on: letting go opens a window. */
out: boolean;
}
| {
kind: 'panel';
@@ -224,7 +275,7 @@ class GestureBridge {
await this.gc.start();
this.running = true;
this.button.classList.add('on');
this.status.textContent = 'on — pinch a tab, window, or button';
this.status.textContent = 'on: pinch a tab, tile, window, or button';
} catch (err) {
// Surface the *real* cause: MediaPipe/Emscripten can throw a non-Error
// (number/string), so `(err as Error).message` was logging "undefined".
@@ -295,6 +346,35 @@ class GestureBridge {
return;
}
// A tile of the open tile grid → carry it to another cell, or (Detach
// Tiles) out of the grid. Anywhere on the tile: the hand is choosing the
// whole tile, as with the agent windows. A tile that can do neither (alone
// or zoomed, Detach Tiles off) is left alone, so the pinch falls through.
const tileId = window.app?.tileAtPoint?.(x, y) ?? null;
const tileEl = tileId ? this.hitClosest(x, y, TILE_SELECTOR) : null;
if (tileId && tileEl && window.app?.canGrabTile?.(tileId)) {
const rect = tileEl.getBoundingClientRect();
const ghost = this.tileGhost(tileEl, rect);
document.body.append(ghost);
tileEl.classList.add('tile--dragging');
this.grabs.set(hand, {
kind: 'tile',
id: tileId,
el: tileEl,
ghost,
offsetX: Math.max(0, Math.min(x - rect.left, rect.width)),
offsetY: Math.max(0, Math.min(y - rect.top, rect.height)),
ox: x,
oy: y,
armed: false,
target: null,
out: false,
});
this.positionGhost(ghost, x, y);
this.status.textContent = 'moving tile';
return;
}
// A session tab → grab-and-pull-out into a floating panel (ghost follows).
const tab = this.hitClosest(x, y, TAB_SELECTOR);
const id = tab?.dataset.id;
@@ -308,7 +388,7 @@ class GestureBridge {
document.body.append(ghost);
tab.classList.add('cg-grabbed');
this.grabs.set(hand, { kind: 'tab', id, tab, ghost, ox: x, oy: y, armed: false });
this.grabs.set(hand, { kind: 'tab', id, tab, ghost, ox: x, oy: y, armed: false, target: null });
this.positionGhost(ghost, x, y);
return;
}
@@ -325,13 +405,42 @@ class GestureBridge {
private onDrag(hand: string, x: number, y: number): void {
const grab = this.grabs.get(hand);
if (grab?.kind === 'tile') {
this.positionGhost(grab.ghost, x, y);
if (!grab.armed && Math.hypot(x - grab.ox, y - grab.oy) >= TILE_MOVE_PX) grab.armed = true;
if (!grab.armed) return;
const app = window.app;
const target = app?.tileDropTargetAt?.(x, y, grab.id) ?? null;
this.setTileTarget(grab, target);
const out = !target && !!app?.tileDetachEnabled?.() && !app?.isOverTileGrid?.(x, y);
grab.out = out;
grab.ghost.classList.toggle('cg-armed', !!target);
grab.ghost.classList.toggle('cg-out', out);
this.status.textContent = target
? target.kind === 'tile'
? 'release to swap tiles'
: 'release to move the tile here'
: out
? 'release to open in a new window'
: 'moving tile';
return;
}
if (grab?.kind === 'tab') {
this.positionGhost(grab.ghost, x, y);
const pulled = Math.hypot(x - grab.ox, y - grab.oy) >= DETACH_PULL_PX;
if (pulled !== grab.armed) {
// The tile grid open: a tile or an empty cell under the hand takes the
// tab there, as a mouse-dragged tab does.
const target = pulled ? (window.app?.tileDropTargetAt?.(x, y, grab.id) ?? null) : null;
const targetChanged = (target?.el ?? null) !== (grab.target?.el ?? null);
this.setTileTarget(grab, target);
if (pulled !== grab.armed || targetChanged) {
grab.armed = pulled;
grab.ghost.classList.toggle('cg-armed', pulled);
this.status.textContent = pulled ? 'release to float out' : 'on — pinch a tab';
this.status.textContent = target
? 'release to tile it here'
: pulled
? 'release to float out'
: 'on — pinch a tab';
}
return;
}
@@ -354,17 +463,44 @@ class GestureBridge {
if (tap && Math.hypot(x - tap.ox, y - tap.oy) > TAP_CANCEL_PX) {
tap.el.classList.remove('cg-tap-armed');
this.taps.delete(hand);
this.status.textContent = 'on — pinch a tab, window, or button';
this.status.textContent = 'on: pinch a tab, tile, window, or button';
}
}
private onDrop(hand: string, x: number, y: number): void {
const grab = this.grabs.get(hand);
if (grab?.kind === 'tile') {
this.grabs.delete(hand);
grab.ghost.remove();
grab.el.classList.remove('tile--dragging');
this.setTileTarget(grab, null);
const app = window.app;
if (!grab.armed) {
this.flash('cancelled');
return;
}
// Asked again at the drop: the grid may have changed since the last frame.
const target = app?.tileDropTargetAt?.(x, y, grab.id) ?? null;
if (target) {
this.flash(app?.dropOnTileTarget?.(grab.id, target) ? 'moved tile' : 'cancelled');
} else if (grab.out && !app?.isOverTileGrid?.(x, y)) {
// A window opened with no click behind it is what popup blockers stop:
// detachSession then says so in a toast and the tile stays.
const opened = app?.detachTileAtPoint?.(grab.id, x, y, { offsetX: grab.offsetX, offsetY: grab.offsetY });
this.flash(opened ? 'opened in a new window' : 'pop-out blocked: allow popups for this site');
} else {
this.flash('cancelled');
}
return;
}
if (grab?.kind === 'tab') {
this.grabs.delete(hand);
grab.ghost.remove();
grab.tab.classList.remove('cg-grabbed');
if (grab.armed) this.floatPanel(grab.id, x, y);
this.setTileTarget(grab, null);
const target = grab.armed ? (window.app?.tileDropTargetAt?.(x, y, grab.id) ?? null) : null;
if (target) this.flash(window.app?.dropOnTileTarget?.(grab.id, target) ? 'tiled' : 'cancelled');
else if (grab.armed) this.floatPanel(grab.id, x, y);
else this.flash('cancelled');
return;
}
@@ -505,6 +641,33 @@ class GestureBridge {
ghost.style.top = `${y}px`;
}
/** A small copy of a tile to follow the hand: its header (a copy: no
* listeners come along) over an empty body, in the tile's proportions. */
private tileGhost(tileEl: HTMLElement, rect: DOMRect): HTMLElement {
const ghost = el('div', 'cg-ghost cg-tile-ghost');
const width = Math.min(TILE_GHOST_W, rect.width);
ghost.style.width = `${width}px`;
ghost.style.height = `${Math.max(48, Math.round((width * rect.height) / Math.max(1, rect.width)))}px`;
const header = tileEl.querySelector('.tile-header');
if (header) {
const copy = header.cloneNode(true) as HTMLElement;
copy.removeAttribute('draggable');
ghost.append(copy);
}
ghost.append(el('div', 'cg-tile-ghost-body'));
return ghost;
}
/** Highlights the tile or empty cell a carried session would drop onto
* (the mouse drag's own `tile--drop-target`), clearing the last one. */
private setTileTarget(grab: { target: TileTarget | null }, target: TileTarget | null): void {
if (grab.target?.el !== target?.el) {
grab.target?.el.classList.remove('tile--drop-target');
target?.el.classList.add('tile--drop-target');
}
grab.target = target;
}
private cancelAllGrabs(): void {
// Floats themselves persist (they're placed windows) — only release any
// in-progress grab cleanly, restoring a moved panel's interactivity.
@@ -512,6 +675,11 @@ class GestureBridge {
if (grab.kind === 'tab') {
grab.ghost.remove();
grab.tab.classList.remove('cg-grabbed');
this.setTileTarget(grab, null);
} else if (grab.kind === 'tile') {
grab.ghost.remove();
grab.el.classList.remove('tile--dragging');
this.setTileTarget(grab, null);
} else if (grab.kind === 'panel') {
grab.panel.el.style.pointerEvents = '';
grab.panel.el.classList.remove('cg-float-grabbed', 'cg-redock');
@@ -525,6 +693,7 @@ class GestureBridge {
document
.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed, .cg-win-grabbed`)
.forEach((t) => t.classList.remove('cg-grabbed', 'cg-tap-armed', 'cg-win-grabbed'));
document.querySelectorAll(`${TILE_SELECTOR}.tile--dragging`).forEach((t) => t.classList.remove('tile--dragging'));
}
private onStatus(fps: number, hands: HandState[]): void {
@@ -607,6 +776,13 @@ function injectStyles(): void {
outline: 2px solid #38bdf8; outline-offset: -2px;
}
.cg-ghost.cg-armed { outline-color: #4ade80; box-shadow: 0 8px 28px rgba(74,222,128,.5); }
.cg-ghost.cg-out { outline-color: #fbbf24; box-shadow: 0 8px 28px rgba(251,191,36,.5); }
.cg-tile-ghost {
display: flex; flex-direction: column; overflow: hidden; transform: translate(-50%, -20%) scale(1);
background: var(--term-bg, #161b23); border: 1px solid var(--border-color, #333);
}
.cg-tile-ghost > .tile-header { flex: 0 0 auto; }
.cg-tile-ghost-body { flex: 1 1 auto; opacity: .5; }
.cg-dock {
position: fixed; right: 12px; bottom: 156px; z-index: ${Z + 3};
display: flex; align-items: center; gap: 8px; font: 12px/1 system-ui, sans-serif;
-62
View File
@@ -1,62 +0,0 @@
#!/bin/bash
# keep-awake-macos.sh: root helper behind Codeman's "Keep this computer awake" on macOS.
#
# caffeinate (which the server runs itself, no root) stops idle sleep but not lid-close
# sleep. Only `pmset -a disablesleep 1` keeps a closed MacBook awake, and that is a
# machine-wide root setting with no owner process. So this helper, run by the
# com.codeman.keepawake LaunchDaemon every 20 seconds, applies it while the server asks
# for it and undoes it when the server stops asking:
#
# - The server writes its pid to the request file and rewrites it every 30 seconds
# while it wants the lid covered (setting on, and on AC when "only on AC" is on).
# - The request counts only while the file is fresh (under 2 minutes old) AND its pid
# is alive AND that process belongs to the file's owner. A crashed or hung server
# therefore releases the lid within about two minutes on its own.
# - The helper undoes only a disablesleep it set itself (tracked by the .owned file),
# so an administrator's own `pmset -a disablesleep 1` is never switched off.
#
# install.sh copies this file to a ROOT-OWNED path before the daemon runs it; never run
# it from the user-writable install directory.
#
# Usage: keep-awake-macos.sh <request-file>
# Test hooks (set only by the test suite): CODEMAN_KEEPAWAKE_PMSET, CODEMAN_KEEPAWAKE_STATE_DIR.
set -u
REQ="${1:?usage: keep-awake-macos.sh <request-file>}"
PMSET="${CODEMAN_KEEPAWAKE_PMSET:-/usr/bin/pmset}"
STATE_DIR="${CODEMAN_KEEPAWAKE_STATE_DIR:-/Library/Application Support/Codeman}"
OWNED="$STATE_DIR/keep-awake.owned"
want=0
# -L: refuse a symlink (root must not be steered to read some other file).
# find -mmin -2: modified within the last 2 minutes (BSD and GNU find both support it).
if [ -f "$REQ" ] && [ ! -L "$REQ" ] && [ -n "$(find "$REQ" -mmin -2 2>/dev/null)" ]; then
pid=$(head -c 32 "$REQ" 2>/dev/null | tr -dc '0-9')
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
file_uid=$(ls -ln "$REQ" 2>/dev/null | awk '{print $3}')
pid_uid=$(ps -o uid= -p "$pid" 2>/dev/null | tr -d ' ')
if [ -n "$file_uid" ] && [ "$file_uid" = "$pid_uid" ]; then
want=1
fi
fi
fi
current=$("$PMSET" -g 2>/dev/null | awk '/SleepDisabled/ {print $2; exit}')
[ -n "$current" ] || current=0
if [ "$want" = "1" ]; then
# Already 1 without our marker means an administrator set it: leave it and do not
# claim it, so releasing later never switches their setting off.
if [ "$current" != "1" ]; then
if "$PMSET" -a disablesleep 1; then
mkdir -p "$STATE_DIR" && : > "$OWNED"
fi
fi
elif [ -f "$OWNED" ]; then
if [ "$current" = "1" ]; then
"$PMSET" -a disablesleep 0 || exit 1
fi
rm -f "$OWNED"
fi
exit 0
-402
View File
@@ -1,402 +0,0 @@
/**
* @fileoverview Holds the OS sleep lock behind `keepAwakeEnabled` for exactly as long
* as Codeman runs. The decisions (which lock, when, what a failure means) are pure and
* live in `keep-awake.ts`; this module only does the IO and keeps the state current.
*
* Lifecycle rules, each load-bearing:
*
* - **The lock dies with the server, never after it.** Linux: `systemd-inhibit` runs a
* `cat` on a stdin pipe from this process, so any exit (SIGKILL included) closes the
* pipe and releases the lock even under the unit's `KillMode=process`. macOS:
* `caffeinate -w <pid>` exits with the server. The macOS lid request file is only a
* heartbeat: the root helper ignores it once it is two minutes old.
* - **Reconcile from settings, never from a request body.** `apply()` takes the merged
* config and is idempotent, so the boot path and every `PUT /api/settings` call the
* same thing.
* - **A refusal is a state, not an error.** polkit denies the Linux lock until someone
* logs in to the desktop; that is reported as `denied` and retried, never thrown.
* - **Inert under vitest** unless a test injects its own deps, so the suite never takes
* a real lock on the machine running it.
*/
import { spawn as nodeSpawn, execFile, type ChildProcess } from 'node:child_process';
import { promises as fs } from 'node:fs';
import { release } from 'node:os';
import { join } from 'node:path';
import { dataPath } from './config/instance.js';
import {
MAC_LID_HEARTBEAT_MS,
MAC_LID_HELPER_PLIST,
MAC_LID_REQUEST_FILE,
LINUX_HELD_MARKER,
POWER_POLL_MS,
RETRY_MS,
classifyInhibitFailure,
isOnAcPowerLinux,
isOnAcPowerMac,
keepAwakePlatform,
linuxInhibitArgs,
macCaffeinateArgs,
shouldHoldLock,
type KeepAwakeConfig,
type KeepAwakePlatform,
type KeepAwakeStatus,
type PowerSupplyInfo,
} from './keep-awake.js';
/** Grace between closing the inhibitor's stdin and SIGTERM. */
const RELEASE_GRACE_MS = 2_000;
/** Bound on captured stderr from the lock process. */
const STDERR_CAP = 2_048;
export interface KeepAwakeDeps {
platform: KeepAwakePlatform;
serverPid: number;
spawn: (command: string, args: string[]) => ChildProcess;
readPowerSupplies: () => Promise<PowerSupplyInfo[]>;
readMacBatt: () => Promise<string | null>;
lidHelperInstalled: () => Promise<boolean>;
writeLidRequest: (pid: number) => Promise<void>;
removeLidRequest: () => Promise<void>;
}
const POWER_SUPPLY_DIR = '/sys/class/power_supply';
async function readSysValue(dir: string, name: string): Promise<string | undefined> {
try {
return (await fs.readFile(join(dir, name), 'utf-8')).trim();
} catch {
return undefined;
}
}
async function readLinuxPowerSupplies(): Promise<PowerSupplyInfo[]> {
let names: string[];
try {
names = await fs.readdir(POWER_SUPPLY_DIR);
} catch {
return [];
}
const out: PowerSupplyInfo[] = [];
for (const name of names) {
const dir = join(POWER_SUPPLY_DIR, name);
const type = await readSysValue(dir, 'type');
if (!type) continue;
const online = await readSysValue(dir, 'online');
out.push({
type,
online: online === undefined ? undefined : online === '1',
status: await readSysValue(dir, 'status'),
scope: await readSysValue(dir, 'scope'),
});
}
return out;
}
function readPmsetBatt(): Promise<string | null> {
return new Promise((resolve) => {
execFile('/usr/bin/pmset', ['-g', 'batt'], { timeout: 5_000 }, (err, stdout) => {
resolve(err ? null : String(stdout));
});
});
}
function defaultDeps(): KeepAwakeDeps {
const lidRequest = () => dataPath(MAC_LID_REQUEST_FILE);
return {
platform: keepAwakePlatform(process.platform, release()),
serverPid: process.pid,
spawn: (command, args) => nodeSpawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'] }),
readPowerSupplies: readLinuxPowerSupplies,
readMacBatt: readPmsetBatt,
lidHelperInstalled: async () => {
try {
await fs.access(MAC_LID_HELPER_PLIST);
return true;
} catch {
return false;
}
},
writeLidRequest: async (pid) => {
await fs.writeFile(lidRequest(), `${pid}\n`, { mode: 0o644 });
},
removeLidRequest: async () => {
await fs.rm(lidRequest(), { force: true });
},
};
}
export class KeepAwakeManager {
private readonly deps: KeepAwakeDeps;
private readonly inert: boolean;
private config: KeepAwakeConfig = { enabled: false, acOnly: true };
private status: KeepAwakeStatus;
private child: ChildProcess | null = null;
/** Children we asked to exit; their exit is expected and must not trigger a retry. */
private releasing = new WeakSet<ChildProcess>();
private powerTimer: NodeJS.Timeout | null = null;
private retryTimer: NodeJS.Timeout | null = null;
private heartbeatTimer: NodeJS.Timeout | null = null;
/** Serializes reconciles: a settings PUT can land while a power poll is mid-read. */
private chain: Promise<void> = Promise.resolve();
private stopped = false;
private lastLoggedState: KeepAwakeStatus['state'] = 'off';
constructor(deps?: KeepAwakeDeps) {
this.inert = !deps && !!process.env.VITEST;
this.deps = deps ?? defaultDeps();
this.status = {
enabled: false,
acOnly: true,
platform: this.deps.platform,
state: 'off',
onAc: null,
lidHelper: null,
detail: null,
};
}
/** Current status (a copy). */
getStatus(): KeepAwakeStatus {
return { ...this.status };
}
/** Reconcile to `config`. Idempotent; safe to call on every settings save. */
apply(config: KeepAwakeConfig): Promise<void> {
this.config = { ...config };
this.stopped = false;
return this.enqueue();
}
/** Release everything and stop all timers (server shutdown). */
async stop(): Promise<void> {
this.stopped = true;
this.clearTimers();
await this.chain.catch(() => {});
await this.release();
this.status = { ...this.status, state: 'off', detail: null };
}
private enqueue(): Promise<void> {
const next = this.chain
.then(() => this.reconcile())
.catch((err) => {
console.error('[keep-awake] reconcile failed:', err);
});
this.chain = next;
return next;
}
private async reconcile(): Promise<void> {
if (this.stopped) return;
const { enabled, acOnly } = this.config;
this.status = { ...this.status, enabled, acOnly };
if (!enabled) {
this.clearTimers();
await this.release();
this.setState('off', null);
return;
}
if (this.inert) {
this.setState('unavailable', 'Disabled under the test runner.');
return;
}
if (this.deps.platform === 'unsupported') {
this.setState('unavailable', 'Not supported on this system.');
return;
}
if (this.deps.platform === 'macos') {
this.status.lidHelper = (await this.deps.lidHelperInstalled()) ? 'installed' : 'missing';
}
const onAc = acOnly ? await this.readOnAc() : null;
this.status.onAc = onAc;
this.ensurePowerPoll(acOnly);
if (!shouldHoldLock(this.config, onAc)) {
await this.release();
this.setState('paused-battery', null);
return;
}
// The lid helper is a separate mechanism from caffeinate: it only needs a fresh
// request file, so it runs whether or not caffeinate is currently up.
if (this.deps.platform === 'macos' && this.status.lidHelper === 'installed') this.startLidHeartbeat();
// A pending retry owns the next attempt; a live child is already the lock.
if (this.child || this.retryTimer) return;
if (this.status.state === 'unavailable') return;
this.acquire();
}
private async readOnAc(): Promise<boolean | null> {
try {
if (this.deps.platform === 'linux') return isOnAcPowerLinux(await this.deps.readPowerSupplies());
if (this.deps.platform === 'macos') {
const out = await this.deps.readMacBatt();
return out === null ? null : isOnAcPowerMac(out);
}
} catch {
/* unknown */
}
return null;
}
private acquire(): void {
if (this.deps.platform === 'linux') this.acquireLinux();
else if (this.deps.platform === 'macos') this.acquireMac();
}
private acquireLinux(): void {
let child: ChildProcess;
try {
child = this.deps.spawn('systemd-inhibit', linuxInhibitArgs());
} catch (err) {
this.onSpawnError(err as NodeJS.ErrnoException);
return;
}
this.child = child;
this.setState('starting', null);
// Closing the pipe to an already-dead process emits EPIPE on the stream; unhandled,
// that would take the whole server down.
child.stdin?.on('error', () => {});
let stderr = '';
child.stdout?.on('data', (chunk: Buffer) => {
if (this.child === child && String(chunk).includes(LINUX_HELD_MARKER)) this.setState('active', null);
});
child.stderr?.on('data', (chunk: Buffer) => {
if (stderr.length < STDERR_CAP) stderr += String(chunk);
});
child.on('error', (err: NodeJS.ErrnoException) => {
if (this.child !== child) return;
this.child = null;
this.onSpawnError(err);
});
child.on('exit', () => {
if (this.releasing.has(child) || this.child !== child) return;
this.child = null;
const { state, detail } = classifyInhibitFailure(stderr);
this.setState(state, detail);
if (state !== 'unavailable') this.scheduleRetry();
});
}
private acquireMac(): void {
let child: ChildProcess;
try {
child = this.deps.spawn('/usr/bin/caffeinate', macCaffeinateArgs(this.deps.serverPid));
} catch (err) {
this.onSpawnError(err as NodeJS.ErrnoException);
return;
}
this.child = child;
this.setState('starting', null);
child.on('spawn', () => {
if (this.child === child) this.setState('active', null);
});
child.stdin?.on('error', () => {});
child.on('error', (err: NodeJS.ErrnoException) => {
if (this.child !== child) return;
this.child = null;
this.onSpawnError(err);
});
child.on('exit', (code, signal) => {
if (this.releasing.has(child) || this.child !== child) return;
this.child = null;
this.setState('failed', `caffeinate exited (${signal ?? `code ${code}`})`);
this.scheduleRetry();
});
}
private onSpawnError(err: NodeJS.ErrnoException): void {
if (err.code === 'ENOENT') {
const tool = this.deps.platform === 'macos' ? 'caffeinate' : 'systemd-inhibit';
this.setState('unavailable', `${tool} is not installed on this machine.`);
return;
}
this.setState('failed', err.message);
this.scheduleRetry();
}
private startLidHeartbeat(): void {
if (this.heartbeatTimer) return;
const beat = () => {
void this.deps.writeLidRequest(this.deps.serverPid).catch((err) => {
console.warn('[keep-awake] could not write the lid request file:', err);
});
};
beat();
this.heartbeatTimer = setInterval(beat, MAC_LID_HEARTBEAT_MS);
this.heartbeatTimer.unref?.();
}
private async release(): Promise<void> {
if (this.retryTimer) {
clearTimeout(this.retryTimer);
this.retryTimer = null;
}
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
if (this.deps.platform === 'macos' && !this.inert) {
await this.deps.removeLidRequest().catch(() => {});
}
const child = this.child;
if (!child) return;
this.child = null;
this.releasing.add(child);
// Closing stdin ends `cat` (Linux), which ends systemd-inhibit and drops the lock.
child.stdin?.end();
if (this.deps.platform === 'macos') {
child.kill('SIGTERM');
return;
}
const timer = setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
}, RELEASE_GRACE_MS);
timer.unref?.();
child.once('exit', () => clearTimeout(timer));
}
private scheduleRetry(): void {
if (this.retryTimer || this.stopped) return;
this.retryTimer = setTimeout(() => {
this.retryTimer = null;
void this.enqueue();
}, RETRY_MS);
this.retryTimer.unref?.();
}
private ensurePowerPoll(acOnly: boolean): void {
if (!acOnly) {
if (this.powerTimer) clearInterval(this.powerTimer);
this.powerTimer = null;
return;
}
if (this.powerTimer) return;
this.powerTimer = setInterval(() => void this.enqueue(), POWER_POLL_MS);
this.powerTimer.unref?.();
}
private clearTimers(): void {
for (const t of [this.powerTimer, this.heartbeatTimer]) if (t) clearInterval(t);
if (this.retryTimer) clearTimeout(this.retryTimer);
this.powerTimer = this.heartbeatTimer = this.retryTimer = null;
}
private setState(state: KeepAwakeStatus['state'], detail: string | null): void {
// Log settled transitions only: a denied lock is retried every minute and would
// otherwise log `starting` + `denied` forever on a box nobody logs in to.
if (state !== 'starting' && state !== this.lastLoggedState) {
this.lastLoggedState = state;
console.log(`[keep-awake] ${state}${detail ? `: ${detail}` : ''}`);
}
this.status = { ...this.status, state, detail };
}
}
/** The process-wide manager. */
export const keepAwake = new KeepAwakeManager();
-196
View File
@@ -1,196 +0,0 @@
/**
* @fileoverview Pure decisions behind "Keep this computer awake while Codeman runs"
* (`keepAwakeEnabled`, SYNCED, default OFF; `keepAwakeAcOnly`, default ON).
*
* A laptop that suspends freezes every agent session: nothing runs while the lid is
* closed, the phone loses its tailnet route to the dashboard, and in-flight API
* requests and ssh links usually break. The IO side (`keep-awake-manager.ts`) holds an
* OS-level sleep lock for exactly as long as Codeman runs; everything it has to decide
* lives here so the tests exercise the shipped logic.
*
* What each platform's lock can and cannot do, measured rather than assumed:
*
* - **Linux (systemd-logind).** Lid-close suspend obeys only the LOW-level
* `handle-lid-switch` lock: logind's default `LidSwitchIgnoreInhibited=yes` makes it
* ignore a plain `sleep` lock for the lid. A `sleep` lock also never blocks a suspend
* requested by the SAME user (logind skips inhibitors whose uid matches the caller),
* so the desktop's own Automatic Suspend timer keeps working; it is the user's setting
* to change. polkit grants `handle-lid-switch` and `sleep` only to a process in an
* active login session, and a systemd user service is not in one: polkit then falls
* back to the user's display session, so the lock is granted while someone is logged
* in to the desktop and DENIED at a login screen (or on a headless box). The manager
* retries a denial, so logging in later picks it up.
* - **macOS.** `caffeinate -i -s` (no root) blocks idle sleep, and system sleep while on
* AC power, but NOT lid-close sleep. Only `pmset -a disablesleep 1` keeps a closed
* MacBook awake, and that is a machine-wide root setting with no owner process, so the
* optional root helper (`scripts/keep-awake-macos.sh`, installed by `install.sh`)
* applies it while the server keeps a fresh request file, and undoes it when the file
* goes stale or disappears.
*/
/** Settings keys this feature reads. */
export interface KeepAwakeConfig {
/** Hold a sleep lock while Codeman runs. Opt-in: only an explicit `true` enables. */
enabled: boolean;
/** Release the lock while the machine runs on battery. Default ON. */
acOnly: boolean;
}
export type KeepAwakePlatform = 'linux' | 'macos' | 'unsupported';
/**
* - `off`: the setting is off.
* - `paused-battery`: `acOnly` and the machine is on battery.
* - `starting`: a lock was requested and has not been confirmed yet.
* - `active`: the lock is held.
* - `denied`: Linux refused the lock (no active desktop login); retried periodically.
* - `unavailable`: this machine has no usable mechanism (no systemd-logind, WSL, …).
* - `failed`: anything else; retried periodically.
*/
export type KeepAwakeState = 'off' | 'paused-battery' | 'starting' | 'active' | 'denied' | 'unavailable' | 'failed';
export interface KeepAwakeStatus {
enabled: boolean;
acOnly: boolean;
platform: KeepAwakePlatform;
state: KeepAwakeState;
/** Last known power source: true = AC, false = battery, null = unknown or not read. */
onAc: boolean | null;
/** macOS only: whether the root lid-close helper is installed. null elsewhere. */
lidHelper: 'installed' | 'missing' | null;
/** Short reason for `denied` / `unavailable` / `failed`, else null. */
detail: string | null;
}
/** One entry of `/sys/class/power_supply/<name>/`. */
export interface PowerSupplyInfo {
/** `type`: Mains, Battery, USB, UPS, Wireless, … */
type: string;
/** `online` for adapters (1/0); undefined when the file is absent. */
online?: boolean;
/** `status` for batteries: Charging, Discharging, Full, Not charging, Unknown. */
status?: string;
/** `scope`: `Device` marks a peripheral's battery (a mouse), not the machine's. */
scope?: string;
}
/** Lock set requested from logind. Order is cosmetic; all three are block locks. */
export const LINUX_INHIBIT_WHAT = 'handle-lid-switch:sleep:idle';
/** Printed by the inhibitor's child once the lock is held (systemd-inhibit execs it only then). */
export const LINUX_HELD_MARKER = 'codeman-keep-awake-held';
/** Name of the request file the macOS lid helper watches, under the data dir. */
export const MAC_LID_REQUEST_FILE = 'keep-awake-lid.pid';
/** The LaunchDaemon the installer writes for the macOS lid helper. */
export const MAC_LID_HELPER_PLIST = '/Library/LaunchDaemons/com.codeman.keepawake.plist';
/** How often the server refreshes the macOS request file. The helper treats it as stale after 2 minutes. */
export const MAC_LID_HEARTBEAT_MS = 30_000;
/** How often the power source is re-read while `acOnly` is on. */
export const POWER_POLL_MS = 30_000;
/** Delay before retrying a denied or failed lock. */
export const RETRY_MS = 60_000;
/** Settings → config. Absent `keepAwakeEnabled` is OFF; absent `keepAwakeAcOnly` is ON. */
export function resolveKeepAwakeConfig(settings: Record<string, unknown>): KeepAwakeConfig {
return {
enabled: settings.keepAwakeEnabled === true,
acOnly: settings.keepAwakeAcOnly !== false,
};
}
/**
* Which mechanism applies. WSL is unsupported even though it may have systemd: the
* Windows host decides when the machine sleeps, and a lock inside the VM does nothing.
*/
export function keepAwakePlatform(platform: string, kernelRelease: string): KeepAwakePlatform {
if (platform === 'darwin') return 'macos';
if (platform === 'linux') return /microsoft/i.test(kernelRelease) ? 'unsupported' : 'linux';
return 'unsupported';
}
/**
* Linux power source from `/sys/class/power_supply`. Peripheral batteries
* (`scope=Device`) are ignored. A machine with no battery of its own runs on external
* power by definition; otherwise any online adapter means AC, adapters that are all
* offline mean battery, and a machine that lists no adapter at all falls back to the
* battery's own charging status. null when nothing conclusive is reported.
*/
export function isOnAcPowerLinux(supplies: readonly PowerSupplyInfo[]): boolean | null {
const system = supplies.filter((s) => (s.scope ?? '').toLowerCase() !== 'device');
const batteries = system.filter((s) => s.type === 'Battery');
if (batteries.length === 0) return true;
const adapters = system.filter((s) => s.type !== 'Battery' && s.online !== undefined);
if (adapters.some((s) => s.online)) return true;
if (adapters.length > 0) return false;
const statuses = batteries.map((b) => (b.status ?? '').toLowerCase());
if (statuses.includes('discharging')) return false;
if (statuses.some((s) => s === 'charging' || s === 'full' || s === 'not charging')) return true;
return null;
}
/** macOS power source from `pmset -g batt` (first line names the source). */
export function isOnAcPowerMac(pmsetBatt: string): boolean | null {
const m = /drawing from '([^']+)'/.exec(pmsetBatt);
if (!m) return null;
if (m[1] === 'AC Power') return true;
if (m[1] === 'Battery Power' || m[1] === 'UPS Power') return false;
return null;
}
/**
* Whether the lock should be held right now. An unknown power source counts as AC:
* it is what a desktop or VM without battery reporting looks like.
*/
export function shouldHoldLock(config: KeepAwakeConfig, onAc: boolean | null): boolean {
if (!config.enabled) return false;
if (!config.acOnly) return true;
return onAc !== false;
}
/**
* argv for `systemd-inhibit`. The child it runs announces the lock and then becomes
* `cat` on a stdin pipe from the server: when the server exits for ANY reason (a
* SIGKILL included) the pipe closes, `cat` exits, and logind drops the lock. That
* matters because the shipped unit uses `KillMode=process`, which leaves children
* running on stop; a `sleep infinity` child would hold the lock forever.
*/
export function linuxInhibitArgs(): string[] {
return [
`--what=${LINUX_INHIBIT_WHAT}`,
'--who=Codeman',
'--why=Keeping agent sessions running',
'--mode=block',
'/bin/sh',
'-c',
`echo ${LINUX_HELD_MARKER}; exec cat`,
];
}
/**
* argv for `caffeinate`: `-i` idle sleep, `-s` system sleep on AC power. `-w` ties
* the assertion to the server's pid, so it ends when the server does, crash included.
*/
export function macCaffeinateArgs(serverPid: number): string[] {
return ['-i', '-s', '-w', String(serverPid)];
}
/** Classify why `systemd-inhibit` exited before the lock was confirmed. */
export function classifyInhibitFailure(stderr: string): { state: 'denied' | 'unavailable' | 'failed'; detail: string } {
const text = stderr.trim();
if (/access denied|not authori[sz]ed|interactive authentication required/i.test(text)) {
return {
state: 'denied',
detail: 'Linux refused the sleep lock: no one is logged in to a desktop session on this machine.',
};
}
if (/failed to connect to (system )?bus|no such file or directory|not found|unknown (unit|object)/i.test(text)) {
return { state: 'unavailable', detail: 'systemd-logind is not reachable on this machine.' };
}
const firstLine = text.split('\n')[0]?.slice(0, 200) || 'the inhibitor exited';
return { state: 'failed', detail: firstLine };
}
+71 -4
View File
@@ -1667,8 +1667,12 @@ class CodemanApp {
* side-effect-light. Calling it again for an already-open window just raises
* that window.
* @param {string} id session id
* @param {{width?: number, height?: number, left?: number, top?: number}} [placement]
* the new window's size and screen position (a detached tile opens its own
* size, where it was let go); omitted, the default 960x680 wherever the
* browser puts it. A host window ignores it.
*/
detachSession(id) {
detachSession(id, placement = null) {
if (this.isSoloWindow) return; // a solo window can't spawn more
if (!this.sessions.has(id)) return;
// Already detached → raise the existing popup instead of opening (or
@@ -1696,7 +1700,7 @@ class CodemanApp {
this._postWindowMessage({ type: 'detached', id });
return;
}
const features = 'width=960,height=680,menubar=no,toolbar=no,location=no,status=no';
const features = this._detachWindowFeatures(placement);
let win = null;
try { win = window.open(CodemanBase.url('/session/' + encodeURIComponent(id)), 'codeman-session-' + id, features); } catch {}
if (!win) {
@@ -1710,6 +1714,21 @@ class CodemanApp {
try { win.focus(); } catch {}
}
/**
* The window.open features of a pop-out: `placement`'s size (default
* 960x680) and, when it has one, its screen position. Only finite numbers
* make it into the string.
*/
_detachWindowFeatures(placement) {
const int = (v) => (Number.isFinite(v) ? Math.round(v) : null);
const width = int(placement?.width) ?? 960;
const height = int(placement?.height) ?? 680;
const left = int(placement?.left);
const top = int(placement?.top);
const at = left !== null && top !== null ? `,left=${left},top=${top}` : '';
return `width=${width},height=${height}${at},menubar=no,toolbar=no,location=no,status=no`;
}
/**
* The embedding app's window opener, when there is one. A native wrapper
* exposes `window.CodemanHost.openWindow(absoluteUrl)` (anything but false
@@ -1878,11 +1897,15 @@ class CodemanApp {
if (!msg || typeof msg !== 'object') return;
if (this.isSoloWindow) {
// Roll-call has no id (broadcast to all) — answer before the id filter.
if (msg.type === 'roll-call') { this._postWindowMessage({ type: 'detached', id: this.soloSessionId }); return; }
// A window that has handed its session back stays silent.
if (msg.type === 'roll-call') {
if (!this._soloReleased) this._postWindowMessage({ type: 'detached', id: this.soloSessionId });
return;
}
if (msg.id !== this.soloSessionId) return;
// A host window ignores window.close()/focus() from script it did not
// open by window.open, so ask the host when it offers the call.
if (msg.type === 'close-request') { this._closeSoloWindow(); }
if (msg.type === 'close-request') { this._releaseSoloWindow(); }
else if (msg.type === 'focus-request') {
try { if (typeof window.CodemanHost?.focusWindow === 'function') window.CodemanHost.focusWindow(); else window.focus(); } catch {}
}
@@ -1890,6 +1913,10 @@ class CodemanApp {
}
// Dashboard side.
if (msg.type === 'detached' && msg.id) {
// A pop-out this window just docked as a tile (Detach Tiles), answering
// a roll-call on its way out: not a new pop-out, which would take the
// tile straight back off.
if (this._tileDockedRecently?.(msg.id)) return;
this._cancelPendingRedock(msg.id); // a re-announce (e.g. popup reload) cancels a deferred redock
this._detachPingPending?.delete(msg.id); // and proves liveness for this tick
this._detachOrphanStrikes.delete(msg.id); // any answer clears accumulated misses
@@ -1899,6 +1926,9 @@ class CodemanApp {
} else if (msg.type === 'detach-request' && msg.id) {
// Future gesture hook: another window asks the dashboard to detach a tab.
this.detachSession(msg.id);
} else if (msg.type === 'tile-adopted' && msg.id && msg.by !== this._wsTabNonce) {
// Another window docked a tile dragged out of this one (tile-grid.js).
this._onTileAdoptedElsewhere?.(msg.id);
}
}
@@ -1945,6 +1975,41 @@ class CodemanApp {
} catch {}
}
/**
* Solo window: a dashboard took the session back (its re-dock, or a
* dashboard docked it as a tile). Says so at once and stops answering
* roll-calls, then closes. A window the browser will not let a script
* close (one opened by typing its URL) says where the session went
* instead, rather than staying a live pop-out that every dashboard would
* mark detached again at its next roll-call.
*/
_releaseSoloWindow() {
if (this._soloReleased) return;
this._soloReleased = true;
this._postWindowMessage({ type: 'redocked', id: this.soloSessionId });
this._closeSoloWindow();
setTimeout(() => {
if (!window.closed) this._showSoloReleased();
}, 300);
}
/** Solo window: the session went back to a dashboard and this window could not close. */
_showSoloReleased() {
if (document.querySelector('.solo-gone-overlay')) return;
const el = document.createElement('div');
el.className = 'solo-gone-overlay';
const title = document.createElement('h2');
title.textContent = 'Session moved';
const text = document.createElement('p');
text.textContent = 'This session is back in a Codeman window. This one can be closed.';
const btn = document.createElement('button');
btn.className = 'btn-primary';
btn.textContent = 'Close window';
btn.addEventListener('click', () => this._closeSoloWindow());
el.append(title, text, btn);
document.body.appendChild(el);
}
/** Solo window: select the target session and apply minimal single-session
* chrome. Called from handleInit once the session list has loaded. */
_applySoloMode() {
@@ -1960,6 +2025,8 @@ class CodemanApp {
if (titleEl) { titleEl.textContent = name; titleEl.style.display = ''; }
const redock = document.getElementById('soloRedockBtn');
if (redock) redock.style.display = '';
// Detach Tiles: the title drags onto a dashboard's tiles to dock there.
this._installSoloTileHandle?.();
document.title = name + ' — ' + (window.CodemanI18n?.displayName || 'Codeman');
if (this.notificationManager) this.notificationManager.originalTitle = document.title;
// Neutralize the dashboard-only brand click in a solo window.
+112 -6
View File
@@ -4448,6 +4448,7 @@ var GestureController = class {
// packages/gesture-control/src/codeman/entry.ts
var TAB_SELECTOR = ".session-tab";
var TILE_SELECTOR = "#tileGrid .tile";
var PANEL_SELECTOR = ".cg-float";
var WINDOW_SELECTOR = ".subagent-window, .ultracode-window";
var DOCK_SELECTOR = ".session-tabs";
@@ -4457,6 +4458,8 @@ var FLOAT_W = 640;
var FLOAT_H = 420;
var DETACH_PULL_PX = 70;
var TAP_CANCEL_PX = 45;
var TILE_MOVE_PX = 40;
var TILE_GHOST_W = 280;
var handColor = (handedness, pinching) => pinching ? "#4ade80" : handedness === "Right" ? "#a78bfa" : "#38bdf8";
var GestureBridge = class {
constructor() {
@@ -4533,7 +4536,7 @@ var GestureBridge = class {
await this.gc.start();
this.running = true;
this.button.classList.add("on");
this.status.textContent = "on \u2014 pinch a tab, window, or button";
this.status.textContent = "on: pinch a tab, tile, window, or button";
} catch (err) {
const msg = describeError(err);
this.status.textContent = `failed: ${msg}`;
@@ -4588,6 +4591,30 @@ var GestureBridge = class {
this.status.textContent = "moving window";
return;
}
const tileId = window.app?.tileAtPoint?.(x2, y2) ?? null;
const tileEl = tileId ? this.hitClosest(x2, y2, TILE_SELECTOR) : null;
if (tileId && tileEl && window.app?.canGrabTile?.(tileId)) {
const rect = tileEl.getBoundingClientRect();
const ghost = this.tileGhost(tileEl, rect);
document.body.append(ghost);
tileEl.classList.add("tile--dragging");
this.grabs.set(hand, {
kind: "tile",
id: tileId,
el: tileEl,
ghost,
offsetX: Math.max(0, Math.min(x2 - rect.left, rect.width)),
offsetY: Math.max(0, Math.min(y2 - rect.top, rect.height)),
ox: x2,
oy: y2,
armed: false,
target: null,
out: false
});
this.positionGhost(ghost, x2, y2);
this.status.textContent = "moving tile";
return;
}
const tab = this.hitClosest(x2, y2, TAB_SELECTOR);
const id = tab?.dataset.id;
if (tab && id) {
@@ -4599,7 +4626,7 @@ var GestureBridge = class {
ghost.style.height = `${rect.height}px`;
document.body.append(ghost);
tab.classList.add("cg-grabbed");
this.grabs.set(hand, { kind: "tab", id, tab, ghost, ox: x2, oy: y2, armed: false });
this.grabs.set(hand, { kind: "tab", id, tab, ghost, ox: x2, oy: y2, armed: false, target: null });
this.positionGhost(ghost, x2, y2);
return;
}
@@ -4613,13 +4640,30 @@ var GestureBridge = class {
}
onDrag(hand, x2, y2) {
const grab = this.grabs.get(hand);
if (grab?.kind === "tile") {
this.positionGhost(grab.ghost, x2, y2);
if (!grab.armed && Math.hypot(x2 - grab.ox, y2 - grab.oy) >= TILE_MOVE_PX) grab.armed = true;
if (!grab.armed) return;
const app = window.app;
const target = app?.tileDropTargetAt?.(x2, y2, grab.id) ?? null;
this.setTileTarget(grab, target);
const out = !target && !!app?.tileDetachEnabled?.() && !app?.isOverTileGrid?.(x2, y2);
grab.out = out;
grab.ghost.classList.toggle("cg-armed", !!target);
grab.ghost.classList.toggle("cg-out", out);
this.status.textContent = target ? target.kind === "tile" ? "release to swap tiles" : "release to move the tile here" : out ? "release to open in a new window" : "moving tile";
return;
}
if (grab?.kind === "tab") {
this.positionGhost(grab.ghost, x2, y2);
const pulled = Math.hypot(x2 - grab.ox, y2 - grab.oy) >= DETACH_PULL_PX;
if (pulled !== grab.armed) {
const target = pulled ? window.app?.tileDropTargetAt?.(x2, y2, grab.id) ?? null : null;
const targetChanged = (target?.el ?? null) !== (grab.target?.el ?? null);
this.setTileTarget(grab, target);
if (pulled !== grab.armed || targetChanged) {
grab.armed = pulled;
grab.ghost.classList.toggle("cg-armed", pulled);
this.status.textContent = pulled ? "release to float out" : "on \u2014 pinch a tab";
this.status.textContent = target ? "release to tile it here" : pulled ? "release to float out" : "on \u2014 pinch a tab";
}
return;
}
@@ -4641,16 +4685,40 @@ var GestureBridge = class {
if (tap && Math.hypot(x2 - tap.ox, y2 - tap.oy) > TAP_CANCEL_PX) {
tap.el.classList.remove("cg-tap-armed");
this.taps.delete(hand);
this.status.textContent = "on \u2014 pinch a tab, window, or button";
this.status.textContent = "on: pinch a tab, tile, window, or button";
}
}
onDrop(hand, x2, y2) {
const grab = this.grabs.get(hand);
if (grab?.kind === "tile") {
this.grabs.delete(hand);
grab.ghost.remove();
grab.el.classList.remove("tile--dragging");
this.setTileTarget(grab, null);
const app = window.app;
if (!grab.armed) {
this.flash("cancelled");
return;
}
const target = app?.tileDropTargetAt?.(x2, y2, grab.id) ?? null;
if (target) {
this.flash(app?.dropOnTileTarget?.(grab.id, target) ? "moved tile" : "cancelled");
} else if (grab.out && !app?.isOverTileGrid?.(x2, y2)) {
const opened = app?.detachTileAtPoint?.(grab.id, x2, y2, { offsetX: grab.offsetX, offsetY: grab.offsetY });
this.flash(opened ? "opened in a new window" : "pop-out blocked: allow popups for this site");
} else {
this.flash("cancelled");
}
return;
}
if (grab?.kind === "tab") {
this.grabs.delete(hand);
grab.ghost.remove();
grab.tab.classList.remove("cg-grabbed");
if (grab.armed) this.floatPanel(grab.id, x2, y2);
this.setTileTarget(grab, null);
const target = grab.armed ? window.app?.tileDropTargetAt?.(x2, y2, grab.id) ?? null : null;
if (target) this.flash(window.app?.dropOnTileTarget?.(grab.id, target) ? "tiled" : "cancelled");
else if (grab.armed) this.floatPanel(grab.id, x2, y2);
else this.flash("cancelled");
return;
}
@@ -4775,11 +4843,41 @@ var GestureBridge = class {
ghost.style.left = `${x2}px`;
ghost.style.top = `${y2}px`;
}
/** A small copy of a tile to follow the hand: its header (a copy: no
* listeners come along) over an empty body, in the tile's proportions. */
tileGhost(tileEl, rect) {
const ghost = el("div", "cg-ghost cg-tile-ghost");
const width = Math.min(TILE_GHOST_W, rect.width);
ghost.style.width = `${width}px`;
ghost.style.height = `${Math.max(48, Math.round(width * rect.height / Math.max(1, rect.width)))}px`;
const header = tileEl.querySelector(".tile-header");
if (header) {
const copy = header.cloneNode(true);
copy.removeAttribute("draggable");
ghost.append(copy);
}
ghost.append(el("div", "cg-tile-ghost-body"));
return ghost;
}
/** Highlights the tile or empty cell a carried session would drop onto
* (the mouse drag's own `tile--drop-target`), clearing the last one. */
setTileTarget(grab, target) {
if (grab.target?.el !== target?.el) {
grab.target?.el.classList.remove("tile--drop-target");
target?.el.classList.add("tile--drop-target");
}
grab.target = target;
}
cancelAllGrabs() {
for (const grab of this.grabs.values()) {
if (grab.kind === "tab") {
grab.ghost.remove();
grab.tab.classList.remove("cg-grabbed");
this.setTileTarget(grab, null);
} else if (grab.kind === "tile") {
grab.ghost.remove();
grab.el.classList.remove("tile--dragging");
this.setTileTarget(grab, null);
} else if (grab.kind === "panel") {
grab.panel.el.style.pointerEvents = "";
grab.panel.el.classList.remove("cg-float-grabbed", "cg-redock");
@@ -4791,6 +4889,7 @@ var GestureBridge = class {
for (const tap of this.taps.values()) tap.el.classList.remove("cg-tap-armed");
this.taps.clear();
document.querySelectorAll(`${TAB_SELECTOR}.cg-grabbed, .cg-tap-armed, .cg-win-grabbed`).forEach((t2) => t2.classList.remove("cg-grabbed", "cg-tap-armed", "cg-win-grabbed"));
document.querySelectorAll(`${TILE_SELECTOR}.tile--dragging`).forEach((t2) => t2.classList.remove("tile--dragging"));
}
onStatus(fps, hands) {
const { width, height } = this.canvas;
@@ -4863,6 +4962,13 @@ function injectStyles() {
outline: 2px solid #38bdf8; outline-offset: -2px;
}
.cg-ghost.cg-armed { outline-color: #4ade80; box-shadow: 0 8px 28px rgba(74,222,128,.5); }
.cg-ghost.cg-out { outline-color: #fbbf24; box-shadow: 0 8px 28px rgba(251,191,36,.5); }
.cg-tile-ghost {
display: flex; flex-direction: column; overflow: hidden; transform: translate(-50%, -20%) scale(1);
background: var(--term-bg, #161b23); border: 1px solid var(--border-color, #333);
}
.cg-tile-ghost > .tile-header { flex: 0 0 auto; }
.cg-tile-ghost-body { flex: 1 1 auto; opacity: .5; }
.cg-dock {
position: fixed; right: 12px; bottom: 156px; z-index: ${Z2 + 3};
display: flex; align-items: center; gap: 8px; font: 12px/1 system-ui, sans-serif;
+15 -3
View File
@@ -139,6 +139,8 @@
Drag: '拖动',
"a tile's header": '窗格的标题栏',
'Move the Tile (onto Another: Swap)': '移动窗格(拖到另一个窗格上:互换位置)',
"a tile's header out of the window": '窗格的标题栏到窗口之外',
'Open the Tile in Its Own Window (Detach Tiles)': '在独立窗口中打开窗格(分离窗格)',
'Zoom Focused Tile': '放大聚焦的窗格',
'Remove Focused Tile': '移除聚焦的窗格',
'Add the Session to the Tile Grid': '将该会话加入平铺网格',
@@ -166,6 +168,11 @@
'Failed to restore terminal size': '恢复终端尺寸失败',
// A tile header's tooltip while tiles can move (with the state above it: a pattern below).
'Drag to move the tile': '拖动可移动窗格',
// The same with Detach Tiles on (tile-grid.js _paintTileHandle), and a
// pop-out window's title as a handle back onto the tiles.
'Drag to move the tile, or out of the window to open it on its own': '拖动可移动窗格,拖出窗口可在独立窗口中打开',
'Drag out of the window to open the tile on its own': '拖出窗口可在独立窗口中打开此窗格',
"Drag onto a Codeman window's tiles to dock this session there": '拖到 {name} 窗口的窗格上,即可将此会话停靠到那里',
'Resize tile columns': '调整窗格列宽',
'Resize tile rows': '调整窗格行高',
Attach: '附加',
@@ -214,6 +221,9 @@
'Close window': '关闭窗口',
'Session unavailable': '会话不可用',
'This session has ended or is no longer available.': '此会话已结束或不再可用。',
// A pop-out whose session a dashboard took back, when it cannot close itself (app.js _showSoloReleased).
'Session moved': '会话已移走',
'This session is back in a Codeman window. This one can be closed.': '此会话已回到 {name} 窗口中。可以关闭此窗口。',
// Welcome / quick start / common actions
'Manage AI Coding tools in persistent tmux sessions.': '在持久化 tmux 会话中管理 AI 编程工具。',
@@ -405,6 +415,9 @@
'CLI Logos on Tabs': '标签页上的 CLI 图标',
"Show each agent's CLI logo before the session name on tabs and the home screen's tab list. Off leaves the status dot and the shell's SH badge. Tiles, split headers and the Run menus keep their logos.":
'在标签页和主界面的标签列表中,于会话名称前显示每个智能体的 CLI 图标。关闭后仍保留状态圆点和 Shell 的 SH 标记。平铺、分屏标题栏和运行菜单中的图标不受影响。',
'Detach Tiles': '分离窗格',
"Drag a tile's header out of the browser to open it in its own window, or onto another Codeman window's tiles to move it there. A popped-out window's title drags back onto tiles.":
'将窗格的标题栏拖出浏览器,即可在独立窗口中打开它;拖到另一个 {name} 窗口的窗格上,即可将它移到那里。弹出窗口的标题也可以拖回窗格中。',
// Tab Layout and Header Stats Style (Discussion #426). The header style's
// "Tiles" is 磁贴, never 平铺: that is the tile grid's word (the Tiles
// button), and "Tiles (label over value)" must not read as the grid.
@@ -1280,9 +1293,8 @@
// The same while tiles can move, with the drag hint on a second line.
// Anchored on the hint, so a bare state word is safe here.
[
/^(needs you|error|waiting|working|idle|done|exited)(?: (<1m|\d+[dhm](?: \d+[hm])?))?\nDrag to move the tile$/,
(_m, state, duration) =>
`${TILE_STATE_ZH[state]}${duration ? ` ${duration}` : ''}\n${ZH_CN['Drag to move the tile']}`,
/^(needs you|error|waiting|working|idle|done|exited)(?: (<1m|\d+[dhm](?: \d+[hm])?))?\n(Drag to move the tile|Drag to move the tile, or out of the window to open it on its own|Drag out of the window to open the tile on its own)$/,
(_m, state, duration, hint) => `${TILE_STATE_ZH[state]}${duration ? ` ${duration}` : ''}\n${ZH_CN[hint]}`,
],
];
for (const [pattern, replacement] of patterns) {
+8 -21
View File
@@ -860,6 +860,7 @@
<div><kbd>Alt/Option</kbd>+<kbd>Shift</kbd>+<kbd>Arrows</kbd></div><div>Focus Tile Left / Right / Up / Down</div>
<div><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Arrows</kbd></div><div>Move Tile Left / Right / Up / Down</div>
<div><kbd>Drag</kbd> a tile's header</div><div>Move the Tile (onto Another: Swap)</div>
<div><kbd>Drag</kbd> a tile's header out of the window</div><div>Open the Tile in Its Own Window (Detach Tiles)</div>
<div><kbd>Alt/Option</kbd>+<kbd>Shift</kbd>+<kbd>Enter</kbd></div><div>Zoom Focused Tile</div>
<div><kbd>Ctrl/Cmd</kbd>+<kbd>Click</kbd> a tab</div><div>Add the Session to the Tile Grid</div>
<div><kbd>Right-click</kbd> the Tiles button</div><div>Choose How Many Tiles (2, 4 or 6)</div>
@@ -2233,6 +2234,13 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowTabDetachButton"><span class="slider"></span></label>
</div>
<div class="set-row" id="appSettingsTileDetachItem" data-search="detach tiles tile pop out window drag move another window">
<div class="set-row-text">
<span class="set-row-label">Detach Tiles <span class="set-tag">desktop</span> <span class="set-tag set-tag-beta">beta</span></span>
<span class="set-row-desc">Drag a tile's header out of the browser to open it in its own window, or onto another Codeman window's tiles to move it there. A popped-out window's title drags back onto tiles.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsTileDetach"><span class="slider"></span></label>
</div>
<div class="set-row" id="appSettingsLineageLinesItem" data-search="lineage lines spawned worker parent connection">
<div class="set-row-text">
<span class="set-row-label">Spawn Lineage Lines <span class="set-tag">desktop</span></span>
@@ -3107,27 +3115,6 @@
</div>
</div>
<div class="set-group" id="keepAwakeGroup">
<div class="set-group-head"><h4>Power</h4><span class="set-scope">server</span></div>
<div class="set-group-body">
<div class="set-row" data-search="keep awake sleep suspend standby lid close laptop notebook power caffeinate inhibit">
<div class="set-row-text">
<span class="set-row-label">Keep this computer awake</span>
<span class="set-row-desc">While Codeman runs, stop the machine it runs on from sleeping, including when a laptop's lid is closed, so agents keep working and stay reachable from your phone. The screen can still turn off.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsKeepAwake"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="keep awake battery ac power charger plugged in">
<div class="set-row-text">
<span class="set-row-label">Only on AC power</span>
<span class="set-row-desc">Sleep normally on battery. A closed laptop in a bag gets hot and drains fast.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsKeepAwakeAcOnly" checked><span class="slider"></span></label>
</div>
<div id="keepAwakeStatus" class="set-note" style="display:none" data-i18n-skip></div>
</div>
</div>
<div class="set-group">
<div class="set-group-head"><h4>Remote access</h4><span class="set-scope">synced</span></div>
<div class="set-group-body">
+12 -55
View File
@@ -424,11 +424,6 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsMcpSync').checked = this._mcpSyncSavedOn;
this.applyMcpSyncVisibility();
this._applyDoctorAdminGate();
// Keep awake: server state (an OS sleep lock), default OFF; "only on AC" default ON.
document.getElementById('appSettingsKeepAwake').checked = settings.keepAwakeEnabled === true;
document.getElementById('appSettingsKeepAwakeAcOnly').checked = settings.keepAwakeAcOnly !== false;
this._applyKeepAwakeAdminGate();
this.loadKeepAwakeStatus();
this.loadWebhook();
// Read My Mind: synced, default OFF (opt-in; capture + prediction cost real tokens).
document.getElementById('appSettingsReadMyMind').checked = settings.readMyMindEnabled === true;
@@ -515,6 +510,11 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsShowTabDetachButton').checked =
this.tabDetachButtonEnabled?.(settings, defaults)
?? (settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false);
// Detach Tiles (tile-grid.js): per-device, OFF unless switched on. The tile
// grid is desktop-only, so the row is hidden elsewhere, like the lineage lines.
document.getElementById('appSettingsTileDetach').checked = settings.tileDetachEnabled === true;
const tileDetachItem = document.getElementById('appSettingsTileDetachItem');
if (tileDetachItem) tileDetachItem.style.display = MobileDetection.getDeviceType() === 'desktop' ? '' : 'none';
document.getElementById('appSettingsSessionListLayout').value =
settings.sessionListLayout ?? defaults.sessionListLayout ?? 'header';
const sessionSidebarFontSize = this.resolveSessionSidebarFontSize(
@@ -1229,53 +1229,6 @@ Object.assign(CodemanApp.prototype, {
group.style.display = me.multiUser && me.role !== 'admin' ? 'none' : '';
},
/**
* Keep awake changes machine state, and PUT /api/settings drops a non-admin's value in
* multi-user mode, so a non-admin gets no Power group at all rather than a switch that
* silently does nothing. Also wired to `codeman:me` for the late-resolving role.
*/
_applyKeepAwakeAdminGate() {
const group = document.getElementById('keepAwakeGroup');
if (!group) return;
const me = window.__codemanUser || {};
group.style.display = me.multiUser && me.role !== 'admin' ? 'none' : '';
},
/** One line on what the sleep lock is doing right now (GET /api/system/keep-awake). */
async loadKeepAwakeStatus() {
const out = document.getElementById('keepAwakeStatus');
if (!out) return;
let s = null;
try {
const res = await this._api('/api/system/keep-awake');
const body = res && res.ok ? await res.json() : null;
s = body?.success ? body.data : null;
} catch { /* leave hidden */ }
const text = s ? this.describeKeepAwakeStatus(s) : '';
out.textContent = text;
out.style.display = text ? 'block' : 'none';
},
/** Status → sentence. Pure; '' hides the note. */
describeKeepAwakeStatus(s) {
switch (s.state) {
case 'off': return '';
case 'starting': return 'Starting…';
case 'paused-battery': return 'Paused: running on battery. It comes back when you plug in.';
case 'unavailable': return `Not available here: ${s.detail || 'no supported sleep lock on this system.'}`;
case 'denied': return `${s.detail || 'The sleep lock was refused.'} Codeman retries every minute, so it applies once you log in.`;
case 'failed': return `Could not take the sleep lock (${s.detail || 'unknown error'}). Retrying every minute.`;
case 'active':
if (s.platform === 'macos') {
return s.lidHelper === 'installed'
? 'Active: this Mac will not sleep while Codeman runs, even with the lid closed. Apple menu > Sleep is blocked too.'
: 'Active for idle sleep only: closing the lid still puts this Mac to sleep. To cover the lid, re-run the installer and answer yes to the lid question (asks for your admin password once).';
}
return "Active: closing the lid will not suspend this machine while Codeman runs. Your desktop's own Automatic Suspend timer is separate and still runs: if it is on, switch it off for when the machine is plugged in.";
default: return '';
}
},
/** Preview (apply=false) or run (apply=true) the MCP server sync across enabled CLIs. */
async mcpSync(apply) {
const out = this.$('mcpSyncResult');
@@ -2668,6 +2621,7 @@ Object.assign(CodemanApp.prototype, {
tabArrangement: document.getElementById('appSettingsTabArrangement').value,
tabStateOrder: document.getElementById('appSettingsTabStateOrder').value,
showTabDetachButton: document.getElementById('appSettingsShowTabDetachButton').checked,
tileDetachEnabled: document.getElementById('appSettingsTileDetach').checked,
sessionListLayout: document.getElementById('appSettingsSessionListLayout').value,
sessionSidebarFontSize: this.resolveSessionSidebarFontSize(
document.getElementById('appSettingsSessionSidebarFontSize').value
@@ -2685,8 +2639,6 @@ Object.assign(CodemanApp.prototype, {
agentTeamsEnabled: document.getElementById('appSettingsAgentTeams').checked,
agentSkillEnabled: document.getElementById('appSettingsAgentSkill').checked,
workspaceHooksEnabled: document.getElementById('appSettingsWorkspaceHooks').checked,
keepAwakeEnabled: document.getElementById('appSettingsKeepAwake').checked,
keepAwakeAcOnly: document.getElementById('appSettingsKeepAwakeAcOnly').checked,
claudeVoiceEnabled: document.getElementById('appSettingsClaudeVoice').checked,
claudeModel: document.getElementById('appSettingsClaudeModel').value,
opusContext1mEnabled: document.getElementById('appSettingsOpusContext1m').checked,
@@ -2921,6 +2873,9 @@ Object.assign(CodemanApp.prototype, {
gitStatusMaxRepos: _gsm,
gitStatusTimeoutSeconds: _gst2,
showTabDetachButton: _tdb,
// Detach Tiles: what a tile drag does is a property of this device's
// windows, and the key is absent from the .strict() SettingsUpdateSchema.
tileDetachEnabled: _tde,
// Phone-only home surface, and absent from SettingsUpdateSchema (.strict()).
mobileOverviewEnabled: _mov,
// Desktop-only tab decoration, per-device, and likewise absent from the
@@ -3956,6 +3911,8 @@ Object.assign(CodemanApp.prototype, {
// Tiles button: same gate and backstop as Split (tile-grid.js).
const showTileGridButton = settings.showTileGridButton ?? defaults.showTileGridButton ?? true;
this._applyTileGridButtonVisibility?.(showTileGridButton);
// Detach Tiles changes what a tile's header does (and says): repaint the handles.
this._renderTileChrome?.();
// Ultracode/Workflow agents launcher — hidden by default; reveal when enabled.
// Marker class only (base is display:inline-flex !important) so it's auto-excluded
@@ -4412,6 +4369,7 @@ Object.assign(CodemanApp.prototype, {
'sessionLineageLines',
'showSplitButton',
'showTileGridButton',
'tileDetachEnabled',
]);
// The plan-usage chip is a PER-DEVICE display setting (desktop default ON,
// handheld default OFF): desktop can show it while mobile stays hidden. Drop
@@ -4820,5 +4778,4 @@ document.addEventListener?.('codeman:me', () => {
window.app?._applyCliManagementAdminGate?.();
window.app?._applyMcpSyncAdminGate?.();
window.app?._applyDoctorAdminGate?.();
window.app?._applyKeepAwakeAdminGate?.();
});
+8
View File
@@ -2990,6 +2990,14 @@ body.solo-mode .btn-lifecycle-log {
overflow: hidden;
text-overflow: ellipsis;
}
/* Detach Tiles: the title is a handle, dragged onto a Codeman window's tiles
to dock the session there (tile-grid.js _installSoloTileHandle). */
.solo-session-title.solo-session-title--handle {
cursor: grab;
}
.solo-session-title.solo-session-title--handle:active {
cursor: grabbing;
}
/* "Session unavailable" overlay for a solo window whose session has ended. */
.solo-gone-overlay {
position: fixed;
+8 -4
View File
@@ -329,10 +329,14 @@ Object.assign(CodemanApp.prototype, {
{ label: 'Session options', run: () => this.openSessionOptions(sessionId) },
// Group placement (vertical rail with a tab layout only; [] elsewhere).
...(this._tabRefMoveActions?.({ kind: 'session', id: sessionId }) || []),
...((this.tabDetachButtonEnabled?.(settings) ?? settings.showTabDetachButton) ||
this.detachedSessions?.has(sessionId)
? [{ label: 'Open in a new window', run: () => this.detachSession(sessionId) }]
: []),
// A tile (Detach Tiles on) opens its own size, over where it is: the
// keyboard's way to what dragging its header out of the window does.
...(this._tileGrid?.has?.(sessionId) && this._tileDetachAllowed?.()
? [{ label: 'Open in a new window', run: () => this.detachTile(sessionId) }]
: (this.tabDetachButtonEnabled?.(settings) ?? settings.showTabDetachButton) ||
this.detachedSessions?.has(sessionId)
? [{ label: 'Open in a new window', run: () => this.detachSession(sessionId) }]
: []),
{ label: 'Close session', className: 'danger', run: () => this.requestCloseSession(sessionId) },
];
for (const action of actions) {
+420 -14
View File
@@ -56,6 +56,26 @@ const TILE_GRID_REFIT_MS = 150;
// the grid section's padding (styles.css .tile-grid), for the drag math.
const TILE_DIVIDER_PX = 6;
const TILE_GRID_PADDING_PX = 4;
// What a tile's header drag (and a popped-out window's title drag) carries:
// the session id under a type of its own, never text, so no text field or
// terminal takes it as typing. Another Codeman window reads it on drop.
const TILE_DRAG_TYPE = 'application/x-codeman-tile';
// Detach Tiles: a tile dropped outside every window waits this long before it
// opens as a window of its own, so another window that took it (a
// 'tile-adopted' message on the window channel) can still say so first.
const TILE_TEAR_OFF_SETTLE_MS = 120;
// How long after its drag ended a tile can still be claimed by another
// window's drop (the claim and the dragend come from two windows).
const TILE_ADOPT_WINDOW_MS = 5000;
// A session docked here from another window: its old window's 'detached'
// announcements this soon after are stale (it is closing), not a new pop-out.
const TILE_DOCK_GRACE_MS = 2000;
// The smallest window a detached tile opens as, and roughly how much browser
// chrome sits above a pop-out's content (its title and address bars), so the
// window's own header lands near where the tile was let go.
const TILE_WINDOW_MIN_W = 480;
const TILE_WINDOW_MIN_H = 320;
const TILE_WINDOW_CHROME_PX = 60;
/** `minmax(0, 1fr) 6px minmax(0, 2fr) ...`: tracks with a divider track between each. */
function tileGridTracks(fr) {
@@ -1552,8 +1572,10 @@ Object.assign(CodemanApp.prototype, {
* `accepts(id)` is the target's own rule (a tile takes any session but its
* own; an empty cell takes any). A session it does not accept
* is held there too, but refused (`dropEffect: 'none'`, no highlight, so no
* drop follows). Any other drag (a file) is left to the grid section's own
* guard (_installTileFileDrop).
* drop follows). With Detach Tiles on, a tile dragged from ANOTHER Codeman
* window (no drag of this page's own, the tile type in the drag) is taken
* too and docks here (_dockForeignTile). Any other drag (a file) is left to
* the grid section's own guard (_installTileFileDrop).
*/
_acceptTabDrops(el, onDrop, { accepts = () => true } = {}) {
const dragged = () => (this._tileGrid?.open ? this.draggedTabId || this._draggedTileId || null : null);
@@ -1561,7 +1583,16 @@ Object.assign(CodemanApp.prototype, {
'dragover',
(e) => {
const id = dragged();
if (!id) return;
if (!id) {
// A tile from another Codeman window (Detach Tiles). Its id can
// only be read on drop, so it is held here whatever it is.
if (!this._isForeignTileDrag(e)) return;
e.preventDefault?.();
e.stopPropagation?.();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
el.classList.add('tile--drop-target');
return;
}
e.preventDefault?.();
e.stopPropagation?.();
const ok = accepts(id);
@@ -1578,7 +1609,13 @@ Object.assign(CodemanApp.prototype, {
(e) => {
el.classList.remove('tile--drop-target');
const id = dragged();
if (!id) return;
if (!id) {
if (!this._isForeignTileDrag(e)) return;
e.preventDefault?.();
e.stopPropagation?.();
this._dockForeignTile(e.dataTransfer?.getData?.(TILE_DRAG_TYPE), onDrop);
return;
}
e.preventDefault?.();
e.stopPropagation?.();
if (accepts(id)) onDrop(id);
@@ -2080,7 +2117,10 @@ Object.assign(CodemanApp.prototype, {
* input starts no drag. dragstart's target is the header whatever was
* pressed, so where the press landed is noted in the capture phase, ahead of
* the buttons' own stopPropagation. `draggable` is off while moving is
* (_paintTileHandle: a zoomed grid, a single tile, a rename in progress).
* (_paintTileHandle: a zoomed grid, a single tile, a rename in progress),
* unless Detach Tiles is on: then a drop outside the window pops the tile
* out, and a drop on another Codeman window's tiles moves it there (see the
* Detach Tiles section); a rename still turns it off.
*/
_installTileMoveDrag(sessionId, header, actions) {
let pressedOnControl = false;
@@ -2094,7 +2134,10 @@ Object.assign(CodemanApp.prototype, {
);
header.addEventListener('dragstart', (e) => {
const entry = this._tileGrid?.open ? this._tileGrid.tiles.get(sessionId) : null;
if (!entry || pressedOnControl || entry.renaming || !this._tilesMovable()) {
// Detach Tiles lets a tile that cannot move (alone, or zoomed) still be
// dragged, out of the window; no drop target here takes it then.
const detachable = this._tileDetachAllowed();
if (!entry || pressedOnControl || entry.renaming || !(this._tilesMovable() || detachable)) {
e.preventDefault?.();
return;
}
@@ -2102,11 +2145,16 @@ Object.assign(CodemanApp.prototype, {
entry.el.classList.add('tile--dragging');
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'move';
// Firefox starts no drag without data.
e.dataTransfer.setData('application/x-codeman-tile', sessionId);
// Firefox starts no drag without data. Another Codeman window reads
// the id from it (Detach Tiles).
e.dataTransfer.setData(TILE_DRAG_TYPE, sessionId);
}
if (detachable) this._beginTileTearOff(sessionId, entry, e);
});
header.addEventListener('dragend', (e) => {
this._settleTileTearOff(sessionId, e);
this._endTileMoveDrag();
});
header.addEventListener('dragend', () => this._endTileMoveDrag());
},
/**
@@ -2117,6 +2165,7 @@ Object.assign(CodemanApp.prototype, {
*/
_endTileMoveDrag() {
this._draggedTileId = null;
this._stopTileTearOffTracking();
const grid = this._tileGrid;
for (const { el } of grid?.tiles.values() || []) el.classList.remove('tile--dragging', 'tile--drop-target');
for (const slot of grid?.slots || []) slot.classList.remove('tile--drop-target');
@@ -2124,19 +2173,25 @@ Object.assign(CodemanApp.prototype, {
/**
* The header as a handle: `draggable` while the tile can move (not while a
* tile is zoomed, alone, or being renamed), and its tooltip, the state and
* how long ("working 3m") plus, while it can move, that it drags. Diffs on
* the last English text, never the DOM (translated in zh-CN; see
* tile is zoomed, alone, or being renamed) or, with Detach Tiles on, be
* dragged out of the window (then also alone or zoomed), and its tooltip,
* the state and how long ("working 3m") plus what a drag does. Diffs on the
* last English text, never the DOM (translated in zh-CN; see
* _renderTileOverlay).
*/
_paintTileHandle(entry) {
const movable = this._tilesMovable();
const title = [entry.stateLabel, movable ? 'Drag to move the tile' : ''].filter(Boolean).join('\n');
const detachable = this._tileDetachAllowed();
let hint = '';
if (movable && detachable) hint = 'Drag to move the tile, or out of the window to open it on its own';
else if (movable) hint = 'Drag to move the tile';
else if (detachable) hint = 'Drag out of the window to open the tile on its own';
const title = [entry.stateLabel, hint].filter(Boolean).join('\n');
if (entry.headerLabel !== title) {
entry.headerLabel = title;
entry.header.title = title;
}
const draggable = movable && !entry.renaming ? 'true' : 'false';
const draggable = (movable || detachable) && !entry.renaming ? 'true' : 'false';
if (entry.header.getAttribute('draggable') !== draggable) entry.header.setAttribute('draggable', draggable);
},
@@ -2859,6 +2914,357 @@ Object.assign(CodemanApp.prototype, {
for (const { tile } of grid.tiles.values()) tile.reconnectNow();
return true;
},
// ── Detach Tiles (per-device `tileDetachEnabled`, default OFF) ───────────
//
// A tile leaves the grid for a window of its own, and comes back into any
// Codeman window's grid, by dragging:
//
// - its header dropped OUTSIDE every window opens it as a pop-out window
// (detachSession, the tab's own "Open in a new window"), at the drop point
// and the tile's size;
// - its header dropped on ANOTHER Codeman window's tile or empty cell moves
// it there: that window docks it and says so on the window channel
// ('tile-adopted'), and this one lets the tile go;
// - a pop-out window's title dropped on a window's tile or empty cell docks
// the session there, and the pop-out closes.
//
// Nothing new on the server: a pop-out is another client of the same session
// (see detachSession), and a tile is a TerminalTile in whichever window has it.
// A session stays in ONE place in this browser, as with every pop-out.
/** Whether Detach Tiles is on for this device. */
tileDetachEnabled() {
return this.loadAppSettingsFromStorage?.()?.tileDetachEnabled === true;
},
/** Detach Tiles applies here: on, and a dashboard (a pop-out has no grid to drag from). */
_tileDetachAllowed() {
return !this.isSoloWindow && this.tileDetachEnabled();
},
/**
* A drag over this page that is a tile from another Codeman window: none of
* this page's own drags is in flight, Detach Tiles is on and the drag
* carries the tile type (its id is only readable on drop).
*/
_isForeignTileDrag(e) {
if (this.draggedTabId || this._draggedTileId || !this._tileGrid?.open || !this._tileDetachAllowed()) return false;
const types = e?.dataTransfer?.types;
return !!types && Array.from(types).includes(TILE_DRAG_TYPE);
},
/**
* A tile from another window dropped on one of this grid's targets: it docks
* through the target's own drop (`place`: a tile it replaces or trades
* places with, an empty cell it fills), and takes focus there (a human
* selection: the user just put it there). A session that was popped out comes
* back first (its window is asked to close). Once it is a tile here, every
* other window hears 'tile-adopted', and the one it was dragged from lets
* its tile go (_onTileAdoptedElsewhere). An id this page does not know (a
* session closed meanwhile, another user's) docks nowhere.
*
* @returns {boolean} whether the session is a tile here afterwards
*/
_dockForeignTile(sessionId, place) {
const grid = this._tileGrid;
if (!grid?.open || typeof sessionId !== 'string' || !this.sessions.has(sessionId)) return false;
const poppedOut = !!this.detachedSessions?.has(sessionId);
// A pop-out window owns its session's place: take it back before mounting
// (a detached session never mounts).
if (poppedOut) this._redock?.(sessionId);
// Already a tile here too (two windows showed it): it moves to where it
// was dropped, as a drag inside this window would move it.
place(sessionId);
if (!grid.has(sessionId)) return false;
(this._tileDockedAt ||= new Map()).set(sessionId, Date.now());
if (poppedOut) this._postWindowMessage?.({ type: 'close-request', id: sessionId });
this._postWindowMessage?.({ type: 'tile-adopted', id: sessionId, by: this._wsTabNonce });
return true;
},
/**
* True for a session this window docked from another one a moment ago: a
* 'detached' announcement from its old pop-out is that window on its way
* out, never a new pop-out (it would take the tile straight back off).
*/
_tileDockedRecently(sessionId) {
const at = this._tileDockedAt?.get(sessionId);
return typeof at === 'number' && Date.now() - at < TILE_DOCK_GRACE_MS;
},
/**
* Another window docked `sessionId` ('tile-adopted'). Only the window it
* was dragged FROM acts: its drag is still settling or ended a moment ago.
* The tile goes without taking the keyboard anywhere (the user is in the
* other window now). The last tile leaving closes the grid onto the welcome
* screen, never onto that session: two windows sizing one PTY garble it.
*/
_onTileAdoptedElsewhere(sessionId) {
const recent = this._lastTileDrag;
const dragging = this._tileTearOff?.id === sessionId;
const pending = this._tileTearOffPending?.id === sessionId;
const justEnded = recent?.id === sessionId && Date.now() - recent.at < TILE_ADOPT_WINDOW_MS;
if (!dragging && !pending && !justEnded) return false;
this._cancelTileTearOff();
this._lastTileDrag = null;
const grid = this._tileGrid;
if (!grid?.has(sessionId)) return false;
if (grid.ids.length > 1) return this.removeTile(sessionId, { focus: false });
this.closeTileGrid({ keepStored: false, reselect: false });
this.activeSessionId = null;
try {
localStorage.removeItem('codeman-active-session');
} catch {
/* Nothing stored. */
}
this.terminal?.clear();
this.showWelcome?.();
return true;
},
/**
* A header drag starts with Detach Tiles on: note the tile's size and where
* in it the press landed (the pop-out opens that size, under the pointer),
* and watch whether the pointer leaves the page. Two signals, since
* browsers differ in what dragend reports for a drop outside the window:
* its coordinates, and the page's own dragleave at the viewport's edge
* with nothing entered (cleared again by any dragover inside).
*/
_beginTileTearOff(sessionId, entry, e) {
this._stopTileTearOffTracking();
const rect = entry.el.getBoundingClientRect();
const within = (v, max) => (Number.isFinite(v) ? Math.max(0, Math.min(v, max)) : 0);
const drag = {
id: sessionId,
width: rect.width,
height: rect.height,
offsetX: within(e?.clientX - rect.left, rect.width),
offsetY: within(e?.clientY - rect.top, rect.height),
outside: false,
stop: null,
};
const onOver = () => {
drag.outside = false;
};
const onLeave = (ev) => {
if (ev.relatedTarget) return;
const x = ev.clientX;
const y = ev.clientY;
if (x <= 0 || y <= 0 || x >= window.innerWidth - 1 || y >= window.innerHeight - 1) drag.outside = true;
};
document.addEventListener('dragover', onOver, true);
document.addEventListener('dragleave', onLeave, true);
drag.stop = () => {
document.removeEventListener('dragover', onOver, true);
document.removeEventListener('dragleave', onLeave, true);
};
this._tileTearOff = drag;
},
/** The header drag is over (or the grid or tile went mid-drag): stop watching the pointer. */
_stopTileTearOffTracking() {
const drag = this._tileTearOff;
if (!drag) return;
this._tileTearOff = null;
drag.stop?.();
},
/**
* dragend of a tile's header with Detach Tiles on. Taken by a drop target
* (here or in another window: `dropEffect` is not 'none'), it stays where
* that put it. Let go OUTSIDE the window (the dragend point, or the page's
* own record of the pointer leaving), it opens as a window of its own after
* TILE_TEAR_OFF_SETTLE_MS, unless another window claims it first. Let go
* inside, on nothing, nothing happens, as before.
*/
_settleTileTearOff(sessionId, e) {
const drag = this._tileTearOff?.id === sessionId ? this._tileTearOff : null;
this._lastTileDrag = { id: sessionId, at: Date.now() };
if (!drag) return false;
this._stopTileTearOffTracking();
const effect = e?.dataTransfer?.dropEffect;
if (effect && effect !== 'none') return false;
const cx = e?.clientX;
const cy = e?.clientY;
// (0, 0) is what a browser reports when it does not know where the drop was.
const known = Number.isFinite(cx) && Number.isFinite(cy) && !(cx === 0 && cy === 0);
const outside = known ? cx < 0 || cy < 0 || cx >= window.innerWidth || cy >= window.innerHeight : drag.outside;
if (!outside) return false;
const sx = e?.screenX;
const sy = e?.screenY;
const placed = Number.isFinite(sx) && Number.isFinite(sy) && !(sx === 0 && sy === 0);
const placement = {
width: drag.width,
height: drag.height,
...(placed ? { screenX: sx, screenY: sy, offsetX: drag.offsetX, offsetY: drag.offsetY } : {}),
};
this._cancelTileTearOff();
const pending = { id: sessionId, timer: null };
pending.timer = setTimeout(() => {
if (this._tileTearOffPending !== pending) return;
this._tileTearOffPending = null;
this.detachTile(sessionId, placement);
}, TILE_TEAR_OFF_SETTLE_MS);
this._tileTearOffPending = pending;
return true;
},
_cancelTileTearOff() {
const pending = this._tileTearOffPending;
if (!pending) return;
this._tileTearOffPending = null;
clearTimeout(pending.timer);
},
/**
* Opens a tile as a window of its own (detachSession, which takes it out of
* the grid), the tile's size (at least TILE_WINDOW_MIN_W x MIN_H). Placed
* with its header under a screen point when given one (`screenX`/`screenY`
* and where in the tile it was held, `offsetX`/`offsetY`: a drop outside the
* window, a hand let go), otherwise over the tile itself (the ⋯ menu).
*
* @returns {boolean} whether the session is popped out afterwards
*/
detachTile(sessionId, { screenX, screenY, offsetX = 0, offsetY = 0, width, height } = {}) {
const entry = this._tileGrid?.open ? this._tileGrid.tiles.get(sessionId) : null;
if (!entry || !this._tileDetachAllowed()) return false;
const rect = entry.el.getBoundingClientRect();
const availW = window.screen?.availWidth || Infinity;
const availH = window.screen?.availHeight || Infinity;
const size = (v, min, max) => Math.round(Math.min(Math.max(Number.isFinite(v) ? v : min, min), max));
const placement = {
width: size(width ?? rect.width, TILE_WINDOW_MIN_W, availW),
height: size(height ?? rect.height, TILE_WINDOW_MIN_H, availH),
};
if (Number.isFinite(screenX) && Number.isFinite(screenY)) {
placement.left = Math.round(screenX - offsetX);
placement.top = Math.round(screenY - offsetY - TILE_WINDOW_CHROME_PX);
} else if (Number.isFinite(window.screenX) && Number.isFinite(window.screenY)) {
// Over the tile: the page's own chrome sits above its viewport.
const chrome = Math.max(0, (window.outerHeight || 0) - (window.innerHeight || 0));
placement.left = Math.round(window.screenX + rect.left);
placement.top = Math.round(window.screenY + chrome + rect.top - TILE_WINDOW_CHROME_PX);
}
this.detachSession?.(sessionId, placement);
return !!this.detachedSessions?.has(sessionId);
},
// ── For the gesture overlay (packages/gesture-control, src/codeman/entry.ts)
//
// A hand is no native drag: the overlay asks where it is and what is under
// it, and every move still goes through the paths a mouse drag takes
// (dropSessionOnTile / dropSessionOnSlot, and so _reorderTiles), the
// pop-out through detachTile.
/** The tiled session whose tile is at viewport point (x, y), or null. */
tileAtPoint(x, y) {
const grid = this._tileGrid;
if (!grid?.open) return null;
const hit = document.elementFromPoint?.(x, y);
if (!hit) return null;
for (const [id, entry] of grid.tiles) if (entry.el.contains?.(hit)) return id;
return null;
},
/** Whether a hand may pick up this tile: it can move, or (Detach Tiles) leave the window. */
canGrabTile(sessionId) {
return !!this._tileGrid?.has(sessionId) && (this._tilesMovable() || this._tileDetachAllowed());
},
/**
* What a session dragged to viewport point (x, y) would drop onto, by the
* mouse drag's own rules: another tile (it takes that tile's place, or the
* two trade places), an empty cell (it moves or joins there). A tiled
* session only while tiles can move (not zoomed). Null for anything else,
* a popped-out session included.
*
* @returns {{kind: 'tile', id: string, el: HTMLElement}|{kind: 'cell', cell: number, el: HTMLElement}|null}
*/
tileDropTargetAt(x, y, draggedId) {
const grid = this._tileGrid;
if (!grid?.open || !this.sessions.has(draggedId) || this.detachedSessions?.has(draggedId)) return null;
if (grid.tiles.has(draggedId) && !this._tilesMovable()) return null;
const hit = document.elementFromPoint?.(x, y);
if (!hit) return null;
for (const [id, entry] of grid.tiles) {
if (entry.el.contains?.(hit)) return id === draggedId ? null : { kind: 'tile', id, el: entry.el };
}
for (const slot of grid.slots || []) {
if (slot.contains?.(hit)) return { kind: 'cell', cell: Number(slot.dataset.cell), el: slot };
}
return null;
},
/**
* Drops a session on a target tileDropTargetAt returned (the hand let go).
*
* @returns {boolean} whether the session is a tile afterwards
*/
dropOnTileTarget(draggedId, target) {
if (!target || !this._tileGrid?.open) return false;
if (target.kind === 'tile') this.dropSessionOnTile(draggedId, target.id);
else if (target.kind === 'cell') this.dropSessionOnSlot(draggedId, target.cell);
return !!this._tileGrid?.has(draggedId);
},
/** Whether viewport point (x, y) is over the open grid (a hand let go outside it pops the tile out). */
isOverTileGrid(x, y) {
if (!this._tileGrid?.open) return false;
const rect = document.getElementById('tileGrid')?.getBoundingClientRect?.();
return !!rect && x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom;
},
/**
* A hand let a tile go outside the grid (Detach Tiles): it opens as a window
* of its own with its header near that point. A script opening a window
* with no click behind it is what popup blockers stop; detachSession then
* says so and the tile stays.
*/
detachTileAtPoint(sessionId, x, y, { offsetX = 0, offsetY = 0 } = {}) {
const chrome = Math.max(0, (window.outerHeight || 0) - (window.innerHeight || 0));
const sx = (window.screenX || 0) + x;
const sy = (window.screenY || 0) + chrome + y;
return this.detachTile(sessionId, { screenX: sx, screenY: sy, offsetX, offsetY });
},
/**
* A pop-out window's title, as a handle (Detach Tiles): dragged onto a
* Codeman window's tile or empty cell, the session docks there as a tile
* and this window closes (_dockForeignTile, which asks it to). The same
* drag type as a tile's header; on or off follows the setting, also when it
* changes in another window.
*/
_installSoloTileHandle() {
const title = document.getElementById('soloSessionTitle');
if (!this.isSoloWindow || !title || title._codemanTileHandle) return;
title._codemanTileHandle = true;
const sync = () => {
this._cachedAppSettings = null;
const on = this.tileDetachEnabled();
title.setAttribute('draggable', on ? 'true' : 'false');
title.classList.toggle('solo-session-title--handle', on);
const label = on ? "Drag onto a Codeman window's tiles to dock this session there" : '';
if (title._codemanTileHandleLabel !== label) {
title._codemanTileHandleLabel = label;
title.title = label;
}
};
sync();
window.addEventListener('storage', (e) => {
if (!e.key || e.key === this.getSettingsStorageKey?.()) sync();
});
title.addEventListener('dragstart', (e) => {
if (!this.tileDetachEnabled() || !this.soloSessionId) {
e.preventDefault?.();
return;
}
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(TILE_DRAG_TYPE, this.soloSessionId);
}
});
},
});
// A tiled session deleted (here or elsewhere) loses its tile; if it held focus,
+1 -22
View File
@@ -17,7 +17,7 @@ import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } f
import { isUnauthenticatedNetworkAcknowledged } from '../network-auth-policy.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned } from '../route-helpers.js';
import { getAuthUser, requireAdmin, canAccessOwned } from '../route-helpers.js';
import {
ConfigUpdateSchema,
SettingsUpdateSchema,
@@ -32,8 +32,6 @@ import {
import { subagentWatcher } from '../../subagent-watcher.js';
import { imageWatcher } from '../../image-watcher.js';
import { workflowRunWatcher } from '../../workflow-run-watcher.js';
import { keepAwake } from '../../keep-awake-manager.js';
import { resolveKeepAwakeConfig } from '../../keep-awake.js';
import { getLifecycleLog } from '../../session-lifecycle-log.js';
import {
buildAwayDigest,
@@ -1006,13 +1004,6 @@ export function registerSystemRoutes(
// acknowledgeUnauthTunnel is an ACTION field (not a stored setting) — strip
// it before persisting so settings.json stays clean.
const { acknowledgeUnauthTunnel, ...settingsToStore } = settings;
// Keep-awake is machine state (an OS sleep lock), so in multi-user mode only an
// admin changes it. A non-admin's save carries whatever value its page loaded, so
// the keys are dropped rather than refused: refusing would fail every settings save.
if (!isAdmin(req)) {
delete settingsToStore.keepAwakeEnabled;
delete settingsToStore.keepAwakeAcOnly;
}
const merged = { ...existing, ...settingsToStore };
await fs.writeFile(SETTINGS_PATH, JSON.stringify(merged, null, 2));
@@ -1041,10 +1032,6 @@ export function registerSystemRoutes(
'Workflow run watcher'
);
// Keep-awake reconciles from `merged` like the watchers above: a partial PUT
// must not read as "turn it off".
void keepAwake.apply(resolveKeepAwakeConfig(merged));
// Handle image watcher toggle dynamically
toggleService((merged.imageWatcherEnabled as boolean) ?? false, imageWatcher, 'Image watcher', () => {
// Re-watch all active sessions that have image watcher enabled
@@ -1095,14 +1082,6 @@ export function registerSystemRoutes(
}
});
// ========== Keep awake ==========
// Status of the sleep lock behind `keepAwakeEnabled` (src/keep-awake-manager.ts). A
// plain in-memory read: the settings toggle lives in PUT /api/settings.
app.get('/api/system/keep-awake', async () => {
return { success: true, data: keepAwake.getStatus() };
});
// ========== Model Configuration ==========
app.get('/api/execution/model-config', async () => {
-8
View File
@@ -1378,14 +1378,6 @@ export const SettingsUpdateSchema = z
* opt-in. While OFF, GET/POST /api/mcp-sync answer 403 and the Settings controls are hidden.
*/
mcpSyncEnabled: z.boolean().optional(),
/**
* Keep this computer awake while Codeman runs (src/keep-awake.ts). SYNCED, default OFF:
* it is machine state (an OS sleep lock), so in multi-user mode only an admin can change
* it; a non-admin's value is dropped by PUT /api/settings. `keepAwakeAcOnly` (default ON)
* releases the lock on battery.
*/
keepAwakeEnabled: z.boolean().optional(),
keepAwakeAcOnly: z.boolean().optional(),
/**
* Read My Mind predictor model override. Empty/absent = the AI-checker
* default (opus: prediction quality is the product and it runs only on an
-11
View File
@@ -111,8 +111,6 @@ import { intentStore } from '../intent-store.js';
import { AI_CHECK_MODEL } from '../config/ai-defaults.js';
import { approvalInbox } from './approval-inbox.js';
import { stopDeepSeekWeb } from '../deepseek-web-server.js';
import { keepAwake } from '../keep-awake-manager.js';
import { resolveKeepAwakeConfig } from '../keep-awake.js';
import {
wireRespawnListeners,
setupTimedRespawn,
@@ -3144,10 +3142,6 @@ export class WebServer extends EventEmitter {
console.log('Image watcher disabled by user settings');
}
// Keep-awake: holds an OS sleep lock while this server runs (opt-in, default OFF).
// A fresh read, like the gesture flag: it decides whether a lock is taken at all.
void keepAwake.apply(resolveKeepAwakeConfig(await this.readSettings(true)));
// Tunnel only starts when user clicks the toggle in the UI — never on boot.
// Reset persisted tunnelEnabled so the UI toggle reflects actual state.
if (await this.isTunnelEnabled()) {
@@ -3982,11 +3976,6 @@ export class WebServer extends EventEmitter {
// got wrong once.
void stopDeepSeekWeb();
// Release the sleep lock with the server, not after it. The lock would also drop on
// its own once this process exits (stdin pipe / caffeinate -w), but a graceful stop
// should not leave the macOS lid request file to go stale on its own.
await keepAwake.stop();
// Same teardown rule: the per-endpoint llama-swap log tails are otherwise closed
// only by the periodic idle sweep, whose interval is disposed just below.
closeAllLlamaSwapLogTails();
-207
View File
@@ -1,207 +0,0 @@
/**
* @fileoverview install.sh's keep-awake follow-up, driven in a real bash where it can be
* (laptop detection over a fake sysfs, the settings.json write, the --yes default) and
* pinned statically where it cannot (the macOS root helper needs sudo and launchd).
*
* The rules: never turned on by --yes or a headless run; the setting is written before
* the service starts; the root helper runs from a ROOT-OWNED copy, never from the
* user-writable install dir; uninstall undoes only what the helper set.
*
* Port: none.
*/
import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
const INSTALL_SH = fileURLToPath(new URL('../install.sh', import.meta.url));
const SOURCE = readFileSync(INSTALL_SH, 'utf-8');
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'install-keep-awake-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
/** Source install.sh (library mode) in a real bash with HOME in the temp dir, then run `body`. */
function drive(body: string, env: Record<string, string> = {}) {
const script = `
set -euo pipefail
export CODEMAN_INSTALL_SH_LIB=1
. "$1"
${body}
`;
const result = spawnSync('bash', ['-c', script, 'bash', INSTALL_SH], {
encoding: 'utf-8',
timeout: 30_000,
input: '',
env: { ...process.env, HOME: join(dir, 'home'), ...env },
});
return result;
}
function fakeSupply(name: string, files: Record<string, string>) {
const d = join(dir, 'ps', name);
mkdirSync(d, { recursive: true });
for (const [k, v] of Object.entries(files)) writeFileSync(join(d, k), `${v}\n`);
}
const laptopCheck = `
POWER_SUPPLY_ROOT="${'$'}FAKE_PS"; LID_BUTTON_ROOT="${'$'}FAKE_LID"
if is_laptop linux; then echo laptop; else echo desktop; fi
`;
describe('is_laptop (Linux)', () => {
const run = () => drive(laptopCheck, { FAKE_PS: join(dir, 'ps'), FAKE_LID: join(dir, 'lid') }).stdout.trim();
it('a machine with no battery and no lid is not a laptop', () => {
mkdirSync(join(dir, 'ps'), { recursive: true });
fakeSupply('AC', { type: 'Mains', online: '1' });
expect(run()).toBe('desktop');
});
it("a wireless mouse's battery does not make a desktop a laptop", () => {
fakeSupply('hidpp_battery_0', { type: 'Battery', scope: 'Device', status: 'Discharging' });
expect(run()).toBe('desktop');
});
it('a system battery or a lid does', () => {
fakeSupply('BAT0', { type: 'Battery', status: 'Charging' });
expect(run()).toBe('laptop');
rmSync(join(dir, 'ps'), { recursive: true });
mkdirSync(join(dir, 'lid', 'LID0'), { recursive: true });
expect(run()).toBe('laptop');
});
it('copes with a missing power_supply tree', () => {
expect(run()).toBe('desktop');
});
});
describe('write_keep_awake_setting', () => {
const settings = () => join(dir, 'home', '.codeman', 'settings.json');
it('creates settings.json with the setting on and AC-only on', () => {
const r = drive('write_keep_awake_setting');
expect(r.status, r.stderr).toBe(0);
expect(JSON.parse(readFileSync(settings(), 'utf-8'))).toEqual({ keepAwakeEnabled: true, keepAwakeAcOnly: true });
});
it('keeps every other key, and an explicit AC-only choice', () => {
mkdirSync(join(dir, 'home', '.codeman'), { recursive: true });
writeFileSync(settings(), JSON.stringify({ theme: 'dark', keepAwakeAcOnly: false }, null, 2));
expect(drive('write_keep_awake_setting').status).toBe(0);
expect(JSON.parse(readFileSync(settings(), 'utf-8'))).toEqual({
theme: 'dark',
keepAwakeAcOnly: false,
keepAwakeEnabled: true,
});
});
it('leaves a settings file that does not parse untouched', () => {
mkdirSync(join(dir, 'home', '.codeman'), { recursive: true });
writeFileSync(settings(), '{ not json');
const r = drive('write_keep_awake_setting || echo refused');
expect(r.stdout).toContain('refused');
expect(readFileSync(settings(), 'utf-8')).toBe('{ not json');
});
it('is what keep_awake_enabled_now reads back', () => {
const r = drive(
'keep_awake_enabled_now && echo before; write_keep_awake_setting >/dev/null 2>&1; keep_awake_enabled_now && echo after'
);
expect(r.stdout.trim()).toBe('after');
});
});
describe('choose_keep_awake', () => {
it('--yes on a laptop never turns it on', () => {
fakeSupply('BAT0', { type: 'Battery', status: 'Charging' });
const r = drive(
`POWER_SUPPLY_ROOT="$FAKE_PS"; ASSUME_YES=1
choose_keep_awake linux
echo "keep=[$KEEP_AWAKE] helper=[$KEEP_AWAKE_LID_HELPER]"`,
{ FAKE_PS: join(dir, 'ps') }
);
expect(r.status, r.stderr).toBe(0);
expect(r.stdout).toContain('keep=[] helper=[]');
});
it('asks nothing on a desktop', () => {
const r = drive(
`POWER_SUPPLY_ROOT="$FAKE_PS"; LID_BUTTON_ROOT="$FAKE_PS"
choose_keep_awake linux 2>&1
echo "keep=[$KEEP_AWAKE]"`,
{ FAKE_PS: join(dir, 'nothing') }
);
expect(r.stdout.trim()).toBe('keep=[]');
});
it('only notes an existing setting, without re-asking', () => {
mkdirSync(join(dir, 'home', '.codeman'), { recursive: true });
writeFileSync(join(dir, 'home', '.codeman', 'settings.json'), JSON.stringify({ keepAwakeEnabled: true }, null, 2));
const r = drive(`choose_keep_awake linux force 2>&1; echo "keep=[$KEEP_AWAKE]"`);
expect(r.stdout).toContain('already on');
expect(r.stdout).toContain('keep=[]');
});
it('defaults to no in the prompt itself', () => {
const fn = SOURCE.slice(SOURCE.indexOf('choose_keep_awake() {'), SOURCE.indexOf('write_keep_awake_setting() {'));
expect(fn).toMatch(/prompt_yes_no "Keep this machine awake[^"]*" "n"/);
// The sudo-needing helper is offered only to a person at a terminal.
expect(fn).toMatch(/"\$NONINTERACTIVE" != "1" && "\$ASSUME_YES" != "1" \]\] && has_tty/);
});
});
describe('install.sh keep-awake wiring', () => {
const fn = (name: string, next: string) => SOURCE.slice(SOURCE.indexOf(`${name}() {`), SOURCE.indexOf(next));
it('asks after question 3 and applies before the service starts', () => {
const main = fn('main', '\npreflight_detect() {');
const ask = main.indexOf('choose_keep_awake "$os"');
const apply = main.indexOf('apply_keep_awake');
expect(ask).toBeGreaterThan(main.indexOf('choose_launch_mode "$os"'));
expect(ask).toBeLessThan(main.indexOf('install_or_update_repo'));
expect(apply).toBeGreaterThan(main.indexOf('run_step "Building Codeman"'));
expect(apply).toBeLessThan(main.indexOf('setup_launchd_service'));
expect(apply).toBeLessThan(main.indexOf('setup_systemd_service'));
});
it('runs the root helper from a root-owned copy, never from the install dir', () => {
const body = fn('install_keep_awake_lid_helper', '\nremove_keep_awake_lid_helper() {');
expect(body).toContain('install -m 755 -o root -g wheel "$src" "$script"');
expect(body).toContain('local script="$KEEP_AWAKE_HELPER_DIR/keep-awake-macos.sh"');
const programArgs = body.slice(body.indexOf('<key>ProgramArguments</key>'), body.indexOf('</array>'));
expect(programArgs).toContain('$(xml_escape "$script")');
expect(programArgs).not.toContain('INSTALL_DIR');
// The request path must match what the server writes (dataPath('keep-awake-lid.pid')).
expect(body).toContain('local request="$HOME/.codeman/keep-awake-lid.pid"');
});
it('uninstall removes the helper and undoes only a disablesleep it set', () => {
expect(fn('uninstall', '\nusage() {')).toContain('remove_keep_awake_lid_helper');
const remove = fn('remove_keep_awake_lid_helper', '\napply_keep_awake() {');
const owned = remove.indexOf('keep-awake.owned');
expect(owned).toBeGreaterThan(-1);
expect(remove.indexOf('pmset -a disablesleep 0')).toBeGreaterThan(owned);
});
it('dispatches the keep-awake subcommand and documents it', () => {
expect(SOURCE).toMatch(/update\|uninstall\|tailscale\|name\|status\|cloudflared\|keep-awake\)/);
expect(SOURCE).toMatch(/\n {4}keep-awake\) {2}keep_awake_subcommand ;;/);
const header = SOURCE.slice(0, SOURCE.indexOf('set -euo pipefail'));
expect(header).toContain('install.sh keep-awake');
expect(fn('usage', '\nparse_flags() {')).toContain('keep-awake');
});
it('update and keep-awake share one restart path', () => {
expect(fn('update', '\nuninstall() {')).toContain('restart_running_service');
expect(fn('keep_awake_subcommand', '\nverify_systemd_active() {')).toContain('restart_running_service');
});
});
-175
View File
@@ -1,175 +0,0 @@
/**
* @fileoverview Runs the real macOS lid helper (scripts/keep-awake-macos.sh) in bash
* against a stub `pmset` that records what it was asked to do. The helper runs as root
* from a LaunchDaemon, so the cases that matter are the ones where it must NOT act: a
* stale, dead, foreign or symlinked request, and an administrator's own
* `disablesleep 1`, which it must never switch off.
*
* Only the BSD/GNU-portable tools the script uses (find -mmin, ps -o uid=, ls -ln) run
* here, so this passes on Linux and macOS alike. Port: none.
*/
import { spawnSync } from 'node:child_process';
import {
chmodSync,
existsSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
utimesSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
const HELPER = fileURLToPath(new URL('../scripts/keep-awake-macos.sh', import.meta.url));
let dir: string;
let stateDir: string;
let request: string;
/** Stub pmset: `-g` prints the stored SleepDisabled, `-a disablesleep N` stores N and logs it. */
function writeStubPmset(initial: '0' | '1' | null) {
const value = join(dir, 'sleepdisabled');
if (initial !== null) writeFileSync(value, initial);
const stub = join(dir, 'pmset');
writeFileSync(
stub,
`#!/bin/bash
if [ "$1" = "-g" ]; then
echo "System-wide power settings:"
[ -f "${value}" ] && printf ' SleepDisabled\\t\\t%s\\n' "$(cat "${value}")"
echo "Currently in use:"
echo " sleep 1"
exit 0
fi
if [ "$1" = "-a" ] && [ "$2" = "disablesleep" ]; then
printf '%s' "$3" > "${value}"
echo "disablesleep $3" >> "${join(dir, 'pmset.log')}"
exit 0
fi
exit 1
`
);
chmodSync(stub, 0o755);
return stub;
}
function run() {
const result = spawnSync('bash', [HELPER, request], {
encoding: 'utf-8',
env: {
...process.env,
CODEMAN_KEEPAWAKE_PMSET: join(dir, 'pmset'),
CODEMAN_KEEPAWAKE_STATE_DIR: stateDir,
},
});
expect(result.status, result.stderr).toBe(0);
}
const calls = () => (existsSync(join(dir, 'pmset.log')) ? readFileSync(join(dir, 'pmset.log'), 'utf-8') : '');
const sleepDisabled = () => readFileSync(join(dir, 'sleepdisabled'), 'utf-8');
const owned = () => existsSync(join(stateDir, 'keep-awake.owned'));
const requestFromLiveServer = () => writeFileSync(request, `${process.pid}\n`);
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'keep-awake-helper-'));
stateDir = join(dir, 'state');
request = join(dir, 'keep-awake-lid.pid');
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
describe('keep-awake-macos.sh', () => {
it('does nothing without a request', () => {
writeStubPmset('0');
run();
expect(calls()).toBe('');
expect(owned()).toBe(false);
});
it('applies disablesleep for a fresh request from a live process, then undoes it when the request goes', () => {
writeStubPmset('0');
requestFromLiveServer();
run();
expect(sleepDisabled()).toBe('1');
expect(owned()).toBe(true);
run(); // steady state: no repeated pmset call
expect(calls()).toBe('disablesleep 1\n');
rmSync(request);
run();
expect(sleepDisabled()).toBe('0');
expect(owned()).toBe(false);
expect(calls()).toBe('disablesleep 1\ndisablesleep 0\n');
});
it("never switches off an administrator's own disablesleep", () => {
writeStubPmset('1');
requestFromLiveServer();
run();
expect(calls()).toBe('');
expect(owned()).toBe(false);
rmSync(request);
run();
expect(sleepDisabled()).toBe('1');
expect(calls()).toBe('');
});
it('treats an absent SleepDisabled line as 0', () => {
writeStubPmset(null);
requestFromLiveServer();
run();
expect(sleepDisabled()).toBe('1');
expect(owned()).toBe(true);
});
it('re-applies after a reboot or OS update reset it, while the request stands', () => {
writeStubPmset('0');
requestFromLiveServer();
run();
writeFileSync(join(dir, 'sleepdisabled'), '0'); // the reset
run();
expect(sleepDisabled()).toBe('1');
});
it('ignores a stale request (a crashed or hung server) and releases', () => {
writeStubPmset('0');
requestFromLiveServer();
run();
expect(sleepDisabled()).toBe('1');
const threeMinutesAgo = (Date.now() - 3 * 60_000) / 1000;
utimesSync(request, threeMinutesAgo, threeMinutesAgo);
run();
expect(sleepDisabled()).toBe('0');
expect(owned()).toBe(false);
});
it('ignores a request whose pid is not running', () => {
writeStubPmset('0');
const gone = spawnSync('true').pid;
writeFileSync(request, `${gone}\n`);
run();
expect(calls()).toBe('');
});
it('ignores garbage and refuses a symlinked request', () => {
writeStubPmset('0');
writeFileSync(request, 'not-a-pid\n');
run();
expect(calls()).toBe('');
rmSync(request);
const real = join(dir, 'elsewhere.pid');
writeFileSync(real, `${process.pid}\n`);
symlinkSync(real, request);
run();
expect(calls()).toBe('');
});
});
-270
View File
@@ -1,270 +0,0 @@
/**
* @fileoverview KeepAwakeManager (src/keep-awake-manager.ts) driven through fake deps: no
* real lock is ever taken. Pins the lifecycle: a lock is confirmed before it reads as
* active, a polkit refusal is a retried state, AC-only follows the power source, a
* release closes the inhibitor's stdin (which is what drops the lock), and the macOS lid
* request file follows the lock only when the root helper is installed.
*
* Port: none.
*/
import { EventEmitter } from 'node:events';
import type { ChildProcess } from 'node:child_process';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { KeepAwakeManager, type KeepAwakeDeps } from '../src/keep-awake-manager.js';
import {
LINUX_HELD_MARKER,
POWER_POLL_MS,
RETRY_MS,
linuxInhibitArgs,
macCaffeinateArgs,
type PowerSupplyInfo,
} from '../src/keep-awake.js';
class FakeChild extends EventEmitter {
stdout = new EventEmitter();
stderr = new EventEmitter();
/** Like the real `cat`: closing stdin ends the process (asynchronously). */
stdin = Object.assign(new EventEmitter(), {
end: vi.fn(() => {
queueMicrotask(() => {
if (this.exitCode !== null || this.signalCode !== null) return;
this.exitCode = 0;
this.emit('exit', 0, null);
});
}),
});
exitCode: number | null = null;
signalCode: string | null = null;
kill = vi.fn((signal?: string) => {
this.signalCode = signal ?? 'SIGTERM';
this.emit('exit', null, this.signalCode);
return true;
});
/** The process announces the lock (systemd-inhibit only execs its child once held). */
hold() {
this.stdout.emit('data', Buffer.from(`${LINUX_HELD_MARKER}\n`));
}
fail(stderr: string, code = 1) {
this.stderr.emit('data', Buffer.from(stderr));
this.exitCode = code;
this.emit('exit', code, null);
}
}
const AC: PowerSupplyInfo[] = [
{ type: 'Mains', online: true },
{ type: 'Battery', status: 'Charging' },
];
const BATTERY: PowerSupplyInfo[] = [
{ type: 'Mains', online: false },
{ type: 'Battery', status: 'Discharging' },
];
/** Let queued reconciles (a promise chain) run to completion. */
const settle = async () => {
for (let i = 0; i < 10; i++) await new Promise((r) => setImmediate(r));
};
function makeDeps(overrides: Partial<KeepAwakeDeps> = {}) {
const children: FakeChild[] = [];
let supplies = AC;
let batt = "Now drawing from 'AC Power'";
const deps: KeepAwakeDeps = {
platform: 'linux',
serverPid: 4242,
spawn: vi.fn(() => {
const c = new FakeChild();
children.push(c);
return c as unknown as ChildProcess;
}),
readPowerSupplies: vi.fn(async () => supplies),
readMacBatt: vi.fn(async () => batt),
lidHelperInstalled: vi.fn(async () => true),
writeLidRequest: vi.fn(async () => {}),
removeLidRequest: vi.fn(async () => {}),
...overrides,
};
return {
deps,
children,
setSupplies: (s: PowerSupplyInfo[]) => (supplies = s),
setBatt: (s: string) => (batt = s),
};
}
describe('KeepAwakeManager on Linux', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'setInterval', 'clearTimeout', 'clearInterval'] });
});
afterEach(() => {
vi.useRealTimers();
});
it('takes the logind lock and reads active only once the lock is confirmed', async () => {
const { deps, children } = makeDeps();
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
expect(deps.spawn).toHaveBeenCalledWith('systemd-inhibit', linuxInhibitArgs());
expect(m.getStatus().state).toBe('starting');
children[0].hold();
expect(m.getStatus()).toMatchObject({ state: 'active', onAc: true, platform: 'linux', lidHelper: null });
await m.stop();
});
it('reports a polkit refusal as denied and retries it', async () => {
const { deps, children } = makeDeps();
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
children[0].fail('Failed to inhibit: Access denied\n');
expect(m.getStatus().state).toBe('denied');
expect(deps.spawn).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(RETRY_MS);
await settle();
expect(deps.spawn).toHaveBeenCalledTimes(2);
children[1].hold();
expect(m.getStatus().state).toBe('active');
await m.stop();
});
it('turning it off closes the inhibitor stdin, which drops the lock, and does not retry', async () => {
const { deps, children } = makeDeps();
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: false });
children[0].hold();
await m.apply({ enabled: false, acOnly: false });
expect(children[0].stdin.end).toHaveBeenCalled();
expect(m.getStatus().state).toBe('off');
// The released child exiting is expected, not a failure to retry.
await settle();
await vi.advanceTimersByTimeAsync(RETRY_MS * 2);
await settle();
expect(deps.spawn).toHaveBeenCalledTimes(1);
expect(m.getStatus().state).toBe('off');
});
it('AC-only: no lock on battery, takes it when plugged in, releases on unplug', async () => {
const { deps, children, setSupplies } = makeDeps();
setSupplies(BATTERY);
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
expect(deps.spawn).not.toHaveBeenCalled();
expect(m.getStatus()).toMatchObject({ state: 'paused-battery', onAc: false });
setSupplies(AC);
await vi.advanceTimersByTimeAsync(POWER_POLL_MS);
await settle();
expect(deps.spawn).toHaveBeenCalledTimes(1);
children[0].hold();
expect(m.getStatus().state).toBe('active');
setSupplies(BATTERY);
await vi.advanceTimersByTimeAsync(POWER_POLL_MS);
await settle();
expect(children[0].stdin.end).toHaveBeenCalled();
expect(m.getStatus().state).toBe('paused-battery');
await m.stop();
});
it('without AC-only it never reads the power source', async () => {
const { deps, setSupplies } = makeDeps();
setSupplies(BATTERY);
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: false });
expect(deps.readPowerSupplies).not.toHaveBeenCalled();
expect(deps.spawn).toHaveBeenCalledTimes(1);
await m.stop();
});
it('a machine without systemd-inhibit is unavailable, and is not retried', async () => {
const { deps } = makeDeps({
spawn: vi.fn(() => {
throw Object.assign(new Error('spawn systemd-inhibit ENOENT'), { code: 'ENOENT' });
}),
});
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
expect(m.getStatus()).toMatchObject({ state: 'unavailable' });
expect(m.getStatus().detail).toMatch(/systemd-inhibit is not installed/);
await vi.advanceTimersByTimeAsync(RETRY_MS * 3);
await settle();
expect(deps.spawn).toHaveBeenCalledTimes(1);
await m.stop();
});
it('stop() releases the lock and leaves nothing scheduled', async () => {
const { deps, children } = makeDeps();
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
children[0].hold();
await m.stop();
await settle();
expect(children[0].stdin.end).toHaveBeenCalled();
expect(children[0].kill).not.toHaveBeenCalled();
expect(m.getStatus().state).toBe('off');
expect(vi.getTimerCount()).toBe(0);
});
});
describe('KeepAwakeManager on macOS', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'setInterval', 'clearTimeout', 'clearInterval'] });
});
afterEach(() => {
vi.useRealTimers();
});
it('runs caffeinate tied to the server pid and keeps the lid request fresh while held', async () => {
const { deps, children } = makeDeps({ platform: 'macos' });
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
expect(deps.spawn).toHaveBeenCalledWith('/usr/bin/caffeinate', macCaffeinateArgs(4242));
children[0].emit('spawn');
expect(m.getStatus()).toMatchObject({ state: 'active', lidHelper: 'installed', onAc: true });
expect(deps.writeLidRequest).toHaveBeenCalledWith(4242);
await vi.advanceTimersByTimeAsync(30_000);
expect((deps.writeLidRequest as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThanOrEqual(2);
await m.apply({ enabled: false, acOnly: true });
expect(deps.removeLidRequest).toHaveBeenCalled();
expect(children[0].kill).toHaveBeenCalled();
const writes = (deps.writeLidRequest as ReturnType<typeof vi.fn>).mock.calls.length;
await vi.advanceTimersByTimeAsync(120_000);
expect((deps.writeLidRequest as ReturnType<typeof vi.fn>).mock.calls.length).toBe(writes);
});
it('writes no lid request when the root helper is not installed', async () => {
const { deps, children } = makeDeps({ platform: 'macos', lidHelperInstalled: vi.fn(async () => false) });
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
children[0].emit('spawn');
expect(m.getStatus()).toMatchObject({ state: 'active', lidHelper: 'missing' });
expect(deps.writeLidRequest).not.toHaveBeenCalled();
await m.stop();
});
it('on battery with AC-only, drops both caffeinate and the lid request', async () => {
const { deps, children, setBatt } = makeDeps({ platform: 'macos' });
const m = new KeepAwakeManager(deps);
await m.apply({ enabled: true, acOnly: true });
children[0].emit('spawn');
setBatt("Now drawing from 'Battery Power'");
await vi.advanceTimersByTimeAsync(POWER_POLL_MS);
await settle();
expect(m.getStatus().state).toBe('paused-battery');
expect(children[0].kill).toHaveBeenCalled();
expect(deps.removeLidRequest).toHaveBeenCalled();
await m.stop();
});
});
describe('the process-wide manager under vitest', () => {
it('is inert: enabling it never spawns a real lock', async () => {
const m = new KeepAwakeManager();
await m.apply({ enabled: true, acOnly: false });
expect(m.getStatus()).toMatchObject({ state: 'unavailable', detail: 'Disabled under the test runner.' });
await m.stop();
});
});
-116
View File
@@ -1,116 +0,0 @@
/**
* @fileoverview Pure decisions behind "Keep this computer awake while Codeman runs"
* (src/keep-awake.ts): settings defaults, platform choice, power-source parsing, the
* hold/release rule, the lock argv and the failure classification.
*
* Port: none (pure).
*/
import { describe, expect, it } from 'vitest';
import {
LINUX_HELD_MARKER,
LINUX_INHIBIT_WHAT,
classifyInhibitFailure,
isOnAcPowerLinux,
isOnAcPowerMac,
keepAwakePlatform,
linuxInhibitArgs,
macCaffeinateArgs,
resolveKeepAwakeConfig,
shouldHoldLock,
} from '../src/keep-awake.js';
describe('resolveKeepAwakeConfig', () => {
it('is off unless explicitly enabled, and AC-only unless explicitly not', () => {
expect(resolveKeepAwakeConfig({})).toEqual({ enabled: false, acOnly: true });
expect(resolveKeepAwakeConfig({ keepAwakeEnabled: 'yes' })).toEqual({ enabled: false, acOnly: true });
expect(resolveKeepAwakeConfig({ keepAwakeEnabled: true })).toEqual({ enabled: true, acOnly: true });
expect(resolveKeepAwakeConfig({ keepAwakeEnabled: true, keepAwakeAcOnly: false })).toEqual({
enabled: true,
acOnly: false,
});
});
});
describe('keepAwakePlatform', () => {
it('maps darwin and linux, and treats WSL as unsupported', () => {
expect(keepAwakePlatform('darwin', '24.0.0')).toBe('macos');
expect(keepAwakePlatform('linux', '6.8.0-124-generic')).toBe('linux');
expect(keepAwakePlatform('linux', '5.15.153.1-microsoft-standard-WSL2')).toBe('unsupported');
expect(keepAwakePlatform('win32', '10.0.22631')).toBe('unsupported');
});
});
describe('isOnAcPowerLinux', () => {
const battery = (status: string) => ({ type: 'Battery', status });
it('a machine with no battery of its own is on external power', () => {
expect(isOnAcPowerLinux([])).toBe(true);
expect(isOnAcPowerLinux([{ type: 'Battery', status: 'Discharging', scope: 'Device' }])).toBe(true);
});
it('an online adapter means AC, all adapters offline means battery', () => {
expect(isOnAcPowerLinux([{ type: 'Mains', online: true }, battery('Charging')])).toBe(true);
expect(isOnAcPowerLinux([{ type: 'USB', online: true }, battery('Unknown')])).toBe(true);
expect(isOnAcPowerLinux([{ type: 'Mains', online: false }, battery('Unknown')])).toBe(false);
});
it('falls back to the battery status when no adapter is listed', () => {
expect(isOnAcPowerLinux([battery('Discharging')])).toBe(false);
expect(isOnAcPowerLinux([battery('Full')])).toBe(true);
expect(isOnAcPowerLinux([battery('Not charging')])).toBe(true);
expect(isOnAcPowerLinux([battery('Unknown')])).toBe(null);
});
});
describe('isOnAcPowerMac', () => {
it('reads the source from `pmset -g batt`', () => {
expect(isOnAcPowerMac("Now drawing from 'AC Power'\n -InternalBattery-0 (id=1)\t100%; charged;")).toBe(true);
expect(isOnAcPowerMac("Now drawing from 'Battery Power'\n -InternalBattery-0 (id=1)\t80%;")).toBe(false);
expect(isOnAcPowerMac("Now drawing from 'UPS Power'")).toBe(false);
expect(isOnAcPowerMac('')).toBe(null);
});
});
describe('shouldHoldLock', () => {
it('holds only when enabled, and on battery only when not AC-only', () => {
expect(shouldHoldLock({ enabled: false, acOnly: false }, true)).toBe(false);
expect(shouldHoldLock({ enabled: true, acOnly: true }, true)).toBe(true);
expect(shouldHoldLock({ enabled: true, acOnly: true }, false)).toBe(false);
expect(shouldHoldLock({ enabled: true, acOnly: false }, false)).toBe(true);
});
it('treats an unknown power source as AC (a desktop without battery reporting)', () => {
expect(shouldHoldLock({ enabled: true, acOnly: true }, null)).toBe(true);
});
});
describe('lock argv', () => {
it('asks logind for the lid lock, not just sleep (LidSwitchIgnoreInhibited=yes ignores sleep)', () => {
const args = linuxInhibitArgs();
expect(LINUX_INHIBIT_WHAT.split(':')).toContain('handle-lid-switch');
expect(args).toContain(`--what=${LINUX_INHIBIT_WHAT}`);
expect(args).toContain('--mode=block');
});
it('ends in a cat on stdin, so the lock dies with the server', () => {
const args = linuxInhibitArgs();
const script = args[args.length - 1];
expect(args.slice(-3, -1)).toEqual(['/bin/sh', '-c']);
expect(script).toBe(`echo ${LINUX_HELD_MARKER}; exec cat`);
expect(script).not.toMatch(/sleep/);
});
it('ties caffeinate to the server pid', () => {
expect(macCaffeinateArgs(4242)).toEqual(['-i', '-s', '-w', '4242']);
});
});
describe('classifyInhibitFailure', () => {
it('reads a polkit refusal as denied', () => {
expect(classifyInhibitFailure('Failed to inhibit: Access denied\n').state).toBe('denied');
expect(classifyInhibitFailure('Interactive authentication required.').state).toBe('denied');
});
it('reads a missing logind as unavailable', () => {
expect(classifyInhibitFailure('Failed to connect to bus: No such file or directory').state).toBe('unavailable');
});
it('keeps the first line of anything else', () => {
const r = classifyInhibitFailure('something odd\nmore');
expect(r).toEqual({ state: 'failed', detail: 'something odd' });
expect(classifyInhibitFailure('').detail).toBe('the inhibitor exited');
});
});
+4
View File
@@ -213,6 +213,8 @@ export const bySelector = new Map<string, FakeEl>();
export const body = new FakeEl();
/** The context's `fetch`; a test sets what it answers. */
export const fetchSpy = vi.fn(async (..._args: unknown[]) => ({ ok: true, json: async () => ({}) }));
/** What `document.elementFromPoint` answers (the gesture overlay's hit test); a test sets it. */
export const pointHits: { at: ((x: number, y: number) => FakeEl | null) | null } = { at: null };
/** `document.addEventListener`, so a test can find a listener the app installed. */
export const documentAddEventListener = vi.fn();
export const documentRemoveEventListener = vi.fn();
@@ -280,6 +282,7 @@ const context = vm.createContext({
return focusedEl;
},
getElementById: (id: string) => (id === 'tileGrid' ? section : (bySelector.get(`#${id}`) ?? null)),
elementFromPoint: (x: number, y: number) => pointHits.at?.(x, y) ?? null,
body,
querySelector: (sel: string) =>
bySelector.get(sel) ?? (sel === '.main' ? main : sel === '.terminal-wrap' ? wrap : null),
@@ -389,4 +392,5 @@ export function resetGridHarness() {
main.appendChild(section);
bySelector.clear();
body.children = [];
pointHits.at = null;
}
@@ -1,132 +0,0 @@
/**
* @fileoverview Keep-awake wiring in system-routes: PUT /api/settings reconciles the sleep
* lock from the MERGED settings (a partial body never reads as "turn it off"), a
* non-admin's value is dropped in multi-user mode (it is machine state), and
* GET /api/system/keep-awake returns the manager's status in the standard envelope.
*
* Uses app.inject(); the manager is mocked, so no real lock is taken. Port: N/A.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerSystemRoutes } from '../../src/web/routes/system-routes.js';
const { store, keepAwake } = vi.hoisted(() => ({
store: { settings: {} as Record<string, unknown>, written: [] as Record<string, unknown>[] },
keepAwake: {
apply: vi.fn(async () => {}),
getStatus: vi.fn(() => ({
enabled: true,
acOnly: true,
platform: 'linux',
state: 'active',
onAc: true,
lidHelper: null,
detail: null,
})),
stop: vi.fn(async () => {}),
},
}));
vi.mock('node:fs/promises', () => ({
default: {
readFile: vi.fn(async () => JSON.stringify(store.settings)),
writeFile: vi.fn(async (_path: string, data: string) => {
store.written.push(JSON.parse(data));
}),
},
}));
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return { ...actual, existsSync: vi.fn(() => true), mkdirSync: vi.fn(), readdirSync: vi.fn(() => []) };
});
vi.mock('../../src/keep-awake-manager.js', () => ({ keepAwake }));
describe('keep-awake in system routes', () => {
let harness: RouteTestHarness;
beforeEach(() => {
store.settings = {};
store.written = [];
keepAwake.apply.mockClear();
delete process.env.CODEMAN_MULTIUSER;
});
afterEach(async () => {
delete process.env.CODEMAN_MULTIUSER;
await harness?.app.close();
});
it('a partial PUT keeps the persisted keep-awake on', async () => {
harness = await createRouteTestHarness(registerSystemRoutes);
store.settings = { keepAwakeEnabled: true, keepAwakeAcOnly: false };
const res = await harness.app.inject({ method: 'PUT', url: '/api/settings', payload: { showMonitor: true } });
expect(res.statusCode).toBe(200);
expect(keepAwake.apply).toHaveBeenCalledWith({ enabled: true, acOnly: false });
});
it('an explicit PUT turns it on and persists it', async () => {
harness = await createRouteTestHarness(registerSystemRoutes);
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
payload: { keepAwakeEnabled: true },
});
expect(res.statusCode).toBe(200);
expect(store.written.at(-1)).toMatchObject({ keepAwakeEnabled: true });
expect(keepAwake.apply).toHaveBeenCalledWith({ enabled: true, acOnly: true });
});
it('rejects a non-boolean value', async () => {
harness = await createRouteTestHarness(registerSystemRoutes);
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
payload: { keepAwakeEnabled: 'yes' },
});
expect(res.statusCode).toBe(400);
expect(keepAwake.apply).not.toHaveBeenCalled();
});
it("drops a non-admin's value in multi-user mode, without failing the rest of the save", async () => {
process.env.CODEMAN_MULTIUSER = '1';
harness = await createRouteTestHarness(registerSystemRoutes, {
authUser: { username: 'bob', role: 'user' },
});
store.settings = { keepAwakeEnabled: false };
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
payload: { keepAwakeEnabled: true, keepAwakeAcOnly: false, showMonitor: true },
});
expect(res.statusCode).toBe(200);
const written = store.written.at(-1)!;
expect(written.keepAwakeEnabled).toBe(false);
expect('keepAwakeAcOnly' in written).toBe(false);
expect(written.showMonitor).toBe(true);
expect(keepAwake.apply).toHaveBeenCalledWith({ enabled: false, acOnly: true });
});
it('an admin can change it in multi-user mode', async () => {
process.env.CODEMAN_MULTIUSER = '1';
harness = await createRouteTestHarness(registerSystemRoutes, {
authUser: { username: 'root', role: 'admin' },
});
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
payload: { keepAwakeEnabled: true },
});
expect(res.statusCode).toBe(200);
expect(keepAwake.apply).toHaveBeenCalledWith({ enabled: true, acOnly: true });
});
it('GET /api/system/keep-awake returns the status envelope', async () => {
harness = await createRouteTestHarness(registerSystemRoutes);
const res = await harness.app.inject({ method: 'GET', url: '/api/system/keep-awake' });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ success: true, data: keepAwake.getStatus() });
});
});
+564
View File
@@ -0,0 +1,564 @@
/**
* @fileoverview Detach Tiles (per-device `tileDetachEnabled`, default OFF): a
* tile leaves the grid for a window of its own, and comes back into any
* Codeman window's grid, by dragging.
*
* - OFF (the default) changes nothing: a lone tile's header does not drag, a
* header let go outside the window opens nothing, and a tile dragged from
* another window is not taken.
* - A header let go OUTSIDE the window (dragend with no drop, its point off the
* viewport, or the page's own record of the pointer leaving when the
* browser reports no point) opens the session as a pop-out after a short
* settle, the tile's size, its header under the drop point. Let go inside
* on nothing, or taken by a drop target (`dropEffect: 'move'`), nothing
* opens. A lone or zoomed tile drags too (out only).
* - Another window docking the tile ('tile-adopted' on the window channel)
* takes it out of THIS grid only when this window dragged it (still
* settling, or ended a moment ago); the keyboard stays put, and the last
* tile leaves for the welcome screen, never for that session.
* - A tile from another window dropped on a tile or an empty cell docks there
* through the target's own drop and says so; a popped-out session is taken
* back first and its window asked to close; its stale 'detached' answers
* are ignored for a moment. Unknown ids dock nowhere.
* - The pop-out window: its features carry the placement (the default stays
* 960x680, unplaced); a released pop-out stops answering roll-calls.
* - The gesture overlay's helpers ask the same rules: what is under a point,
* what a drop there would do, and the pop-out at a hand's point.
* - A tile's ⋯ menu offers "Open in a new window" with Detach Tiles on (the
* keyboard's way to the drag), placed over the tile.
* - The setting is per-device: a display key, stripped from the settings PUT,
* absent from the .strict() schema, OFF unless switched on, its row shown on
* desktop only.
*
* Real code via the shared vm harness (test/mocks/tile-grid-vm.ts). Port: N/A.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
FakeEl,
FakeTile,
documentAddEventListener,
documentRemoveEventListener,
makeGridApp,
pointHits,
resetGridHarness,
section,
type GridApp,
tileEl,
windowStub,
} from './mocks/tile-grid-vm.js';
const TILE_TYPE = 'application/x-codeman-tile';
const FOUR = ['s-a', 's-b', 's-c', 's-d'];
const THREE = ['s-a', 's-b', 's-c'];
// Five tiles lay out 3x2 here: one empty cell, the last.
const FIVE = ['s-a', 's-b', 's-c', 's-d', 's-e'];
const headerOf = (id: string) => tileEl(id).children[0];
const slots = () => section.children.filter((el) => el.className.split(' ').includes('tile-slot'));
const settle = () => new Promise((r) => setTimeout(r, 200));
function dragEvent(extra: Record<string, unknown> = {}, transfer: Record<string, unknown> = {}) {
return {
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
clientX: 100,
clientY: 10,
...extra,
dataTransfer: { effectAllowed: '', dropEffect: 'none', setData: vi.fn(), ...transfer },
};
}
/** A drag from another window: none of this page's own, the tile type carried, its id readable on drop. */
function foreign(id: string) {
return dragEvent({}, { types: [TILE_TYPE], getData: (t: string) => (t === TILE_TYPE ? id : '') });
}
function openGrid(ids: string[], { detach = true, focusedId = ids[0] } = {}): GridApp {
const app = makeGridApp(ids);
app.loadAppSettingsFromStorage = () => ({ tileDetachEnabled: detach });
app._postWindowMessage = vi.fn();
app._wsTabNonce = 'c-here';
app.openTileGrid(ids, { focusedId });
return app;
}
/** Press the header and start its native drag (a press at (40, 10) inside the tile). */
function startDrag(id: string) {
headerOf(id).dispatch('pointerdown', { target: headerOf(id), button: 0 });
const start = dragEvent({ clientX: 40, clientY: 10 });
headerOf(id).dispatch('dragstart', start);
return start;
}
const endDrag = (id: string, extra: Record<string, unknown>, effect = 'none') =>
headerOf(id).dispatch('dragend', dragEvent(extra, { dropEffect: effect }));
/** The page-level drag listeners the tear-off installed (capture phase). */
const docListener = (type: string) =>
documentAddEventListener.mock.calls.filter((c) => c[0] === type).at(-1)?.[1] as (e: unknown) => void;
beforeEach(() => {
resetGridHarness();
documentAddEventListener.mockClear();
});
afterEach(() => {
delete windowStub.screenX;
delete windowStub.screenY;
delete windowStub.outerHeight;
delete windowStub.screen;
delete windowStub.open;
});
describe('Detach Tiles OFF (the default) changes nothing', () => {
it('a lone tile does not drag, and a header let go outside the window opens nothing', async () => {
const app = openGrid(['s-a'], { detach: false });
app.detachSession = vi.fn();
expect(headerOf('s-a').getAttribute('draggable')).toBe('false');
expect(startDrag('s-a').preventDefault).toHaveBeenCalled();
const four = openGrid(FOUR, { detach: false });
four.detachSession = vi.fn();
startDrag('s-b');
endDrag('s-b', { clientX: -50, clientY: 300, screenX: 20, screenY: 400 });
await settle();
expect(four.detachSession).not.toHaveBeenCalled();
expect(four._tileGrid.ids).toEqual(FOUR);
});
it('a tile dragged from another window is not taken', () => {
const app = openGrid(THREE, { detach: false });
const over = foreign('s-other');
tileEl('s-b').dispatch('dragover', over);
expect(over.preventDefault).not.toHaveBeenCalled();
tileEl('s-b').dispatch('drop', foreign('s-other'));
expect(app._tileGrid.ids).toEqual(THREE);
expect(app._postWindowMessage).not.toHaveBeenCalled();
});
it('the header tooltip keeps its old wording', () => {
openGrid(THREE, { detach: false });
expect(headerOf('s-a').title).toContain('Drag to move the tile');
expect(headerOf('s-a').title).not.toContain('window');
});
});
describe('dragging a header out of the window', () => {
it('opens the session as a pop-out after a short settle, the tile size, its header under the drop point', async () => {
const app = openGrid(FOUR);
app.detachSession = vi.fn();
startDrag('s-b');
endDrag('s-b', { clientX: -50, clientY: 300, screenX: 900, screenY: 500 });
expect(app.detachSession).not.toHaveBeenCalled();
await settle();
expect(app.detachSession).toHaveBeenCalledTimes(1);
const [id, placement] = app.detachSession.mock.calls[0];
expect(id).toBe('s-b');
// The harness's tiles measure 2400x1200; the press was at (40, 10).
expect(placement).toEqual({ width: 2400, height: 1200, left: 860, top: 430 });
});
it('a lone tile, or a zoomed one, drags out too (no target inside takes it)', async () => {
const app = openGrid(['s-a']);
app.detachSession = vi.fn();
expect(headerOf('s-a').getAttribute('draggable')).toBe('true');
expect(headerOf('s-a').title).toContain('Drag out of the window to open the tile on its own');
expect(startDrag('s-a').preventDefault).not.toHaveBeenCalled();
endDrag('s-a', { clientX: 5000, clientY: 300, screenX: 5000, screenY: 300 });
await settle();
expect(app.detachSession).toHaveBeenCalledWith('s-a', expect.any(Object));
const zoomed = openGrid(FOUR);
zoomed.zoomTile('s-c');
expect(headerOf('s-c').getAttribute('draggable')).toBe('true');
});
it('let go inside the window on nothing, or taken by a drop target: nothing opens', async () => {
const app = openGrid(FOUR);
app.detachSession = vi.fn();
startDrag('s-b');
endDrag('s-b', { clientX: 300, clientY: 300, screenX: 300, screenY: 400 });
startDrag('s-c');
endDrag('s-c', { clientX: -50, clientY: 300, screenX: 20, screenY: 400 }, 'move');
await settle();
expect(app.detachSession).not.toHaveBeenCalled();
expect(app._tileGrid.ids).toEqual(FOUR);
});
it('no point reported: the page record of the pointer leaving at the edge decides, a dragover inside undoes it', async () => {
const app = openGrid(FOUR);
app.detachSession = vi.fn();
startDrag('s-b');
docListener('dragleave')({ relatedTarget: null, clientX: 0, clientY: 500 });
endDrag('s-b', { clientX: 0, clientY: 0, screenX: 0, screenY: 0 });
await settle();
expect(app.detachSession).toHaveBeenCalledTimes(1);
// No screen point: placed over the tile instead (no window position known here: size only).
expect(app.detachSession.mock.calls[0][1]).toEqual({ width: 2400, height: 1200 });
app.detachSession.mockClear();
startDrag('s-c');
docListener('dragleave')({ relatedTarget: null, clientX: 0, clientY: 500 });
docListener('dragover')({});
endDrag('s-c', { clientX: 0, clientY: 0, screenX: 0, screenY: 0 });
await settle();
expect(app.detachSession).not.toHaveBeenCalled();
});
it('the page drag listeners go when the drag ends, and when the grid closes mid-drag', () => {
const app = openGrid(FOUR);
startDrag('s-b');
const over = docListener('dragover');
const leave = docListener('dragleave');
documentRemoveEventListener.mockClear();
endDrag('s-b', { clientX: 300, clientY: 300 });
expect(documentRemoveEventListener).toHaveBeenCalledWith('dragover', over, true);
expect(documentRemoveEventListener).toHaveBeenCalledWith('dragleave', leave, true);
startDrag('s-c');
const over2 = docListener('dragover');
documentRemoveEventListener.mockClear();
app.closeTileGrid({ reselect: false });
expect(documentRemoveEventListener).toHaveBeenCalledWith('dragover', over2, true);
expect(app._tileTearOff).toBeNull();
});
it('the real pop-out takes the tile out of the grid (as the tab pop-out does)', async () => {
const app = openGrid(FOUR);
const win = { closed: false, focus: vi.fn() };
windowStub.open = vi.fn(() => win);
app.detachedWindows = new Map();
app._detachWatchTimers = new Map();
app.hasHostWindows = () => false;
// No tab strip in this harness.
app.$ = () => null;
startDrag('s-b');
endDrag('s-b', { clientX: -50, clientY: 300, screenX: 900, screenY: 500 });
await settle();
expect(windowStub.open).toHaveBeenCalledWith(
'/session/s-b',
'codeman-session-s-b',
'width=2400,height=1200,left=860,top=430,menubar=no,toolbar=no,location=no,status=no'
);
expect(app.detachedSessions.has('s-b')).toBe(true);
expect(app._tileGrid.ids).toEqual(['s-a', 's-c', 's-d']);
});
});
describe('another window docking the tile this one dragged', () => {
it('a drop target in another window took it: the tile goes, the keyboard stays put', () => {
const app = openGrid(FOUR, { focusedId: 's-b' });
startDrag('s-b');
endDrag('s-b', { clientX: -50, clientY: 300 }, 'move');
const focusBefore = FakeTile.all.map((t) => t.terminal.focus.mock.calls.length);
app._onWindowMessage({ type: 'tile-adopted', id: 's-b', by: 'c-there' });
expect(app._tileGrid.ids).toEqual(['s-a', 's-c', 's-d']);
expect(app._tileGrid.focusedId).not.toBe('s-b');
expect(FakeTile.all.map((t) => t.terminal.focus.mock.calls.length)).toEqual(focusBefore);
});
it('a claim that arrives while the pop-out is settling cancels the pop-out', async () => {
const app = openGrid(FOUR);
app.detachSession = vi.fn();
startDrag('s-c');
endDrag('s-c', { clientX: -50, clientY: 300, screenX: 20, screenY: 400 });
app._onWindowMessage({ type: 'tile-adopted', id: 's-c', by: 'c-there' });
await settle();
expect(app.detachSession).not.toHaveBeenCalled();
expect(app._tileGrid.ids).toEqual(['s-a', 's-b', 's-d']);
});
it('the last tile leaves for the welcome screen, never for that session', () => {
const app = openGrid(['s-a']);
startDrag('s-a');
endDrag('s-a', { clientX: -50, clientY: 300 }, 'move');
app._onWindowMessage({ type: 'tile-adopted', id: 's-a', by: 'c-there' });
expect(app._tileGrid.open).toBe(false);
expect(app.activeSessionId).toBeNull();
expect(app.showWelcome).toHaveBeenCalled();
expect(app.terminal.clear).toHaveBeenCalled();
});
it('a claim for a tile this window did not drag, or one it dragged long ago, is ignored', () => {
const app = openGrid(FOUR);
app._onWindowMessage({ type: 'tile-adopted', id: 's-b', by: 'c-there' });
expect(app._tileGrid.ids).toEqual(FOUR);
startDrag('s-b');
endDrag('s-b', { clientX: 300, clientY: 300 }, 'move');
app._lastTileDrag.at -= 60_000;
app._onWindowMessage({ type: 'tile-adopted', id: 's-b', by: 'c-there' });
expect(app._tileGrid.ids).toEqual(FOUR);
});
it("this window's own claim (same nonce) is never acted on", () => {
const app = openGrid(FOUR);
startDrag('s-b');
endDrag('s-b', { clientX: 300, clientY: 300 }, 'move');
app._onWindowMessage({ type: 'tile-adopted', id: 's-b', by: 'c-here' });
expect(app._tileGrid.ids).toEqual(FOUR);
});
});
describe('a tile from another window dropped here', () => {
it('on a tile: it takes that tile’s place, focused, and every window hears it was docked', () => {
const app = openGrid(THREE);
const over = foreign('s-other');
tileEl('s-b').dispatch('dragover', over);
expect(over.preventDefault).toHaveBeenCalled();
expect(over.stopPropagation).toHaveBeenCalled();
expect(over.dataTransfer.dropEffect).toBe('move');
expect(tileEl('s-b').classList.contains('tile--drop-target')).toBe(true);
tileEl('s-b').dispatch('drop', foreign('s-other'));
expect(app._tileGrid.ids).toEqual(['s-a', 's-other', 's-c']);
expect(app._tileGrid.focusedId).toBe('s-other');
expect(app._postWindowMessage).toHaveBeenCalledWith({ type: 'tile-adopted', id: 's-other', by: 'c-here' });
expect(tileEl('s-other').classList.contains('tile--drop-target')).toBe(false);
});
it('on an empty cell: it joins there', () => {
const app = openGrid(FIVE);
expect(slots()).toHaveLength(1);
slots()[0].dispatch('drop', foreign('s-other'));
expect(app._tileGrid.cells).toEqual([...FIVE, 's-other']);
expect(app._postWindowMessage).toHaveBeenCalledWith({ type: 'tile-adopted', id: 's-other', by: 'c-here' });
});
it('a popped-out session is taken back first and its window asked to close; its stale answers are ignored', () => {
const app = openGrid(THREE);
app.detachedSessions.add('s-other');
app._redock = vi.fn((id: string) => app.detachedSessions.delete(id));
app._markDetached = vi.fn();
tileEl('s-c').dispatch('drop', foreign('s-other'));
expect(app._redock).toHaveBeenCalledWith('s-other');
expect(app._tileGrid.ids).toContain('s-other');
expect(app._postWindowMessage).toHaveBeenCalledWith({ type: 'close-request', id: 's-other' });
expect(app._postWindowMessage).toHaveBeenCalledWith({ type: 'tile-adopted', id: 's-other', by: 'c-here' });
// The closing pop-out answering a roll-call on its way out.
app._onWindowMessage({ type: 'detached', id: 's-other' });
expect(app._markDetached).not.toHaveBeenCalled();
expect(app._tileGrid.ids).toContain('s-other');
});
it('an id this page does not know docks nowhere', () => {
const app = openGrid(THREE);
tileEl('s-b').dispatch('drop', foreign('s-gone'));
tileEl('s-b').dispatch('drop', foreign(''));
expect(app._tileGrid.ids).toEqual(THREE);
expect(app._postWindowMessage).not.toHaveBeenCalled();
});
it("a drag of this page's own is never read as a foreign one", () => {
const app = openGrid(FOUR);
startDrag('s-a');
const over = foreign('s-other');
over.dataTransfer.types = [TILE_TYPE];
tileEl('s-d').dispatch('drop', over);
// The own drag wins: s-a and s-d trade places, nothing docks.
expect(app._tileGrid.ids).toEqual(['s-d', 's-b', 's-c', 's-a']);
expect(app._postWindowMessage).not.toHaveBeenCalled();
});
});
describe('the pop-out window', () => {
it('features: the placement when given, the old default otherwise', () => {
const app = makeGridApp();
expect(app._detachWindowFeatures(null)).toBe('width=960,height=680,menubar=no,toolbar=no,location=no,status=no');
expect(app._detachWindowFeatures({ width: 700.4, height: 500, left: -1200, top: 40 })).toBe(
'width=700,height=500,left=-1200,top=40,menubar=no,toolbar=no,location=no,status=no'
);
// A position needs both coordinates; non-numbers never reach the string.
expect(app._detachWindowFeatures({ left: 10, top: Number.NaN, width: 'x' })).toBe(
'width=960,height=680,menubar=no,toolbar=no,location=no,status=no'
);
});
it('from the ⋯ menu (no point): over the tile, at least the minimum size, within the screen', () => {
const app = openGrid(FOUR);
app.detachSession = vi.fn();
windowStub.screenX = 100;
windowStub.screenY = 50;
windowStub.outerHeight = 1300;
windowStub.screen = { availWidth: 1920, availHeight: 1080 };
app.detachTile('s-b');
expect(app.detachSession).toHaveBeenCalledWith('s-b', { width: 1920, height: 1080, left: 100, top: 90 });
});
it('never with Detach Tiles off, nor for a session that is not a tile', () => {
const off = openGrid(FOUR, { detach: false });
off.detachSession = vi.fn();
expect(off.detachTile('s-b')).toBe(false);
const on = openGrid(FOUR);
on.detachSession = vi.fn();
expect(on.detachTile('s-other')).toBe(false);
expect(off.detachSession).not.toHaveBeenCalled();
expect(on.detachSession).not.toHaveBeenCalled();
});
it('a released pop-out says so, then stops answering roll-calls', () => {
const app = makeGridApp();
app.isSoloWindow = true;
app.soloSessionId = 's-a';
app._postWindowMessage = vi.fn();
app._closeSoloWindow = vi.fn();
app._onWindowMessage({ type: 'roll-call' });
expect(app._postWindowMessage).toHaveBeenLastCalledWith({ type: 'detached', id: 's-a' });
app._onWindowMessage({ type: 'close-request', id: 's-a' });
expect(app._postWindowMessage).toHaveBeenLastCalledWith({ type: 'redocked', id: 's-a' });
expect(app._closeSoloWindow).toHaveBeenCalled();
app._postWindowMessage.mockClear();
app._onWindowMessage({ type: 'roll-call' });
expect(app._postWindowMessage).not.toHaveBeenCalled();
});
});
describe('the gesture overlay helpers', () => {
it('what is under a point: the tile, and whether a hand may pick it up', () => {
const app = openGrid(FOUR);
const inner = new FakeEl();
tileEl('s-c').children[1].appendChild(inner);
pointHits.at = () => inner;
expect(app.tileAtPoint(10, 10)).toBe('s-c');
expect(app.canGrabTile('s-c')).toBe(true);
pointHits.at = () => null;
expect(app.tileAtPoint(10, 10)).toBeNull();
// Alone with Detach Tiles off it can neither move nor leave.
const lone = openGrid(['s-a'], { detach: false });
expect(lone.canGrabTile('s-a')).toBe(false);
const loneOn = openGrid(['s-a']);
expect(loneOn.canGrabTile('s-a')).toBe(true);
});
it("what a drop there would do, by the mouse drag's rules, and doing it", () => {
const app = openGrid(FIVE);
pointHits.at = () => tileEl('s-c');
expect(app.tileDropTargetAt(1, 1, 's-a')).toEqual({ kind: 'tile', id: 's-c', el: tileEl('s-c') });
// Its own tile is no target; a popped-out or unknown session has none.
expect(app.tileDropTargetAt(1, 1, 's-c')).toBeNull();
app.detachedSessions.add('s-other');
expect(app.tileDropTargetAt(1, 1, 's-other')).toBeNull();
app.detachedSessions.delete('s-other');
expect(app.tileDropTargetAt(1, 1, 's-nope')).toBeNull();
expect(app.dropOnTileTarget('s-a', app.tileDropTargetAt(1, 1, 's-a'))).toBe(true);
expect(app._tileGrid.ids).toEqual(['s-c', 's-b', 's-a', 's-d', 's-e']);
pointHits.at = () => slots()[0];
const cell = app.tileDropTargetAt(1, 1, 's-other');
expect(cell).toEqual({ kind: 'cell', cell: 5, el: slots()[0] });
expect(app.dropOnTileTarget('s-other', cell)).toBe(true);
expect(app._tileGrid.cells).toEqual(['s-c', 's-b', 's-a', 's-d', 's-e', 's-other']);
});
it('a tiled session has no target while a tile is zoomed (moving is off)', () => {
const app = openGrid(FOUR);
app.zoomTile('s-a');
pointHits.at = () => tileEl('s-a');
expect(app.tileDropTargetAt(1, 1, 's-b')).toBeNull();
});
it('a hand let go outside the grid: the pop-out at that point, the page chrome counted', () => {
const app = openGrid(FOUR);
app.detachSession = vi.fn();
windowStub.screenX = 0;
windowStub.screenY = 0;
windowStub.outerHeight = 1300;
app.detachTileAtPoint('s-d', 500, 20, { offsetX: 100, offsetY: 10 });
expect(app.detachSession).toHaveBeenCalledWith('s-d', { width: 2400, height: 1200, left: 400, top: 50 });
});
it('whether a point is over the grid', () => {
const app = openGrid(FOUR);
expect(app.isOverTileGrid(10, 10)).toBe(true);
expect(app.isOverTileGrid(10, 5000)).toBe(false);
app.closeTileGrid({ reselect: false });
expect(app.isOverTileGrid(10, 10)).toBe(false);
});
});
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
const read = (f: string) => readFileSync(resolve(PUBLIC, f), 'utf8');
describe("a tile's ⋯ menu", () => {
function menuFor(sessionId: string, { tiled = true, detach = true, tabPopOut = false } = {}) {
const dom = new JSDOM('<!doctype html><html><body><button id="t">⋯</button></body></html>', {
runScripts: 'outside-only',
url: 'http://localhost/',
});
const ctx = dom.getInternalVMContext();
vm.runInContext('globalThis.CodemanApp = class CodemanApp {};', ctx);
vm.runInContext(read('tab-rail-resize.js'), ctx, { filename: 'tab-rail-resize.js' });
const App = (dom.window as unknown as { CodemanApp: { prototype: object } }).CodemanApp;
const app = Object.assign(Object.create(App.prototype), {
loadAppSettingsFromStorage: () => ({ showTabDetachButton: tabPopOut }),
tabDetachButtonEnabled: (s: { showTabDetachButton?: boolean }) => s.showTabDetachButton === true,
detachedSessions: new Set(),
_tileGrid: { has: () => tiled },
_tileDetachAllowed: () => detach,
detachTile: vi.fn(),
detachSession: vi.fn(),
openSessionOptions: vi.fn(),
requestCloseSession: vi.fn(),
}) as Record<string, ReturnType<typeof vi.fn> & ((...a: unknown[]) => unknown)>;
const doc = dom.window.document;
app.openTabRailActionMenu(
{ preventDefault() {}, stopPropagation() {}, currentTarget: doc.getElementById('t') },
sessionId
);
const items = [...doc.querySelectorAll('.tab-rail-action-menu [role="menuitem"]')] as HTMLButtonElement[];
return {
app,
labels: items.map((b) => b.textContent),
click: (label: string) => items.find((b) => b.textContent === label)!.click(),
};
}
it('with Detach Tiles on: "Open in a new window" pops the tile out, placed over it', () => {
const { app, labels, click } = menuFor('s-b');
expect(labels).toEqual(['Session options', 'Open in a new window', 'Close session']);
click('Open in a new window');
expect(app.detachTile).toHaveBeenCalledWith('s-b');
expect(app.detachSession).not.toHaveBeenCalled();
});
it('with it off: the menu is what it was (the tab pop-out setting still adds its own entry)', () => {
expect(menuFor('s-b', { detach: false }).labels).toEqual(['Session options', 'Close session']);
const tabbed = menuFor('s-b', { detach: false, tabPopOut: true });
expect(tabbed.labels).toEqual(['Session options', 'Open in a new window', 'Close session']);
tabbed.click('Open in a new window');
expect(tabbed.app.detachSession).toHaveBeenCalledWith('s-b');
// A tab (not a tile) with Detach Tiles on: only the tab setting decides.
expect(menuFor('s-x', { tiled: false }).labels).toEqual(['Session options', 'Close session']);
});
});
describe('tileDetachEnabled stays per-device and OFF by default', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8');
const index = read('index.html');
it('is a display key, stripped from the settings PUT, and absent from the .strict() schema', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
expect(settingsUi.slice(start, settingsUi.indexOf('])', start))).toContain("'tileDetachEnabled'");
expect(settingsUi).toContain('tileDetachEnabled: _tde,');
expect(schemas).not.toContain('tileDetachEnabled');
});
it('loads OFF unless switched on, saves from its switch, and its row shows on desktop only', () => {
expect(settingsUi).toContain(
"document.getElementById('appSettingsTileDetach').checked = settings.tileDetachEnabled === true;"
);
expect(settingsUi).toContain("tileDetachEnabled: document.getElementById('appSettingsTileDetach').checked,");
expect(settingsUi).toMatch(/tileDetachItem\.style\.display = MobileDetection\.getDeviceType\(\) === 'desktop'/);
expect(index).toMatch(/id="appSettingsTileDetachItem"[\s\S]*?<input type="checkbox" id="appSettingsTileDetach">/);
// Not `checked` in the markup: OFF is the default.
expect(index).not.toMatch(/id="appSettingsTileDetach" checked/);
});
it('a saved change repaints the tile handles (draggable, tooltip)', () => {
expect(settingsUi).toContain('this._renderTileChrome?.();');
});
});
+49
View File
@@ -217,6 +217,18 @@ async function exercise() {
}
pill = 'idle';
// Detach Tiles on: the drag hint says a tile also leaves the window, and
// a tile that cannot move (zoomed) says only that.
const settings = app.loadAppSettingsFromStorage;
app.loadAppSettingsFromStorage = () => ({ tileDetachEnabled: true });
app._renderTileChrome();
harvestAll(app, 'detach tiles');
app.zoomTile('s-1');
harvestAll(app, 'detach tiles, zoomed');
app.zoomTile('s-1');
app.loadAppSettingsFromStorage = settings;
app._renderTileChrome();
// Zoom and back.
app.zoomTile('s-1');
harvestAll(app, 'zoomed');
@@ -320,6 +332,8 @@ describe('every tile grid string the code puts on screen translates to zh-CN', (
'idle 3m\nDrag to move the tile',
'needs you 3m\nDrag to move the tile',
'exited 3m\nDrag to move the tile',
'idle 3m\nDrag to move the tile, or out of the window to open it on its own',
'idle 3m\nDrag out of the window to open the tile on its own',
'Not attached',
'Attach',
'Attaching…',
@@ -390,6 +404,30 @@ describe('every tile grid string the code puts on screen translates to zh-CN', (
expect(zh.api.t('idle\nDrag to move the tile')).toBe('空闲\n拖动可移动窗格');
expect(zh.api.t('Drag to move the tile')).toBe('拖动可移动窗格');
expect(en.api.t('idle\nDrag to move the tile')).toBe('idle\nDrag to move the tile');
// Detach Tiles' two hints ride the same pattern.
expect(zh.api.t('idle\nDrag out of the window to open the tile on its own')).toBe(
'空闲\n拖出窗口可在独立窗口中打开此窗格'
);
expect(zh.api.t('working <1m\nDrag to move the tile, or out of the window to open it on its own')).toBe(
'工作中 <1m\n拖动可移动窗格,拖出窗口可在独立窗口中打开'
);
});
it("Detach Tiles' pop-out strings: its title as a handle, and a pop-out that could not close", () => {
const strings = [
"Drag onto a Codeman window's tiles to dock this session there",
'Session moved',
'This session is back in a Codeman window. This one can be closed.',
'Close window',
];
// Not vacuous: each is a string the code really shows.
const code = read('app.js') + read('tile-grid.js');
expect(strings.filter((source) => !code.includes(source))).toEqual([]);
const bad = strings.filter((source) => {
const text = zh.api.t(source);
return text === source || leftover(text.replace(/Codeman/g, '')).length > 0 || en.api.t(source) !== source;
});
expect(bad).toEqual([]);
});
it('no UI label sits inside a skipped subtree (where the translator cannot reach it)', () => {
@@ -458,6 +496,17 @@ describe('the static markup through the real translator (JSDOM, zh-CN)', () => {
expect(tiles!.textContent).toContain('向左 / 右 / 上 / 下移动窗格');
expect(tiles!.textContent).toContain('拖动');
expect(tiles!.textContent).toContain('窗格的标题栏');
// Detach Tiles: a header dragged out of the window.
expect(tiles!.textContent).toContain('窗格的标题栏到窗口之外');
expect(tiles!.textContent).toContain('在独立窗口中打开窗格(分离窗格)');
});
it('the Detach Tiles row in App Settings: its name and what it does', () => {
const row = doc.getElementById('appSettingsTileDetachItem')!;
expect(row.querySelector('.set-row-label')!.textContent).toContain('分离窗格');
const desc = row.querySelector('.set-row-desc')!.textContent!;
expect(desc).toContain('独立窗口');
expect(leftover(desc.replace('Codeman', ''))).toEqual([]);
});
it('user text stays as typed: a session name and a group name that are also UI words', () => {