From 10e443a30983412084e8ade9bca3e67a3898b7a4 Mon Sep 17 00:00:00 2001 From: JD Date: Sat, 14 Nov 2026 14:31:41 -0500 Subject: [PATCH 01/52] fix(watchers): stop a chokidar watcher whose fs.watch fails instead of retrying forever chokidar 3 with `persistent: false` has no guard for an `fs.watch` that throws (EMFILE once the inotify instance limit is used up, ENOSPC once the watch limit is). It emits the error, then a TypeError, then retries on the parent directory, and ends up re-adding `/` forever. TeamWatcher only logged its `'error'` events, so one failed watch became an endless stream of stack traces. WorkflowRunWatcher already closed its watcher on error, but `close()` removes every listener, so the TypeError from the same pass became an unhandled rejection, one per 10 s poll, and the server exits after five of those in a minute. `closeWatcherOnError()` closes the watcher on its first error, keeps a no-op listener on it, and turns its `add()` into a no-op, since a callback chokidar still has in flight can otherwise re-add a path and reopen it. TeamWatcher logs one line per watcher and relies on its 30 s poll; WorkflowRunWatcher still drops the watcher and re-arms it on the next poll. --- CLAUDE.md | 2 + src/team-watcher.ts | 10 +- src/utils/close-watcher-on-error.ts | 38 +++ src/workflow-run-watcher.ts | 7 +- test/watcher-fs-watch-failure.test.ts | 416 ++++++++++++++++++++++++++ 5 files changed, 465 insertions(+), 8 deletions(-) create mode 100644 src/utils/close-watcher-on-error.ts create mode 100644 test/watcher-fs-watch-failure.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 9472b727..9f21bc7e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -160,6 +160,8 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded) +**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched. Tests: `test/watcher-fs-watch-failure.test.ts`. + **Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit) **Auto-compact and auto-clear** (opt-in per session, Respawn tab; `session-auto-ops.ts`, pure decision `decideAutoThreshold()`): for a Claude session the size compared with the threshold is the context Claude Code reports on its statusline (`context_window.total_input_tokens`, cache reads included, handed over by `POST /api/status-telemetry` through `Session.noteContextReport()`); the session's token counter never sees the cached context and is only the fallback for a launch without the exporter. Thresholds go up to the reported window (`contextWindowSize`, 1M while unknown). ⚠️ After a `/compact` or `/clear` the report from before the command is ignored by VALUE, never for a length of time (a 601k compact took 39 s). ⚠️ The decision is made AGAIN when the command goes out (`_decideAtSend()`): a report fires the trigger in the middle of a turn, and the wait for that turn to end can outlast a compaction by Claude Code itself, so a `/clear` sent on the old answer would wipe a conversation that is small again. A skipped command stamps nothing. ⚠️ Nothing is sent into a usage-limit pause (`_heldByLimit()`, until auto-resume's `continue` went out), or that `continue` is typed into an empty conversation. → [architecture-invariants#auto-compact-and-auto-clear-thresholds](docs/architecture-invariants.md#auto-compact-and-auto-clear-thresholds) diff --git a/src/team-watcher.ts b/src/team-watcher.ts index d54d1c69..74b821e6 100644 --- a/src/team-watcher.ts +++ b/src/team-watcher.ts @@ -16,6 +16,8 @@ import { join } from 'node:path'; import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar'; import type { TeamConfig, TeamTask, InboxMessage } from './types.js'; +import { getErrorMessage } from './types/api.js'; +import { closeWatcherOnError } from './utils/close-watcher-on-error.js'; import { LRUMap } from './utils/lru-map.js'; import { TEAM_POLL_INTERVAL_MS, MAX_CACHED_TEAMS, MAX_CACHED_TASKS } from './config/team-config.js'; @@ -66,8 +68,8 @@ export class TeamWatcher extends EventEmitter { this.teamsWatcher.on('change', teamsHandler); this.teamsWatcher.on('unlink', teamsHandler); this.teamsWatcher.on('unlinkDir', teamsHandler); - this.teamsWatcher.on('error', (err) => { - console.warn('[TeamWatcher] chokidar teams watcher error:', err); + closeWatcherOnError(this.teamsWatcher, (err) => { + console.warn(`[TeamWatcher] teams watcher stopped, relying on polling: ${getErrorMessage(err)}`); }); } catch (err) { console.warn('[TeamWatcher] Failed to set up teams chokidar watcher, relying on polling:', err); @@ -84,8 +86,8 @@ export class TeamWatcher extends EventEmitter { this.tasksWatcher.on('add', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry this.tasksWatcher.on('change', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry - this.tasksWatcher.on('error', (err) => { - console.warn('[TeamWatcher] chokidar tasks watcher error:', err); + closeWatcherOnError(this.tasksWatcher, (err) => { + console.warn(`[TeamWatcher] tasks watcher stopped, relying on polling: ${getErrorMessage(err)}`); }); } catch (err) { console.warn('[TeamWatcher] Failed to set up tasks chokidar watcher, relying on polling:', err); diff --git a/src/utils/close-watcher-on-error.ts b/src/utils/close-watcher-on-error.ts new file mode 100644 index 00000000..7e27f9c7 --- /dev/null +++ b/src/utils/close-watcher-on-error.ts @@ -0,0 +1,38 @@ +/** + * @fileoverview Close a chokidar watcher on its first error, safely. + * + * chokidar 3 with `persistent: false` has no guard for an `fs.watch` that + * throws (EMFILE once the inotify instance limit is used up, ENOSPC once the + * watch limit is): it emits the error, then a TypeError from closing the + * watcher it never got, then retries on the parent directory, one level per + * pass, and re-adds `/` forever, since the parent of `/` is `/`. Only a closed + * watcher ends that loop, so a watcher whose `'error'` handler just logs logs + * forever. + * + * Closing from the handler is not enough on its own: + * - `close()` removes every listener, and the TypeError of the same pass is + * emitted after it. With no `'error'` listener EventEmitter throws it, and it + * reaches the process as an unhandled rejection. So a no-op listener stays + * on the closed watcher. + * - callbacks chokidar already has in flight can still call `add()` (a deleted + * file's `_remove()` re-adds the file when chokidar thinks it was the only + * watched path), and `add()` sets `closed = false`, which starts the climb + * again, silently now. So `add()` becomes a no-op on the closed watcher. + * + * @module utils/close-watcher-on-error + */ + +import type { FSWatcher } from 'chokidar'; + +/** + * Close `watcher` on its first `'error'` and pass that error to `onClosed`, + * once. The caller's polling has to cover what the watcher watched. + */ +export function closeWatcherOnError(watcher: FSWatcher, onClosed: (err: unknown) => void): void { + watcher.once('error', (err: unknown) => { + watcher.close().catch(() => {}); // best-effort, like the stop() paths + watcher.on('error', () => {}); // see the fileoverview + watcher.add = () => watcher; // likewise + onClosed(err); + }); +} diff --git a/src/workflow-run-watcher.ts b/src/workflow-run-watcher.ts index ee7c9144..675dc046 100644 --- a/src/workflow-run-watcher.ts +++ b/src/workflow-run-watcher.ts @@ -40,6 +40,7 @@ import { join } from 'node:path'; import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar'; import type { WorkflowRunInfo, WorkflowRunSummary, WorkflowAgentInfo, WorkflowRunPhase } from './types/workflow-run.js'; +import { closeWatcherOnError } from './utils/close-watcher-on-error.js'; import { LRUMap } from './utils/lru-map.js'; import { WORKFLOW_RUN_POLL_INTERVAL_MS, @@ -865,10 +866,8 @@ export class WorkflowRunWatcher extends EventEmitter { // subagents/workflows/ children are wf_/ DIRS — catch their add/remove too. watcher.on('addDir', handler); watcher.on('unlinkDir', handler); - watcher.on('error', () => { - // chokidar surfaced an error for this dir — drop the watcher; poll still covers it. - this.removeDirWatcher(workflowsDir); - }); + // chokidar surfaced an error for this dir — drop the watcher; poll still covers it. + closeWatcherOnError(watcher, () => this.dirWatchers.delete(workflowsDir)); this.dirWatchers.set(workflowsDir, watcher); } catch { // Watch setup failed — periodic poll still discovers changes. diff --git a/test/watcher-fs-watch-failure.test.ts b/test/watcher-fs-watch-failure.test.ts new file mode 100644 index 00000000..bf74e847 --- /dev/null +++ b/test/watcher-fs-watch-failure.test.ts @@ -0,0 +1,416 @@ +/** + * @fileoverview Pins bounded fs.watch failure handling and polling fallback after a production chokidar retry loop flooded logs and synchronous close caused unhandled rejections. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { TeamWatcher } from '../src/team-watcher.js'; +import { WorkflowRunWatcher } from '../src/workflow-run-watcher.js'; +import { TEAM_POLL_INTERVAL_MS } from '../src/config/team-config.js'; +import { WORKFLOW_RUN_POLL_INTERVAL_MS } from '../src/config/workflow-config.js'; +import type { TeamConfig } from '../src/types.js'; +import type { WorkflowRunInfo } from '../src/types/workflow-run.js'; + +const FAILURES = [ + { code: 'EMFILE', errno: -24, text: 'too many open files' }, + { code: 'ENOSPC', errno: -28, text: 'no space left on device' }, +] as const; +type WatchFailure = (typeof FAILURES)[number]; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function waitUntil(predicate: () => boolean, message: string): Promise { + const deadline = Date.now() + 1500; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error(message); + await delay(10); + } +} + +function watchError(failure: WatchFailure, path: string): NodeJS.ErrnoException { + return Object.assign(new Error(`${failure.code}: ${failure.text}, watch '${path}'`), { + code: failure.code, + errno: failure.errno, + syscall: 'watch', + path, + }); +} + +function failEveryWatch(failure: WatchFailure) { + return vi.spyOn(fs, 'watch').mockImplementation((path) => { + throw watchError(failure, String(path)); + }); +} + +let tempDir: string; +let watcher: TeamWatcher | WorkflowRunWatcher | undefined; +let warn: ReturnType>; +let error: ReturnType>; +let unhandled: unknown[]; +let onUnhandled: (reason: unknown) => void; + +beforeEach(async () => { + watcher = undefined; + tempDir = await mkdtemp(join(tmpdir(), 'codeman-watch-failure-')); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + error = vi.spyOn(console, 'error').mockImplementation(() => {}); + unhandled = []; + onUnhandled = (reason) => unhandled.push(reason); + process.on('unhandledRejection', onUnhandled); +}); + +afterEach(async () => { + try { + watcher?.stop(); + // Keep mocks and the rejection listener installed while asynchronous close settles. + await delay(100); + await rm(tempDir, { recursive: true, force: true }); + } finally { + process.off('unhandledRejection', onUnhandled); + vi.useRealTimers(); + vi.restoreAllMocks(); + } +}); + +function createTeamConfig(): TeamConfig { + return { + name: 'test-team', + createdAt: 1_700_000_000_000, + leadAgentId: 'team-lead@test-team', + leadSessionId: 'session-123', + members: [ + { + agentId: 'team-lead@test-team', + name: 'team-lead', + agentType: 'team-lead', + joinedAt: 1_700_000_000_000, + }, + ], + }; +} + +async function writeTeam(teamsDir: string, config: TeamConfig): Promise { + const dir = join(teamsDir, config.name); + await mkdir(dir); + await writeFile(join(dir, 'config.json'), JSON.stringify(config)); +} + +describe('TeamWatcher fs.watch failure', () => { + let teamsDir: string; + let tasksDir: string; + let teamWatcher: TeamWatcher; + + beforeEach(async () => { + teamsDir = join(tempDir, 'teams'); + tasksDir = join(tempDir, 'tasks'); + await mkdir(teamsDir); + await mkdir(tasksDir); + watcher = teamWatcher = new TeamWatcher(teamsDir, tasksDir); + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + }); + + it.each(FAILURES)('$code stops both watchers with two warnings and keeps polling', async (failure) => { + const watch = failEveryWatch(failure); + try { + teamWatcher.start(); + await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings'); + const attempts = watch.mock.calls.length; + await delay(500); + + // Check counts before arguments so the unfixed log storm cannot flood failure output. + expect(warn).toHaveBeenCalledTimes(2); + expect(error).toHaveBeenCalledTimes(0); + for (const call of warn.mock.calls) expect(call.length).toBe(1); + expect(warn.mock.calls.map(([message]) => message).sort()).toEqual( + [ + `[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`, + `[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`, + ].sort() + ); + expect(watch.mock.calls.length).toBe(attempts); + expect(attempts).toBeGreaterThanOrEqual(2); + // Allow a handful of in-flight attempts, but never an ancestor retry loop. + expect(attempts).toBeLessThanOrEqual(6); + expect(unhandled.length).toBe(0); + + const config = createTeamConfig(); + await writeTeam(teamsDir, config); + expect(teamWatcher.getTeams()).toEqual([]); + vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS); + await waitUntil(() => teamWatcher.getTeams().length > 0, 'polling did not discover the new team'); + expect(teamWatcher.getTeams()).toEqual([config]); + expect(watch.mock.calls.length).toBe(attempts); + expect(warn).toHaveBeenCalledTimes(2); + + expect(() => teamWatcher.stop()).not.toThrow(); + await delay(500); + expect(watch.mock.calls.length).toBe(attempts); + expect(warn).toHaveBeenCalledTimes(2); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + } finally { + teamWatcher.stop(); + } + }); + + it('keeps a healthy watcher active and discovers a new team before the poll interval', async () => { + try { + teamWatcher.start(); + await delay(200); + const config = createTeamConfig(); + await writeTeam(teamsDir, config); + // No interval is advanced: discovery must come from the real filesystem watcher. + await waitUntil(() => teamWatcher.getTeams().length > 0, 'healthy watcher did not discover the new team'); + expect(teamWatcher.getTeams()).toEqual([config]); + teamWatcher.stop(); + await delay(100); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + } finally { + teamWatcher.stop(); + } + }); +}); + +describe('TeamWatcher in-flight fs.watch failure', () => { + it('stays stopped when file replacement and deletion race with ENOSPC', async () => { + const teamsDir = join(tempDir, 'teams'); + const tasksDir = join(tempDir, 'tasks'); + const teamDir = join(teamsDir, 't'); + await mkdir(teamDir, { recursive: true }); + await mkdir(tasksDir); + await writeFile(join(teamDir, 'a.json'), '{}'); + await writeFile(join(teamDir, 'b.json'), '{}'); + const teamWatcher = new TeamWatcher(teamsDir, tasksDir); + watcher = teamWatcher; + const realWatch = fs.watch; + const listeners = new Map>(); + const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => { + const handle = realWatch(...args); + if (args[2]) listeners.set(String(args[0]), args[2]); + return handle; + }); + let firstFailure: NodeJS.ErrnoException | undefined; + let failingCalls = 0; + + try { + teamWatcher.start(); + await waitUntil( + () => listeners.has(join(teamDir, 'a.json')) && listeners.has(join(teamDir, 'b.json')), + 'timed out waiting for both file watches' + ); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + watch.mockImplementation((...args) => { + // Bound the unfixed retry loop so it can recover and the test can finish. + if (failingCalls >= 2000) return realWatch(...args); + failingCalls++; + const failure = watchError(FAILURES[1], String(args[0])); + firstFailure ??= failure; + throw failure; + }); + + fs.writeFileSync(join(teamDir, 'b.json.tmp'), '{"replaced":true}'); + fs.renameSync(join(teamDir, 'b.json.tmp'), join(teamDir, 'b.json')); + await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the teams watcher warning'); + // Deliver the queued deletion callback only after the replacement failure stops the watcher. + fs.unlinkSync(join(teamDir, 'a.json')); + listeners.get(join(teamDir, 'a.json'))!('rename', 'a.json'); + await delay(1000); + const attempts = watch.mock.calls.length; + const failures = failingCalls; + await delay(500); + const settledAttempts = watch.mock.calls.length; + const settledFailures = failingCalls; + const warnings = warn.mock.calls.length; + + teamWatcher.stop(); + await delay(500); + + // Check counts before arguments so a retry storm cannot flood failure output. + expect(warn).toHaveBeenCalledTimes(1); + expect(warnings).toBe(1); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + expect(watch.mock.calls.length).toBe(settledAttempts); + expect(failingCalls).toBe(settledFailures); + expect(settledAttempts).toBe(attempts); + expect(settledFailures).toBe(failures); + expect(failures).toBeGreaterThanOrEqual(1); + expect(failures).toBeLessThanOrEqual(6); + expect(firstFailure?.code).toBe('ENOSPC'); + expect(firstFailure?.path?.startsWith(`${teamDir}/`)).toBe(true); + expect(warn.mock.calls).toEqual([ + [`[TeamWatcher] teams watcher stopped, relying on polling: ${firstFailure?.message}`], + ]); + } finally { + teamWatcher.stop(); + } + }); +}); + +const PROJECT_HASH = '-home-arkon-default-claudeman'; +const SESSION_UUID = '388113c8-cd01-4e80-93a8-3be66ab1519b'; +const RUN_ID = 'wf_test1234-abc'; +const RUN_START = 1_700_000_000_000; + +function sampleRunJson() { + return { + runId: RUN_ID, + timestamp: new Date(RUN_START).toISOString(), + workflowName: 'watch-failure-test', + summary: 'Discover a run despite exhausted filesystem watches', + status: 'completed', + startTime: RUN_START, + agentCount: 0, + durationMs: 1234, + totalTokens: 0, + totalToolCalls: 0, + phases: [], + workflowProgress: [], + }; +} + +const { workflowProgress: _progress, ...runFields } = sampleRunJson(); +const EXPECTED_RUN: WorkflowRunInfo = { + ...runFields, + agents: [], + projectHash: PROJECT_HASH, + sessionUuid: SESSION_UUID, + lastActivityAt: RUN_START, +}; + +describe('WorkflowRunWatcher fs.watch failure', () => { + let runWatcher: WorkflowRunWatcher; + let workflowsDir: string; + + beforeEach(async () => { + const projectsDir = join(tempDir, 'projects'); + workflowsDir = join(projectsDir, PROJECT_HASH, SESSION_UUID, 'workflows'); + await mkdir(workflowsDir, { recursive: true }); + await writeFile(join(workflowsDir, `${RUN_ID}.json`), JSON.stringify(sampleRunJson())); + watcher = runWatcher = new WorkflowRunWatcher(projectsDir); + // Later interval polls run only when a test explicitly advances the clock. + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + }); + + function firstRun(): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + runWatcher.off('run_discovered', onRun); + reject(new Error('timed out waiting for run_discovered')); + }, 1500); + function onRun(info: WorkflowRunInfo) { + clearTimeout(timer); + resolve(info); + } + runWatcher.once('run_discovered', onRun); + runWatcher.start(); + }); + } + + it.each(FAILURES)('$code discovers the run without retries, logging, or unhandled rejections', async (failure) => { + const watch = failEveryWatch(failure); + try { + const discovered = await firstRun(); + await delay(500); + const attempts = watch.mock.calls.length; + await delay(500); + + expect(unhandled.length).toBe(0); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + expect(watch.mock.calls.length).toBe(attempts); + expect(attempts).toBeGreaterThanOrEqual(1); + expect(attempts).toBeLessThanOrEqual(3); + expect(discovered).toEqual(EXPECTED_RUN); + expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN); + expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]); + expect(runWatcher.isRunning()).toBe(true); + runWatcher.stop(); + expect(runWatcher.isRunning()).toBe(false); + await delay(100); + expect(unhandled.length).toBe(0); + expect(watch.mock.calls.length).toBe(attempts); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + } finally { + runWatcher.stop(); + } + }); + + it('retries a failed directory once per poll and resumes live discovery when fs.watch recovers', async () => { + const watch = failEveryWatch(FAILURES[0]); + const discovered = vi.fn(); + try { + expect(await firstRun()).toEqual(EXPECTED_RUN); + await delay(500); + const attemptsPerPoll = watch.mock.calls.length; + expect(attemptsPerPoll).toBeGreaterThanOrEqual(1); + expect(attemptsPerPoll).toBeLessThanOrEqual(3); + await delay(500); + expect(watch).toHaveBeenCalledTimes(attemptsPerPoll); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + + for (const pollCount of [2, 3]) { + vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS); + await waitUntil( + () => watch.mock.calls.length > attemptsPerPoll * (pollCount - 1), + 'later poll did not retry the failed workflows directory' + ); + await delay(500); + expect(watch).toHaveBeenCalledTimes(attemptsPerPoll * pollCount); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + } + + watch.mockRestore(); + const recoveredWatch = vi.spyOn(fs, 'watch'); + vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS); + await waitUntil(() => recoveredWatch.mock.calls.length > 0, 'recovery poll did not install a watcher'); + // Let watcher setup and the recovery poll settle before creating the new completion file. + await delay(500); + expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]); + const otherId = 'wf_recovered5678-def'; + runWatcher.on('run_discovered', discovered); + await writeFile(join(workflowsDir, `${otherId}.json`), JSON.stringify({ ...sampleRunJson(), runId: otherId })); + // Do not advance the interval again: only the recovered watcher can discover this file. + await waitUntil(() => discovered.mock.calls.length > 0, 'recovered watcher did not discover the new run'); + expect(discovered).toHaveBeenCalledTimes(1); + const expectedRun = { ...EXPECTED_RUN, runId: otherId }; + expect(discovered).toHaveBeenCalledWith(expectedRun); + expect(runWatcher.getRun(otherId)).toEqual(expectedRun); + runWatcher.stop(); + await delay(100); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + } finally { + runWatcher.stop(); + runWatcher.off('run_discovered', discovered); + } + }); + + it('discovers a run with a healthy watcher without logging or unhandled rejections', async () => { + try { + const discovered = await firstRun(); + await delay(1000); + expect(discovered).toEqual(EXPECTED_RUN); + expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN); + expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]); + runWatcher.stop(); + await delay(100); + expect(warn).toHaveBeenCalledTimes(0); + expect(error).toHaveBeenCalledTimes(0); + expect(unhandled.length).toBe(0); + } finally { + runWatcher.stop(); + } + }); +}); From e0e2f689cf02d81ff459646223e2d835a8ea75b2 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Sun, 15 Nov 2026 18:38:25 +0100 Subject: [PATCH 02/52] feat(mobile): Send on Enter for the pinned CJK input field A per-device setting next to CJK Input keeps typed text in the pinned field until Enter instead of streaming it to the PTY, so a phone user can scroll the terminal and edit an answer before sending (Termux-style). One line goes as text + CR, several lines as one bracketed paste with a delayed Enter, like the prompt composer. Shift+Enter is a newline, Escape clears, Backspace on an empty field still reaches the PTY, and autocorrect is on in this mode. The field grows with its text and the keyboard layout reserves its real height. Co-Authored-By: Claude Opus 5.5 --- .changeset/cjk-send-on-enter.md | 5 + docs/wiki/Settings-Reference.md | 1 + src/web/public/app.js | 5 + src/web/public/index.html | 7 ++ src/web/public/input-cjk.js | 77 +++++++++++- src/web/public/mobile-handlers.js | 6 +- src/web/public/settings-ui.js | 7 +- test/input-cjk-hold.test.ts | 202 ++++++++++++++++++++++++++++++ 8 files changed, 307 insertions(+), 3 deletions(-) create mode 100644 .changeset/cjk-send-on-enter.md create mode 100644 test/input-cjk-hold.test.ts diff --git a/.changeset/cjk-send-on-enter.md b/.changeset/cjk-send-on-enter.md new file mode 100644 index 00000000..9241ef1f --- /dev/null +++ b/.changeset/cjk-send-on-enter.md @@ -0,0 +1,5 @@ +--- +"aicodeman": patch +--- + +Add a per-device "Send on Enter" mode for the pinned CJK input field, so phone users can scroll the terminal while a typed answer waits in the field until Enter. diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 821d6ab0..99d00430 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -48,6 +48,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service). | Local Echo | On for touch devices | Paints keystrokes locally and flushes on Enter. See [Input And Voice](Input-And-Voice). | | Keep Size Under Keyboard | On | For local Claude sessions, the on-screen keyboard no longer resizes the session: the terminal keeps its rows and the view scrolls so the prompt sits just above the keyboard. Resizing made Claude reprint its screen and drop transcript lines from history. Codex, Claude's fullscreen mode, remote and Docker sessions resize as before. See [Mobile Guide](Mobile-Guide). | | CJK Input | Off | IME composition through a dedicated text field. | +| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. Shift+Enter adds a line, Esc clears, autocorrect is on. | | Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. | | Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. | | Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. | diff --git a/src/web/public/app.js b/src/web/public/app.js index e2b4c68c..1f178c2a 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -4929,6 +4929,11 @@ class CodemanApp { document.body.classList.toggle('cjk-input-visible', !!showCjk); cjkEl.style.display = showCjk ? 'block' : 'none'; cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true'); + if (typeof CjkInput !== 'undefined') { + CjkInput.setHoldUntilEnter?.( + !!(settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false) + ); + } if (!showCjk) window.cjkActive = false; if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard(); } diff --git a/src/web/public/index.html b/src/web/public/index.html index 7d1d1430..4ce3de8b 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -2064,6 +2064,13 @@ +
+
+ Input Field: Send on Enter + With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode. +
+ +
Extended Keyboard Bar phone diff --git a/src/web/public/input-cjk.js b/src/web/public/input-cjk.js index 4f5420b7..89d7cccd 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -57,6 +57,10 @@ const CjkInput = (() => { let _dictationActive = false; let _dictationDecayTimer = null; let _printableKeydownAt = null; + // Send-on-Enter mode (setting cjkInputHoldUntilEnter): typed text stays in the + // field until Enter, like a chat box, instead of streaming to the PTY as it is + // typed. Lets a phone user scroll the terminal and edit an answer before sending. + let _hold = false; const _listeners = {}; const PHANTOM = '​'; @@ -189,6 +193,12 @@ const CjkInput = (() => { _t('flush SKIP composing'); return; } + // Send-on-Enter: nothing leaves the field until Enter (keydown handler). + if (_hold) { + _t('flush SKIP hold'); + _autoGrow(); + return; + } const val = _strip(_textarea.value); _t(`flush ${val ? 'send len=' + val.length : 'empty'}`); if (val) { @@ -197,6 +207,35 @@ const CjkInput = (() => { _resetToPhantom(); } + /** Send-on-Enter: grow the field with its content (up to the CSS max-height) + * and let the keyboard layout re-read its height. */ + function _autoGrow() { + if (!_textarea) return; + const before = _textarea.style.height; + _textarea.style.height = 'auto'; + _textarea.style.height = `${_textarea.scrollHeight}px`; + if (_textarea.style.height !== before && typeof KeyboardHandler !== 'undefined') { + KeyboardHandler.updateLayoutForKeyboard?.(); + } + } + + /** Send-on-Enter: deliver the held text as one prompt, then Enter. One line + * goes as typed text + CR in one write (what live mode's Enter sends, so CLI + * menus that answer to a digit keep working). Several lines go as one + * bracketed paste with Enter as a separate, delayed write, the same bytes as + * the mobile prompt composer (keyboard-accessory.js _sendComposedPrompt), so + * embedded newlines don't submit early. */ + function _sendHeld(val) { + if (!/\n/.test(val)) { + _send(val + '\r'); + return; + } + let text = val; + while (/\x1b\[20[01]~/.test(text)) text = text.replace(/\x1b\[20[01]~/g, ''); + _send(`\x1b[200~${text.replace(/\r?\n/g, '\r')}\x1b[201~`); + setTimeout(() => _send('\r'), 120); + } + /** Cancel any pending debounced flush */ function _cancelDebouncedFlush() { if (_flushTimer) { @@ -316,16 +355,25 @@ const CjkInput = (() => { _t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`); _printableKeydownAt = null; if (e.key === 'Enter') { + // Send-on-Enter: Shift+Enter (or an IME still composing) is a newline + // in the field, never a send. + if (_hold && (e.shiftKey || e.isComposing || e.keyCode === 229)) { + setTimeout(_autoGrow, 0); + return; + } e.preventDefault(); _composing = false; _cancelDebouncedFlush(); const val = _strip(_textarea.value); - if (val) { + if (_hold && val) { + _sendHeld(val); + } else if (val) { _send(val + '\r'); } else { _send('\r'); } _resetToPhantom(); + if (_hold) _autoGrow(); return; } @@ -334,6 +382,7 @@ const CjkInput = (() => { _composing = false; _cancelDebouncedFlush(); _resetToPhantom(); + if (_hold) _autoGrow(); return; } @@ -475,6 +524,32 @@ const CjkInput = (() => { _resetToPhantom(); }, + /** + * Send-on-Enter mode on or off (setting cjkInputHoldUntilEnter). On: text + * stays in the field until Enter and the browser's autocorrect is allowed, + * since nothing typed has reached the PTY yet. Off: the original live mode. + */ + setHoldUntilEnter(on) { + _hold = !!on; + if (!_textarea) return; + const v = _hold ? 'on' : 'off'; + _textarea.setAttribute('autocorrect', v); + _textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off'); + _textarea.setAttribute('spellcheck', _hold ? 'true' : 'false'); + _textarea.placeholder = _hold + ? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)' + : 'CJK input (Enter = send, Esc = clear)'; + if (_hold) { + _cancelDebouncedFlush(); + _autoGrow(); + } else { + _textarea.style.height = ''; + } + _t(`hold ${v}`); + }, + + get holdUntilEnter() { return _hold; }, + /** Diagnostic: recent IME event trace (ring buffer). */ getTrace() { return _trace.slice(); diff --git a/src/web/public/mobile-handlers.js b/src/web/public/mobile-handlers.js index e172683e..8e008dcd 100644 --- a/src/web/public/mobile-handlers.js +++ b/src/web/public/mobile-handlers.js @@ -455,7 +455,11 @@ const KeyboardHandler = { caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : ''; } if (main && keyboardHeight > 0) { - const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0; + // The field grows with its text in Send-on-Enter mode, so reserve its + // real height (44 = the one-line field plus its border, the old constant). + const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') + ? Math.max(44, cjkInput.offsetHeight + 10) + : 0; main.style.paddingBottom = `${84 + cjkInputHeight}px`; } } else if (keyboardHeight > 0) { diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index 8cd7a874..8a9f9c76 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -649,6 +649,8 @@ Object.assign(CodemanApp.prototype, { document.getElementById('appSettingsTerminalWheelLocal').checked = settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false; document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false; + document.getElementById('appSettingsCjkHoldUntilEnter').checked = + settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false; document.getElementById('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false; document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false; document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings); @@ -3195,6 +3197,7 @@ Object.assign(CodemanApp.prototype, { ), terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked, cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked, + cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked, webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked, extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked, tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked, @@ -3440,6 +3443,7 @@ Object.assign(CodemanApp.prototype, { // SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT. keyboardHoldsRows: _khr, cjkInputEnabled: _cjk, + cjkInputHoldUntilEnter: _cjkHold, extendedKeyboardBar: _ekb, skin: _skin, language: _language, @@ -4478,6 +4482,7 @@ Object.assign(CodemanApp.prototype, { sessionListLayout: 'header', sessionSidebarFontSize: 12, cjkInputEnabled: false, + cjkInputHoldUntilEnter: false, terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel webglRendererEnabled: false, // mobile always uses the DOM renderer skin: 'daylight-blue', @@ -5206,7 +5211,7 @@ Object.assign(CodemanApp.prototype, { 'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost', 'showLifecycleLog', 'showResponseViewer', 'showRedrawButton', 'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents', - 'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'extendedKeyboardBar', + 'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'cjkInputHoldUntilEnter', 'extendedKeyboardBar', 'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled', 'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold', 'language', diff --git a/test/input-cjk-hold.test.ts b/test/input-cjk-hold.test.ts new file mode 100644 index 00000000..5d59349c --- /dev/null +++ b/test/input-cjk-hold.test.ts @@ -0,0 +1,202 @@ +/** + * @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js, + * setting cjkInputHoldUntilEnter): typed text stays in the field until Enter, + * so a phone user can scroll the terminal and edit an answer before sending. + * + * Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also + * carries the attributes and style the mode touches. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const PHANTOM = '​'; + +function makeTextarea() { + const listeners = new Map void>>(); + const attrs: Record = {}; + return { + value: '', + placeholder: '', + style: { height: '' } as Record, + scrollHeight: 34, + attrs, + blur: () => {}, + focus: () => {}, + classList: { contains: (c: string) => c === 'cjk-input-visible' }, + setSelectionRange: () => {}, + setAttribute: (k: string, v: string) => { + attrs[k] = v; + }, + addEventListener: (ev: string, fn: (e?: unknown) => void) => { + listeners.set(ev, [...(listeners.get(ev) ?? []), fn]); + }, + removeEventListener: (ev: string, fn: (e?: unknown) => void) => { + listeners.set( + ev, + (listeners.get(ev) ?? []).filter((f) => f !== fn) + ); + }, + fire(ev: string, arg: Record = {}) { + const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg }; + for (const fn of listeners.get(ev) ?? []) fn(base); + }, + }; +} + +function load({ hold = true } = {}) { + const textarea = makeTextarea(); + const sent: string[] = []; + const layout = vi.fn(); + const context = vm.createContext({ + window: {}, + document: { getElementById: (id: string) => (id === 'cjkInput' ? textarea : null), activeElement: null }, + navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' }, + KeyboardHandler: { updateLayoutForKeyboard: layout }, + setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms), + clearTimeout: (t: ReturnType) => clearTimeout(t), + performance: { now: () => performance.now() }, + console, + }); + const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8'); + vm.runInContext(src, context, { filename: 'input-cjk.js' }); + const CjkInput = vm.runInContext('CjkInput', context); + CjkInput.init({ send: (t: string) => sent.push(t) }); + CjkInput.setHoldUntilEnter(hold); + textarea.fire('focus'); + return { CjkInput, textarea, sent, layout }; +} + +function type(textarea: ReturnType, text: string) { + textarea.value = PHANTOM + text; + textarea.fire('input', { isComposing: false, inputType: 'insertText' }); +} + +describe('CJK input: Send on Enter', () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] }); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it('keeps typed text in the field instead of streaming it', () => { + const { textarea, sent } = load(); + type(textarea, 'use Postgres'); + vi.advanceTimersByTime(5000); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM + 'use Postgres'); + }); + + it('keeps text after a physical keystroke (no zero-latency flush)', () => { + const { textarea, sent } = load(); + textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false }); + type(textarea, 'a'); + vi.advanceTimersByTime(1000); + expect(sent).toEqual([]); + }); + + it('keeps text across a composition cycle and autocorrect rewrites', () => { + const { textarea, sent } = load(); + textarea.fire('compositionstart'); + textarea.value = PHANTOM + 'teh'; + textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' }); + textarea.fire('compositionend'); + textarea.value = PHANTOM + 'the'; + textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' }); + vi.advanceTimersByTime(5000); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM + 'the'); + }); + + it('sends one line as text + CR on Enter, then clears the field', () => { + const { textarea, sent } = load(); + type(textarea, 'yes, use Postgres'); + const preventDefault = vi.fn(); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault }); + expect(preventDefault).toHaveBeenCalled(); + expect(sent).toEqual(['yes, use Postgres\r']); + expect(textarea.value).toBe(PHANTOM); + }); + + it('sends a digit as typed so CLI menus still answer to it', () => { + const { textarea, sent } = load(); + type(textarea, '2'); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent).toEqual(['2\r']); + }); + + it('sends several lines as one bracketed paste, Enter as a later write', () => { + const { textarea, sent } = load(); + type(textarea, 'line one\nline two'); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~']); + vi.advanceTimersByTime(150); + expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~', '\r']); + }); + + it('drops paste markers inside the held text', () => { + const { textarea, sent } = load(); + type(textarea, 'a\x1b[201~b\nc'); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent[0]).toBe('\x1b[200~ab\rc\x1b[201~'); + }); + + it('treats Shift+Enter as a newline, never a send', () => { + const { textarea, sent } = load(); + type(textarea, 'first'); + const preventDefault = vi.fn(); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault }); + vi.advanceTimersByTime(10); + expect(preventDefault).not.toHaveBeenCalled(); + expect(sent).toEqual([]); + }); + + it('sends a bare Enter when the field is empty (accepting a default answer)', () => { + const { textarea, sent } = load(); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent).toEqual(['\r']); + }); + + it('still forwards Backspace on an empty field to the PTY', () => { + const { textarea, sent } = load(); + textarea.fire('keydown', { key: 'Backspace', keyCode: 8 }); + expect(sent).toEqual(['\x7f']); + }); + + it('Escape clears the held text without sending', () => { + const { textarea, sent } = load(); + type(textarea, 'never mind'); + textarea.fire('keydown', { key: 'Escape', keyCode: 27 }); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM); + }); + + it('turns autocorrect on in the mode and back off without it', () => { + const { CjkInput, textarea } = load(); + expect(textarea.attrs.autocorrect).toBe('on'); + expect(textarea.attrs.spellcheck).toBe('true'); + CjkInput.setHoldUntilEnter(false); + expect(textarea.attrs.autocorrect).toBe('off'); + expect(textarea.attrs.spellcheck).toBe('false'); + expect(CjkInput.holdUntilEnter).toBe(false); + }); + + it('grows the field with its text and re-runs the keyboard layout', () => { + const { textarea, layout } = load(); + layout.mockClear(); + textarea.scrollHeight = 60; + type(textarea, 'a\nb\nc'); + vi.advanceTimersByTime(1000); + expect(textarea.style.height).toBe('60px'); + expect(layout).toHaveBeenCalled(); + }); + + it('live mode is unchanged: text streams after the debounce', () => { + const { textarea, sent } = load({ hold: false }); + type(textarea, 'hi'); + vi.advanceTimersByTime(1000); + expect(sent).toEqual(['hi']); + }); +}); From b8a44666439c45c99ae4f741159a013e8b939870 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Sun, 15 Nov 2026 18:42:59 +0100 Subject: [PATCH 03/52] docs(mobile): zh-CN strings and Input And Voice section for Send on Enter Co-Authored-By: Claude Opus 5.5 --- docs/wiki/Input-And-Voice.md | 6 ++++++ src/web/public/i18n.js | 3 +++ 2 files changed, 9 insertions(+) diff --git a/docs/wiki/Input-And-Voice.md b/docs/wiki/Input-And-Voice.md index d15e7864..2bbfb83a 100644 --- a/docs/wiki/Input-And-Voice.md +++ b/docs/wiki/Input-And-Voice.md @@ -67,6 +67,12 @@ below the terminal that owns composition, then delivers the composed text to the Ctrl- and Alt-modified navigation keys typed through it reach the CLI as the modified sequences, so word jumps and history keys keep working. +On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box: +typed text stays in it until Enter, so you can scroll the terminal back to a question and edit +your answer before sending. Shift+Enter adds a line, Esc clears the field, and autocorrect is on. +A one-line answer is sent as typed, so CLI menus that take a digit still work; several lines go +as one paste followed by Enter. + ## Voice dictation `Ctrl+Shift+V`, or the microphone button. There are three providers and the default is diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 923742fe..a85f1dfe 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -743,6 +743,9 @@ "For local Claude sessions, opening the on-screen keyboard keeps the session's size and scrolls the view instead, so Claude does not reprint its screen and lose transcript lines. Full-screen interfaces (Codex, Claude's fullscreen mode) are resized as before.": '对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。', 'CJK Input': '中日韩输入', + 'Input Field: Send on Enter': '输入框:按 Enter 发送', + 'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.': + '开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。', 'Extended Keyboard Bar': '扩展键盘栏', 'Gesture Control (beta)': '手势控制(测试版)', 'Wheel Scrolls Local History': '滚轮滚动本地历史', From c497869ee5ba6c62498c7a4b53fe4d55d03451d2 Mon Sep 17 00:00:00 2001 From: Aamer Akhter Date: Sun, 15 Nov 2026 15:06:07 -0500 Subject: [PATCH 04/52] fix(tmux): read a one-binding key table from the full listing A tmux built from master (`tmux -V`: next-3.7) prints nothing, exit 0, for `list-keys -T ` when the table holds exactly one binding. tmux 3.4 prints the line. One binding is the shape restrictTmuxPrefixTable leaves behind (` send-prefix`), so on that tmux the reduced table read as needing a reset and every session create reset it again. `codeman tui` read its prefix table the same way, so readPrefixBinding called a bound key free and readDetachKey found no detach key. A blank answer is now read from the full `list-keys` listing, keeping only that table's lines. The parsers already match on `-T
`. Tests: recorded-command cases for the blank answer (reduced table kept, stray binding still reset) and TuiClient cases for both reads. The real-tmux helper reads tables through the same fallback, and the escaped `C-\` check accepts the unescaped form the full listing prints. --- .changeset/tmux-one-binding-list-keys.md | 5 +++ docs/architecture-invariants.md | 2 +- src/tmux-prefix-table.ts | 10 +++++ src/tui/tui-client.ts | 19 +++++++-- test/tmux-prefix-table.test.ts | 52 ++++++++++++++++++++++-- test/tui/tui-client.test.ts | 32 +++++++++++++++ 6 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 .changeset/tmux-one-binding-list-keys.md diff --git a/.changeset/tmux-one-binding-list-keys.md b/.changeset/tmux-one-binding-list-keys.md new file mode 100644 index 00000000..10605ac6 --- /dev/null +++ b/.changeset/tmux-one-binding-list-keys.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +A tmux built from master (`next-3.7`) prints nothing for `list-keys -T prefix` when the prefix table holds exactly one binding, which is the shape Codeman reduces it to. Codeman then reset the already reduced table on every session create, and `codeman tui` read a bound key as free, so it could claim a key the user relies on. Both now read a blank answer from the full `list-keys` listing. tmux 3.4 is unchanged. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index e17a089b..7d8c5970 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -18,7 +18,7 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough ### The prefix table on Codeman's socket holds only send-prefix -**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. +**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to ` send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): a tmux built from master (`next-3.7`) prints nothing for `list-keys -T
` when the table holds exactly one binding, which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C- detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`. ### Reverse-proxy base path diff --git a/src/tmux-prefix-table.ts b/src/tmux-prefix-table.ts index 3af1d7da..3e452179 100644 --- a/src/tmux-prefix-table.ts +++ b/src/tmux-prefix-table.ts @@ -153,6 +153,16 @@ export function restrictTmuxPrefixTable(tmux: string, run: TmuxRunner = defaultR let listing: string | null; try { listing = run(`${tmux} list-keys -T prefix`); + // ⚠️ Some tmux builds (a `next-3.7` development build) print NOTHING for + // `list-keys -T prefix` when the table holds exactly one binding, which is the + // shape this function leaves behind: read blank as "ask the full listing" and keep + // only its prefix-table lines, or every call would reset an already-reduced table. + if (!listing.trim()) { + listing = run(`${tmux} list-keys`) + .split('\n') + .filter((line) => PREFIX_LINE.test(line.trim())) + .join('\n'); + } } catch { listing = null; // an empty table makes list-keys fail on some tmux builds } diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index dcfa0efc..7f72070a 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -991,6 +991,19 @@ export class TuiClient { return null; } + /** + * One key table as `list-keys` prints it. ⚠️ Some tmux builds (seen on a `next-3.7` + * development build) print NOTHING for `list-keys -T
` when the table holds + * exactly one binding, which is the shape Codeman reduces the prefix table to. So a + * blank answer is retried as the full listing: every line there names its table, + * and both parsers already filter on it. + */ + private async listKeyTable(table: TuiKeyTable): Promise { + const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]); + if (stdout.trim()) return stdout; + return (await this.exec('tmux', ['-L', this.socket, 'list-keys'])).stdout; + } + /** * The key that detaches, straight from tmux's own key table. Key tables are * server-global, so unlike the prefix this takes no session. A failure is @@ -998,8 +1011,7 @@ export class TuiClient { */ async readDetachKey(): Promise { try { - const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', 'prefix']); - return parseDetachKey(stdout); + return parseDetachKey(await this.listKeyTable('prefix')); } catch { return null; } @@ -1012,8 +1024,7 @@ export class TuiClient { */ async readPrefixBinding(key: string, table: TuiKeyTable = 'prefix'): Promise { try { - const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]); - return parsePrefixBinding(stdout, key, table); + return parsePrefixBinding(await this.listKeyTable(table), key, table); } catch { return null; } diff --git a/test/tmux-prefix-table.test.ts b/test/tmux-prefix-table.test.ts index 6d497f12..472a4e9b 100644 --- a/test/tmux-prefix-table.test.ts +++ b/test/tmux-prefix-table.test.ts @@ -115,6 +115,32 @@ describe('restrictTmuxPrefixTable (recorded commands)', () => { expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false); expect(tmux.calls.filter((c) => c.includes('bind-key'))).toEqual([]); }); + + it('reads a one-binding table from the full listing when `list-keys -T prefix` prints nothing', () => { + // A tmux `next-3.7` build lists a table holding exactly one binding as nothing at + // all. The reduced table must still read as reduced, or every call resets it. + const tmux = fakeTmux({ + 'show-options -gv prefix': 'C-b\n', + 'list-keys -T prefix': '', + 'list-keys': + 'bind-key -T copy-mode C-a send-keys -X start-of-line\n' + + 'bind-key -T prefix C-b send-prefix\n' + + 'bind-key -T root F1 detach-client\n', + }); + expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false); + expect(tmux.calls).toContain(`tmux -L 'codeman' list-keys`); + expect(tmux.calls.filter((c) => c.includes('bind-key') || c.includes('unbind-key'))).toEqual([]); + }); + + it('still resets when the full listing shows a stock prefix binding', () => { + const tmux = fakeTmux({ + 'show-options -gv prefix': 'C-b\n', + 'list-keys -T prefix': '', + 'list-keys': 'bind-key -T prefix ) switch-client -n\n', + }); + expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(true); + expect(tmux.calls).toContain(`tmux -L 'codeman' unbind-key -a -T prefix`); + }); }); const hasTmux = (() => { @@ -126,12 +152,29 @@ const hasTmux = (() => { } })(); +/** + * One key table as `list-keys -T
` prints it. Some tmux builds (a `next-3.7` + * development build) print NOTHING there when the table holds exactly one binding, + * which is the shape every reset in this file produces, so a blank answer is read from + * the full listing instead, its padding folded to the `-T
` form. + */ +function listKeyTable(base: string, table: string): string { + const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + const direct = run(`${base} list-keys -T ${table}`); + if (direct.trim()) return direct; + return run(`${base} list-keys`) + .split('\n') + .filter((line) => new RegExp(`^bind-key\\s+(?:-\\S+\\s+)*?-T\\s+${table}\\s`).test(line.trim())) + .map((line) => line.trim().replace(/-T\s+(\S+)\s+/, '-T $1 ')) + .join('\n'); +} + describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private socket)', () => { // Throwaway server, never Codeman's socket; -f /dev/null keeps the user's config out. const socket = `codeman-prefix-test-${process.pid}`; const tmux = `tmux -L ${socket} -f /dev/null`; const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); - const keys = (table: string) => run(`${tmux} list-keys -T ${table}`); + const keys = (table: string) => listKeyTable(tmux, table); let client: pty.IPty | null = null; /** The session the attach client is looking at right now. */ @@ -275,7 +318,8 @@ describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private run(`${tmux} set-option -g prefix 'C-\\'`); try { expect(restrictTmuxPrefixTable(tmux, run)).toBe(true); - expect(keys('prefix')).toMatch(/-T prefix C-\\\\\s+send-prefix/); + // `list-keys -T` escapes the key (`C-\\`); the full listing some builds fall back to does not. + expect(keys('prefix')).toMatch(/-T prefix C-\\(?:\\)?\s+send-prefix/); expect(restrictTmuxPrefixTable(tmux, run)).toBe(false); } finally { run(`${tmux} set-option -g prefix C-b`); @@ -345,7 +389,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke it('after the nested reset, Ctrl+Q ), s and w leave the client, and Ctrl+Q Ctrl+Q reaches the pane', async () => { for (const command of nestedPrefixTableResetCommands()) run(`${tmux} ${command}`); - const prefix = run(`${tmux} list-keys -T prefix`) + const prefix = listKeyTable(tmux, 'prefix') .split('\n') .filter((line) => line.trim()); expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]); @@ -381,7 +425,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke ].join(' \\; '); try { run(`${base} -f ${config} ${chain}`); - const prefix = run(`${base} list-keys -T prefix`) + const prefix = listKeyTable(base, 'prefix') .split('\n') .filter((line) => line.trim()); expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]); diff --git a/test/tui/tui-client.test.ts b/test/tui/tui-client.test.ts index ce1c39d1..1239f937 100644 --- a/test/tui/tui-client.test.ts +++ b/test/tui/tui-client.test.ts @@ -1015,3 +1015,35 @@ describe('resumeSession', () => { expect(recorded).toHaveLength(1); }); }); + +describe('TuiClient key-table reads on a tmux that lists a one-binding table as nothing', () => { + // A tmux `next-3.7` build prints nothing for `list-keys -T prefix` when the table + // holds exactly one binding, which is how Codeman leaves it. Reading that as "free" + // would let the TUI claim a key the user has bound. + const fullListing = + 'bind-key -T copy-mode C-a send-keys -X start-of-line\n' + + 'bind-key -T prefix C-b send-prefix\n' + + 'bind-key -T root F1 detach-client\n'; + function client(direct: string) { + const calls: string[][] = []; + const exec = async (_file: string, args: readonly string[]) => { + calls.push([...args]); + return { stdout: args.includes('-T') ? direct : fullListing, stderr: '' }; + }; + return { tui: new TuiClient({ socket: 'cod563', exec }), calls }; + } + + it('falls back to the full listing when the table answer is blank', async () => { + const { tui, calls } = client(''); + expect(await tui.readPrefixBinding('C-b')).toBe('send-prefix'); + expect(await tui.readPrefixBinding('F1', 'root')).toBe('detach-client'); + expect(await tui.readPrefixBinding('x')).toBeNull(); + expect(calls.some((args) => args.length === 3 && args[2] === 'list-keys')).toBe(true); + }); + + it('keeps the table answer when there is one, with no second call', async () => { + const { tui, calls } = client('bind-key -T prefix d detach-client\n'); + expect(await tui.readDetachKey()).toBe('d'); + expect(calls).toEqual([['-L', 'cod563', 'list-keys', '-T', 'prefix']]); + }); +}); From 0e913eedf24a698d3e92773ebe6ae27138640508 Mon Sep 17 00:00:00 2001 From: Aamer Akhter Date: Sun, 15 Nov 2026 15:09:20 -0500 Subject: [PATCH 05/52] fix(docker): bound Start-Codeman.sh's port probe to about a second port_in_use() connected with bash's /dev/tcp and waited for the answer. A listening port answers at once and a closed one is normally refused at once, but on WSL a connect to a closed 127.0.0.1 port is dropped and only fails at the kernel's connect timeout, minutes later (measured: still waiting after 10 s; ::1 is refused at once). The first-run port search tries up to 100 ports from 3000 and the start path checks the chosen port again, so a first run on WSL stalled. Each connect now runs in a background subshell that port_answers() waits on for at most 20 x 50 ms, then kills; no answer in time reads as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`. Test: a python3 listener with a full accept queue (Linux drops further SYNs, the same no-answer a WSL closed port gives) must be given up on within 3 s; a listening port and a closed one still answer at once. With the old unbounded connect the first test fails at its 10 s cap. --- .changeset/start-codeman-port-probe.md | 5 ++ docker/Start-Codeman.sh | 23 ++++++++- test/docker-start-setup.test.ts | 69 ++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 .changeset/start-codeman-port-probe.md diff --git a/.changeset/start-codeman-port-probe.md b/.changeset/start-codeman-port-probe.md new file mode 100644 index 00000000..c86dcd36 --- /dev/null +++ b/.changeset/start-codeman-port-probe.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +`docker/Start-Codeman.sh` no longer hangs on WSL while it looks for a free port. On WSL a connect to a closed 127.0.0.1 port is dropped rather than refused and only fails at the kernel's connect timeout, so the first-run port search (up to 100 ports) and the check before `docker compose up` could stall for many minutes. Each port check now gives up after about a second and reads no answer as free. diff --git a/docker/Start-Codeman.sh b/docker/Start-Codeman.sh index 9f94c058..68f573b4 100644 --- a/docker/Start-Codeman.sh +++ b/docker/Start-Codeman.sh @@ -156,10 +156,31 @@ ask() { fi } +# True when host $1 accepts a connection on port $2 within about a second. +# A listening port answers at once and a closed one is normally refused at +# once, but on WSL a connect to a closed 127.0.0.1 port is dropped and only +# fails at the kernel's connect timeout, minutes later. No answer in time +# reads as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`. +port_answers() { + local pid tries=0 + (exec 3<>"/dev/tcp/$1/$2") 2>/dev/null & + pid=$! + while kill -0 "$pid" 2>/dev/null; do + if ((tries >= 20)); then + kill "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + return 1 + fi + tries=$((tries + 1)) + sleep 0.05 + done + wait "$pid" +} + # True when something on this host already accepts connections on the port. # bash's /dev/tcp needs no extra tool on Linux or macOS. port_in_use() { - (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null || (exec 3<>"/dev/tcp/::1/$1") 2>/dev/null + port_answers 127.0.0.1 "$1" || port_answers ::1 "$1" } first_free_port() { diff --git a/test/docker-start-setup.test.ts b/test/docker-start-setup.test.ts index 045a6de8..ecfee7b9 100644 --- a/test/docker-start-setup.test.ts +++ b/test/docker-start-setup.test.ts @@ -639,3 +639,72 @@ describe('version_older_than', () => { expect(out).toBe(older ? 'yes' : 'no'); }); }); + +/** + * A listener whose accept queue is full, so the kernel drops further SYNs and a + * connect to it gets no answer, the same thing a WSL host does for a CLOSED + * 127.0.0.1 port. Held by a python3 child, since Node accepts every connection + * as it arrives and so can never leave its own queue full. + */ +const HAS_PYTHON = spawnSync('python3', ['-c', 'pass']).status === 0; +const SILENT_LISTENER = [ + 'import socket, sys, time', + 's = socket.socket(); s.bind(("127.0.0.1", 0)); s.listen(0)', + 'port = s.getsockname()[1]; held = []', + 'for _ in range(3):', + ' c = socket.socket(); c.setblocking(False)', + ' try: c.connect(("127.0.0.1", port))', + ' except BlockingIOError: pass', + ' held.append(c)', + 'time.sleep(0.3); print(port, flush=True); time.sleep(60)', +].join('\n'); + +describe.skipIf(process.platform !== 'linux' || !HAS_PYTHON)('port_answers', () => { + /** Runs the script's own port_answers on host/port, returning its status and how long it took. */ + function probe(host: string, port: number): { status: number | null; ms: number } { + const script = [ + 'set -euo pipefail', + `eval "$(sed -n '/^port_answers() {/,/^}/p' "$1")"`, + 'if port_answers "$2" "$3"; then exit 0; else exit 1; fi', + ].join('\n'); + const started = Date.now(); + const res = spawnSync('bash', ['-c', script, '_', join(ROOT, 'docker/Start-Codeman.sh'), host, String(port)], { + encoding: 'utf-8', + timeout: 10_000, + }); + return { status: res.status, ms: Date.now() - started }; + } + + it('gives up on a connect that gets no answer within about a second, and reads it as free', async () => { + const { spawn } = await import('node:child_process'); + const child = spawn('python3', ['-I', '-c', SILENT_LISTENER], { stdio: ['ignore', 'pipe', 'ignore'] }); + try { + const port = await new Promise((resolve, reject) => { + child.stdout!.once('data', (chunk: Buffer) => resolve(Number(String(chunk).trim()))); + child.once('exit', () => reject(new Error('listener exited'))); + }); + const { status, ms } = probe('127.0.0.1', port); + expect(status).toBe(1); + expect(ms).toBeLessThan(3000); + } finally { + child.kill(); + } + }); + + it('still answers at once for a listening port and a closed one', async () => { + const net = await import('node:net'); + const server = net.createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const port = (server.address() as { port: number }).port; + try { + const open = probe('127.0.0.1', port); + expect(open.status).toBe(0); + expect(open.ms).toBeLessThan(1000); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + const closed = probe('::1', port); + expect(closed.status).toBe(1); + expect(closed.ms).toBeLessThan(1000); + }); +}); From 9304f98efbd2c16d72402f240e813cd80cd5bcb9 Mon Sep 17 00:00:00 2001 From: Ludo Fourrage Date: Sun, 15 Nov 2026 14:56:33 -0800 Subject: [PATCH 06/52] fix(header): the CPU reading shows CPU use, not the load average per core The header's CPU figure was the 1-minute load average divided by the core count, capped at 100. Load counts runnable tasks, not busy time, so a host with bursty processes, or a VM whose vCPU threads count as runnable, read 100% while most cores were idle. It is now busy time across all cores since the previous reading, from os.cpus(), with a one-second minimum window on the monotonic clock. Co-Authored-By: Claude Opus 5.5 --- .changeset/header-cpu-use.md | 5 +++ src/cpu-usage.ts | 52 ++++++++++++++++++++++ src/web/routes/system-routes.ts | 10 +++-- test/cpu-usage.test.ts | 77 +++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 .changeset/header-cpu-use.md create mode 100644 src/cpu-usage.ts create mode 100644 test/cpu-usage.test.ts diff --git a/.changeset/header-cpu-use.md b/.changeset/header-cpu-use.md new file mode 100644 index 00000000..48ef904b --- /dev/null +++ b/.changeset/header-cpu-use.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +The header CPU reading shows CPU use: busy time across all cores since the previous reading, from `os.cpus()`. It used to show the 1-minute load average divided by the core count, capped at 100, which counts runnable tasks rather than busy time. A host with bursty short-lived processes, or with a VM whose vCPU threads count as runnable, read 100% while most of its cores were idle. Readings under a second apart reuse the last value, so several open browsers share one window. The load-average figure remains only as a fallback for a platform that reports no core times. diff --git a/src/cpu-usage.ts b/src/cpu-usage.ts new file mode 100644 index 00000000..03a8d93a --- /dev/null +++ b/src/cpu-usage.ts @@ -0,0 +1,52 @@ +/** + * @fileoverview The header CPU reading: CPU use over all cores since the previous reading, from each core's + * busy and idle time as `os.cpus()` reports it (the kernel's per-core counters on Linux, macOS and Windows). + * + * It replaces the 1-minute load average divided by the core count. Load counts runnable tasks, not busy time, + * so a host with bursty short-lived processes, or a VM whose vCPU threads count as runnable, read 100% while + * most of its cores were idle. + */ +import type { CpuInfo } from 'node:os'; + +/** Readings closer together than this reuse the last value, so several open browsers never shrink the window. */ +export const CPU_USAGE_MIN_WINDOW_MS = 1000; + +interface CpuTimes { + busy: number; + total: number; + at: number; +} + +/** + * A meter that answers the CPU use, 0 to 100, between this reading and the previous one. Without usable core + * times (none reported, or counters that went backwards, as when a core goes offline) it answers the last + * reading, else `fallback()`. The first reading covers the time since the meter was created. + */ +export function createCpuUsageMeter( + readCores: () => Pick[], + clock: () => number, + fallback: () => number +): () => number { + const sample = (): CpuTimes => { + let busy = 0; + let total = 0; + for (const { times } of readCores()) { + const all = times.user + times.nice + times.sys + times.idle + times.irq; + total += all; + busy += all - times.idle; + } + return { busy, total, at: clock() }; + }; + let base = sample(); + let last: number | undefined; + return () => { + const now = sample(); + if (last !== undefined && now.at - base.at < CPU_USAGE_MIN_WINDOW_MS) return last; + const busy = now.busy - base.busy; + const total = now.total - base.total; + base = now; + if (!(total > 0) || busy < 0) return last ?? fallback(); + last = Math.min(100, Math.max(0, Math.round((busy / total) * 100))); + return last; + }; +} diff --git a/src/web/routes/system-routes.ts b/src/web/routes/system-routes.ts index 560155b1..8b8851c9 100644 --- a/src/web/routes/system-routes.ts +++ b/src/web/routes/system-routes.ts @@ -14,6 +14,7 @@ import { execSync, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { dataPath } from '../../config/instance.js'; import { readHostSensors } from '../../host-sensors.js'; +import { createCpuUsageMeter } from '../../cpu-usage.js'; import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } from '../../types.js'; import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js'; import { isMultiUserMode } from '../../config/multiuser.js'; @@ -93,6 +94,11 @@ const SCREENSHOTS_DIR = dataPath('screenshots'); /** Cached CPU count — doesn't change at runtime */ const CPU_COUNT = cpus().length; +/** Header CPU use; the 1-minute load average per core only when the platform reports no core times. */ +const cpuUsagePercent = createCpuUsageMeter(cpus, () => performance.now(), () => + Math.min(100, Math.round((loadavg()[0] / CPU_COUNT) * 100)) +); + function parseOptionalNumber(value: string | undefined): number | undefined { if (value === undefined || value.trim() === '') return undefined; const parsed = Number(value); @@ -125,9 +131,7 @@ function getSystemStats(): { usedMem = totalMem - freemem(); } - // CPU load average (1 min) as percentage (rough approximation) - const load = loadavg()[0]; - const cpuPercent = Math.min(100, Math.round((load / CPU_COUNT) * 100)); + const cpuPercent = cpuUsagePercent(); return { cpu: cpuPercent, diff --git a/test/cpu-usage.test.ts b/test/cpu-usage.test.ts new file mode 100644 index 00000000..e6818663 --- /dev/null +++ b/test/cpu-usage.test.ts @@ -0,0 +1,77 @@ +/** + * @fileoverview The header CPU reading's meter: busy time over all cores between readings, the minimum window + * that keeps several browsers from shrinking it, and the fallback when no usable core times exist. + */ +import { describe, expect, it } from 'vitest'; +import { createCpuUsageMeter } from '../src/cpu-usage.js'; + +const core = (busy: number, idle: number) => ({ times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } }); + +function meterOver(samples: ReturnType[][], fallback = () => 999) { + let at = 0; + let index = 0; + const meter = createCpuUsageMeter( + () => samples[Math.min(index, samples.length - 1)], + () => at, + fallback + ); + return (ms: number) => { + at += ms; + index += 1; + return meter(); + }; +} + +describe('createCpuUsageMeter', () => { + it('reports busy time over all cores between readings', () => { + const next = meterOver([ + [core(0, 0), core(0, 0)], + [core(50, 50), core(50, 50)], + [core(150, 50), core(50, 150)], + ]); + expect(next(2000)).toBe(50); + expect(next(2000)).toBe(50); + }); + + it('counts nice, system and interrupt time as busy', () => { + const times = (user: number, nice: number, sys: number, irq: number, idle: number) => ({ + times: { user, nice, sys, idle, irq }, + }); + const meter = createCpuUsageMeter( + (() => { + let calls = 0; + return () => [calls++ === 0 ? times(0, 0, 0, 0, 0) : times(10, 20, 30, 15, 25)]; + })(), + (() => { + let at = 0; + return () => (at += 2000); + })(), + () => 999 + ); + expect(meter()).toBe(75); + }); + + it('reads idle cores as idle however long the run queue is', () => { + expect(meterOver([[core(0, 0)], [core(40, 60)]])(5000)).toBe(40); + }); + + it('reuses the last value for readings under a second apart and keeps the baseline', () => { + const next = meterOver([[core(0, 0)], [core(30, 70)], [core(30, 170)], [core(130, 170)]]); + expect(next(2000)).toBe(30); + expect(next(200)).toBe(30); + expect(next(2000)).toBe(50); + }); + + it('falls back without a bogus reading when there are no core times or the counters go backwards', () => { + expect(meterOver([[], []], () => 7)(2000)).toBe(7); + const next = meterOver([[core(100, 100)], [core(10, 10)], [core(60, 60)]], () => 7); + expect(next(2000)).toBe(7); + expect(next(2000)).toBe(50); + }); + + it('answers a whole number from 0 to 100', () => { + expect(meterOver([[core(0, 0)], [core(2, 1)]])(2000)).toBe(67); + expect(meterOver([[core(0, 0)], [core(0, 9)]])(2000)).toBe(0); + expect(meterOver([[core(0, 0)], [core(9, 0)]])(2000)).toBe(100); + }); +}); From 0b3087918fe431c8060de7f561722bf577575198 Mon Sep 17 00:00:00 2001 From: ArizeSky <97787713+ArizeSky@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:26:12 +0800 Subject: [PATCH 07/52] fix(deepseek): make the Harness web tab render, not just authenticate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `dsh web` gates its own index behind a per-process launch token it prints on boot, and only that URL mints the `dsh-auth-*` cookie every later request needs. The managed tab stores the clean URL, so nothing on the browser side could present the token: the iframe rendered dsh's 401 text, a blank tab. Read the token out of the captured boot output, trade it for the cookie once at startup (`redirect: 'manual'`, since the 303 is what carries Set-Cookie), and let the proxy present it on both the HTTP and WebSocket legs. Scoped to the exact loopback authority the cookie was minted for; a token-less banner (an older dsh) keeps the previous behaviour untouched. The banner is scanned on its own 256 KB budget rather than the 16 KB error-tail buffer: a chatty profile can fill that cap before the banner prints. Authentication alone was not enough. dsh ships ``, which a browser resolves against the DOCUMENT url — and the proxy's runtime shim rewrites that url to strip the `/webview//` prefix. The base therefore landed on Codeman's root: every module script 404'd and the page painted its inline `#151517` background with nothing on it (the black screen that replaced the white one). `rewriteHtml` now resolves a relative base against the proxy prefix before the mask can run, leaving a cross-origin base exactly as written. Verified against dsh 0.2.1-rc.5 and a live Codeman build: bare GET 401, captured cookie 200, proxied `/api` WebSocket 101, and a headless-Chrome load of the proxied tab boots the full Harness UI with no console errors. --- .changeset/dsh-web-launch-token.md | 5 + .changeset/webview-relative-base.md | 5 + docs/deepseek-integration.md | 12 +++ src/deepseek-web-server.ts | 160 +++++++++++++++++++++++++++- src/web/routes/webview-routes.ts | 36 ++++++- src/web/webview-proxy.ts | 67 +++++++++++- test/deepseek-web-server.test.ts | 158 ++++++++++++++++++++++++++- test/webview-proxy.test.ts | 40 +++++++ 8 files changed, 474 insertions(+), 9 deletions(-) create mode 100644 .changeset/dsh-web-launch-token.md create mode 100644 .changeset/webview-relative-base.md diff --git a/.changeset/dsh-web-launch-token.md b/.changeset/dsh-web-launch-token.md new file mode 100644 index 00000000..6fc62748 --- /dev/null +++ b/.changeset/dsh-web-launch-token.md @@ -0,0 +1,5 @@ +--- +"aicodeman": patch +--- + +The DeepSeek Harness web tab opens on the dashboard again instead of a blank 401 page. `dsh web` now gates its own index behind a one-time launch token it prints on boot; the supervisor reads that token out of the captured output, trades it for the session cookie once at startup, and the webview proxy presents the cookie on both the HTTP and WebSocket legs — scoped to the loopback authority it was minted for. A dsh without the gate keeps working unchanged. diff --git a/.changeset/webview-relative-base.md b/.changeset/webview-relative-base.md new file mode 100644 index 00000000..1698d9ec --- /dev/null +++ b/.changeset/webview-relative-base.md @@ -0,0 +1,5 @@ +--- +"aicodeman": patch +--- + +Web tabs whose dashboard ships a relative `` render again. The proxy rewrites the document URL to strip its `/webview//` prefix, and a relative base is resolved against that URL — so `./` (what Vite builds emit, DeepSeek Harness among them) pointed at Codeman's root: every module script 404'd and the page painted its background with nothing on it. The rewrite now resolves such a base against the proxy prefix before the mask runs; a cross-origin base is left exactly as the author wrote it. diff --git a/docs/deepseek-integration.md b/docs/deepseek-integration.md index 02af1002..834054c7 100644 --- a/docs/deepseek-integration.md +++ b/docs/deepseek-integration.md @@ -288,6 +288,18 @@ dsh fences its `/api` behind a browser-trust check on the request authority, and Codeman web tab reaches it through Codeman's own origin via the webview proxy, not directly. Without it the page renders and every API call fails. +Since dsh's browser-auth gate, the index is not public either: boot prints +`dsh web: http://127.0.0.1:/?token=` and only a request +carrying that token is answered with the `dsh-auth-*` cookie that authorizes +everything after it. The saved tab deliberately keeps the clean URL, so the +browser can never present that token, and the tab used to open on dsh's 401 page. +`src/deepseek-web-server.ts` now reads the token out of the captured boot output, +trades it for the cookie once at startup, and `webview-routes.ts` presents that +cookie on both the HTTP and WebSocket legs — scoped to the exact loopback +authority it was minted for, so a repointed or stale tab cannot carry it +elsewhere. A dsh without the gate prints a token-less banner and keeps working +unchanged. + ## 7. Docker and remote cases Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui` diff --git a/src/deepseek-web-server.ts b/src/deepseek-web-server.ts index 78dbf961..7520fb4f 100644 --- a/src/deepseek-web-server.ts +++ b/src/deepseek-web-server.ts @@ -27,6 +27,11 @@ * - **Failures reported, not swallowed.** The shell tab used to be where the * stack trace landed. With no tab, the spawn's own output is captured and * handed back to the caller instead. + * - **The launch token traded, not forwarded.** `dsh web` gates its own index + * behind a one-time token it prints on stdout and exchanges for a browser + * cookie. The tab stores a clean URL, so nothing on the browser side could + * ever present that token and every load answered 401. This module trades it + * here, once, and hands the cookie to the proxy (`getDeepSeekWebCookie`). */ import { spawn, type ChildProcess } from 'node:child_process'; @@ -53,6 +58,23 @@ const READY_POLL_MS = 400; const KILL_GRACE_MS = 3_000; /** Bound on captured child output, so a chatty boot cannot grow without limit. */ const OUTPUT_CAP = 16_384; +/** + * Bound on the boot-output window searched for the launch banner. + * + * Deliberately larger and separate from {@link OUTPUT_CAP}: that one only has to + * keep an error tail, while this one must survive a chatty plugin tree's boot + * logs long enough to see a banner printed after them. 256 KB of one-line output + * is far beyond anything a real boot prints, and a bound still exists because a + * wedged child can print forever. + */ +const BANNER_SCAN_CAP = 262_144; + +/** How long boot waits for `dsh web` to print the launch URL it gates itself on. */ +const LAUNCH_URL_WAIT_MS = 4_000; +/** Bound on the one-shot token→cookie exchange (loopback, so this is generous). */ +const TOKEN_EXCHANGE_TIMEOUT_MS = 5_000; +/** Cookie name `dsh web` mints for a browser session that presented the token. */ +const DSH_AUTH_COOKIE_PREFIX = 'dsh-auth-'; export interface DeepSeekWebStatus { running: boolean; @@ -67,6 +89,18 @@ interface RunningServer { port: number; authority: string; output: () => string; + /** + * Boot output scanned for the launch banner, on its own (larger) budget than + * `output`. Read through this rather than `output` so a banner printed after + * the error-tail cap filled is still found. + */ + banner: () => string; + /** + * The `dsh-auth-*` cookie bought with this process's launch token, once the + * exchange succeeded. Null on a dsh old enough to serve its index without a + * token, which is why "no cookie" is not a startup failure. + */ + cookie: string | null; } let current: RunningServer | null = null; @@ -105,6 +139,101 @@ async function answersHttp(port: number): Promise { } } +/** + * The authenticated URL `dsh web` prints once it is up. + * + * Its browser-auth gate made the index private: boot writes + * `dsh web: http://127.0.0.1:/?token=` and only a request + * carrying that token is answered with the cookie that authorizes everything + * after it. The token is per process, so it can be neither guessed nor carried + * across restarts — it has to be read out of the boot output. + * + * Null for output without one, which is the older-dsh case and stays working. + * + * @param output - captured stdout+stderr so far. + * @returns absolute http(s) URL carrying a `token`, or null. + */ +export function parseLaunchUrl(output: string): string | null { + // Strip SGR sequences first: a coloured banner would otherwise hide the URL + // behind escape codes and turn a perfectly working server into a 401. Built + // from the code point rather than written as `\x1b` so the linter's + // no-control-regex rule does not read it as an accidental control character. + const plain = output.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'), ''); + const match = /dsh web:\s*(\S+)/.exec(plain); + if (!match) return null; + let url: URL; + try { + url = new URL(match[1]); + } catch { + return null; + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + return url.searchParams.get('token') ? url.href : null; +} + +/** + * Trade the launch URL for the `dsh-auth-*` cookie the proxy will present. + * + * `redirect: 'manual'` is load-bearing: the 303 is the response that carries + * `Set-Cookie`, and following it would burn the token on a redirect to `./` + * while dropping the only credential the exchange produces. + * + * @param launchUrl - token-bearing URL from {@link parseLaunchUrl}. + * @returns `name=value` pair ready for a Cookie header, or null. + */ +async function exchangeLaunchToken(launchUrl: string): Promise { + try { + const response = await fetch(launchUrl, { + redirect: 'manual', + signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS), + }); + for (const header of response.headers.getSetCookie()) { + const pair = header.split(';', 1)[0]?.trim(); + if (pair?.startsWith(DSH_AUTH_COOKIE_PREFIX)) return pair; + } + return null; + } catch { + return null; + } +} + +/** + * Wait for the banner, then exchange it. + * + * Never fails startup: a dsh without the gate prints a token-less banner, which + * is answered as "nothing to exchange" immediately rather than after the whole + * wait, and a gate that changes shape must not turn a serving UI into a boot + * failure. + * + * @param running - the just-started server, read for its captured output. + * @returns the cookie to hand the proxy, or null. + */ +async function captureSessionCookie(running: RunningServer): Promise { + const deadline = Date.now() + LAUNCH_URL_WAIT_MS; + while (Date.now() < deadline) { + const banner = running.banner(); + const launchUrl = parseLaunchUrl(banner); + if (launchUrl) { + const cookie = await exchangeLaunchToken(launchUrl); + // The URL is a credential: never log it, only the fact that it did not work. + if (!cookie) { + console.warn( + '[DeepSeek web] the launch token was printed but could not be exchanged for a session cookie; ' + + "the tab will show dsh's 401 page until `dsh web` is restarted" + ); + } + return cookie; + } + // Only a printed http(s) URL settles this: it is the older dsh, which needs + // no cookie. Any other line carrying the prefix (a diagnostic, a truncated + // write) is not a banner, so the wait continues instead of giving up early. + const printed = /dsh web:\s*(\S+)/.exec(banner)?.[1]; + if (printed && /^https?:\/\//.test(printed)) return null; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + return null; +} + /** * Signal the whole process group. * @@ -134,6 +263,22 @@ export function getDeepSeekWebStatus(): DeepSeekWebStatus { }; } +/** + * The cookie this server's launch token bought, for the proxy to present. + * + * Keyed by `port` because the cookie is signed for the authority it was minted + * under (`127.0.0.1:`): handing it to a web tab pointed at some other + * server would neither authenticate nor be that server's to receive. Null also + * covers a dsh old enough to need no cookie at all. + * + * @param port - loopback port the upstream request is bound for. + * @returns `name=value` cookie pair, or null. + */ +export function getDeepSeekWebCookie(port: number): string | null { + if (!current || current.port !== port) return null; + return current.cookie; +} + /** Stop the background server, if one is running. Safe to call when none is. */ export async function stopDeepSeekWeb(): Promise { const running = current; @@ -223,8 +368,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis // The pipes must be drained whether or not anyone reads them: a full pipe // blocks the child. Storage is capped; draining is not. let output = ''; + // Scanned for the launch banner separately from `output`. That cap exists to + // bound the error tail, and a chatty profile can fill it before the banner is + // printed — losing the banner there produces exactly the 401 tab this module + // exists to prevent, so the two buffers must not share a limit. + let banner = ''; const capture = (chunk: Buffer) => { - if (output.length < OUTPUT_CAP) output += chunk.toString('utf-8'); + const text = chunk.toString('utf-8'); + if (output.length < OUTPUT_CAP) output += text; + if (banner.length < BANNER_SCAN_CAP) banner += text; }; child.stdout?.on('data', capture); child.stderr?.on('data', capture); @@ -241,7 +393,7 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis if (current?.child === child) current = null; }); - const running: RunningServer = { child, port, authority, output: () => output }; + const running: RunningServer = { child, port, authority, output: () => output, banner: () => banner, cookie: null }; current = running; const deadline = Date.now() + READY_TIMEOUT_MS; @@ -255,6 +407,10 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis return { ok: false, error: tail ? `dsh web exited during startup: ${tail}` : 'dsh web exited during startup' }; } if (await answersHttp(port)) { + // Bought before this call resolves, so the first proxied page load + // already carries a credential — a tab opened a moment earlier would + // otherwise get the 401 this whole module exists to prevent. + running.cookie = await captureSessionCookie(running); return { ok: true, port, url: `http://127.0.0.1:${port}`, reused: false }; } await new Promise((r) => setTimeout(r, READY_POLL_MS)); diff --git a/src/web/routes/webview-routes.ts b/src/web/routes/webview-routes.ts index 579aada5..2cd5bc43 100644 --- a/src/web/routes/webview-routes.ts +++ b/src/web/routes/webview-routes.ts @@ -50,6 +50,7 @@ import { readWebviews, writeWebviews } from '../../webview-store.js'; import { webviewCapabilities } from '../../webview-capabilities.js'; import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js'; import { blockedWebviewHostReason } from '../webview-egress-policy.js'; +import { getDeepSeekWebCookie } from '../../deepseek-web-server.js'; import { ApiErrorCode, createErrorResponse } from '../../types.js'; import type { Webview, WebviewOpenData, WebviewProbe } from '../../types.js'; import { AUTH_COOKIE_NAME } from '../middleware/auth.js'; @@ -426,6 +427,31 @@ function proxyHttp( return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '', basePath); } +/** + * The credential a Codeman-managed dashboard needs on every upstream request. + * + * `dsh web` now gates its index and `/api` behind a cookie minted for the + * authority it was started on, and only the URL it prints on boot carries the + * token that buys it. The managed DeepSeek tab deliberately stores the clean + * URL, so the browser can never hold that cookie: `deepseek-web-server.ts` + * exchanges the token at startup, and this is where the supervisor's result + * reaches the request. + * + * Strictly scoped to the exact loopback origin the cookie was minted for. A + * web tab the user repointed at another host, or a stale tab still naming a + * previous port, must not be handed a credential that is not its own. + * + * @param webview - the saved tab being proxied. + * @param upstream - resolved upstream URL for this request. + * @returns `name=value` cookie pair, or undefined when none applies. + */ +function managedDashboardCookie(webview: Webview, upstream: URL): string | undefined { + if (webview.managed !== 'deepseek-web') return undefined; + if (upstream.hostname !== '127.0.0.1') return undefined; + const port = Number(upstream.port || (upstream.protocol === 'https:' ? 443 : 80)); + return getDeepSeekWebCookie(port) ?? undefined; +} + /** * Proxy one request to the dashboard behind `cap`, serving `wildcard` as the * upstream path. Split out from the route handler so the 404 fallback (which has @@ -468,12 +494,14 @@ async function proxyRequest( } const hasBody = req.method !== 'GET' && req.method !== 'HEAD'; + const injectedCookie = managedDashboardCookie(webview, upstream); const headers = buildUpstreamRequestHeaders(req.headers, upstream, { forwardCookies: webview.trusted, sessionCookieName: AUTH_COOKIE_NAME, refererPath: typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap, basePath) : undefined, relayBodyLength: hasBody && req.body !== undefined, + ...(injectedCookie ? { injectedCookie } : {}), }); // #237: the timeout bounds TIME-TO-HEADERS only. A plain AbortSignal.timeout on @@ -707,13 +735,19 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa }; const protocols = req.headers['sec-websocket-protocol']; + // The same credential the HTTP leg presents. A managed dashboard's realtime + // channel is gated exactly like its index, so without this the page loads + // and then sits there silently disconnected. + const cookie = + managedDashboardCookie(webview, upstream) ?? + (webview.trusted && req.headers.cookie ? String(req.headers.cookie) : undefined); // `lookup` is absent from ws's ClientOptions typings but flows through // http.request to net.connect untouched, which is where the resolved // address is judged (see webview-egress.ts). const upstreamOptions: WsClientOptions & { lookup: EgressLookup } = { headers: { origin: upstream.origin, - ...(webview.trusted && req.headers.cookie ? { cookie: String(req.headers.cookie) } : {}), + ...(cookie ? { cookie } : {}), }, handshakeTimeout: WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS, lookup: webviewEgressLookup, diff --git a/src/web/webview-proxy.ts b/src/web/webview-proxy.ts index bc05feed..45b7ca16 100644 --- a/src/web/webview-proxy.ts +++ b/src/web/webview-proxy.ts @@ -311,7 +311,19 @@ export function filterCookieHeader(cookie: string | undefined, drop: string[]): export function buildUpstreamRequestHeaders( incoming: Record, upstream: URL, - opts: { forwardCookies: boolean; sessionCookieName: string; refererPath?: string; relayBodyLength?: boolean } + opts: { + forwardCookies: boolean; + sessionCookieName: string; + refererPath?: string; + relayBodyLength?: boolean; + /** + * A credential the SERVER holds for this dashboard, replacing whatever the + * browser sent. `dsh web` mints its session cookie for a loopback authority + * the browser never visits, so the proxy is the only party that can present + * it (see `deepseek-web-server.ts`). + */ + injectedCookie?: string; + } ): Record { const headers: Record = {}; @@ -343,6 +355,11 @@ export function buildUpstreamRequestHeaders( if (cookie) headers['cookie'] = cookie; } + // After the relay above, so a browser copy can never shadow it: these cookies + // are scoped to the browser's origin, and the authority this request is for is + // one it has never been able to store anything against. + if (opts.injectedCookie) headers['cookie'] = opts.injectedCookie; + // Present as if the browser were talking to the dashboard directly. Apps that // check Origin on writes (CSRF defenses) need this to match their own origin. headers['origin'] = upstream.origin; @@ -646,6 +663,45 @@ try{ }catch(e){}})();`; } +/** + * Make a page's own RELATIVE `` absolute under the proxy prefix. + * + * A base element is resolved against the document's URL, and {@link runtimeUrlShim} + * deliberately rewrites that URL to strip the proxy prefix. So a page shipping + * `` — which is what a Vite build does, DeepSeek Harness among + * them — has its base re-resolved to Codeman's ROOT the moment the shim runs: + * every module script, stylesheet and `fetch('./api')` then asks the Codeman + * origin instead of the dashboard. The visible symptom is not an error page but + * a blank one: the markup and inline `