mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-26 15:39:33 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79f85415d8 |
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"aicodeman": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
**Closing a dialog you opened with the mouse puts the keyboard back in the terminal.** After App Settings or Session Options was opened with a click and closed again, nothing you typed reached the terminal until you clicked it: focus was left on the button you had clicked, and in Safari and the Mac app on nothing at all. A dialog now returns the keyboard to the field you were typing in when you clicked, which with the tile grid or the split open is the pane you were in. The Session Manager and the command palette follow the same rule. A dialog opened with the keyboard still returns to the control it was opened from.
|
||||||
@@ -158,7 +158,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
|||||||
|
|
||||||
**Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept)
|
**Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept)
|
||||||
|
|
||||||
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. ⚠️ **A kill never takes pid 0 or 1** (`isSignalablePid()`): the children of pid 0 are the whole machine, and tmux really answers 0 for an empty pane (`split-window ''`), which the pane list at server start records as `session.pid`; a close then signalled every process of the account. `killSession` signals only through `signalProcess()`, walks nothing for such a pid and leaves the close to `tmux kill-session`. Never call `process.kill` in tmux-manager.ts with a signal anywhere else, and never drive a real `killSession` from a script: stub `process.kill` in vitest (`test/kill-pid-guard.test.ts`). → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
|
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
|
||||||
|
|
||||||
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
|
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export const BROWSER_TEST_GLOBS = [
|
|||||||
'test/tab-layout-editing.browser.test.ts',
|
'test/tab-layout-editing.browser.test.ts',
|
||||||
'test/tab-rail-search.browser.test.ts',
|
'test/tab-rail-search.browser.test.ts',
|
||||||
'test/tab-focus.browser.test.ts',
|
'test/tab-focus.browser.test.ts',
|
||||||
|
'test/dialog-focus-return.browser.test.ts',
|
||||||
'test/session-sidebar-ux.browser.test.ts',
|
'test/session-sidebar-ux.browser.test.ts',
|
||||||
'test/header-divider.browser.test.ts',
|
'test/header-divider.browser.test.ts',
|
||||||
'test/tab-strip-corner.browser.test.ts',
|
'test/tab-strip-corner.browser.test.ts',
|
||||||
|
|||||||
@@ -1385,8 +1385,6 @@ Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: termina
|
|||||||
|
|
||||||
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
|
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
|
||||||
|
|
||||||
⚠️ **A kill never takes pid 0 or 1** (2026-11-25). A bound limits how MUCH a walk collects, not what it is a walk of: the children of pid 0 are init and everything below it, so `killSession()` with pid 0 signalled every process of the account, which took down every session, tmux itself and the systemd user manager (the machine did not reboot, and with the manager gone the server did not come back until the next login). It was reached by a script that drove the real `killSession()` on an empty pane lookup (`Number('')` is 0), but it needs no script. tmux answers `0` for `#{pane_pid}` of a pane without a process (`split-window ''`; measured on 3.4), `parsePaneRows()` keeps that row, and `reconcileSessions()` at server start writes it to `session.pid`, where the last pane of a session wins. The next close read 0 from tmux, fell back to the record, found 0 there too, and walked it. Reproduced on master with the signals logged instead of sent, inside a PID namespace: "Killing session codeman-feed1234 (PID 0)", "Found 15 child processes to kill". So 0 is an ordinary answer and means "nothing to signal". Three layers, all pinned in `test/kill-pid-guard.test.ts`: `killSession()` decides once (`isSignalablePid()`, an integer above 1) and otherwise leaves the close to `tmux kill-session`; `getChildPidsFresh()` walks nothing for such a root; and `signalProcess()`, the only place in `tmux-manager.ts` that sends a signal, refuses it for the group form as well (`kill(-1)` is every process, `kill(0)` is our own group). `collectDescendants()` itself stays a plain walk. A recorded 0 is deliberately left on the record rather than replaced by the older pid: that pid belongs to a process that may have exited since and been reused.
|
|
||||||
|
|
||||||
## Local packages and build artifacts
|
## Local packages and build artifacts
|
||||||
|
|
||||||
### xterm-zerolag-input is single-source
|
### xterm-zerolag-input is single-source
|
||||||
|
|||||||
@@ -32,23 +32,6 @@ export const PROC_WALK_MAX_DEPTH = 10;
|
|||||||
/** Hard ceiling on collected descendants. A backstop, not an expected limit. */
|
/** Hard ceiling on collected descendants. A backstop, not an expected limit. */
|
||||||
export const PROC_WALK_MAX_NODES = 500;
|
export const PROC_WALK_MAX_NODES = 500;
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether a session kill may signal `pid`, or walk the tree below it: a real process of
|
|
||||||
* the user's, so an integer above 1.
|
|
||||||
*
|
|
||||||
* On 2026-11-25 a kill that got pid 0 took down every process of the account: all of the
|
|
||||||
* user's sessions, tmux itself and the systemd user manager. The children of pid 0 are
|
|
||||||
* the whole machine, so the bounds above do not help (500 processes are most of one), and
|
|
||||||
* `kill(-1)` means every process one may signal while `kill(0)` means one's own group.
|
|
||||||
*
|
|
||||||
* tmux answers 0 for a pane with no process (`split-window ''`), and that 0 reaches the
|
|
||||||
* session record through the pane list read at server start. So 0 is an ordinary answer
|
|
||||||
* here, not a corrupt one, and it means "nothing to signal".
|
|
||||||
*/
|
|
||||||
export function isSignalablePid(pid: number | null | undefined): pid is number {
|
|
||||||
return typeof pid === 'number' && Number.isInteger(pid) && pid > 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WalkOptions {
|
export interface WalkOptions {
|
||||||
maxDepth?: number;
|
maxDepth?: number;
|
||||||
maxNodes?: number;
|
maxNodes?: number;
|
||||||
|
|||||||
+10
-30
@@ -22,7 +22,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { collectDescendants, descendantsInPaneGroup, isSignalablePid } from './proc-tree.js';
|
import { collectDescendants, descendantsInPaneGroup } from './proc-tree.js';
|
||||||
import {
|
import {
|
||||||
foreignViewSessionName,
|
foreignViewSessionName,
|
||||||
buildForeignDockerViewKillCommand,
|
buildForeignDockerViewKillCommand,
|
||||||
@@ -3148,8 +3148,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
* its process-group and tmux fallbacks.
|
* its process-group and tmux fallbacks.
|
||||||
*/
|
*/
|
||||||
private async getChildPidsFresh(pid: number): Promise<number[]> {
|
private async getChildPidsFresh(pid: number): Promise<number[]> {
|
||||||
// The children of pid 0 or 1 are the whole machine (see isSignalablePid).
|
|
||||||
if (!isSignalablePid(pid)) return [];
|
|
||||||
let byParent: ReadonlyMap<number, readonly number[]>;
|
let byParent: ReadonlyMap<number, readonly number[]>;
|
||||||
try {
|
try {
|
||||||
byParent = await Promise.race([
|
byParent = await Promise.race([
|
||||||
@@ -3207,19 +3205,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The one way this class signals a process. Refuses what is not a session's process
|
|
||||||
* (see {@link isSignalablePid}); a negative `pid` is the process group, so it is judged
|
|
||||||
* by its absolute value and `-1` (everything) and `-0` (our own group) are refused too.
|
|
||||||
*/
|
|
||||||
private signalProcess(pid: number, signal: 'SIGTERM' | 'SIGKILL'): void {
|
|
||||||
if (!isSignalablePid(Math.abs(pid))) {
|
|
||||||
console.error(`[TmuxManager] Refusing to send ${signal} to pid ${pid}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.kill(pid, signal);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if a process is still alive. Signal decisions only: an unreaped zombie
|
// Check if a process is still alive. Signal decisions only: an unreaped zombie
|
||||||
// counts here, so its process group still gets the SIGKILL below. The WAITS use
|
// counts here, so its process group still gets the SIGKILL below. The WAITS use
|
||||||
// waitForProcessesExit(), which counts a zombie as exited.
|
// waitForProcessesExit(), which counts a zombie as exited.
|
||||||
@@ -3363,15 +3348,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
|
|
||||||
// Get current PID (may have changed)
|
// Get current PID (may have changed)
|
||||||
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
|
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
|
||||||
// An empty pane has no process: tmux says 0, and so does the record once a server
|
|
||||||
// start has read it. Nothing is signalled then, and only tmux is asked to close it.
|
|
||||||
const hasProcess = isSignalablePid(currentPid);
|
|
||||||
|
|
||||||
console.log(
|
console.log(`[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`);
|
||||||
`[TmuxManager] Killing session ${session.muxName} (${hasProcess ? `PID ${currentPid}` : `no process, pane pid ${currentPid}`})`
|
|
||||||
);
|
|
||||||
|
|
||||||
const allPids: number[] = hasProcess ? [currentPid] : [];
|
const allPids: number[] = [currentPid];
|
||||||
|
|
||||||
// Strategy 1: Kill all child processes recursively (but never a shared daemon the
|
// Strategy 1: Kill all child processes recursively (but never a shared daemon the
|
||||||
// pane's CLI started for every session of that CLI: see killableDescendants)
|
// pane's CLI started for every session of that CLI: see killableDescendants)
|
||||||
@@ -3383,7 +3363,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
for (const childPid of [...childPids].reverse()) {
|
for (const childPid of [...childPids].reverse()) {
|
||||||
if (this.isProcessAlive(childPid)) {
|
if (this.isProcessAlive(childPid)) {
|
||||||
try {
|
try {
|
||||||
this.signalProcess(childPid, 'SIGTERM');
|
process.kill(childPid, 'SIGTERM');
|
||||||
} catch {
|
} catch {
|
||||||
// Process may already be dead
|
// Process may already be dead
|
||||||
}
|
}
|
||||||
@@ -3398,7 +3378,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
for (const childPid of childPids) {
|
for (const childPid of childPids) {
|
||||||
if (this.isProcessAlive(childPid)) {
|
if (this.isProcessAlive(childPid)) {
|
||||||
try {
|
try {
|
||||||
this.signalProcess(childPid, 'SIGKILL');
|
process.kill(childPid, 'SIGKILL');
|
||||||
} catch {
|
} catch {
|
||||||
// Process already terminated
|
// Process already terminated
|
||||||
}
|
}
|
||||||
@@ -3407,12 +3387,12 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Strategy 2: Kill the entire process group
|
// Strategy 2: Kill the entire process group
|
||||||
if (hasProcess && this.isProcessAlive(currentPid)) {
|
if (this.isProcessAlive(currentPid)) {
|
||||||
try {
|
try {
|
||||||
this.signalProcess(-currentPid, 'SIGTERM');
|
process.kill(-currentPid, 'SIGTERM');
|
||||||
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
|
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
|
||||||
if (this.isProcessAlive(currentPid)) {
|
if (this.isProcessAlive(currentPid)) {
|
||||||
this.signalProcess(-currentPid, 'SIGKILL');
|
process.kill(-currentPid, 'SIGKILL');
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Process group may not exist or already terminated
|
// Process group may not exist or already terminated
|
||||||
@@ -3459,9 +3439,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Strategy 4: Direct kill by PID as final fallback
|
// Strategy 4: Direct kill by PID as final fallback
|
||||||
if (hasProcess && this.isProcessAlive(currentPid)) {
|
if (this.isProcessAlive(currentPid)) {
|
||||||
try {
|
try {
|
||||||
this.signalProcess(currentPid, 'SIGKILL');
|
process.kill(currentPid, 'SIGKILL');
|
||||||
} catch {
|
} catch {
|
||||||
// Already dead
|
// Already dead
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
|||||||
|
|
||||||
**Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry)
|
**Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry)
|
||||||
|
|
||||||
|
**Where a dialog hands the keyboard back to** (`FocusTrap.focusToReturn()`, keyboard-accessory.js): a dialog that saves focus on open asks this, never `document.activeElement`. By the time a dialog opens, the mouse press that opened it has already moved focus (onto the pressed control in Chromium and Firefox, onto `<body>` in WebKit on macOS, where a button takes no focus from the mouse), and restoring that left the keyboard out of the terminal until it was clicked. The answer is the typing field (textarea, text-like input, editable region) that had focus at `pointerdown`, whenever focus now sits on the pressed control or on `<body>`. ⚠️ `pointerdown`, never `mousedown` or `click`: moving focus is `mousedown`'s default action, so only the earlier event still sees what had the keyboard. ⚠️ One press, from a typing field, by mouse: the field of an earlier press is not carried over (it can be behind a dialog opened since), a press that began on a button (a dialog opened inside a dialog) still returns to the pressed control, any key but a held modifier forgets the press (a keyboard user gets the control back), and a finger or pen records nothing (a focused field there means the on-screen keyboard). The one press that inherits a field is a press on an item inside `[role="menu"]`, from the press that opened the menu (a tile's menu button, then "Session options"); a menu that hands focus back to its trigger before running the item is not covered. ⚠️ Asking spends the press, so nothing pressed inside the opening dialog can hand the keyboard to a field behind it; call it once, when the dialog opens. Callers: `FocusTrap.activate()` (App Settings, Session Options, Help, Kill All, the phone composer) and `_rememberOverlayFocus()` (command palette, Session Manager); the local model window places its own focus. A dialog that never handed focus back (most of the small confirm dialogs) is not changed by this. Tests: `test/dialog-focus-return.test.ts`, `test/dialog-focus-return.browser.test.ts` (real Chromium, not in the gate).
|
||||||
|
|
||||||
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
||||||
|
|
||||||
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
|
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
|
||||||
|
|||||||
@@ -27,6 +27,8 @@
|
|||||||
*
|
*
|
||||||
* - FocusTrap (class) — Traps Tab/Shift+Tab keyboard focus within a modal element.
|
* - FocusTrap (class) — Traps Tab/Shift+Tab keyboard focus within a modal element.
|
||||||
* Saves and restores previously focused element on deactivate. Used by the modal dialogs.
|
* Saves and restores previously focused element on deactivate. Used by the modal dialogs.
|
||||||
|
* A dialog opened by a mouse press goes back to the field the user was typing in when
|
||||||
|
* the press began (FocusTrap.focusToReturn), not to the pressed control.
|
||||||
*
|
*
|
||||||
* @globals {object} KeyboardAccessoryBar
|
* @globals {object} KeyboardAccessoryBar
|
||||||
* @globals {object} PathPicker
|
* @globals {object} PathPicker
|
||||||
@@ -1846,6 +1848,13 @@ const KeyboardAccessoryBar = {
|
|||||||
/**
|
/**
|
||||||
* FocusTrap - Traps keyboard focus within an element (typically a modal).
|
* FocusTrap - Traps keyboard focus within an element (typically a modal).
|
||||||
* Saves the previously focused element and restores focus when deactivated.
|
* Saves the previously focused element and restores focus when deactivated.
|
||||||
|
*
|
||||||
|
* What it saves is {@link FocusTrap.focusToReturn}, not `document.activeElement`.
|
||||||
|
* By the time a dialog opens, the mouse press that opened it has already moved
|
||||||
|
* focus: in Chromium and Firefox the pressed control took it, and in WebKit on
|
||||||
|
* macOS (Safari, the Mac app) a button takes no focus from the mouse, so the
|
||||||
|
* press clears focus to `<body>`. Handing either one back left the keyboard out
|
||||||
|
* of the terminal the user was typing in until they clicked it again.
|
||||||
*/
|
*/
|
||||||
class FocusTrap {
|
class FocusTrap {
|
||||||
constructor(element) {
|
constructor(element) {
|
||||||
@@ -1854,8 +1863,96 @@ class FocusTrap {
|
|||||||
this.boundHandleKeydown = this.handleKeydown.bind(this);
|
this.boundHandleKeydown = this.handleKeydown.bind(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The element a dialog that is about to open should hand the keyboard back to
|
||||||
|
* when it closes.
|
||||||
|
*
|
||||||
|
* That is `document.activeElement`, with one exception: a dialog opened by a
|
||||||
|
* mouse press while the user was typing in a field (a terminal's textarea, the
|
||||||
|
* CJK field, a search box). The field is the answer when that press is the
|
||||||
|
* only reason focus is somewhere else now, which is the case when focus sits
|
||||||
|
* on the pressed control or on nothing at all.
|
||||||
|
*
|
||||||
|
* ⚠️ One press, and only from a typing field. A press made from a button (a
|
||||||
|
* dialog opened from inside another dialog) still returns to the pressed
|
||||||
|
* control, and the field of an earlier press is not carried over: it can be
|
||||||
|
* behind a dialog that has opened since. The one exception is a press on a
|
||||||
|
* menu item, see {@link FocusTrap._notePress}. A control reached with the
|
||||||
|
* keyboard keeps the usual pattern too, because any key forgets the press.
|
||||||
|
*
|
||||||
|
* ⚠️ Asking spends the press. Whatever is pressed inside the dialog that is
|
||||||
|
* opening starts with nothing remembered, so nothing in it can hand the
|
||||||
|
* keyboard to a field behind it.
|
||||||
|
*/
|
||||||
|
static focusToReturn() {
|
||||||
|
const active = document.activeElement || null;
|
||||||
|
const press = FocusTrap._press;
|
||||||
|
FocusTrap._press = null;
|
||||||
|
if (!press || !press.field || press.field === active || press.field.isConnected === false) return active;
|
||||||
|
const moved =
|
||||||
|
!active ||
|
||||||
|
active === document.body ||
|
||||||
|
active === press.target ||
|
||||||
|
(typeof active.contains === 'function' && active.contains(press.target));
|
||||||
|
return moved ? press.field : active;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True for an element text is typed into: a textarea, a text-like input, an editable region. */
|
||||||
|
static isTypingField(el) {
|
||||||
|
if (!el || el === document.body) return false;
|
||||||
|
const tag = String(el.tagName || '').toUpperCase();
|
||||||
|
if (tag === 'TEXTAREA') return true;
|
||||||
|
if (tag === 'INPUT') return !FocusTrap.NON_TEXT_INPUT_TYPES.includes(String(el.type || 'text').toLowerCase());
|
||||||
|
return el.isContentEditable === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remember what a mouse press began on and which typing field had the keyboard.
|
||||||
|
*
|
||||||
|
* ⚠️ `pointerdown`, not `mousedown` or `click`: moving focus is the default
|
||||||
|
* action of `mousedown`, which comes after it, so `activeElement` is still the
|
||||||
|
* element that had the keyboard before the press.
|
||||||
|
*
|
||||||
|
* ⚠️ A finger or a pen forgets the press and records nothing: on a touch device
|
||||||
|
* a focused field means the on-screen keyboard, and handing focus back to it
|
||||||
|
* would raise the keyboard when a dialog closes.
|
||||||
|
*
|
||||||
|
* ⚠️ A press on an item of a menu (`[role="menu"]`) keeps the field of the
|
||||||
|
* press before it, the one that opened the menu: a tile's menu button and then
|
||||||
|
* "Session options" are two presses and one way into a dialog. No other press
|
||||||
|
* inherits a field.
|
||||||
|
*/
|
||||||
|
static _notePress(e) {
|
||||||
|
if (!e || e.pointerType !== 'mouse') {
|
||||||
|
FocusTrap._press = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const active = document.activeElement;
|
||||||
|
const target = e.target || null;
|
||||||
|
let field = FocusTrap.isTypingField(active) ? active : null;
|
||||||
|
if (!field && FocusTrap._press && typeof target?.closest === 'function' && target.closest('[role="menu"]')) {
|
||||||
|
field = FocusTrap._press.field;
|
||||||
|
}
|
||||||
|
FocusTrap._press = { target, field };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Any key but a modifier held for the click (Shift+click) ends the press's say. */
|
||||||
|
static _forgetPress(e) {
|
||||||
|
if (e && FocusTrap.MODIFIER_KEYS.includes(e.key)) return;
|
||||||
|
FocusTrap._press = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Install the two document listeners behind {@link FocusTrap.focusToReturn}, once per page. */
|
||||||
|
static watchPresses() {
|
||||||
|
if (FocusTrap._watching) return;
|
||||||
|
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return;
|
||||||
|
FocusTrap._watching = true;
|
||||||
|
document.addEventListener('pointerdown', FocusTrap._notePress, true);
|
||||||
|
document.addEventListener('keydown', FocusTrap._forgetPress, true);
|
||||||
|
}
|
||||||
|
|
||||||
activate() {
|
activate() {
|
||||||
this.previouslyFocused = document.activeElement;
|
this.previouslyFocused = FocusTrap.focusToReturn();
|
||||||
this.element.addEventListener('keydown', this.boundHandleKeydown);
|
this.element.addEventListener('keydown', this.boundHandleKeydown);
|
||||||
|
|
||||||
// Focus first focusable element after a brief delay (for CSS transitions)
|
// Focus first focusable element after a brief delay (for CSS transitions)
|
||||||
@@ -1907,3 +2004,11 @@ class FocusTrap {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The last mouse press, `{ target, field }`, or null. See {@link FocusTrap._notePress}. */
|
||||||
|
FocusTrap._press = null;
|
||||||
|
FocusTrap._watching = false;
|
||||||
|
/** `<input>` types nobody types text into; every other type counts as a typing field. */
|
||||||
|
FocusTrap.NON_TEXT_INPUT_TYPES = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'];
|
||||||
|
FocusTrap.MODIFIER_KEYS = ['Shift', 'Control', 'Alt', 'Meta'];
|
||||||
|
FocusTrap.watchPresses();
|
||||||
@@ -376,7 +376,14 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
* for, typing a filter the moment it opens.
|
* for, typing a filter the moment it opens.
|
||||||
*/
|
*/
|
||||||
_rememberOverlayFocus(key) {
|
_rememberOverlayFocus(key) {
|
||||||
this[key] = (typeof document !== 'undefined' && document.activeElement) || null;
|
if (typeof document === 'undefined') {
|
||||||
|
this[key] = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The same answer a FocusTrap dialog saves (keyboard-accessory.js): an overlay
|
||||||
|
// opened by a mouse press goes back to the field the user was typing in, not
|
||||||
|
// to the pressed button.
|
||||||
|
this[key] = (typeof FocusTrap === 'function' ? FocusTrap.focusToReturn() : document.activeElement) || null;
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Real-Chromium coverage for where a dialog hands the keyboard
|
||||||
|
* back to (`FocusTrap.focusToReturn`, keyboard-accessory.js).
|
||||||
|
*
|
||||||
|
* What the vm test in `test/dialog-focus-return.test.ts` cannot answer is the
|
||||||
|
* order a browser does things in: the rule reads `document.activeElement` in a
|
||||||
|
* `pointerdown` listener and relies on the engine moving focus only afterwards,
|
||||||
|
* as the default action of `mousedown`. Here a real mouse presses real controls
|
||||||
|
* and a real keyboard types, on a page that holds the shipping
|
||||||
|
* keyboard-accessory.js, a textarea standing in for the terminal's own, and a
|
||||||
|
* dialog built on `FocusTrap` the way App Settings and Session Options are.
|
||||||
|
*
|
||||||
|
* Four ways into the dialog: a button (Chromium gives it focus on a press), an
|
||||||
|
* element that cannot take focus (the press clears focus to `<body>`, which is
|
||||||
|
* what WebKit on macOS does for a button), a focusable element pressed on an
|
||||||
|
* icon inside it (a tab's gear), and an item of a menu opened by a press before
|
||||||
|
* it (a tile's menu button, then "Session options").
|
||||||
|
*
|
||||||
|
* Port: none (page.route on a fake origin, no server).
|
||||||
|
*/
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
|
||||||
|
|
||||||
|
const publicDir = resolve(import.meta.dirname, '../src/web/public');
|
||||||
|
const ORIGIN = 'http://codeman.test/';
|
||||||
|
|
||||||
|
const PAGE = `<!doctype html><html><body>
|
||||||
|
<textarea id="term" style="display:block;width:300px;height:80px"></textarea>
|
||||||
|
<button id="other">Other</button>
|
||||||
|
<button id="open">Open</button>
|
||||||
|
<div id="plain" style="display:inline-block;padding:8px;background:#ccc">Open, takes no focus</div>
|
||||||
|
<span id="gear" tabindex="0" style="display:inline-block;padding:8px">
|
||||||
|
<svg width="24" height="24"><rect id="gearIcon" width="24" height="24"></rect></svg>
|
||||||
|
</span>
|
||||||
|
<button id="menuButton">Menu</button>
|
||||||
|
<div id="modal" hidden style="position:fixed;left:40px;top:160px;padding:20px;background:#eee">
|
||||||
|
<button id="close">Close</button><input id="name">
|
||||||
|
</div>
|
||||||
|
</body></html>`;
|
||||||
|
|
||||||
|
const WIRING = `
|
||||||
|
const modal = document.getElementById('modal');
|
||||||
|
const focused = () => (document.activeElement === document.body ? 'body' : document.activeElement.id);
|
||||||
|
window.__focused = focused;
|
||||||
|
window.__focusAtClick = [];
|
||||||
|
let trap = null;
|
||||||
|
const open = () => {
|
||||||
|
window.__focusAtClick.push(focused());
|
||||||
|
modal.hidden = false;
|
||||||
|
trap = new FocusTrap(modal);
|
||||||
|
trap.activate();
|
||||||
|
};
|
||||||
|
const close = () => {
|
||||||
|
if (!trap) return;
|
||||||
|
modal.hidden = true;
|
||||||
|
trap.deactivate();
|
||||||
|
trap = null;
|
||||||
|
};
|
||||||
|
for (const id of ['open', 'plain', 'gear']) document.getElementById(id).addEventListener('click', open);
|
||||||
|
document.getElementById('close').addEventListener('click', close);
|
||||||
|
// A menu the way the rail's row menu is built: appended to <body>, its first
|
||||||
|
// item focused, removed by the item's click before the action runs.
|
||||||
|
document.getElementById('menuButton').addEventListener('click', () => {
|
||||||
|
const menu = document.createElement('div');
|
||||||
|
menu.id = 'menu';
|
||||||
|
menu.setAttribute('role', 'menu');
|
||||||
|
menu.style.cssText = 'position:fixed;left:400px;top:160px;padding:8px;background:#ddd';
|
||||||
|
for (const [id, action] of [['menuFirst', () => {}], ['menuOptions', open]]) {
|
||||||
|
const item = document.createElement('button');
|
||||||
|
item.id = id;
|
||||||
|
item.setAttribute('role', 'menuitem');
|
||||||
|
item.textContent = id;
|
||||||
|
item.addEventListener('click', () => {
|
||||||
|
menu.remove();
|
||||||
|
action();
|
||||||
|
});
|
||||||
|
menu.appendChild(item);
|
||||||
|
}
|
||||||
|
document.body.appendChild(menu);
|
||||||
|
menu.querySelector('button').focus();
|
||||||
|
});
|
||||||
|
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); }, true);
|
||||||
|
`;
|
||||||
|
|
||||||
|
describe('where a dialog hands the keyboard back to, in Chromium', () => {
|
||||||
|
let browser: Browser;
|
||||||
|
const contexts: BrowserContext[] = [];
|
||||||
|
let page: Page;
|
||||||
|
const errors: string[] = [];
|
||||||
|
|
||||||
|
async function newPage(options: { hasTouch?: boolean } = {}): Promise<Page> {
|
||||||
|
const context = await browser.newContext({ viewport: { width: 800, height: 500 }, ...options });
|
||||||
|
contexts.push(context);
|
||||||
|
const p = await context.newPage();
|
||||||
|
p.on('pageerror', (e) => errors.push(e.message));
|
||||||
|
await p.route(ORIGIN, (route) => route.fulfill({ contentType: 'text/html', body: PAGE }));
|
||||||
|
await p.goto(ORIGIN);
|
||||||
|
await p.addScriptTag({ content: readFileSync(resolve(publicDir, 'keyboard-accessory.js'), 'utf8') });
|
||||||
|
await p.addScriptTag({ content: WIRING });
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
const focused = (p: Page = page) => p.evaluate(() => (window as any).__focused());
|
||||||
|
const focusAtClick = (p: Page = page) => p.evaluate(() => (window as any).__focusAtClick);
|
||||||
|
const termText = (p: Page = page) => p.evaluate(() => (document.getElementById('term') as HTMLTextAreaElement).value);
|
||||||
|
|
||||||
|
/** Put the keyboard in the terminal stand-in and type, as a user in the middle of a prompt. */
|
||||||
|
async function typeInTerminal(p: Page = page) {
|
||||||
|
await p.click('#term');
|
||||||
|
await p.keyboard.type('a');
|
||||||
|
expect(await focused(p)).toBe('term');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The trap moves focus to the dialog's first control one frame after it opens. */
|
||||||
|
async function dialogOpen(p: Page = page) {
|
||||||
|
await p.waitForFunction(() => (window as any).__focused() === 'close');
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
browser = await chromium.launch({ headless: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
errors.length = 0;
|
||||||
|
page = await newPage();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
for (const context of contexts) await context.close();
|
||||||
|
await browser?.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a button pressed with the mouse: the keyboard is back in the terminal', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#open');
|
||||||
|
await dialogOpen();
|
||||||
|
// The engine fact the rule exists for: the press gave the button focus.
|
||||||
|
expect(await focusAtClick()).toEqual(['open']);
|
||||||
|
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
await page.keyboard.type('b');
|
||||||
|
expect(await termText()).toBe('ab');
|
||||||
|
expect(errors).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a control that takes no focus (a button in WebKit on macOS): the keyboard is back in the terminal', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#plain');
|
||||||
|
await dialogOpen();
|
||||||
|
// The press cleared focus: before the fix this is what the dialog handed back.
|
||||||
|
expect(await focusAtClick()).toEqual(['body']);
|
||||||
|
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
await page.keyboard.type('b');
|
||||||
|
expect(await termText()).toBe('ab');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a press on the icon inside a focusable control (a tab's gear): the keyboard is back in the terminal", async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#gearIcon');
|
||||||
|
await dialogOpen();
|
||||||
|
expect(await focusAtClick()).toEqual(['gear']);
|
||||||
|
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
await page.keyboard.type('b');
|
||||||
|
expect(await termText()).toBe('ab');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("two presses through a menu (a tile's menu, then Session options): the keyboard is back in the terminal", async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#menuButton');
|
||||||
|
expect(await focused()).toBe('menuFirst');
|
||||||
|
await page.click('#menuOptions');
|
||||||
|
await dialogOpen();
|
||||||
|
// The item's click removed the menu, so nothing had focus when the dialog opened.
|
||||||
|
expect(await focusAtClick()).toEqual(['body']);
|
||||||
|
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
await page.keyboard.type('b');
|
||||||
|
expect(await termText()).toBe('ab');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a menu walked with the keyboard keeps the keyboard pattern', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#menuButton');
|
||||||
|
await page.keyboard.press('Tab');
|
||||||
|
expect(await focused()).toBe('menuOptions');
|
||||||
|
await page.keyboard.press('Enter');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
// Nothing was remembered: the dialog hands back what had focus, and that was nothing.
|
||||||
|
expect(await focused()).not.toBe('term');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closing the dialog with the mouse instead of Escape changes nothing', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#open');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.click('#close');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
await page.keyboard.type('b');
|
||||||
|
expect(await termText()).toBe('ab');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('typing in the dialog and opening it a second time still ends in the terminal', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#open');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.click('#name');
|
||||||
|
await page.keyboard.type('x');
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
|
||||||
|
await page.click('#open');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
await page.keyboard.type('b');
|
||||||
|
expect(await termText()).toBe('ab');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a keyboard user gets the control back that opened the dialog', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.keyboard.press('Tab');
|
||||||
|
await page.keyboard.press('Tab');
|
||||||
|
expect(await focused()).toBe('open');
|
||||||
|
await page.keyboard.press('Enter');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a keyboard user gets the control back even after pressing it with the mouse earlier', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#open');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('term');
|
||||||
|
|
||||||
|
await page.keyboard.press('Tab');
|
||||||
|
await page.keyboard.press('Tab');
|
||||||
|
await page.keyboard.press('Enter');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a press that began on a button returns to the pressed control, as before', async () => {
|
||||||
|
await typeInTerminal();
|
||||||
|
await page.click('#other');
|
||||||
|
expect(await focused()).toBe('other');
|
||||||
|
await page.click('#open');
|
||||||
|
await dialogOpen();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
expect(await focused()).toBe('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a finger changes nothing: focus returns to what had it when the dialog opened', async () => {
|
||||||
|
const touch = await newPage({ hasTouch: true });
|
||||||
|
await touch.tap('#term');
|
||||||
|
expect(await focused(touch)).toBe('term');
|
||||||
|
await touch.tap('#open');
|
||||||
|
await dialogOpen(touch);
|
||||||
|
const atClick = (await focusAtClick(touch))[0];
|
||||||
|
await touch.keyboard.press('Escape');
|
||||||
|
expect(await focused(touch)).toBe(atClick);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview A dialog hands the keyboard back to the field the user was
|
||||||
|
* typing in when the mouse press that opened it began.
|
||||||
|
*
|
||||||
|
* Measured in Chromium against a real shell session before the change: App
|
||||||
|
* Settings opened from the header gear and closed left `activeElement` on the
|
||||||
|
* gear button, Session Options opened from a tab's gear left it on that gear,
|
||||||
|
* and nothing typed afterwards reached the terminal. With the press clearing
|
||||||
|
* focus (what WebKit on macOS does for a button) it was left on `<body>`.
|
||||||
|
*
|
||||||
|
* `FocusTrap` is loaded with `vm` against a fake document, like the other
|
||||||
|
* accessory-bar tests. A press is the two steps a browser takes: `pointerdown`
|
||||||
|
* reaches the page first, then the engine moves focus. The real event order is
|
||||||
|
* covered in `test/dialog-focus-return.browser.test.ts`.
|
||||||
|
*/
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import vm from 'node:vm';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
type Listener = (e: unknown) => void;
|
||||||
|
type Node = Record<string, any>;
|
||||||
|
|
||||||
|
const read = (name: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8');
|
||||||
|
|
||||||
|
function node(tagName: string, extra: Node = {}): Node {
|
||||||
|
return { tagName, isConnected: true, focus: vi.fn(), contains: () => false, ...extra };
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadPage({ panels = false } = {}) {
|
||||||
|
const listeners: Record<string, Listener[]> = {};
|
||||||
|
const body = node('BODY');
|
||||||
|
let active: Node | null = body;
|
||||||
|
const document = {
|
||||||
|
body,
|
||||||
|
get activeElement() {
|
||||||
|
return active;
|
||||||
|
},
|
||||||
|
addEventListener: (type: string, fn: Listener, capture?: boolean) => {
|
||||||
|
(listeners[`${type}:${capture === true}`] ||= []).push(fn);
|
||||||
|
},
|
||||||
|
createElement: () => node('DIV'),
|
||||||
|
querySelector: () => null,
|
||||||
|
getElementById: () => null,
|
||||||
|
};
|
||||||
|
const CodemanApp = function CodemanApp(this: unknown) {};
|
||||||
|
const context = vm.createContext({
|
||||||
|
console,
|
||||||
|
document,
|
||||||
|
CodemanApp,
|
||||||
|
MobileDetection: { isTouchDevice: () => false },
|
||||||
|
localStorage: { getItem: () => null, setItem: () => {} },
|
||||||
|
requestAnimationFrame: (fn: () => void) => fn(),
|
||||||
|
});
|
||||||
|
vm.runInContext(`${read('keyboard-accessory.js')}\nglobalThis.__FocusTrap = FocusTrap;`, context, {
|
||||||
|
filename: 'keyboard-accessory.js',
|
||||||
|
});
|
||||||
|
if (panels) vm.runInContext(read('panels-ui.js'), context, { filename: 'panels-ui.js' });
|
||||||
|
const FocusTrap = (context as unknown as { __FocusTrap: any }).__FocusTrap;
|
||||||
|
const fire = (type: string, event: unknown) => (listeners[`${type}:true`] ?? []).forEach((fn) => fn(event));
|
||||||
|
return {
|
||||||
|
FocusTrap,
|
||||||
|
listeners,
|
||||||
|
body,
|
||||||
|
app: panels ? new (CodemanApp as any)() : null,
|
||||||
|
setActive: (el: Node | null) => (active = el),
|
||||||
|
/** A press: the page hears `pointerdown`, then the engine moves focus to `focusAfter`. */
|
||||||
|
press(target: Node, focusAfter?: Node | null, pointerType = 'mouse') {
|
||||||
|
fire('pointerdown', { pointerType, target });
|
||||||
|
if (focusAfter !== undefined) active = focusAfter;
|
||||||
|
},
|
||||||
|
key: (key: string) => fire('keydown', { key }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('FocusTrap.focusToReturn', () => {
|
||||||
|
it('answers the typing field when the pressed control took focus (Chromium, Firefox)', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers the typing field when the press cleared focus (a button in WebKit on macOS)', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(node('BUTTON'), page.body);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers the typing field when the press landed inside the control that took focus', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const icon = node('path');
|
||||||
|
const gear = node('BUTTON', { contains: (el: Node) => el === icon });
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(icon, gear);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the control for a keyboard user: any key forgets the press', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
// Later the same control is reached with Tab and opened with Enter.
|
||||||
|
page.key('Tab');
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(gear);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let a modifier held for the click forget the press', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
for (const key of ['Shift', 'Control', 'Alt', 'Meta']) page.key(key);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns to the pressed control when the press came from a button (a dialog opened inside a dialog)', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const closeButton = node('BUTTON');
|
||||||
|
const row = node('BUTTON');
|
||||||
|
page.setActive(closeButton);
|
||||||
|
page.press(row, row);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(row);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never carries the field of an earlier press over', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
const row = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
// A dialog is open now and the terminal is behind it; the next press starts from a button.
|
||||||
|
page.press(row, row);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(row);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the field through a menu: the press on a menu item belongs to the press that opened the menu', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const menuButton = node('BUTTON');
|
||||||
|
const firstItem = node('BUTTON');
|
||||||
|
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
|
||||||
|
page.setActive(terminal);
|
||||||
|
// The menu focuses its first item when it opens.
|
||||||
|
page.press(menuButton, firstItem);
|
||||||
|
// The item's click removes the menu, which drops focus on <body>, and opens the dialog.
|
||||||
|
page.press(item, page.body);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps nothing through a menu that was opened from a button', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const closeButton = node('BUTTON');
|
||||||
|
const menuButton = node('BUTTON');
|
||||||
|
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
|
||||||
|
page.setActive(closeButton);
|
||||||
|
page.press(menuButton, menuButton);
|
||||||
|
page.press(item, page.body);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('spends the press when a dialog asks, so nothing pressed inside the dialog reaches the field behind it', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(gear);
|
||||||
|
|
||||||
|
// The dialog is open. A menu item in it is pressed directly, with a dialog control focused.
|
||||||
|
const dialogControl = node('BUTTON');
|
||||||
|
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
|
||||||
|
page.setActive(dialogControl);
|
||||||
|
page.press(item, page.body);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves a finger alone, and a finger forgets an earlier mouse press', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear, 'touch');
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(gear);
|
||||||
|
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear, 'mouse');
|
||||||
|
page.press(gear, gear, 'touch');
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(gear);
|
||||||
|
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear, 'pen');
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(gear);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers what has focus when the field is gone from the page', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
terminal.isConnected = false;
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(gear);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers what has focus when the click itself moved it somewhere else', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const elsewhere = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(node('BUTTON'), elsewhere);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(elsewhere);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers what has focus when there was no press at all', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
page.setActive(terminal);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
page.setActive(page.body);
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers the field itself when the press left focus in it', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
page.setActive(terminal);
|
||||||
|
// An accessory key cancels the mousedown default, so the terminal keeps focus.
|
||||||
|
page.press(node('BUTTON'));
|
||||||
|
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FocusTrap.isTypingField', () => {
|
||||||
|
it('counts textareas, text-like inputs and editable regions, and nothing else', () => {
|
||||||
|
const { FocusTrap, body } = loadPage();
|
||||||
|
expect(FocusTrap.isTypingField(node('TEXTAREA'))).toBe(true);
|
||||||
|
expect(FocusTrap.isTypingField(node('textarea'))).toBe(true);
|
||||||
|
expect(FocusTrap.isTypingField(node('INPUT'))).toBe(true);
|
||||||
|
for (const type of ['text', 'search', 'number', 'password', 'email', 'url']) {
|
||||||
|
expect(FocusTrap.isTypingField(node('INPUT', { type }))).toBe(true);
|
||||||
|
}
|
||||||
|
for (const type of [
|
||||||
|
'button',
|
||||||
|
'checkbox',
|
||||||
|
'color',
|
||||||
|
'file',
|
||||||
|
'hidden',
|
||||||
|
'image',
|
||||||
|
'radio',
|
||||||
|
'range',
|
||||||
|
'reset',
|
||||||
|
'submit',
|
||||||
|
]) {
|
||||||
|
expect(FocusTrap.isTypingField(node('INPUT', { type }))).toBe(false);
|
||||||
|
}
|
||||||
|
expect(FocusTrap.isTypingField(node('DIV', { isContentEditable: true }))).toBe(true);
|
||||||
|
expect(FocusTrap.isTypingField(node('DIV'))).toBe(false);
|
||||||
|
expect(FocusTrap.isTypingField(node('BUTTON'))).toBe(false);
|
||||||
|
expect(FocusTrap.isTypingField(node('SELECT'))).toBe(false);
|
||||||
|
expect(FocusTrap.isTypingField(body)).toBe(false);
|
||||||
|
expect(FocusTrap.isTypingField(null)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the document listeners', () => {
|
||||||
|
it('are two capture listeners, installed once however often the page asks', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
page.FocusTrap.watchPresses();
|
||||||
|
page.FocusTrap.watchPresses();
|
||||||
|
expect(Object.keys(page.listeners).sort()).toEqual(['keydown:true', 'pointerdown:true']);
|
||||||
|
expect(page.listeners['pointerdown:true']).toHaveLength(1);
|
||||||
|
expect(page.listeners['keydown:true']).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('are skipped on a page with no document to listen on', () => {
|
||||||
|
const context = vm.createContext({ console, document: { createElement: () => node('DIV') } });
|
||||||
|
vm.runInContext(`${read('keyboard-accessory.js')}\nglobalThis.__FocusTrap = FocusTrap;`, context);
|
||||||
|
expect((context as unknown as { __FocusTrap: any }).__FocusTrap._watching).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('a dialog built on FocusTrap', () => {
|
||||||
|
function dialog() {
|
||||||
|
return { addEventListener: vi.fn(), removeEventListener: vi.fn(), querySelectorAll: () => [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('hands the keyboard back to the terminal after it was opened by a mouse press', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
|
||||||
|
const trap = new page.FocusTrap(dialog());
|
||||||
|
trap.activate();
|
||||||
|
expect(trap.previouslyFocused).toBe(terminal);
|
||||||
|
trap.deactivate();
|
||||||
|
expect(terminal.focus).toHaveBeenCalledTimes(1);
|
||||||
|
expect(gear.focus).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still hands it back to the control it was opened from with the keyboard', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
page.setActive(gear);
|
||||||
|
page.key('Enter');
|
||||||
|
|
||||||
|
const trap = new page.FocusTrap(dialog());
|
||||||
|
trap.activate();
|
||||||
|
trap.deactivate();
|
||||||
|
expect(gear.focus).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is not misled by the press that closes it', () => {
|
||||||
|
const page = loadPage();
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const gear = node('BUTTON');
|
||||||
|
const close = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(gear, gear);
|
||||||
|
const trap = new page.FocusTrap(dialog());
|
||||||
|
trap.activate();
|
||||||
|
page.setActive(close);
|
||||||
|
page.press(close, close);
|
||||||
|
trap.deactivate();
|
||||||
|
expect(terminal.focus).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the command palette and the Session Manager', () => {
|
||||||
|
it('save the same answer, so an overlay opened by a mouse press returns to the terminal', () => {
|
||||||
|
const page = loadPage({ panels: true });
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
const headerButton = node('BUTTON');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.press(headerButton, headerButton);
|
||||||
|
page.app._rememberOverlayFocus('_sessionManagerPrevFocus');
|
||||||
|
expect(page.app._sessionManagerPrevFocus).toBe(terminal);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('save what has focus when the overlay was opened with its shortcut', () => {
|
||||||
|
const page = loadPage({ panels: true });
|
||||||
|
const terminal = node('TEXTAREA');
|
||||||
|
page.setActive(terminal);
|
||||||
|
page.key('k');
|
||||||
|
page.app._rememberOverlayFocus('_commandPalettePrevFocus');
|
||||||
|
expect(page.app._commandPalettePrevFocus).toBe(terminal);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,143 +0,0 @@
|
|||||||
/**
|
|
||||||
* @fileoverview killSession() must never signal the machine.
|
|
||||||
*
|
|
||||||
* On 2026-11-25 a kill that got pid 0 took down every process of the account: every
|
|
||||||
* session, tmux and the systemd user manager. The children of pid 0 are the whole process
|
|
||||||
* table, so the descendant walk handed all of it to SIGTERM. tmux answers 0 for a pane
|
|
||||||
* with no process (`split-window ''`), the pane list read at server start records it on
|
|
||||||
* the session, and the next close of that tab killed everything.
|
|
||||||
*
|
|
||||||
* These drive the SHIPPED killSession() with the tmux and ps answers mocked and
|
|
||||||
* process.kill stubbed: nothing here may reach a real process.
|
|
||||||
*
|
|
||||||
* Port: N/A (no server needed)
|
|
||||||
*/
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
|
|
||||||
import { exec, execFile, execSync } from 'node:child_process';
|
|
||||||
import { isSignalablePid } from '../src/proc-tree.js';
|
|
||||||
import type { MuxSession } from '../src/mux-interface.js';
|
|
||||||
|
|
||||||
vi.mock('node:child_process', async () => {
|
|
||||||
const actual = await vi.importActual('node:child_process');
|
|
||||||
return { ...actual, exec: vi.fn(), execFile: vi.fn(), execSync: vi.fn(), spawn: vi.fn() };
|
|
||||||
});
|
|
||||||
|
|
||||||
/** A machine: init, kthreadd, the user's own programs, and one agent (4242) with a child. */
|
|
||||||
const PS = ['1 0', '2 0', '900 1', '901 900', '902 900', '4242 901', '4243 4242'].join('\n') + '\n';
|
|
||||||
|
|
||||||
describe('isSignalablePid', () => {
|
|
||||||
it('admits only a process of the user', () => {
|
|
||||||
for (const pid of [2, 4242, 2 ** 22]) expect(isSignalablePid(pid)).toBe(true);
|
|
||||||
for (const pid of [1, 0, -0, -1, -4242, NaN, Infinity, 1.5, null, undefined]) {
|
|
||||||
expect(isSignalablePid(pid as number)).toBe(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('killSession and a pane without a process', () => {
|
|
||||||
let panePid: string;
|
|
||||||
let commands: string[];
|
|
||||||
let kill: MockInstance<typeof process.kill>;
|
|
||||||
let signals: [number, string | number | undefined][];
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
panePid = '4242\n';
|
|
||||||
commands = [];
|
|
||||||
signals = [];
|
|
||||||
vi.mocked(execSync).mockImplementation(((cmd: string) => {
|
|
||||||
if (cmd.includes('list-panes -a')) return `codeman-feed1234|${panePid.trim()}|0||\n`;
|
|
||||||
return '';
|
|
||||||
}) as unknown as typeof execSync);
|
|
||||||
vi.mocked(exec).mockImplementation(((cmd: string, options: unknown, maybeCallback?: unknown) => {
|
|
||||||
commands.push(cmd);
|
|
||||||
const callback = (typeof options === 'function' ? options : maybeCallback) as (e: null, out: object) => void;
|
|
||||||
const stdout = cmd.includes('display-message') ? panePid : '';
|
|
||||||
setImmediate(() => callback(null, { stdout, stderr: '' }));
|
|
||||||
return { on: vi.fn(), kill: vi.fn(), pid: 12345 };
|
|
||||||
}) as unknown as typeof exec);
|
|
||||||
// The process snapshot the descendant walk reads.
|
|
||||||
vi.mocked(execFile).mockImplementation(((file: string, _args: string[], _options: unknown, callback: unknown) => {
|
|
||||||
setImmediate(() => (callback as (e: null, out: string) => void)(null, file === 'ps' ? PS : ''));
|
|
||||||
return { on: vi.fn(), kill: vi.fn(), pid: 12345 };
|
|
||||||
}) as unknown as typeof execFile);
|
|
||||||
// Every process dies at its first real signal, so no wait runs its full length.
|
|
||||||
const gone = new Set<number>();
|
|
||||||
kill = vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: string | number) => {
|
|
||||||
if (signal !== 0) {
|
|
||||||
signals.push([pid, signal]);
|
|
||||||
gone.add(Math.abs(pid));
|
|
||||||
} else if (gone.has(Math.abs(pid))) {
|
|
||||||
throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' });
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}) as typeof process.kill);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
kill.mockRestore();
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
async function manager(recordedPid: number) {
|
|
||||||
const vitest = process.env.VITEST;
|
|
||||||
vi.resetModules();
|
|
||||||
delete process.env.VITEST;
|
|
||||||
const { TmuxManager } = await import('../src/tmux-manager.js');
|
|
||||||
process.env.VITEST = vitest;
|
|
||||||
const m = new TmuxManager();
|
|
||||||
m.registerSession({
|
|
||||||
sessionId: 'feed1234',
|
|
||||||
muxName: 'codeman-feed1234',
|
|
||||||
pid: recordedPid,
|
|
||||||
createdAt: Date.now(),
|
|
||||||
workingDir: '/tmp',
|
|
||||||
mode: 'claude',
|
|
||||||
attached: false,
|
|
||||||
} as MuxSession);
|
|
||||||
return m;
|
|
||||||
}
|
|
||||||
const closedByTmux = () => commands.some((c) => c.includes('kill-session -t "codeman-feed1234"'));
|
|
||||||
|
|
||||||
// The control: without it, a guard that refused every kill would pass the rest.
|
|
||||||
it('still signals the process tree of a real pane', async () => {
|
|
||||||
const m = await manager(4242);
|
|
||||||
expect(await m.killSession('feed1234')).toBe(true);
|
|
||||||
expect(signals).toContainEqual([4243, 'SIGTERM']);
|
|
||||||
expect(signals).toContainEqual([-4242, 'SIGTERM']);
|
|
||||||
expect(signals.every(([pid]) => [4242, 4243].includes(Math.abs(pid)))).toBe(true);
|
|
||||||
expect(closedByTmux()).toBe(true);
|
|
||||||
m.destroy();
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const pid of [0, 1]) {
|
|
||||||
it(`signals nothing for pid ${pid}, and tmux still closes the session`, async () => {
|
|
||||||
panePid = `${pid}\n`;
|
|
||||||
const m = await manager(pid);
|
|
||||||
expect(await m.killSession('feed1234')).toBe(true);
|
|
||||||
expect(signals).toEqual([]);
|
|
||||||
expect(closedByTmux()).toBe(true);
|
|
||||||
expect(m.getSession('feed1234')).toBeUndefined();
|
|
||||||
m.destroy();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
it('signals nothing when tmux gives no answer and the record holds 0', async () => {
|
|
||||||
panePid = '\n';
|
|
||||||
const m = await manager(0);
|
|
||||||
expect(await m.killSession('feed1234')).toBe(true);
|
|
||||||
expect(signals).toEqual([]);
|
|
||||||
expect(closedByTmux()).toBe(true);
|
|
||||||
m.destroy();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('survives the real route: the pane list at server start records 0, then the tab is closed', async () => {
|
|
||||||
panePid = '0\n';
|
|
||||||
const m = await manager(4242);
|
|
||||||
await m.reconcileSessions();
|
|
||||||
expect(m.getSession('feed1234')?.pid).toBe(0); // what master did next was walk it
|
|
||||||
expect(await m.killSession('feed1234')).toBe(true);
|
|
||||||
expect(signals).toEqual([]);
|
|
||||||
expect(closedByTmux()).toBe(true);
|
|
||||||
m.destroy();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -146,14 +146,11 @@ describe('collectDescendants', () => {
|
|||||||
* even with both caps bypassed.
|
* even with both caps bypassed.
|
||||||
*/
|
*/
|
||||||
describe('TmuxManager uses the bounded walk', () => {
|
describe('TmuxManager uses the bounded walk', () => {
|
||||||
/** A pane's pid. Never 0 or 1: the kill path walks nothing for those (kill-pid-guard.test.ts). */
|
/** Build a tree `width` wide and `depth` deep, rooted at 1. */
|
||||||
const ROOT = 1000;
|
|
||||||
|
|
||||||
/** Build a tree `width` wide and `depth` deep, rooted at ROOT. */
|
|
||||||
function bigTree(width: number, depth: number): Map<number, number[]> {
|
function bigTree(width: number, depth: number): Map<number, number[]> {
|
||||||
const t = new Map<number, number[]>();
|
const t = new Map<number, number[]>();
|
||||||
let next = ROOT + 1;
|
let next = 2;
|
||||||
let frontier = [ROOT];
|
let frontier = [1];
|
||||||
for (let d = 0; d < depth; d += 1) {
|
for (let d = 0; d < depth; d += 1) {
|
||||||
const nf: number[] = [];
|
const nf: number[] = [];
|
||||||
for (const p of frontier) {
|
for (const p of frontier) {
|
||||||
@@ -166,7 +163,7 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function walkVia(fixture: Map<number, number[]>, root = ROOT): Promise<number[]> {
|
async function walkVia(fixture: Map<number, number[]>): Promise<number[]> {
|
||||||
const { TmuxManager } = await import('../src/tmux-manager.js');
|
const { TmuxManager } = await import('../src/tmux-manager.js');
|
||||||
const Klass = TmuxManager as unknown as {
|
const Klass = TmuxManager as unknown as {
|
||||||
refreshProcSnapshot(): Promise<Map<number, number[]>>;
|
refreshProcSnapshot(): Promise<Map<number, number[]>>;
|
||||||
@@ -177,7 +174,7 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
Klass.procSnapshot = { at: Date.now(), byParent: fixture };
|
Klass.procSnapshot = { at: Date.now(), byParent: fixture };
|
||||||
try {
|
try {
|
||||||
const mgr = new TmuxManager();
|
const mgr = new TmuxManager();
|
||||||
return await (mgr as unknown as { getChildPidsFresh(pid: number): Promise<number[]> }).getChildPidsFresh(root);
|
return await (mgr as unknown as { getChildPidsFresh(pid: number): Promise<number[]> }).getChildPidsFresh(1);
|
||||||
} finally {
|
} finally {
|
||||||
Klass.refreshProcSnapshot = original;
|
Klass.refreshProcSnapshot = original;
|
||||||
Klass.procSnapshot = null;
|
Klass.procSnapshot = null;
|
||||||
@@ -193,7 +190,7 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
|
|
||||||
it('honours the depth cap on a deep chain', async () => {
|
it('honours the depth cap on a deep chain', async () => {
|
||||||
const chainTree = new Map<number, number[]>();
|
const chainTree = new Map<number, number[]>();
|
||||||
for (let i = ROOT; i < ROOT + 39; i += 1) chainTree.set(i, [i + 1]);
|
for (let i = 1; i < 40; i += 1) chainTree.set(i, [i + 1]);
|
||||||
|
|
||||||
const out = await walkVia(chainTree);
|
const out = await walkVia(chainTree);
|
||||||
|
|
||||||
@@ -206,16 +203,6 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
const out = await walkVia(bigTree(4, 6));
|
const out = await walkVia(bigTree(4, 6));
|
||||||
expect(out.length).toBeLessThanOrEqual(PROC_WALK_MAX_NODES);
|
expect(out.length).toBeLessThanOrEqual(PROC_WALK_MAX_NODES);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([0, 1])('walks nothing below pid %i, whose children are the whole machine', async (root) => {
|
|
||||||
const machine = new Map([
|
|
||||||
[0, [1, 2]],
|
|
||||||
[1, [900]],
|
|
||||||
[900, [901]],
|
|
||||||
]);
|
|
||||||
expect(await walkVia(machine, root)).toEqual([]);
|
|
||||||
expect(await walkVia(machine, 900)).toEqual([901]);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('descendantsInPaneGroup (a shared daemon outlives the pane that started it)', () => {
|
describe('descendantsInPaneGroup (a shared daemon outlives the pane that started it)', () => {
|
||||||
|
|||||||
Reference in new issue
Block a user