Merge master into fix/dead-pane-blank-pid

Resolves the killSession() conflict with babb55e4 (never signal pid 0
or 1). The dead-pane read decides first; a pid that is not signalable
(isSignalablePid) then also means nothing is signalled and only
`tmux kill-session` runs. killPaneProcessTree() sends every signal
through signalProcess().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kamil KaliszandClaude Opus 5.5 committed 2026-11-25 21:16:11 +01:00
commit 95918b80b4
77 files changed
+5430 -194

No files matched your search

+201
View File
@@ -0,0 +1,201 @@
// test/cjk-hold-per-device-setting.test.ts
// Port: none (static analysis + vm, runs in CI, no browser/server).
//
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
// merge policy, stripped out of the object saveAppSettings() PUTs
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
// never declared in the schema. Plus the pieces around the mode: a held draft
// surviving a reload of the same session, the field staying one line tall with
// the keyboard down, and zh-CN strings for its placeholders.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'cjkInputHoldUntilEnter'");
});
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
});
it('is never declared in the .strict() SettingsUpdateSchema', () => {
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
});
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
});
it('is loaded into and saved from its App Settings switch', () => {
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
expect(settingsUi).toContain(
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
);
});
});
describe('a held draft survives a reload of the same session', () => {
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
// activeSessionId before calling it on a same-session forceReload (tapping the
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) {
const clear = vi.fn();
const stashDraft = vi.fn();
const context = vm.createContext({
console,
setTimeout,
clearTimeout,
setInterval: vi.fn(),
clearInterval: vi.fn(),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
fetch: vi.fn(),
URLSearchParams,
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null },
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
CjkInput: { holdUntilEnter: hold, clear, stashDraft },
});
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.create(CodemanApp.prototype) as Record<string, unknown> & {
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
};
app.activeSessionId = outgoing;
app.sessions = new Map();
app._clearTimer = vi.fn();
app._disconnectWs = vi.fn();
app._xtermSnapshots = new Map();
app.pendingWrites = [];
app._cleanupPreviousSession('s1', { keepCjkDraft });
return Object.assign(clear, { stashDraft });
}
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
expect(cleanup(true, true)).not.toHaveBeenCalled();
});
it('still clears on a real switch', () => {
expect(cleanup(true, false)).toHaveBeenCalled();
});
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
expect(cleanup(false, true)).toHaveBeenCalled();
});
it('stashes the held draft of the session being left before clearing', () => {
const clear = cleanup(true, false, 's0');
expect(clear.stashDraft).toHaveBeenCalledWith('s0');
expect(clear.stashDraft.mock.invocationCallOrder[0]).toBeLessThan(clear.mock.invocationCallOrder[0]);
});
it('selectSession restores the draft of the session it lands on', () => {
// After _activateFileBrowserSession: test/file-browser-search.test.ts pins
// that call as the line right after the activeSessionId assignment.
expect(read('app.js')).toContain(
"this.activeSessionId = sessionId;\n this._activateFileBrowserSession?.(sessionId);\n if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);"
);
});
it('leaving the tile grid for another session stashes the focused tile draft', () => {
// selectSession nulls activeSessionId there, which hides the tile from
// _cleanupPreviousSession.
expect(read('app.js')).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\n(?:\s*\/\/.*\n)*\s*this\.activeSessionId = null;/
);
});
it('tile focus does not stash again for a tile closed from this tab', () => {
// removeSession discards the closed session's draft first; a stash after
// that would keep it in the map until the page reloads.
expect(read('tile-grid.js')).toContain(
'if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);'
);
});
it('tile focus stashes the draft of the tile left and restores the focused one', () => {
const tiles = read('tile-grid.js');
const start = tiles.indexOf(' _selectTiledSession(sessionId, options = {}) {');
const body = tiles.slice(start, tiles.indexOf('grid.focusedId = sessionId;', start));
expect(body).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\s*CjkInput\.clear\(\);\s*\}\s*CjkInput\.restoreDraft\?\.\(sessionId\);\s*\}\s*this\.activeSessionId = sessionId;/
);
});
it('going Home stashes the draft of the session it leaves', () => {
const appJs = read('app.js');
const start = appJs.indexOf(' goHome() {');
const body = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(body).toContain('CjkInput.stashDraft?.(this.activeSessionId);');
});
it('a removed session drops its stashed draft', () => {
expect(read('app.js')).toMatch(
/discardComposerDraft\?\.\(sessionId\);\n\s*if \(typeof CjkInput !== 'undefined'\) CjkInput\.discardDraft\?\.\(sessionId\);/
);
});
it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => {
const appJs = read('app.js');
expect(appJs).toMatch(
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
});
});
describe('Send on Enter field layout and strings', () => {
it('keeps the field one line tall while the keyboard is down', () => {
// .main reserves a fixed 84px there; a grown field would cover the terminal.
expect(read('styles.css')).toMatch(
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
);
});
it('caps the field on every device, not only in the .touch-device rule', () => {
// The setting is not limited to phones; on desktop an uncapped field grew to
// 502px at 25 lines and resized the PTY on every step.
const css = read('styles.css');
const base = css.slice(css.indexOf('#cjkInput {'), css.indexOf('}', css.indexOf('#cjkInput {')));
expect(base).toContain('max-height: 68px;');
expect(base).toContain('overflow-y: auto;');
});
it('the phone toolbar Enter presses Enter in the visible CJK field', () => {
// onData drops everything while cjkActive, so the xterm path does nothing.
const sessionUi = read('session-ui.js');
const start = sessionUi.indexOf(' sendEnterKey() {');
const body = sessionUi.slice(start, sessionUi.indexOf('triggerDataEvent', start));
expect(body).toContain("classList.contains('cjk-input-visible')");
expect(body).toContain('CjkInput.submit?.();');
});
it('has zh-CN strings for both field placeholders', () => {
const i18n = read('i18n.js');
const cjk = read('input-cjk.js');
for (const placeholder of [
'CJK input (Enter = send, Esc = clear)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
]) {
expect(cjk).toContain(`'${placeholder}'`);
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
}
});
});
+1 -1
View File
@@ -172,7 +172,7 @@ describe('registered arguments', () => {
['attach', ['path']],
['start', []],
// Optional: bare `codeman tui` opens the dashboard.
['tui', ['n']],
['tui', ['session']],
])('declares the operands of `%s`', (name, expected) => {
const args = find(program, name)!.registeredArguments.map((arg) => arg.name());
expect(args).toEqual(expected);
@@ -435,7 +435,6 @@ describe('declared-for-later fields', () => {
const DECLARED_FOR_LATER = [
'accent',
'capabilities.echo',
'capabilities.wheelForward',
'capabilities.keyboardAccessory',
'capabilities.maxFrameBytes',
// The Docker credential-seeding path still reads its own CRED_STORES table: this shape
+77
View File
@@ -0,0 +1,77 @@
/**
* @fileoverview The header CPU reading's meter: busy time over all cores between readings, the minimum window
* that keeps several browsers from shrinking it, and the fallback when no usable core times exist.
*/
import { describe, expect, it } from 'vitest';
import { createCpuUsageMeter } from '../src/cpu-usage.js';
const core = (busy: number, idle: number) => ({ times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } });
function meterOver(samples: ReturnType<typeof core>[][], fallback = () => 999) {
let at = 0;
let index = 0;
const meter = createCpuUsageMeter(
() => samples[Math.min(index, samples.length - 1)],
() => at,
fallback
);
return (ms: number) => {
at += ms;
index += 1;
return meter();
};
}
describe('createCpuUsageMeter', () => {
it('reports busy time over all cores between readings', () => {
const next = meterOver([
[core(0, 0), core(0, 0)],
[core(50, 50), core(50, 50)],
[core(150, 50), core(50, 150)],
]);
expect(next(2000)).toBe(50);
expect(next(2000)).toBe(50);
});
it('counts nice, system and interrupt time as busy', () => {
const times = (user: number, nice: number, sys: number, irq: number, idle: number) => ({
times: { user, nice, sys, idle, irq },
});
const meter = createCpuUsageMeter(
(() => {
let calls = 0;
return () => [calls++ === 0 ? times(0, 0, 0, 0, 0) : times(10, 20, 30, 15, 25)];
})(),
(() => {
let at = 0;
return () => (at += 2000);
})(),
() => 999
);
expect(meter()).toBe(75);
});
it('reads idle cores as idle however long the run queue is', () => {
expect(meterOver([[core(0, 0)], [core(40, 60)]])(5000)).toBe(40);
});
it('reuses the last value for readings under a second apart and keeps the baseline', () => {
const next = meterOver([[core(0, 0)], [core(30, 70)], [core(30, 170)], [core(130, 170)]]);
expect(next(2000)).toBe(30);
expect(next(200)).toBe(30);
expect(next(2000)).toBe(50);
});
it('falls back without a bogus reading when there are no core times or the counters go backwards', () => {
expect(meterOver([[], []], () => 7)(2000)).toBe(7);
const next = meterOver([[core(100, 100)], [core(10, 10)], [core(60, 60)]], () => 7);
expect(next(2000)).toBe(7);
expect(next(2000)).toBe(50);
});
it('answers a whole number from 0 to 100', () => {
expect(meterOver([[core(0, 0)], [core(2, 1)]])(2000)).toBe(67);
expect(meterOver([[core(0, 0)], [core(0, 9)]])(2000)).toBe(0);
expect(meterOver([[core(0, 0)], [core(9, 0)]])(2000)).toBe(100);
});
});
+362 -2
View File
@@ -12,10 +12,25 @@
* 2. The supervisor tracks at most ONE server. The status accessor is what every
* caller reads to decide whether to start another, so "no server" must report
* as absent rather than as a half-populated record.
* 3. `dsh web` now gates its index behind a launch token it prints on boot. The
* supervisor is the only party that can trade it, and the cookie it produces
* is authority-bound: getting that wrong is a blank tab, not a visible error.
*/
import { describe, expect, it, beforeEach } from 'vitest';
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import http from 'node:http';
import { DeepSeekWebStartSchema } from '../src/web/schemas.js';
import { getDeepSeekWebStatus, resetDeepSeekWebForTest, stopDeepSeekWeb } from '../src/deepseek-web-server.js';
import {
getDeepSeekWebCookie,
getDeepSeekWebStatus,
launchUrlTargetsServer,
parseLaunchUrl,
resetDeepSeekWebForTest,
startDeepSeekWeb,
stopDeepSeekWeb,
} from '../src/deepseek-web-server.js';
describe('DeepSeekWebStartSchema: the authority reaching --trusted-host', () => {
it('accepts the authority shapes a browser can actually report', () => {
@@ -71,3 +86,348 @@ describe('DeepSeek web supervisor: status', () => {
expect(getDeepSeekWebStatus().running).toBe(false);
});
});
describe('parseLaunchUrl: the one-time token dsh prints on boot', () => {
it('pulls the URL out of the banner a real boot writes', () => {
const output = ['dsh web: http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc', 'ready'].join('\n');
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc');
});
it('sees through SGR colouring, which would otherwise hide the token', () => {
const output = '\u001b[36mdsh web:\u001b[0m \u001b[4mhttp://127.0.0.1:3080/?token=abc123\u001b[0m\n';
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=abc123');
});
// dsh prints diagnostics under the same prefix before the banner. Taking the
// FIRST match made the real URL invisible and boot gave up 4 seconds later.
it('skips a diagnostic line and keeps scanning for the URL', () => {
expect(parseLaunchUrl('dsh web: loading profiles\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('skips a URL without a token and keeps scanning for the token one', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('returns null for a token-less banner, which is the older dsh', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\n')).toBeNull();
});
it('refuses anything that is not an http(s) URL carrying a token', () => {
expect(parseLaunchUrl('')).toBeNull();
expect(parseLaunchUrl('booting...')).toBeNull();
expect(parseLaunchUrl('dsh web: javascript:alert(1)?token=x')).toBeNull();
expect(parseLaunchUrl('dsh web: not a url?token=x')).toBeNull();
});
});
describe('launchUrlTargetsServer: the exchange must hit the spawned port', () => {
it('accepts only 127.0.0.1 on the port that was just spawned', () => {
expect(launchUrlTargetsServer('http://127.0.0.1:3080/?token=x', 3080)).toBe(true);
expect(launchUrlTargetsServer('http://127.0.0.1:3081/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://localhost:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://evil.example:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('not a url', 3080)).toBe(false);
});
});
describe('DeepSeek web supervisor: the launch-token cookie', () => {
let dir: string;
beforeEach(() => {
resetDeepSeekWebForTest();
dir = mkdtempSync(join(tmpdir(), 'codeman-dsh-web-'));
});
afterEach(async () => {
await stopDeepSeekWeb();
rmSync(dir, { recursive: true, force: true });
});
/**
* A stand-in for `dsh web` with the browser-auth gate: prints the banner,
* refuses `/` without a cookie, and trades the token for one 303.
*/
const FAKE_DSH = `#!/usr/bin/env node
const http = require('node:http');
const portArg = process.argv.indexOf('--port');
const port = Number(process.argv[portArg + 1]);
const token = 'test-launch-token';
const cookie = 'dsh-auth-test=v1.payload.sig';
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.pathname === '/' && url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/; HttpOnly' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<!doctype html><title>harness</title>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`;
it('trades the boot token for the cookie, scoped to its own port', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
// Before the exchange this page is exactly the blank tab being fixed: 401.
expect((await fetch(`http://127.0.0.1:${result.port}/`)).status).toBe(401);
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-test=v1.payload.sig');
// A credential minted for this authority must never travel to another port.
expect(getDeepSeekWebCookie(result.port + 1)).toBeNull();
const authed = await fetch(`http://127.0.0.1:${result.port}/`, {
headers: { cookie: getDeepSeekWebCookie(result.port) as string },
});
expect(authed.status).toBe(200);
}, 20_000);
// `managed` is a client-supplied field and the port is published by
// GET /api/deepseek/web, so the supervisor additionally binds the cookie to the
// identity whose request started the process: another user's tab must not be
// handed it, and their POST must not reuse bob's server either.
it('hands the cookie only to the identity that started the server', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const bob = await startDeepSeekWeb(dir, 'localhost:3000', 'bob');
expect(bob.ok).toBe(true);
if (!bob.ok) return;
expect(getDeepSeekWebCookie(bob.port, 'bob')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(bob.port)).toBeNull();
expect(getDeepSeekWebCookie(bob.port, 'alice')).toBeNull();
// A different owner restarts rather than reusing bob's cookie.
const alice = await startDeepSeekWeb(dir, 'localhost:3000', 'alice');
expect(alice.ok).toBe(true);
if (!alice.ok) return;
expect(alice.reused).toBe(false);
expect(getDeepSeekWebCookie(alice.port, 'alice')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(alice.port, 'bob')).toBeNull();
}, 20_000);
// A failed exchange leaves a server that answers 401 to everything. Reuse used
// to hand that same server back on every POST, so the restart the warning asks
// for could never happen. The next start request must perform it.
it('restarts rather than reusing a server whose exchange failed', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'retry-token';
const cookie = 'dsh-auth-retry=v1.sig';
const marker = path.join(__dirname, '.exchange-failed');
const failedBefore = fs.existsSync(marker);
if (!failedBefore) fs.writeFileSync(marker, '1');
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
if (!failedBefore) {
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('temporary failure');
return;
}
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const first = await startDeepSeekWeb(dir, 'localhost:3000');
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(getDeepSeekWebCookie(first.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be exchanged'));
} finally {
warn.mockRestore();
}
const second = await startDeepSeekWeb(dir, 'localhost:3000');
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(second.reused).toBe(false);
expect(getDeepSeekWebCookie(second.port)).toBe('dsh-auth-retry=v1.sig');
// The recovered server is healthy again, so ordinary reuse resumes.
const third = await startDeepSeekWeb(dir, 'localhost:3000');
expect(third.ok).toBe(true);
if (!third.ok) return;
expect(third.reused).toBe(true);
}, 20_000);
// The exchange is a request made by the SERVER. A banner naming another local
// port would let captured child output aim it, so the URL is judged before it
// is fetched at all.
it('does not fetch a banner naming another port', async () => {
const hits: string[] = [];
const target = http.createServer((req, res) => {
hits.push(req.url ?? '');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('should never be reached');
});
await new Promise<void>((resolve) => target.listen(0, '127.0.0.1', resolve));
const address = target.address();
if (!address || typeof address === 'string') throw new Error('target has no address');
try {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
process.stdout.write('dsh web: http://127.0.0.1:${address.port}/?token=stolen\\n');
http
.createServer((_req, res) => {
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('not fetching it'));
} finally {
warn.mockRestore();
}
expect(hits).toEqual([]);
} finally {
await new Promise<void>((resolve) => target.close(() => resolve()));
}
}, 20_000);
it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync(
join(dir, 'dsh'),
'#!/usr/bin/env node\nconst http = require("node:http");\nconst port = Number(process.argv[process.argv.indexOf("--port") + 1]);\nprocess.stdout.write("dsh web: http://127.0.0.1:" + port + "/\\n");\nhttp.createServer((_q, s) => s.end("ok")).listen(port, "127.0.0.1");\n',
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
}, 20_000);
// The error-tail buffer is capped at 16 KB, and a chatty plugin tree can fill
// it before dsh prints its banner. Scanning that buffer alone lost the token
// and put the tab back on the 401 page, so the banner is matched on its own
// (larger) budget.
// The banner can arrive in two stdout writes: `capture()` sees two chunks and
// neither is a complete line. Scanning the raw buffer either missed it or, with
// a partial URL that happened to parse, exchanged a truncated token.
it('waits for a banner split across two output chunks', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'split-token';
const cookie = 'dsh-auth-split=v1.sig';
process.stdout.write('dsh web: loading profiles\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1', () => {
const line = 'dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n';
process.stdout.write(line.slice(0, 30));
setTimeout(() => process.stdout.write(line.slice(30)), 150);
});
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-split=v1.sig');
}, 20_000);
it('still finds a banner printed after more than the error-tail cap', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'late-banner-token';
const cookie = 'dsh-auth-late=v1.sig';
process.stdout.write('warn: plugin noise '.repeat(1100) + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
setTimeout(() => process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n'), 300);
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-late=v1.sig');
}, 20_000);
});
+69 -3
View File
@@ -448,6 +448,72 @@ describe('DiscordBridge', () => {
return b;
}
it('deduplicates replayed real gateway IDs across restart while new replies still work', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
b.stop();
t += 10_000;
const next = await ready();
await next.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555556', content: 'continue' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('claims rate-limited snowflake replies so replays remain refused across restart', async () => {
const b = await ready();
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
t += 200;
const refused = reply({ id: '555555555555555556', content: 'too soon' });
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(true);
t += 5_000;
const count = posts.length;
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts).toHaveLength(count);
b.stop();
const next = await ready();
await next.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555557', content: 'new attempt' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('ignores an immediate replay without adding an hourglass to a successful reply', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
t += 200;
await b.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.filter((p) => p.method === 'PUT')).toHaveLength(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(false);
b.stop();
});
it('delivers replies and alerts when metadata is corrupt and recovers without restarting', async () => {
const b = await ready();
writeFileSync(join(dir, 'discord-reply-dedupe.json'), '{');
const log = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
expect(sendInput).toHaveBeenCalledTimes(1);
t += 10_000;
expect((await b.notify(MSG))?.ok).toBe(true);
rmSync(join(dir, 'discord-reply-dedupe.json'));
await b.onGatewayMessage(reply({ id: '555555555555555556' }));
expect(sendInput).toHaveBeenCalledTimes(2);
expect(log).toHaveBeenCalledTimes(1);
} finally {
log.mockRestore();
b.stop();
}
});
it('types an allowed reply into the mapped session and ticks it', async () => {
const b = await ready();
await b.onGatewayMessage(reply());
@@ -1143,7 +1209,7 @@ describe('DiscordBridge files and startup hint', () => {
it('types a reply that waits on a download before a later text reply', async () => {
const b = await make();
const slow = b.onGatewayMessage(reply({ content: 'first' }));
await new Promise((r) => setTimeout(r, 0)); // the first reply is under way (gate passed) before the clock moves
await vi.waitFor(() => expect(downloads).toHaveLength(1)); // wait for the claim and rate-limit gate
t += 5_000;
const fast = b.onGatewayMessage(reply({ id: '555555555555555556', content: 'second', attachments: [] }));
await Promise.all([slow, fast]);
@@ -1157,11 +1223,11 @@ describe('DiscordBridge files and startup hint', () => {
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2');
t += 5_000;
await b.onGatewayMessage(reply({ content: 'yes', attachments: [] }));
await b.onGatewayMessage(reply({ id: '555555555555555556', content: 'yes', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('yes\r');
t += 5_000;
waiting = false;
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
await b.onGatewayMessage(reply({ id: '555555555555555557', content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2\r');
b.stop();
});
+151
View File
@@ -0,0 +1,151 @@
import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { DiscordReplyDedupe } from '../src/discord-reply-dedupe.js';
import fs from 'node:fs/promises';
let dir: string;
const guild = '111111111111111111',
channel = '222222222222222222',
message = '333333333333333333';
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'discord-replies-'));
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
it('claims once across concurrent events and restarts, without storing message content', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await Promise.all([store.claim(guild, channel, message), store.claim(guild, channel, message)])).toEqual([
true,
false,
]);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(join(dir, 'discord-reply-dedupe.json'))).mode & 0o777).toBe(0o600);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toEqual([
[`${guild}:${channel}:${message}`, expect.any(Number)],
]);
});
it('falls back on corrupt metadata, logs once, retries after recovery, and retains memory claims', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, '{');
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('does not poison metadata with incomplete restored configuration', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await store.claim('', channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('keeps accepting new replies during ENOSPC and persists memory claims when writes recover', async () => {
const warn = vi.fn();
const store = new DiscordReplyDedupe(dir, Date.now, warn);
const rename = vi.spyOn(fs, 'rename').mockRejectedValueOnce(Object.assign(new Error('full'), { code: 'ENOSPC' }));
try {
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
} finally {
rename.mockRestore();
}
});
it('evicts old records rather than refusing replies at capacity', async () => {
await writeFile(
join(dir, 'discord-reply-dedupe.json'),
JSON.stringify(
Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${String(100000000000000000n + BigInt(i))}`,
Date.now(),
])
)
);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(true);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toHaveLength(2048);
});
it.each(['{', '{}', '[null]'])(
'heals readable invalid metadata %s and keeps the claim across restart',
async (invalid) => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, invalid);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
}
);
it('retains newer outage claims when disk recovery reaches capacity, without overwriting an unread file', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const rows = Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${100000000000000000n + BigInt(i)}`,
Date.now(),
]);
const original = JSON.stringify(rows);
await writeFile(path, original);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
const read = vi
.spyOn(fs, 'readFile')
.mockRejectedValueOnce(Object.assign(new Error('descriptor limit'), { code: 'EMFILE' }));
expect(await store.claim(guild, channel, message)).toBe(true);
read.mockRestore();
expect(await readFile(path, 'utf8')).toBe(original);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
const saved = JSON.parse(await readFile(path, 'utf8'));
expect(saved).toHaveLength(2048);
expect(saved.some((row: [string, number]) => row[0] === rows[0][0])).toBe(false);
});
it('heals an over-cap readable store rather than remaining memory-only until manual deletion', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(
path,
JSON.stringify(
Array.from({ length: 2049 }, (_, i) => [`${guild}:${channel}:${100000000000000000n + BigInt(i)}`, Date.now()])
)
);
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
});
it('heals oversized regular metadata and persists replay protection across restart', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, ' '.repeat(512 * 1024 + 1));
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(path)).size).toBeLessThan(512 * 1024);
expect(warn).toHaveBeenCalledTimes(1);
});
it('never replaces a symlink or a folder at the metadata path, and still accepts replies', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const target = join(dir, 'target');
await writeFile(target, 'keep');
await symlink(target, path);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect((await lstat(path)).isSymbolicLink()).toBe(true);
expect(await readFile(target, 'utf8')).toBe('keep');
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
await mkdir(path);
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect((await lstat(path)).isDirectory()).toBe(true);
});
+68 -1
View File
@@ -38,7 +38,7 @@ import {
symlinkSync,
readdirSync,
} from 'node:fs';
import { execFileSync, spawnSync } from 'node:child_process';
import { spawn, execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { diffRequiredEnvKeys, parseEnvKeys } from '../src/web/self-update.js';
@@ -639,3 +639,70 @@ describe('version_older_than', () => {
expect(out).toBe(older ? 'yes' : 'no');
});
});
/**
* A listener whose accept queue is full, so the kernel drops further SYNs and a
* connect to it gets no answer, the same thing a WSL host does for a CLOSED
* 127.0.0.1 port. Held by a python3 child, since Node accepts every connection
* as it arrives and so can never leave its own queue full.
*/
const HAS_PYTHON = spawnSync('python3', ['-c', 'pass']).status === 0;
const SILENT_LISTENER = [
'import socket, sys, time',
's = socket.socket(); s.bind(("127.0.0.1", 0)); s.listen(0)',
'port = s.getsockname()[1]; held = []',
'for _ in range(3):',
' c = socket.socket(); c.setblocking(False)',
' try: c.connect(("127.0.0.1", port))',
' except BlockingIOError: pass',
' held.append(c)',
'time.sleep(0.3); print(port, flush=True); time.sleep(60)',
].join('\n');
describe.skipIf(process.platform !== 'linux' || !HAS_PYTHON)('port_answers', () => {
/** Runs the script's own port_answers on host/port, returning its status and how long it took. */
function probe(host: string, port: number): { status: number | null; ms: number } {
const script = [
'set -euo pipefail',
`eval "$(sed -n '/^port_answers() {/,/^}/p' "$1")"`,
'if port_answers "$2" "$3"; then exit 0; else exit 1; fi',
].join('\n');
const started = Date.now();
const res = spawnSync('bash', ['-c', script, '_', join(ROOT, 'docker/Start-Codeman.sh'), host, String(port)], {
encoding: 'utf-8',
timeout: 10_000,
});
return { status: res.status, ms: Date.now() - started };
}
it('gives up on a connect that gets no answer within about a second, and reads it as free', async () => {
const child = spawn('python3', ['-I', '-c', SILENT_LISTENER], { stdio: ['ignore', 'pipe', 'ignore'] });
try {
const port = await new Promise<number>((resolve, reject) => {
child.stdout!.once('data', (chunk: Buffer) => resolve(Number(String(chunk).trim())));
child.once('exit', () => reject(new Error('listener exited')));
});
const { status, ms } = probe('127.0.0.1', port);
expect(status).toBe(1);
expect(ms).toBeLessThan(3000);
} finally {
child.kill();
}
});
it('still answers at once for a listening port and a closed one', async () => {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as { port: number }).port;
try {
const open = probe('127.0.0.1', port);
expect(open.status).toBe(0);
expect(open.ms).toBeLessThan(1000);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
const closed = probe('::1', port);
expect(closed.status).toBe(1);
expect(closed.ms).toBeLessThan(1000);
});
});
+617
View File
@@ -0,0 +1,617 @@
/**
* @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js,
* setting cjkInputHoldUntilEnter): typed text stays in the field until Enter,
* so a phone user can scroll the terminal and edit an answer before sending.
*
* Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also
* carries the attributes and style the mode touches.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const PHANTOM = '​';
function makeTextarea() {
const listeners = new Map<string, Array<(e?: unknown) => void>>();
const attrs: Record<string, string> = {};
return {
value: '',
placeholder: '',
style: { height: '' } as Record<string, string>,
scrollHeight: 34,
// border-box with a 1px border: offsetHeight - clientHeight is the borders.
offsetHeight: 36,
clientHeight: 34,
attrs,
blur: vi.fn(),
focus: vi.fn(),
getClientRects: (): unknown[] => [{}],
classList: { contains: (c: string) => c === 'cjk-input-visible' },
setSelectionRange: () => {},
setAttribute: vi.fn((k: string, v: string) => {
attrs[k] = v;
}),
addEventListener: (ev: string, fn: (e?: unknown) => void) => {
listeners.set(ev, [...(listeners.get(ev) ?? []), fn]);
},
removeEventListener: (ev: string, fn: (e?: unknown) => void) => {
listeners.set(
ev,
(listeners.get(ev) ?? []).filter((f) => f !== fn)
);
},
fire(ev: string, arg: Record<string, unknown> = {}) {
const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg };
for (const fn of listeners.get(ev) ?? []) fn(base);
},
};
}
function load({
hold = true,
promptResult = true,
touch = true,
translate,
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const prompts: string[] = [];
const layout = vi.fn();
// The shell bar's one-shot Ctrl, reduced to its armed flag.
const bar = {
armed: false,
isCtrlArmed() {
return this.armed;
},
clearCtrl() {
this.armed = false;
},
};
const context = vm.createContext({
window: translate ? { CodemanI18n: { t: translate } } : {},
document: {
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
activeElement: null,
body: { classList: { contains: (c: string) => touch && c === 'touch-device' } },
},
navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' },
KeyboardHandler: { updateLayoutForKeyboard: layout },
KeyboardAccessoryBar: bar,
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
performance: { now: () => performance.now() },
console,
});
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8');
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({
send: (t: string) => sent.push(t),
sendPrompt: (t: string) => {
prompts.push(t);
return promptResult;
},
});
CjkInput.setHoldUntilEnter(hold);
textarea.fire('focus');
return { CjkInput, textarea, sent, prompts, layout, bar };
}
function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
textarea.value = PHANTOM + text;
textarea.fire('input', { isComposing: false, inputType: 'insertText' });
}
function backspace(textarea: ReturnType<typeof makeTextarea>, valueAfter: string) {
textarea.value = valueAfter;
textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' });
}
const enter = (textarea: ReturnType<typeof makeTextarea>) =>
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
describe('CJK input: Send on Enter', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] });
});
afterEach(() => {
vi.useRealTimers();
});
it('keeps typed text in the field instead of streaming it', () => {
const { textarea, sent } = load();
type(textarea, 'use Postgres');
vi.advanceTimersByTime(5000);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'use Postgres');
});
it('keeps text after a physical keystroke (no zero-latency flush)', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false });
type(textarea, 'a');
vi.advanceTimersByTime(1000);
expect(sent).toEqual([]);
});
it('keeps text across a composition cycle and autocorrect rewrites', () => {
const { textarea, sent } = load();
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'teh';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
textarea.value = PHANTOM + 'the';
textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' });
vi.advanceTimersByTime(5000);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'the');
});
it('sends one line on Enter through the prompt path, then clears the field', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'yes, use Postgres');
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(prompts).toEqual(['yes, use Postgres']);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('never writes text and Enter together, whatever the length', () => {
// Codex takes characters arriving in one burst as a paste and folds an Enter
// inside it into the paste, so even `1\r` in one write stays unsent; Claude
// Code does the same for a long burst. terminal-ui.js _sendCjkPrompt types a
// single character and pastes anything longer, Enter always on its own.
const { textarea, sent, prompts } = load();
for (const answer of ['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]) {
type(textarea, answer);
enter(textarea);
}
expect(sent).toEqual([]);
expect(prompts).toEqual(['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]);
expect(textarea.value).toBe(PHANTOM);
});
it('keeps a short answer in the field when it is refused (no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'yes');
enter(textarea);
expect(prompts).toEqual(['yes']);
expect(textarea.value).toBe(PHANTOM + 'yes');
});
it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'line one\nline two');
enter(textarea);
vi.advanceTimersByTime(500);
expect(prompts).toEqual(['line one\nline two']);
expect(sent).toEqual([]);
});
it('keeps the text in the field when the prompt is refused (too long, no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'line one\nline two');
enter(textarea);
expect(prompts).toHaveLength(1);
expect(textarea.value).toBe(PHANTOM + 'line one\nline two');
});
it('treats Shift+Enter as a newline, never a send', () => {
const { textarea, sent } = load();
type(textarea, 'first');
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault });
vi.advanceTimersByTime(10);
expect(preventDefault).not.toHaveBeenCalled();
expect(sent).toEqual([]);
});
it('sends a bare Enter when the field is empty (accepting a default answer)', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
expect(sent).toEqual(['\r']);
});
it('still forwards Backspace on an empty field to the PTY', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'Backspace', keyCode: 8 });
expect(sent).toEqual(['\x7f']);
});
it('does not send Backspace when deleting the last held character', () => {
// The CLI's own composer may hold text (Attach, image paste, Path, mic):
// a stray DEL would eat its last character.
const { textarea, sent } = load();
type(textarea, 'a');
type(textarea, 'ab');
backspace(textarea, PHANTOM + 'a');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('sends Backspace once the field is empty and the phantom itself is deleted', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
backspace(textarea, '');
expect(sent).toEqual(['\x7f']);
expect(textarea.value).toBe(PHANTOM);
});
it('does not send Backspace for select-all + delete of held text', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, '');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('deletes held text right after typing it, before any debounce, without a DEL', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
vi.advanceTimersByTime(2000);
expect(sent).toEqual([]);
});
it('puts the phantom back when Backspace at the start of the text deleted it', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, 'abc');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'abc');
});
it('one-shot Ctrl: the next typed character goes out instead of being held', () => {
// _handleCjkInput turns the single character into the control byte.
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'c');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: held text stays and only the new character leaves the field', () => {
const { textarea, sent, bar } = load();
type(textarea, 'ab');
bar.armed = true;
type(textarea, 'abc');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM + 'ab');
});
it('one-shot Ctrl: a character committed by an IME composition also goes out', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'c';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
vi.advanceTimersByTime(10);
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'hello');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'hello');
expect(bar.armed).toBe(false);
});
it('Escape clears the held text without sending', () => {
const { textarea, sent } = load();
type(textarea, 'never mind');
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('turning the mode off drops the held draft and the stashes, so live mode sends only new keys', () => {
const { CjkInput, textarea, sent } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'rm -rf build\nsecond line');
CjkInput.stashDraft('session-b');
CjkInput.setHoldUntilEnter(false);
expect(textarea.value).toBe(PHANTOM);
type(textarea, 'x');
vi.advanceTimersByTime(1000);
expect(sent).toEqual(['x']);
CjkInput.setHoldUntilEnter(true);
CjkInput.clear();
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('stays one line on a desktop, where growing would resize the PTY', () => {
const { textarea, layout } = load({ touch: false });
layout.mockClear();
textarea.scrollHeight = 60;
type(textarea, 'a\nb\nc');
vi.advanceTimersByTime(1000);
expect(textarea.style.height).toBe('');
expect(layout).not.toHaveBeenCalled();
});
it('translates its placeholder itself, since i18n.js skips textareas', () => {
const { CjkInput, textarea } = load({ translate: (s) => `zh:${s}` });
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
CjkInput.setHoldUntilEnter(false);
expect(textarea.placeholder).toBe('zh:CJK input (Enter = send, Esc = clear)');
});
it('turns autocorrect on in the mode and back off without it', () => {
const { CjkInput, textarea } = load();
expect(textarea.attrs.autocorrect).toBe('on');
expect(textarea.attrs.spellcheck).toBe('true');
CjkInput.setHoldUntilEnter(false);
expect(textarea.attrs.autocorrect).toBe('off');
expect(textarea.attrs.spellcheck).toBe('false');
expect(CjkInput.holdUntilEnter).toBe(false);
});
it('grows the field with its text and re-runs the keyboard layout', () => {
const { textarea, layout } = load();
layout.mockClear();
textarea.scrollHeight = 60;
type(textarea, 'a\nb\nc');
vi.advanceTimersByTime(1000);
// scrollHeight + the 2px of border, so a two-line draft does not scroll inside.
expect(textarea.style.height).toBe('62px');
expect(layout).toHaveBeenCalled();
});
it('leaves the field alone when the mode is set again unchanged', () => {
// Runs on every session select and SSE reconnect, possibly mid-composition.
const { CjkInput, textarea } = load();
textarea.setAttribute.mockClear();
const placeholder = textarea.placeholder;
let writes = 0;
Object.defineProperty(textarea, 'placeholder', {
get: () => placeholder,
set: () => {
writes++;
},
});
CjkInput.setHoldUntilEnter(true);
expect(textarea.setAttribute).not.toHaveBeenCalled();
expect(writes).toBe(0);
CjkInput.setHoldUntilEnter(false);
expect(textarea.setAttribute).toHaveBeenCalled();
});
it('follows a live language switch with the mode unchanged', () => {
// App Settings runs applyLocalization(), then _updateCjkInputState(), which
// calls setHoldUntilEnter() with the same mode.
let lang = 'en';
const { CjkInput, textarea } = load({ translate: (s) => (lang === 'zh' ? `zh:${s}` : s) });
expect(textarea.placeholder).toBe('Type, Enter to send (Shift+Enter: new line, Esc: clear)');
textarea.setAttribute.mockClear();
lang = 'zh';
CjkInput.setHoldUntilEnter(true);
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
expect(textarea.setAttribute).not.toHaveBeenCalled();
});
it('submit() from outside the field (toolbar Enter) sends like Enter', () => {
const { CjkInput, textarea, prompts, sent } = load();
type(textarea, 'go ahead');
expect(CjkInput.submit()).toBe(true);
expect(prompts).toEqual(['go ahead']);
expect(textarea.value).toBe(PHANTOM);
expect(CjkInput.submit()).toBe(true);
expect(sent).toEqual(['\r']);
});
it('submit() keeps a refused answer and reports it', () => {
const { CjkInput, textarea } = load({ promptResult: false });
type(textarea, 'go ahead');
expect(CjkInput.submit()).toBe(false);
expect(textarea.value).toBe(PHANTOM + 'go ahead');
});
it('a draft stashed on a switch comes back for its own session only', () => {
const { CjkInput, textarea, sent, prompts } = load();
type(textarea, 'half an answer');
CjkInput.stashDraft('session-a');
CjkInput.clear();
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'half an answer');
// Restored once: the stash is consumed, so once the user empties the
// field (Esc here) a second visit does not bring it back. A draft still in
// the field when the session is left is stashed again by clear().
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
expect(sent).toEqual([]);
expect(prompts).toEqual([]);
});
it('a restored draft is held text: Backspace edits it without a DEL', () => {
const { CjkInput, textarea, sent } = load();
type(textarea, 'ok');
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
backspace(textarea, PHANTOM + 'o');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
});
it('an empty field stashes nothing, and a discarded draft is gone', () => {
const { CjkInput, textarea } = load();
type(textarea, 'draft');
CjkInput.stashDraft('session-a');
CjkInput.discardDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
CjkInput.stashDraft('session-b');
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('a switch with an empty field keeps the draft already stashed for that session', () => {
// The tile grid stashes the session it parks, then may stash it again from
// tile focus with the field already cleared.
const { CjkInput, textarea } = load();
type(textarea, 'keep me');
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.stashDraft('session-a');
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'keep me');
});
it('clear() stashes a held draft for the session it was typed for, with no stash call', () => {
// goHome(), _replaceTileGrid and _onTileAdoptedElsewhere drop the active
// session before the next cleanup, which then has no session to stash for.
const { CjkInput, textarea, sent } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'typed for a');
CjkInput.clear();
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'typed for a');
expect(sent).toEqual([]);
});
it('clear({ discard }) throws the draft away: a same-tab restore and a switch back stay empty', () => {
// The keyboard bar's clear-line key (terminal-ui.js clearTerminalInput).
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'thrown away');
CjkInput.clear({ discard: true });
expect(textarea.value).toBe(PHANTOM);
expect(CjkInput.draftOwner).toBe('session-a');
// Tapping the session's own tab: the field is kept, then restoreDraft runs.
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
// Switching away and back.
CjkInput.clear();
CjkInput.restoreDraft('session-b');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('clear({ discard }) also drops an older stash of the same session', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'old');
CjkInput.stashDraft('session-a');
CjkInput.clear({ discard: true });
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('a removed session loses its field text: discardDraft drops the owner', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'for a closed tile');
CjkInput.discardDraft('session-a');
expect(CjkInput.draftOwner).toBe(null);
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('a field still holding text keeps its owner when another session is shown', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'still for a');
CjkInput.restoreDraft('session-b');
expect(CjkInput.draftOwner).toBe('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'still for a');
});
it('Ctrl shortcuts stay in the field while it holds a draft', () => {
// Ctrl+Z is undo, Ctrl+A select all, Ctrl+C copy: never a control byte to
// the CLI while there is a draft to act on.
const { textarea, sent } = load();
type(textarea, 'draft');
for (const key of ['z', 'a', 'c']) {
const preventDefault = vi.fn();
textarea.fire('keydown', { key, keyCode: key.toUpperCase().charCodeAt(0), ctrlKey: true, preventDefault });
expect(preventDefault).not.toHaveBeenCalled();
}
expect(sent).toEqual([]);
});
it('Ctrl shortcuts reach the CLI from an empty field', () => {
const { textarea, sent } = load();
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true, preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(sent).toEqual(['\x03']);
});
it('live mode keeps sending Ctrl shortcuts with text in the field', () => {
const { textarea, sent } = load({ hold: false });
textarea.value = PHANTOM + 'x';
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true });
expect(sent).toEqual(['\x03']);
});
it('sends a bare Enter when the field holds only blank lines', () => {
const { textarea, sent, prompts } = load();
type(textarea, '\n');
enter(textarea);
expect(prompts).toEqual([]);
expect(sent).toEqual(['\r']);
});
it('submit() mid-composition commits it first (blur, focus) and sends what landed', () => {
const { CjkInput, textarea, prompts } = load();
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'yes';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
expect(CjkInput.submit()).toBe(true);
expect(textarea.blur).toHaveBeenCalled();
expect(textarea.focus).toHaveBeenCalled();
expect(prompts).toEqual(['yes']);
expect(textarea.value).toBe(PHANTOM);
});
it('a hidden field does not get a 0px height (no session shown yet)', () => {
const { CjkInput, textarea } = load({ hold: false });
textarea.getClientRects = () => [];
textarea.scrollHeight = 0;
textarea.style.height = '40px';
CjkInput.setHoldUntilEnter(true);
expect(textarea.style.height).toBe('');
});
it('live mode stashes no drafts', () => {
const { CjkInput, textarea } = load({ hold: false });
textarea.value = PHANTOM + 'abc';
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('live mode is unchanged: text streams after the debounce', () => {
const { textarea, sent } = load({ hold: false });
type(textarea, 'hi');
vi.advanceTimersByTime(1000);
expect(sent).toEqual(['hi']);
});
});
+174
View File
@@ -0,0 +1,174 @@
// Port: none (pure logic in a vm context — no browser, no server).
//
// KeyboardHandler scrolls a newly focused text field into view (scrollInputIntoView,
// `scrollIntoView({ block: 'center' })`) once the keyboard is up. The pinned CJK /
// Send on Enter field (#cjkInput) is position:fixed and already lifted above the
// keyboard by updateLayoutForKeyboard(), so scrolling it into view only centred it in
// its scrollable ancestors and pushed the terminal off screen. It must be skipped,
// like xterm's own inputs, while ordinary inputs keep the behaviour.
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/mobile-handlers.js'), 'utf8');
function loadHandler() {
const context = vm.createContext({
console,
navigator: { userAgent: 'test', maxTouchPoints: 1 },
window: { addEventListener: () => {}, matchMedia: () => ({ matches: false }), scrollTo: () => {} },
document: {
body: { classList: { add: () => {}, remove: () => {} } },
addEventListener: () => {},
getElementById: () => null,
querySelector: () => null,
},
setTimeout: () => 1,
clearTimeout: () => {},
});
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
return (context as { __KH: any }).__KH;
}
function element(tagName: string, { id = '', inside = '' }: { id?: string; inside?: string } = {}) {
return { tagName, id, type: '', isContentEditable: false, closest: (sel: string) => (sel === inside ? {} : null) };
}
describe('KeyboardHandler.isInputElement', () => {
it('skips the pinned CJK field, which the keyboard layout positions itself', () => {
expect(loadHandler().isInputElement(element('TEXTAREA', { id: 'cjkInput' }))).toBe(false);
});
it('still skips xterm inputs and still scrolls ordinary fields into view', () => {
const kh = loadHandler();
expect(kh.isInputElement(element('TEXTAREA', { inside: '.xterm' }))).toBe(false);
expect(kh.isInputElement(element('TEXTAREA', { id: 'someOtherField' }))).toBe(true);
expect(kh.isInputElement(element('INPUT'))).toBe(true);
});
});
function loadLayout({
focused = 'cjkInput',
offsetTop,
height = 458,
width = 390,
innerHeight = 744,
clientHeight = 744,
}: {
focused?: string;
offsetTop: number;
height?: number;
width?: number;
innerHeight?: number;
clientHeight?: number;
}) {
const el = (offsetHeight = 36) => ({
style: {} as Record<string, string>,
offsetHeight,
classList: { contains: () => true },
});
// .app is sized to the visual viewport (--app-height), which is what its fixed
// children are placed against once it carries a transform.
const nodes: Record<string, any> = {
'.app': el(height),
'.toolbar': el(),
'.main': el(),
'.keyboard-accessory-bar': el(),
'.mobile-case-picker.active .mobile-case-picker-sheet': el(300),
};
const cjk = { ...el(), id: 'cjkInput' };
const context = vm.createContext({
console,
navigator: { userAgent: 'test', maxTouchPoints: 1 },
window: {
addEventListener: () => {},
matchMedia: () => ({ matches: false }),
scrollTo: () => {},
innerHeight,
innerWidth: width, // MobileDetection (defined in the module) reads this
visualViewport: { offsetTop, height },
},
document: {
body: { classList: { add: () => {}, remove: () => {} } },
documentElement: { clientHeight },
addEventListener: () => {},
activeElement: focused === 'cjkInput' ? cjk : { id: focused },
getElementById: (id: string) => (id === 'cjkInput' ? cjk : null),
querySelector: (sel: string) => nodes[sel] || null,
},
setTimeout: () => 1,
clearTimeout: () => {},
});
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
const kh = (context as { __KH: any }).__KH;
kh.keyboardVisible = true;
kh.initialViewportHeight = 744;
return { kh, nodes, cjk };
}
describe('KeyboardHandler follows the visual-viewport pan on phones', () => {
it('moves the app down by the pan and lifts nothing more (measured Android case)', () => {
const { kh, nodes, cjk } = loadLayout({ offsetTop: 285 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
// .app bottom = 285 + 458 = 743, visual bottom = 743: the bars already sit on it.
expect(nodes['.toolbar'].style.transform).toBe('');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
expect(cjk.style.transform).toBe('');
});
it('does not lift the bars twice on a partial pan', () => {
// Mid-animation: offsetTop 100 in a 744 layout. Lifting by the layout gap (186px)
// inside the shifted .app would float the bars 186px above the keyboard.
const { kh, nodes, cjk } = loadLayout({ offsetTop: 100 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(100px)');
expect(nodes['.toolbar'].style.transform).toBe('');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
expect(cjk.style.transform).toBe('');
// The open case sheet is inside .app too (index.html #mobileCasePickerModal):
// the layout gap on top of the shift floated it 186px above the keyboard.
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('');
});
it('keeps the old lift when there is no pan', () => {
const { kh, nodes } = loadLayout({ offsetTop: 0 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('');
expect(nodes['.toolbar'].style.transform).toBe('translateY(-286px)');
// Without a pan insideLift is the layout gap, so the case sheet keeps its lift
// (test/mobile-case-sheet-keyboard-lift.test.ts).
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('translateY(-286px)');
});
it('follows a pan whatever has focus, so a focus change cannot drop the shift', () => {
const { kh, nodes } = loadLayout({ focused: 'someOtherField', offsetTop: 285 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
});
it('never shifts the app outside the phone layout (tablet landscape)', () => {
const { kh, nodes } = loadLayout({ offsetTop: 285, width: 1024 });
nodes['.app'].style.transform = 'translateY(285px)'; // left over from portrait
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('');
});
it('lifts the bars when iOS reports innerHeight as the shrunk visual height', () => {
// Measured on an iPhone, first keyboard open: innerHeight 323 = visual height,
// documentElement.clientHeight 640. Lifting by innerHeight - visual bottom gave 0.
const { kh, nodes, cjk } = loadLayout({ offsetTop: 0, height: 323, innerHeight: 323, clientHeight: 640 });
kh.updateLayoutForKeyboard();
expect(nodes['.toolbar'].style.transform).toBe('translateY(-317px)');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('translateY(-317px)');
expect(cjk.style.transform).toBe('translateY(-317px)');
});
it('clears the shift when the layout resets', () => {
const { kh, nodes } = loadLayout({ offsetTop: 285 });
kh.updateLayoutForKeyboard();
kh.resetLayout();
expect(nodes['.app'].style.transform).toBe('');
});
});
+143
View File
@@ -0,0 +1,143 @@
/**
* @fileoverview killSession() must never signal the machine.
*
* On 2026-11-25 a kill that got pid 0 took down every process of the account: every
* session, tmux and the systemd user manager. The children of pid 0 are the whole process
* table, so the descendant walk handed all of it to SIGTERM. tmux answers 0 for a pane
* with no process (`split-window ''`), the pane list read at server start records it on
* the session, and the next close of that tab killed everything.
*
* These drive the SHIPPED killSession() with the tmux and ps answers mocked and
* process.kill stubbed: nothing here may reach a real process.
*
* Port: N/A (no server needed)
*/
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { exec, execFile, execSync } from 'node:child_process';
import { isSignalablePid } from '../src/proc-tree.js';
import type { MuxSession } from '../src/mux-interface.js';
vi.mock('node:child_process', async () => {
const actual = await vi.importActual('node:child_process');
return { ...actual, exec: vi.fn(), execFile: vi.fn(), execSync: vi.fn(), spawn: vi.fn() };
});
/** A machine: init, kthreadd, the user's own programs, and one agent (4242) with a child. */
const PS = ['1 0', '2 0', '900 1', '901 900', '902 900', '4242 901', '4243 4242'].join('\n') + '\n';
describe('isSignalablePid', () => {
it('admits only a process of the user', () => {
for (const pid of [2, 4242, 2 ** 22]) expect(isSignalablePid(pid)).toBe(true);
for (const pid of [1, 0, -0, -1, -4242, NaN, Infinity, 1.5, null, undefined]) {
expect(isSignalablePid(pid as number)).toBe(false);
}
});
});
describe('killSession and a pane without a process', () => {
let panePid: string;
let commands: string[];
let kill: MockInstance<typeof process.kill>;
let signals: [number, string | number | undefined][];
beforeEach(() => {
panePid = '4242\n';
commands = [];
signals = [];
vi.mocked(execSync).mockImplementation(((cmd: string) => {
if (cmd.includes('list-panes -a')) return `codeman-feed1234|${panePid.trim()}|0||\n`;
return '';
}) as unknown as typeof execSync);
vi.mocked(exec).mockImplementation(((cmd: string, options: unknown, maybeCallback?: unknown) => {
commands.push(cmd);
const callback = (typeof options === 'function' ? options : maybeCallback) as (e: null, out: object) => void;
const stdout = cmd.includes('display-message') ? panePid : '';
setImmediate(() => callback(null, { stdout, stderr: '' }));
return { on: vi.fn(), kill: vi.fn(), pid: 12345 };
}) as unknown as typeof exec);
// The process snapshot the descendant walk reads.
vi.mocked(execFile).mockImplementation(((file: string, _args: string[], _options: unknown, callback: unknown) => {
setImmediate(() => (callback as (e: null, out: string) => void)(null, file === 'ps' ? PS : ''));
return { on: vi.fn(), kill: vi.fn(), pid: 12345 };
}) as unknown as typeof execFile);
// Every process dies at its first real signal, so no wait runs its full length.
const gone = new Set<number>();
kill = vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: string | number) => {
if (signal !== 0) {
signals.push([pid, signal]);
gone.add(Math.abs(pid));
} else if (gone.has(Math.abs(pid))) {
throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' });
}
return true;
}) as typeof process.kill);
});
afterEach(() => {
kill.mockRestore();
vi.restoreAllMocks();
});
async function manager(recordedPid: number) {
const vitest = process.env.VITEST;
vi.resetModules();
delete process.env.VITEST;
const { TmuxManager } = await import('../src/tmux-manager.js');
process.env.VITEST = vitest;
const m = new TmuxManager();
m.registerSession({
sessionId: 'feed1234',
muxName: 'codeman-feed1234',
pid: recordedPid,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'claude',
attached: false,
} as MuxSession);
return m;
}
const closedByTmux = () => commands.some((c) => c.includes('kill-session -t "codeman-feed1234"'));
// The control: without it, a guard that refused every kill would pass the rest.
it('still signals the process tree of a real pane', async () => {
const m = await manager(4242);
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toContainEqual([4243, 'SIGTERM']);
expect(signals).toContainEqual([-4242, 'SIGTERM']);
expect(signals.every(([pid]) => [4242, 4243].includes(Math.abs(pid)))).toBe(true);
expect(closedByTmux()).toBe(true);
m.destroy();
});
for (const pid of [0, 1]) {
it(`signals nothing for pid ${pid}, and tmux still closes the session`, async () => {
panePid = `${pid}\n`;
const m = await manager(pid);
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toEqual([]);
expect(closedByTmux()).toBe(true);
expect(m.getSession('feed1234')).toBeUndefined();
m.destroy();
});
}
it('signals nothing when tmux gives no answer and the record holds 0', async () => {
panePid = '\n';
const m = await manager(0);
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toEqual([]);
expect(closedByTmux()).toBe(true);
m.destroy();
});
it('survives the real route: the pane list at server start records 0, then the tab is closed', async () => {
panePid = '0\n';
const m = await manager(4242);
await m.reconcileSessions();
expect(m.getSession('feed1234')?.pid).toBe(0); // what master did next was walk it
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toEqual([]);
expect(closedByTmux()).toBe(true);
m.destroy();
});
});
+138 -2
View File
@@ -41,8 +41,9 @@ function loadTerminalModule(): TerminalModule {
console,
setInterval: vi.fn(),
clearInterval: vi.fn(),
setTimeout,
clearTimeout,
// Looked up per call, so a test's vi.useFakeTimers() reaches the cached module.
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
@@ -547,6 +548,141 @@ describe('one-shot Ctrl through the CJK input field', () => {
});
});
describe('Send on Enter: a held answer goes out with Enter as its own write', () => {
// _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one
// character goes to the composer's _sendComposedPrompt with the session
// captured at Enter, so the delayed Enter cannot follow a tab switch.
function promptApp() {
const { CodemanApp, bar } = loadTerminalModule();
bar.clearCtrl();
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string | null;
_sendCjkPrompt(text: string): boolean;
};
app.activeSessionId = 'session-a';
const composed = vi
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
.mockReturnValue(true);
return { app, bar, composed };
}
it('sends through the composer path, bound to the session active at Enter', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
app.activeSessionId = 'session-b';
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
composed.mockRestore();
});
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
const { app, bar, composed } = promptApp();
bar.toggleCtrl();
app._sendCjkPrompt('x'.repeat(100));
expect(bar.isCtrlArmed()).toBe(false);
composed.mockRestore();
});
it('types a single character, then Enter ~120 ms later to the same session', () => {
// Codex folds an Enter that arrives in the same burst as the text into a
// paste, even for `1\r`; a selection dialog ignores a pasted digit. Same
// split as TmuxManager.sendInput (submitsAsKeys).
vi.useFakeTimers();
try {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) =>
writes.push([id, input, opts]);
expect(app._sendCjkPrompt('1')).toBe(true);
expect(writes).toEqual([['session-a', '1', undefined]]);
app.activeSessionId = 'session-b';
vi.advanceTimersByTime(119);
expect(writes).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]);
expect(composed).not.toHaveBeenCalled();
composed.mockRestore();
} finally {
vi.useRealTimers();
}
});
it('sends a lone digit without Enter while a permission or question dialog waits', () => {
// The dialog acts on the digit keypress itself; an Enter 120 ms later would
// confirm whatever the CLI shows next (a second permission prompt, unseen).
// Same rule as the Approvals Inbox and the Discord bridge (awaitingChoice).
vi.useFakeTimers();
try {
for (const hook of ['permission_prompt', 'elicitation_dialog']) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt('2')).toBe(true);
vi.advanceTimersByTime(500);
expect(writes).toEqual([['session-a', '2', undefined]]);
composed.mockRestore();
}
} finally {
vi.useRealTimers();
}
});
it('keeps the delayed Enter for a digit when only an idle prompt is pending, or for a letter in a dialog', () => {
vi.useFakeTimers();
try {
const cases: Array<[string, string]> = [
['idle_prompt', '1'],
['permission_prompt', 'y'],
];
for (const [hook, text] of cases) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt(text)).toBe(true);
vi.advanceTimersByTime(120);
expect(writes).toEqual([
['session-a', text, undefined],
['session-a', '\r', { useMux: true }],
]);
composed.mockRestore();
}
} finally {
vi.useRealTimers();
}
});
it('pastes even a short word: only one character is typed', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('yes')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'yes');
composed.mockRestore();
});
it('reports a refusal so the field keeps the text', () => {
const { app, composed } = promptApp();
composed.mockReturnValue(false);
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
app.activeSessionId = null;
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('1')).toBe(false);
expect(composed).toHaveBeenCalledTimes(1);
composed.mockRestore();
});
});
describe('armed styling survives the light-skin overrides', () => {
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');
+19 -6
View File
@@ -146,11 +146,14 @@ describe('collectDescendants', () => {
* even with both caps bypassed.
*/
describe('TmuxManager uses the bounded walk', () => {
/** Build a tree `width` wide and `depth` deep, rooted at 1. */
/** A pane's pid. Never 0 or 1: the kill path walks nothing for those (kill-pid-guard.test.ts). */
const ROOT = 1000;
/** Build a tree `width` wide and `depth` deep, rooted at ROOT. */
function bigTree(width: number, depth: number): Map<number, number[]> {
const t = new Map<number, number[]>();
let next = 2;
let frontier = [1];
let next = ROOT + 1;
let frontier = [ROOT];
for (let d = 0; d < depth; d += 1) {
const nf: number[] = [];
for (const p of frontier) {
@@ -163,7 +166,7 @@ describe('TmuxManager uses the bounded walk', () => {
return t;
}
async function walkVia(fixture: Map<number, number[]>): Promise<number[]> {
async function walkVia(fixture: Map<number, number[]>, root = ROOT): Promise<number[]> {
const { TmuxManager } = await import('../src/tmux-manager.js');
const Klass = TmuxManager as unknown as {
refreshProcSnapshot(): Promise<Map<number, number[]>>;
@@ -174,7 +177,7 @@ describe('TmuxManager uses the bounded walk', () => {
Klass.procSnapshot = { at: Date.now(), byParent: fixture };
try {
const mgr = new TmuxManager();
return await (mgr as unknown as { getChildPidsFresh(pid: number): Promise<number[]> }).getChildPidsFresh(1);
return await (mgr as unknown as { getChildPidsFresh(pid: number): Promise<number[]> }).getChildPidsFresh(root);
} finally {
Klass.refreshProcSnapshot = original;
Klass.procSnapshot = null;
@@ -190,7 +193,7 @@ describe('TmuxManager uses the bounded walk', () => {
it('honours the depth cap on a deep chain', async () => {
const chainTree = new Map<number, number[]>();
for (let i = 1; i < 40; i += 1) chainTree.set(i, [i + 1]);
for (let i = ROOT; i < ROOT + 39; i += 1) chainTree.set(i, [i + 1]);
const out = await walkVia(chainTree);
@@ -203,6 +206,16 @@ describe('TmuxManager uses the bounded walk', () => {
const out = await walkVia(bigTree(4, 6));
expect(out.length).toBeLessThanOrEqual(PROC_WALK_MAX_NODES);
});
it.each([0, 1])('walks nothing below pid %i, whose children are the whole machine', async (root) => {
const machine = new Map([
[0, [1, 2]],
[1, [900]],
[900, [901]],
]);
expect(await walkVia(machine, root)).toEqual([]);
expect(await walkVia(machine, 900)).toEqual([901]);
});
});
describe('descendantsInPaneGroup (a shared daemon outlives the pane that started it)', () => {
+18
View File
@@ -0,0 +1,18 @@
/**
* @fileoverview The manifest link must be fetched with credentials. Browsers fetch the web app
* manifest without cookies unless the link says `crossorigin="use-credentials"`, and every
* non-exempt path needs the `codeman_session` cookie when a password is set, so without the
* attribute the manifest answers 401 and the browser refuses to install Codeman as an app.
*/
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
const HTML = readFileSync(new URL('../src/web/public/index.html', import.meta.url), 'utf-8');
describe('PWA manifest link', () => {
it('requests the manifest with credentials so a password-protected install can be installed', () => {
const links = HTML.match(/<link\b[^>]*rel="manifest"[^>]*>/g) ?? [];
expect(links).toHaveLength(1);
expect(links[0]).toContain('crossorigin="use-credentials"');
});
});
+72
View File
@@ -181,6 +181,78 @@ describe('WebServer.renderIndexHtml', () => {
}
});
it('injects the wheelForward rules of every CLI that forwards, custom and disabled entries included', async () => {
// A custom clis.json entry shaped like pi (its mouse DECSETs stripped, wheel forwarded)
// must reach the browser's gate by its own id, and every `never` stays out. A DISABLED
// entry stays in: disabling a CLI never ends its running sessions, so a fullscreen copilot
// tab opened before the switch still needs its wheel after a reload (and an entry enabled
// after the page loaded already has its rule). A solo window scrolls a terminal too, so
// it gets the same map.
const path = dataPath('clis.json');
mkdirSync(dirname(path), { recursive: true });
const custom = {
label: 'PiD',
shortBadge: 'PL',
accent: '#6b7280',
enabled: true,
order: 120,
kind: 'agent',
discovery: { binaries: ['pi-locked'], searchDirs: [], install: { command: {} } },
launch: { params: {}, variants: [{ id: 'default', args: [{ lit: 'pi-locked' }] }] },
env: { exports: [], unset: [], tmuxSetenvKeys: [], dockerExecEnvNames: [], allowedPrefixes: [], allowedKeys: [] },
capabilities: {
external: true,
requiresMux: true,
hooks: 'none',
transcript: 'none',
altScreen: 'strip-mux-and-mouse',
echo: { policy: 'buffer', anchor: { kind: 'none' } },
wheelForward: { mode: 'always' },
keyboardAccessory: 'agent',
privilegedCommandGate: false,
startMode: 'interactive',
stripInkBloat: false,
ralph: false,
respawn: false,
effort: false,
agentSkillInjection: false,
statusLineTelemetry: false,
model: { source: 'none' },
privilegedParams: [],
privilegedEnvKeys: [],
gates: {},
customModelInjection: { kind: 'unsupported' },
},
overlays: {},
};
writeFileSync(
path,
JSON.stringify({ schemaVersion: 1, clis: { copilot: { enabled: false }, 'pi-locked': custom } }),
{
mode: 0o600,
}
);
reloadCliRegistry();
try {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer({});
const html = await render(server, solo);
const match = html.match(/window\.__codemanWheelForward=(\{[^<]*\});/);
expect(match, String(solo)).not.toBeNull();
expect(JSON.parse(match![1])).toEqual({
claude: { mode: 'version-gated', minVersion: '2.1.187' },
codex: { mode: 'always' },
pi: { mode: 'always' },
copilot: { mode: 'always' },
'pi-locked': { mode: 'always' },
});
}
} finally {
writeFileSync(path, JSON.stringify({ clis: {} }, null, 2), { mode: 0o600 });
reloadCliRegistry();
}
});
it('injects the keyboard-hold modes from the keyboardHold capability: inline Claude, never full-height codex', async () => {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer();
+339
View File
@@ -9,7 +9,11 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import fastifyWebsocket from '@fastify/websocket';
import WebSocket, { WebSocketServer } from 'ws';
import { once } from 'node:events';
import type { AddressInfo } from 'node:net';
import fs from 'node:fs/promises';
import http, { createServer, type IncomingHttpHeaders, type Server } from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { registerWebviewRoutes } from '../../src/web/routes/webview-routes.js';
@@ -17,12 +21,28 @@ import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { webviewCapabilities } from '../../src/webview-capabilities.js';
import { capabilityFromProxyPath } from '../../src/web/webview-proxy.js';
import { writeWebviews } from '../../src/webview-store.js';
import { readUsers } from '../../src/user-store.js';
import { TabLayoutService } from '../../src/tab-layout-service.js';
import type { TabLayout } from '../../src/tab-layout.js';
/**
* The supervisor is the one process-spawning piece in this path. Its own tests
* cover the launch-token exchange and the starter binding; here a stub stands in
* for "this port has a cookie" so the route-level question stays what the proxy
* actually puts on the upstream request.
*/
const { getDeepSeekWebCookie } = vi.hoisted(() => ({
getDeepSeekWebCookie: vi.fn((_port: number, _owner?: string): string | null => null),
}));
vi.mock('../../src/deepseek-web-server.js', () => ({ getDeepSeekWebCookie }));
let app: FastifyInstance;
let tmpDir: string;
let savedDataDir: string | undefined;
let savedMultiUser: string | undefined;
/** Stands in for what the auth middleware decorates on the request. */
let currentUser: { username: string; role: 'admin' | 'user' } | undefined;
const broadcasts: Array<{ event: string; data: unknown }> = [];
const webviewCreated = vi.fn(async () => {});
const webviewDeleted = vi.fn(async () => {});
@@ -30,15 +50,23 @@ const webviewDeleted = vi.fn(async () => {});
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'codeman-webviews-'));
savedDataDir = process.env.CODEMAN_DATA_DIR;
savedMultiUser = process.env.CODEMAN_MULTIUSER;
process.env.CODEMAN_DATA_DIR = tmpDir;
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
broadcasts.length = 0;
webviewCreated.mockClear();
webviewDeleted.mockClear();
getDeepSeekWebCookie.mockReset();
getDeepSeekWebCookie.mockReturnValue(null);
app = Fastify({ logger: false });
await app.register(fastifyCookie);
// The proxy route declares a wsHandler, so the plugin must be present.
await app.register(fastifyWebsocket);
app.addHook('onRequest', async (req) => {
if (currentUser) (req as unknown as { authUser: typeof currentUser }).authUser = currentUser;
});
registerWebviewRoutes(app, {
broadcast: (event: string, data: unknown) => broadcasts.push({ event, data }),
tabLayouts: { webviewCreated, webviewDeleted },
@@ -51,11 +79,22 @@ afterEach(async () => {
await app.close();
if (savedDataDir === undefined) delete process.env.CODEMAN_DATA_DIR;
else process.env.CODEMAN_DATA_DIR = savedDataDir;
if (savedMultiUser === undefined) delete process.env.CODEMAN_MULTIUSER;
else process.env.CODEMAN_MULTIUSER = savedMultiUser;
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
const create = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/webviews', payload });
/** Wait for something a relayed connection reports asynchronously. */
async function waitUntil(check: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!check()) {
if (Date.now() > deadline) throw new Error('condition not met in time');
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
describe('GET /api/webviews', () => {
it('starts empty and reports the frame budget the client must honour', async () => {
const res = await app.inject({ method: 'GET', url: '/api/webviews' });
@@ -268,6 +307,306 @@ describe('proxy route', () => {
});
});
describe('proxy route: WebSocket cookie forwarding', () => {
let upstream: Server;
let upstreamPort: number;
let wss: WebSocketServer;
let appPort: number;
let upgradeHeaders: Promise<IncomingHttpHeaders>;
let client: WebSocket | undefined;
beforeEach(async () => {
let resolveUpgrade!: (headers: IncomingHttpHeaders) => void;
upgradeHeaders = new Promise((resolve) => {
resolveUpgrade = resolve;
});
// A real loopback dashboard: its upgrade handler is what records the cookie
// the proxy put on the handshake.
upstream = createServer();
wss = new WebSocketServer({ noServer: true });
upstream.on('upgrade', (req, socket, head) => {
resolveUpgrade(req.headers);
wss.handleUpgrade(req, socket, head, (upstreamSocket) => {
wss.emit('connection', upstreamSocket, req);
});
});
await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));
upstreamPort = (upstream.address() as AddressInfo).port;
// WebSocket upgrades cannot go through inject(); this app needs a real port.
await app.listen({ port: 0, host: '127.0.0.1' });
appPort = (app.server.address() as AddressInfo).port;
});
afterEach(async () => {
client?.terminate();
client = undefined;
for (const socket of wss.clients) socket.terminate();
await new Promise<void>((resolve) => wss.close(() => resolve()));
await new Promise<void>((resolve) => upstream.close(() => resolve()));
await app.close();
});
/** Wait for a promise without letting a missing handshake hang the test until vitest's timeout. */
function within<T>(promise: Promise<T>, timeoutMs = 5000): Promise<T> {
let timer!: NodeJS.Timeout;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('timed out waiting for the upstream WebSocket handshake')), timeoutMs);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
/** Create a trusted tab, open it for a capability, and connect the browser leg with `cookie`. */
async function connectThroughProxy(cookie: string): Promise<void> {
const created = await create({
name: 'Trusted dashboard',
url: `http://127.0.0.1:${upstreamPort}/`,
trusted: true,
});
expect(created.statusCode).toBe(200);
const opened = await app.inject({ method: 'POST', url: `/api/webviews/${created.json().data.id}/open` });
const cap = capabilityFromProxyPath(opened.json().data.embedUrl)!;
client = await new Promise<WebSocket>((resolve, reject) => {
const socket = new WebSocket(`ws://127.0.0.1:${appPort}/webview/${cap}/ws`, { headers: { cookie } });
socket.once('open', () => resolve(socket));
socket.once('error', reject);
});
}
it('forwards only the dashboard cookie, never the Codeman session cookie', async () => {
await connectThroughProxy('codeman_session=SECRET; theme=dark');
const headers = await within(upgradeHeaders);
expect(headers.cookie).toBe('theme=dark');
expect(headers.cookie).not.toContain('codeman_session');
});
it('sends no cookie header when the browser only has the Codeman session cookie', async () => {
await connectThroughProxy('codeman_session=SECRET');
const headers = await within(upgradeHeaders);
expect(headers.cookie).toBeUndefined();
});
});
describe('managed DeepSeek web cookie', () => {
const COOKIE = 'dsh-auth-test=v1.payload.sig';
const upstreams: Array<{ port: number; cookies: Array<string | undefined>; close: () => Promise<void> }> = [];
/** A real loopback listener, so the assertion is on the bytes dsh would receive. */
async function startUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer((req, res) => {
cookies.push(req.headers.cookie);
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('ok');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
upstreams.push(upstream);
return upstream;
}
/** The stub answers for one port and one owner, like the supervisor's two checks. */
function mintCookieOn(port: number, owner: string | undefined): void {
getDeepSeekWebCookie.mockImplementation((askedPort, askedOwner) =>
askedPort === port && askedOwner === owner ? COOKIE : null
);
}
async function openManaged(url: string): Promise<string> {
const created = (await create({ name: 'DeepSeek Harness', url, managed: 'deepseek-web', trusted: true })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
return capabilityFromProxyPath(opened.embedUrl)!;
}
const getThrough = (cap: string) => app.inject({ method: 'GET', url: `/webview/${cap}/` });
async function writeUsersFixture(users: Array<{ username: string; role: string; canBypassPermissions: boolean }>) {
await fs.writeFile(
path.join(tmpDir, 'users.json'),
JSON.stringify({
version: 1,
users: users.map((user) => ({
...user,
password: { algo: 'scrypt', N: 1, r: 1, p: 1, salt: '00', hash: '00' },
createdAt: 1,
})),
})
);
// The store keeps a short cache; write through it instead of waiting for the TTL.
await readUsers(true);
}
afterEach(async () => {
await Promise.all(upstreams.splice(0).map((upstream) => upstream.close()));
});
it('presents it to a managed tab on 127.0.0.1 at the minted port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
it('presents nothing to a managed tab on another port', async () => {
const minted = await startUpstream();
const other = await startUpstream();
mintCookieOn(minted.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${other.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(other.cookies).toEqual([undefined]);
});
it('presents nothing to an unmanaged tab on the same port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const created = (await create({ name: 'Not managed', url: `http://127.0.0.1:${upstream.port}/` })).json().data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
// `managed` comes from the client and the port is public, so this is the case
// the gate exists for: a regular user must not receive the starter's cookie.
it('presents nothing in multi-user mode when the owner has no privileged grant', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'bob', role: 'user' };
await writeUsersFixture([{ username: 'bob', role: 'user', canBypassPermissions: false }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'bob');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
it('presents it in multi-user mode to a granted owner who started the server', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'carol');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, 'carol');
});
// A record keeps the owner it was created under. Back in single-user mode the
// server is started with no starter, so comparing that stale owner would leave
// the tab on dsh's 401 for good.
it('presents it in single-user mode to a managed tab created under multi-user mode', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
mintCookieOn(upstream.port, undefined);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
/**
* A loopback listener that completes the upgrade and records the cookie on the
* handshake. The realtime leg is a separate code path from `proxyRequest`, so
* the HTTP assertions above say nothing about what it puts on the wire.
*/
async function startWebSocketUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
cookies.push(req.headers.cookie);
wss.handleUpgrade(req, socket, head, (client) => client.close());
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('ws upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () =>
new Promise<void>((resolve) => {
wss.close();
server.close(() => resolve());
}),
};
upstreams.push(upstream);
return upstream;
}
it('presents it on the websocket leg too, ahead of the browser cookies', async () => {
const upstream = await startWebSocketUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
// Upgrades need a real listener: inject() cannot carry them.
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address() as AddressInfo;
const client = new WebSocket(`ws://127.0.0.1:${port}/webview/${cap}/ws`, {
headers: { cookie: 'codeman_session=SECRET; dsh-ui=dark' },
});
await once(client, 'open');
await waitUntil(() => upstream.cookies.length > 0);
// The credential leads so a stale browser copy cannot win, other dashboard
// cookies survive, and Codeman's own session cookie never goes upstream.
expect(upstream.cookies).toEqual([`${COOKIE}; dsh-ui=dark`]);
client.close();
});
});
describe('proxy HTML rewrite', () => {
// The request path is what the page's relative URLs are relative to. Proving
// it here (rather than only on rewriteHtml) pins that proxyRequest passes it.
it("resolves the document's relative base against its own directory", async () => {
const server = http.createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<html><head><base href="./"></head><body>app</body></html>');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
try {
const created = (await create({ name: 'App', url: `http://127.0.0.1:${address.port}/app/page.html` })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
const res = await app.inject({ method: 'GET', url: `/webview/${cap}/app/page.html` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain(`<base href="/webview/${cap}/app/">`);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
});
describe('POST /api/webviews/probe', () => {
it('reports an unreachable target as a normal answer, not a 500', async () => {
// Port 1 is reserved and refuses instantly.
+3 -1
View File
@@ -117,7 +117,9 @@ describe('WebServer index.html <title> templating (#82)', () => {
// Likewise the page-key mode list: an array, possibly empty, always injected.
.replace(/<script>window\.__codemanTranscriptPageKeys=\[.*?\];<\/script>\n/, '')
// And the keyboard-hold mode list, built the same way.
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '');
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '')
// And the wheel-forwarding rules: an object keyed by run mode, always injected.
.replace(/<script>window\.__codemanWheelForward=\{.*?\};<\/script>\n/, '');
const beforeTitle = rawTemplate.split('<title>Codeman</title>')[0];
const afterTitle = rawTemplate.split('<title>Codeman</title>')[1];
expect(html.startsWith(beforeTitle)).toBe(true);
+102 -1
View File
@@ -28,8 +28,19 @@ import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
*/
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
/**
* The run modes that take the wheel as SGR reports, read off the shipped registry the way
* the server builds `__codemanWheelForward` (every `wheelForward` other than `never`).
*/
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
function loadTerminalUiHarness(
windowGlobals: Record<string, unknown> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES }
windowGlobals: Record<string, unknown> = {
__codemanTranscriptPageKeys: PAGE_KEY_MODES,
__codemanWheelForward: WHEEL_FORWARD,
}
) {
const CodemanApp = function CodemanApp(this: any) {};
const logs: string[] = [];
@@ -927,6 +938,96 @@ describe('pi wheel forwarding (fullscreen by default since 1.0.0)', () => {
});
});
describe('wheel forwarding read from the injected wheelForward map, for any CLI id', () => {
// A custom CLI (clis.json, e.g. a pi wrapper under its own id) that strips its mouse
// DECSETs gets `cliMouseTracking` like pi, but the gate used to name copilot and pi by id,
// so its wheel hit an empty local buffer after every tab switch or reload.
function customApp(
map: Record<string, unknown> | undefined,
session: { mode: string; cliMouseTracking?: boolean; cliVersion?: string }
) {
const globals: Record<string, unknown> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES };
if (map) globals.__codemanWheelForward = map;
const { app } = loadTerminalUiHarness(globals);
app.activeSessionId = 'sess-1';
app.sessions = new Map([['sess-1', session]]);
app.terminal = {
rows: 36,
modes: { mouseTrackingMode: 'none' },
buffer: { active: { type: 'normal', viewportY: 0, baseY: 0, length: 36 } },
};
return app;
}
it('forwards a custom id the map lists as always, only while it tracks the mouse', () => {
const map = { 'pi-locked': { mode: 'always' } };
const tracking = customApp(map, { mode: 'pi-locked', cliMouseTracking: true });
expect(tracking._shouldForwardWheelToApp({ shiftKey: false })).toBe(true);
expect(tracking._shouldForwardWheelToApp({ shiftKey: true })).toBe(false);
expect(customApp(map, { mode: 'pi-locked', cliMouseTracking: false })._shouldForwardWheelToApp({})).toBe(false);
expect(customApp(map, { mode: 'pi-locked' })._shouldForwardWheelToApp({})).toBe(false);
});
it('applies a version-gated rule to a custom id: at or above minVersion only, unknown version never', () => {
const map = { 'my-cli': { mode: 'version-gated', minVersion: '2.0.0' } };
const at = (cliVersion?: string) =>
customApp(map, { mode: 'my-cli', cliMouseTracking: true, cliVersion })._shouldForwardWheelToApp({});
expect(at('1.9.9')).toBe(false);
expect(at('2.0.0')).toBe(true);
expect(at('2.0.1')).toBe(true);
expect(at(undefined)).toBe(false);
});
it('a version-gated rule whose minVersion is not three numbers forwards nothing, whatever the CLI version', () => {
// The schema takes any string up to 20 characters. A minimum that cannot be read as
// MAJOR.MINOR.PATCH must refuse, the conservative answer an unreadable session version gets.
for (const minVersion of ['', '0', '2.0', '1.2.3.4', '0.bad.999', 'x.y.z', '2..0', '+2.0.0', '0x1.0.0']) {
const app = customApp(
{ 'my-cli': { mode: 'version-gated', minVersion } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({}), JSON.stringify(minVersion)).toBe(false);
}
// A well-formed minimum keeps working, a leading `v` and surrounding spaces included.
for (const minVersion of ['9.9.9', 'v2.0.0', ' 2.0.0 ']) {
const app = customApp(
{ 'my-cli': { mode: 'version-gated', minVersion } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({}), JSON.stringify(minVersion)).toBe(true);
}
});
it('a version-gated rule with no minVersion (the schema allows it) forwards nothing and does not throw', () => {
const app = customApp(
{ 'my-cli': { mode: 'version-gated' } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({})).toBe(false);
});
it('never forwards an id the map leaves out, and nothing at all from a page rendered without the map', () => {
expect(
customApp(
{ 'pi-locked': { mode: 'always' } },
{ mode: 'other', cliMouseTracking: true }
)._shouldForwardWheelToApp({})
).toBe(false);
for (const mode of ['claude', 'codex', 'copilot', 'pi']) {
expect(
customApp(undefined, { mode, cliMouseTracking: true, cliVersion: '9.9.9' })._shouldForwardWheelToApp({}),
mode
).toBe(false);
}
});
it('a map entry of mode never forwards, even for a stock id', () => {
expect(
customApp({ pi: { mode: 'never' } }, { mode: 'pi', cliMouseTracking: true })._shouldForwardWheelToApp({})
).toBe(false);
});
});
describe('the paging gates asked for another pane (a TerminalTile)', () => {
it('exports the paging math, and the primary pane runs on it', () => {
const { app, sent, windowRef } = hollowApp();
+6
View File
@@ -49,6 +49,11 @@ const fetchMock = vi.fn();
*/
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
/** The wheel-forwarding rules, read off the registry as the server builds `window.__codemanWheelForward`. */
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
/**
* The clock both panes read gesture gaps from (`performance.now()`). Real time by
* default; a test that needs a pause or a burst moves it by hand.
@@ -62,6 +67,7 @@ function loadContext() {
removeEventListener: vi.fn(),
CodemanBase: { base: '' },
__codemanTranscriptPageKeys: PAGE_KEY_MODES,
__codemanWheelForward: WHEEL_FORWARD,
};
const context = vm.createContext({
console: { ...console, log: vi.fn(), debug: vi.fn() },
+48 -2
View File
@@ -2,6 +2,12 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
/** The wheel-forwarding rules, read off the registry as the server builds `window.__codemanWheelForward`. */
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
function loadTerminalUiHarness() {
const CodemanApp = function CodemanApp(this: any) {};
@@ -10,7 +16,7 @@ function loadTerminalUiHarness() {
let activeElement: unknown = null;
// The module hangs its constants off window (CodemanTerminalInput) and the URL branch of
// the link provider opens through window.open, so tests need a handle on the same object.
const windowRef: Record<string, any> = {};
const windowRef: Record<string, any> = { __codemanWheelForward: WHEEL_FORWARD };
const context = vm.createContext({
window: windowRef,
document: {
@@ -139,6 +145,28 @@ describe('terminal touch tap mouse guard', () => {
expect(app._isMobileTerminalInputFocused()).toBe(true);
});
it('a content touchstart blurs xterm input but leaves the pinned CJK field focused', () => {
const { app, setActiveElement } = loadTerminalUiHarness();
setActiveElement({ id: '', classList: { contains: (c: string) => c === 'xterm-helper-textarea' } });
expect(app._contentTouchStartBlurs()).toBe(true);
// A swipe that starts on the live screen must not close the keyboard the field owns.
setActiveElement({ id: 'cjkInput', classList: { contains: () => false } });
expect(app._contentTouchStartBlurs()).toBe(false);
setActiveElement(null);
expect(app._contentTouchStartBlurs()).toBe(true);
});
it('the content touchstart only blurs through _contentTouchStartBlurs()', () => {
// The touchstart listener lives in initTerminal, which this harness does not run,
// so pin its one line: an unconditional blur there closes the pinned field's
// keyboard on every swipe that starts on the live screen.
const code = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
const branch = code.slice(code.indexOf("if (touchStartIntent === 'content') {"));
const body = branch.slice(0, branch.indexOf('// Hold still and this press becomes a text selection.'));
expect(body).toContain('if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();');
expect(body.match(/_blurMobileTerminalInput\(\)/g)).toHaveLength(1);
});
it('routes a readback row to the TUI while keeping the prompt row as keyboard input', () => {
const { app } = loadTerminalUiHarness();
app.activeSessionId = 'sess-1';
@@ -967,9 +995,27 @@ describe('terminal link tap', () => {
app._isOutsideWorktreePath = () => false;
windowRef.open = vi.fn();
app.registerFilePathLinkProvider();
return { app, windowRef, sent };
return { app, windowRef, sent, setActiveElement: harness.setActiveElement };
}
it('a link tap closes the keyboard of the pinned CJK field, which touchstart left focused', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
const cjk = { id: 'cjkInput', classList: { contains: () => false }, blur: vi.fn() };
setActiveElement(cjk);
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
expect(cjk.blur).toHaveBeenCalled();
});
it('a link tap leaves focus alone otherwise (touchstart already blurred xterm input)', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
const other = { id: '', classList: { contains: () => false }, blur: vi.fn() };
setActiveElement(other);
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
expect(other.blur).not.toHaveBeenCalled();
});
it('opens a URL under the finger in a new tab', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, windowRef } = linkHarness([line, '', '❯ ']);
+48 -4
View File
@@ -115,6 +115,32 @@ describe('restrictTmuxPrefixTable (recorded commands)', () => {
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false);
expect(tmux.calls.filter((c) => c.includes('bind-key'))).toEqual([]);
});
it('reads a one-binding table from the full listing when `list-keys -T prefix` prints nothing', () => {
// tmux 3.7 through 3.7c list a table holding exactly one binding as nothing at
// all on stdout (fixed in 3.8). The reduced table must still read as reduced, or every call resets it.
const tmux = fakeTmux({
'show-options -gv prefix': 'C-b\n',
'list-keys -T prefix': '',
'list-keys':
'bind-key -T copy-mode C-a send-keys -X start-of-line\n' +
'bind-key -T prefix C-b send-prefix\n' +
'bind-key -T root F1 detach-client\n',
});
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false);
expect(tmux.calls).toContain(`tmux -L 'codeman' list-keys`);
expect(tmux.calls.filter((c) => c.includes('bind-key') || c.includes('unbind-key'))).toEqual([]);
});
it('still resets when the full listing shows a stock prefix binding', () => {
const tmux = fakeTmux({
'show-options -gv prefix': 'C-b\n',
'list-keys -T prefix': '',
'list-keys': 'bind-key -T prefix ) switch-client -n\n',
});
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(true);
expect(tmux.calls).toContain(`tmux -L 'codeman' unbind-key -a -T prefix`);
});
});
const hasTmux = (() => {
@@ -126,12 +152,29 @@ const hasTmux = (() => {
}
})();
/**
* One key table as `list-keys -T <table>` prints it. tmux 3.7 through 3.7c (fixed in
* 3.8) print NOTHING there when the table holds exactly one binding,
* which is the shape every reset in this file produces, so a blank answer is read from
* the full listing instead, its padding folded to the `-T <table>` form.
*/
function listKeyTable(base: string, table: string): string {
const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const direct = run(`${base} list-keys -T ${table}`);
if (direct.trim()) return direct;
return run(`${base} list-keys`)
.split('\n')
.filter((line) => new RegExp(`^bind-key\\s+(?:-\\S+\\s+)*?-T\\s+${table}\\s`).test(line.trim()))
.map((line) => line.trim().replace(/-T\s+(\S+)\s+/, '-T $1 '))
.join('\n');
}
describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private socket)', () => {
// Throwaway server, never Codeman's socket; -f /dev/null keeps the user's config out.
const socket = `codeman-prefix-test-${process.pid}`;
const tmux = `tmux -L ${socket} -f /dev/null`;
const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const keys = (table: string) => run(`${tmux} list-keys -T ${table}`);
const keys = (table: string) => listKeyTable(tmux, table);
let client: pty.IPty | null = null;
/** The session the attach client is looking at right now. */
@@ -275,7 +318,8 @@ describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private
run(`${tmux} set-option -g prefix 'C-\\'`);
try {
expect(restrictTmuxPrefixTable(tmux, run)).toBe(true);
expect(keys('prefix')).toMatch(/-T prefix C-\\\\\s+send-prefix/);
// `list-keys -T` escapes the key (`C-\\`); the full listing some builds fall back to does not.
expect(keys('prefix')).toMatch(/-T prefix C-\\(?:\\)?\s+send-prefix/);
expect(restrictTmuxPrefixTable(tmux, run)).toBe(false);
} finally {
run(`${tmux} set-option -g prefix C-b`);
@@ -345,7 +389,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke
it('after the nested reset, Ctrl+Q ), s and w leave the client, and Ctrl+Q Ctrl+Q reaches the pane', async () => {
for (const command of nestedPrefixTableResetCommands()) run(`${tmux} ${command}`);
const prefix = run(`${tmux} list-keys -T prefix`)
const prefix = listKeyTable(tmux, 'prefix')
.split('\n')
.filter((line) => line.trim());
expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]);
@@ -381,7 +425,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke
].join(' \\; ');
try {
run(`${base} -f ${config} ${chain}`);
const prefix = run(`${base} list-keys -T prefix`)
const prefix = listKeyTable(base, 'prefix')
.split('\n')
.filter((line) => line.trim());
expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]);
+57
View File
@@ -13,6 +13,7 @@ import { describe, it, expect } from 'vitest';
import {
applyLiveMetrics,
applyMuxNames,
attachTargetError,
beginAttachHandoff,
buildAttachBanner,
buildListLines,
@@ -30,6 +31,7 @@ import {
planResume,
previewIntervalMs,
previewNoteFor,
resolveAttachTarget,
resyncDelayMs,
sameFrame,
samePreview,
@@ -915,3 +917,58 @@ describe('planResume', () => {
});
});
});
describe('resolveAttachTarget (codeman tui <session>)', () => {
function named(name: string, group: TuiRow['group'], sessionId: string): TuiRow {
return {
session: { sessionId, sources: ['live'], name },
state: group === 'recent' ? 'recent' : 'idle',
group,
since: 0,
};
}
const rows: TuiRow[] = [
named('api', 'working', 'aaaaaaaa01'),
named('docs', 'idle', 'bbbbbbbb02'),
named('twin', 'idle', 'cccccccc03'),
named('twin', 'needs-you', 'dddddddd04'),
named('old', 'recent', 'eeeeeeee05'),
named('docs', 'recent', 'ffffffff06'),
];
it('keeps digits-only as a list position, as a number or as a string', () => {
expect(resolveAttachTarget(rows, 2)).toEqual({ kind: 'row', row: rows[1] });
expect(resolveAttachTarget(rows, '2')).toEqual({ kind: 'row', row: rows[1] });
expect(resolveAttachTarget(rows, '7')).toEqual({ kind: 'none' });
});
it('attaches the one live session with that exact name, ignoring a finished namesake', () => {
expect(resolveAttachTarget(rows, 'api')).toEqual({ kind: 'row', row: rows[0] });
expect(resolveAttachTarget(rows, 'docs')).toEqual({ kind: 'row', row: rows[1] });
});
it('matches case-sensitively and never by prefix', () => {
expect(resolveAttachTarget(rows, 'API')).toEqual({ kind: 'none' });
expect(resolveAttachTarget(rows, 'ap')).toEqual({ kind: 'none' });
});
it('refuses a name two live sessions share, naming their positions', () => {
expect(resolveAttachTarget(rows, 'twin')).toEqual({ kind: 'ambiguous', positions: [3, 4] });
});
it('says a name only history carries is finished, not missing', () => {
expect(resolveAttachTarget(rows, 'old')).toEqual({ kind: 'finished' });
expect(resolveAttachTarget(rows, 'nope')).toEqual({ kind: 'none' });
});
it('words each refusal for a human and points at --list', () => {
expect(attachTargetError({ kind: 'ambiguous', positions: [3, 4] }, 'twin')).toMatch(
/2 live sessions are named twin \(3, 4 in the list\)[\s\S]*codeman tui 3/
);
expect(attachTargetError({ kind: 'finished' }, 'old')).toContain('no live session named old');
expect(attachTargetError({ kind: 'none' }, 'nope')).toContain('there is no session named nope');
expect(attachTargetError({ kind: 'none' }, 9)).toContain('there is no session 9');
for (const kind of ['finished', 'none'] as const)
expect(attachTargetError({ kind }, 'x')).toContain('codeman tui --list');
});
});
+32
View File
@@ -1015,3 +1015,35 @@ describe('resumeSession', () => {
expect(recorded).toHaveLength(1);
});
});
describe('TuiClient key-table reads on a tmux that lists a one-binding table as nothing', () => {
// tmux 3.7 through 3.7c (fixed in 3.8) print nothing for `list-keys -T prefix` when
// the table holds exactly one binding, which is how Codeman leaves it. Reading that as "free"
// would let the TUI claim a key the user has bound.
const fullListing =
'bind-key -T copy-mode C-a send-keys -X start-of-line\n' +
'bind-key -T prefix C-b send-prefix\n' +
'bind-key -T root F1 detach-client\n';
function client(direct: string) {
const calls: string[][] = [];
const exec = async (_file: string, args: readonly string[]) => {
calls.push([...args]);
return { stdout: args.includes('-T') ? direct : fullListing, stderr: '' };
};
return { tui: new TuiClient({ socket: 'cod563', exec }), calls };
}
it('falls back to the full listing when the table answer is blank', async () => {
const { tui, calls } = client('');
expect(await tui.readPrefixBinding('C-b')).toBe('send-prefix');
expect(await tui.readPrefixBinding('F1', 'root')).toBe('detach-client');
expect(await tui.readPrefixBinding('x')).toBeNull();
expect(calls.some((args) => args.length === 3 && args[2] === 'list-keys')).toBe(true);
});
it('keeps the table answer when there is one, with no second call', async () => {
const { tui, calls } = client('bind-key -T prefix d detach-client\n');
expect(await tui.readDetachKey()).toBe('d');
expect(calls).toEqual([['-L', 'cod563', 'list-keys', '-T', 'prefix']]);
});
});
+41
View File
@@ -778,6 +778,47 @@ describe('codeman tui --list', () => {
}, 30_000);
});
describe('codeman tui <session name>', () => {
it('resolves an exact live name before asking for a terminal', async () => {
const result = await runPiped(['tui', 'w1-alpha']);
expect(result.code).toBe(1);
// Got past resolution: the only refusal left is the missing TTY.
expect(result.stderr).toContain('attaching needs an interactive terminal');
expect(result.stderr).not.toContain('no session');
}, 30_000);
it('says a name nothing carries is missing, and points at --list', async () => {
const result = await runPiped(['tui', 'w9-nope']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('there is no session named w9-nope');
expect(result.stderr).toContain('codeman tui --list');
}, 30_000);
it('says a name only history carries is finished', async () => {
const result = await runPiped(['tui', 'w3-gamma']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('no live session named w3-gamma, only a finished one');
}, 30_000);
it('refuses a name two live sessions share and names their numbers', async () => {
sessions.push({ ...sessions[1], sessionId: 'eeee5555-0000-0000-0000-000000000000' });
try {
const result = await runPiped(['tui', 'w1-alpha']);
expect(result.code).toBe(1);
expect(result.stderr).toMatch(/2 live sessions are named w1-alpha \(\d+, \d+ in the list\)/);
expect(result.stderr).toContain('Attach by number instead');
} finally {
resetSessions();
}
}, 30_000);
it('still reads digits as a list number', async () => {
const result = await runPiped(['tui', '42']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('there is no session 42');
}, 30_000);
});
describe('codeman tui without a terminal', () => {
it('refuses to open the dashboard and points at the fast paths', async () => {
const result = await runPiped(['tui']);
+695
View File
@@ -0,0 +1,695 @@
/**
* @fileoverview Pins bounded fs.watch failure handling and polling fallback after a production chokidar retry loop flooded logs and synchronous close caused unhandled rejections.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { TeamWatcher } from '../src/team-watcher.js';
import { WorkflowRunWatcher } from '../src/workflow-run-watcher.js';
import { TEAM_POLL_INTERVAL_MS } from '../src/config/team-config.js';
import { WORKFLOW_RUN_POLL_INTERVAL_MS } from '../src/config/workflow-config.js';
import type { TeamConfig } from '../src/types.js';
import type { WorkflowRunInfo } from '../src/types/workflow-run.js';
const FAILURES = [
{ code: 'EMFILE', errno: -24, text: 'too many open files' },
{ code: 'ENOSPC', errno: -28, text: 'no space left on device' },
] as const;
type WatchFailure = { code: string; errno: number; text: string };
// On macOS chokidar 3 never calls fs.watch for these watchers: it uses fsevents,
// or polling when fsevents is missing, so the retry loop these tests pin cannot
// happen there and the stubbed fs.watch never fires.
const describeLinuxWatch = describe.skipIf(process.platform === 'darwin');
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function waitUntil(predicate: () => boolean, message: string): Promise<void> {
const deadline = Date.now() + 1500;
while (!predicate()) {
if (Date.now() >= deadline) throw new Error(message);
await delay(10);
}
}
function watchError(failure: WatchFailure, path: string): NodeJS.ErrnoException {
return Object.assign(new Error(`${failure.code}: ${failure.text}, watch '${path}'`), {
code: failure.code,
errno: failure.errno,
syscall: 'watch',
path,
});
}
function failEveryWatch(failure: WatchFailure) {
return vi.spyOn(fs, 'watch').mockImplementation((path) => {
throw watchError(failure, String(path));
});
}
let tempDir: string;
let watcher: TeamWatcher | WorkflowRunWatcher | undefined;
let warn: ReturnType<typeof vi.spyOn<typeof console, 'warn'>>;
let error: ReturnType<typeof vi.spyOn<typeof console, 'error'>>;
let unhandled: unknown[];
let onUnhandled: (reason: unknown) => void;
beforeEach(async () => {
watcher = undefined;
tempDir = await mkdtemp(join(tmpdir(), 'codeman-watch-failure-'));
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
error = vi.spyOn(console, 'error').mockImplementation(() => {});
unhandled = [];
onUnhandled = (reason) => unhandled.push(reason);
process.on('unhandledRejection', onUnhandled);
});
afterEach(async () => {
try {
watcher?.stop();
// Keep mocks and the rejection listener installed while asynchronous close settles.
await delay(100);
await rm(tempDir, { recursive: true, force: true });
} finally {
process.off('unhandledRejection', onUnhandled);
vi.useRealTimers();
vi.restoreAllMocks();
}
});
function createTeamConfig(): TeamConfig {
return {
name: 'test-team',
createdAt: 1_700_000_000_000,
leadAgentId: 'team-lead@test-team',
leadSessionId: 'session-123',
members: [
{
agentId: 'team-lead@test-team',
name: 'team-lead',
agentType: 'team-lead',
joinedAt: 1_700_000_000_000,
},
],
};
}
async function writeTeam(teamsDir: string, config: TeamConfig): Promise<void> {
const dir = join(teamsDir, config.name);
await mkdir(dir);
await writeFile(join(dir, 'config.json'), JSON.stringify(config));
}
describeLinuxWatch('TeamWatcher fs.watch failure', () => {
let teamsDir: string;
let tasksDir: string;
let teamWatcher: TeamWatcher;
beforeEach(async () => {
teamsDir = join(tempDir, 'teams');
tasksDir = join(tempDir, 'tasks');
await mkdir(teamsDir);
await mkdir(tasksDir);
watcher = teamWatcher = new TeamWatcher(teamsDir, tasksDir);
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
});
function expectWarnings(messages: string[]): void {
// Check counts before arguments so a retry storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(messages.length);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
expect(warn.mock.calls.map((call) => [...call]).sort()).toEqual(messages.map((message) => [message]).sort());
}
it.each(FAILURES)('$code stops both watchers with two warnings and keeps polling', async (failure) => {
const watch = failEveryWatch(failure);
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
const attempts = watch.mock.calls.length;
await delay(500);
// Check counts before arguments so the unfixed log storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(2);
expect(error).toHaveBeenCalledTimes(0);
for (const call of warn.mock.calls) expect(call.length).toBe(1);
expect(warn.mock.calls.map(([message]) => message).sort()).toEqual(
[
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
].sort()
);
expect(watch.mock.calls.length).toBe(attempts);
expect(attempts).toBeGreaterThanOrEqual(2);
// Allow a handful of in-flight attempts, but never an ancestor retry loop.
expect(attempts).toBeLessThanOrEqual(6);
expect(unhandled.length).toBe(0);
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
for (const pollCount of [2, 3, 4]) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
// The same empty roots must cost the same bounded number of attempts on every tick.
expect(watch).toHaveBeenCalledTimes(attempts * pollCount);
expectWarnings(expectedWarnings);
expect(teamWatcher.getTeams()).toEqual([]);
await delay(200);
expect(watch).toHaveBeenCalledTimes(attempts * pollCount);
}
const config = createTeamConfig();
await writeTeam(teamsDir, config);
expect(teamWatcher.getTeams()).toEqual([]);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await waitUntil(() => teamWatcher.getTeams().length > 0, 'polling did not discover the new team');
expect(teamWatcher.getTeams()).toEqual([config]);
await delay(500);
const finalAttempts = watch.mock.calls.length;
expect(finalAttempts - attempts * 4).toBeGreaterThanOrEqual(2);
expect(finalAttempts - attempts * 4).toBeLessThanOrEqual(6);
expectWarnings(expectedWarnings);
expect(() => teamWatcher.stop()).not.toThrow();
expect(() => teamWatcher.stop()).not.toThrow();
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS * 3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(finalAttempts);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
}
});
it('warns again about a watcher that still fails after stop() and start() on the same instance', async () => {
const failure = FAILURES[0];
const watch = failEveryWatch(failure);
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
await delay(200);
expectWarnings(expectedWarnings);
teamWatcher.stop();
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 4, 'a restarted watcher stayed silent about the same outage');
await delay(200);
expectWarnings([...expectedWarnings, ...expectedWarnings]);
} finally {
teamWatcher.stop();
watch.mockRestore();
}
});
it('keeps a healthy watcher active and discovers a new team before the poll interval', async () => {
const watch = vi.spyOn(fs, 'watch');
try {
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'healthy watchers did not start');
await delay(200);
const attempts = watch.mock.calls.length;
for (let tick = 0; tick < 3; tick++) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(200);
expect(watch).toHaveBeenCalledTimes(attempts);
expect(teamWatcher.getTeams()).toEqual([]);
expectWarnings([]);
}
const config = createTeamConfig();
await writeTeam(teamsDir, config);
// No interval is advanced: discovery must come from the real filesystem watcher.
await waitUntil(() => teamWatcher.getTeams().length > 0, 'healthy watcher did not discover the new team');
expect(teamWatcher.getTeams()).toEqual([config]);
teamWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
teamWatcher.stop();
}
});
it.each(FAILURES)('$code resumes live discovery when both watchers recover on the next poll', async (failure) => {
const watch = failEveryWatch(failure);
const created = vi.fn();
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
try {
teamWatcher.on('teamCreated', created);
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
await delay(200);
expectWarnings(expectedWarnings);
watch.mockRestore();
const recoveredWatch = vi.spyOn(fs, 'watch');
await delay(200);
expect(recoveredWatch).toHaveBeenCalledTimes(0);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(recoveredWatch).toHaveBeenCalledTimes(2);
expect(recoveredWatch.mock.calls.map(([path]) => String(path)).sort()).toEqual([teamsDir, tasksDir].sort());
expect(teamWatcher.getTeams()).toEqual([]);
const config = createTeamConfig();
await writeTeam(teamsDir, config);
// No further interval tick: the recovered teams watcher must discover this team.
await waitUntil(() => created.mock.calls.length > 0, 'recovered watcher did not discover the new team');
expect(created).toHaveBeenCalledTimes(1);
expect(created.mock.calls).toEqual([[config]]);
expect(teamWatcher.getTeams()).toEqual([config]);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
teamWatcher.off('teamCreated', created);
}
});
it('re-arms after one new file throws ENOENT and resumes live discovery without another poll', async () => {
const realWatch = fs.watch;
const vanishedPath = join(teamsDir, 'vanished.json');
const failure = watchError({ code: 'ENOENT', errno: -2, text: 'no such file or directory' }, vanishedPath);
let failedCalls = 0;
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
if (String(args[0]) === vanishedPath && failedCalls === 0) {
failedCalls++;
throw failure;
}
return realWatch(...args);
});
const created = vi.fn();
let closeErrorMessage = '';
try {
(undefined as unknown as fs.FSWatcher).close();
} catch (error) {
closeErrorMessage = (error as TypeError).message;
}
const expectedWarnings = [`[TeamWatcher] teams watcher stopped, relying on polling: ${closeErrorMessage}`];
try {
teamWatcher.on('teamCreated', created);
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'healthy watchers did not start');
await delay(200);
await writeFile(vanishedPath, '{}');
await waitUntil(() => warn.mock.calls.length > 0, 'the transient failure did not stop the teams watcher');
await delay(200);
expect(failedCalls).toBe(1);
expectWarnings(expectedWarnings);
await rm(vanishedPath);
const stoppedAttempts = watch.mock.calls.length;
await delay(200);
expect(watch).toHaveBeenCalledTimes(stoppedAttempts);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(stoppedAttempts + 1);
expect(watch.mock.calls.slice(stoppedAttempts).map(([path]) => String(path))).toEqual([teamsDir]);
expect(teamWatcher.getTeams()).toEqual([]);
const config = createTeamConfig();
await writeTeam(teamsDir, config);
await waitUntil(() => created.mock.calls.length > 0, 're-armed watcher did not discover the new team');
expect(created).toHaveBeenCalledTimes(1);
expect(created.mock.calls).toEqual([[config]]);
expect(teamWatcher.getTeams()).toEqual([config]);
expect(failedCalls).toBe(1);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
teamWatcher.off('teamCreated', created);
}
});
it.each(FAILURES.flatMap((failure) => ['teams', 'tasks'].map((kind) => ({ ...failure, kind }))))(
'$code re-arms only the $kind watcher and warns again only after a healthy poll',
async ({ kind, ...failure }) => {
const root = kind === 'teams' ? teamsDir : tasksDir;
const healthyRoot = kind === 'teams' ? tasksDir : teamsDir;
const realWatch = fs.watch;
let failingPath: string | undefined = root;
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
if (String(args[0]) === failingPath) throw watchError(failure, failingPath);
return realWatch(...args);
});
const expectedWarnings = [
`[TeamWatcher] ${kind} watcher stopped, relying on polling: ${watchError(failure, root).message}`,
];
const attemptsAt = (path: string) =>
watch.mock.calls.filter(([watchedPath]) => String(watchedPath) === path).length;
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the failed watcher warning');
await delay(200);
expectWarnings(expectedWarnings);
expect(attemptsAt(root)).toBe(1);
expect(attemptsAt(healthyRoot)).toBe(1);
for (const expectedAttempts of [2, 3]) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(expectedAttempts + 1);
expect(attemptsAt(root)).toBe(expectedAttempts);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
await delay(200);
expect(watch).toHaveBeenCalledTimes(expectedAttempts + 1);
}
failingPath = undefined;
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(5);
expect(attemptsAt(root)).toBe(4);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
// A successful re-arm alone does not end the outage before the following poll.
failingPath = join(root, 'before-healthy-poll.json');
await writeFile(failingPath, '{}');
await waitUntil(() => attemptsAt(failingPath!) > 0, 'recreated watcher did not watch the first new file');
await delay(200);
expect(watch).toHaveBeenCalledTimes(6);
expectWarnings(expectedWarnings);
await rm(failingPath);
failingPath = undefined;
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(7);
expect(attemptsAt(root)).toBe(5);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(200);
expect(watch).toHaveBeenCalledTimes(7);
expectWarnings(expectedWarnings);
failingPath = join(root, 'after-healthy-poll.json');
await writeFile(failingPath, '{}');
await waitUntil(() => attemptsAt(failingPath!) > 0, 'healthy watcher did not watch the second new file');
await delay(200);
expect(watch).toHaveBeenCalledTimes(8);
expectWarnings([
...expectedWarnings,
`[TeamWatcher] ${kind} watcher stopped, relying on polling: ${watchError(failure, failingPath).message}`,
]);
expect(teamWatcher.getTeams()).toEqual([]);
} finally {
teamWatcher.stop();
}
}
);
it.each([{ code: 'healthy', failure: undefined }, ...FAILURES.map((failure) => ({ code: failure.code, failure }))])(
'$code stop closes both watchers and the interval and is idempotent',
async ({ failure }) => {
const watch = failure ? failEveryWatch(failure) : vi.spyOn(fs, 'watch');
const expectedWarnings = failure
? [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
]
: [];
try {
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'watchers did not attempt to start');
await delay(200);
expectWarnings(expectedWarnings);
const attempts = watch.mock.calls.length;
const closed: string[] = [];
if (!failure) {
expect(watch).toHaveBeenCalledTimes(2);
watch.mock.results.forEach((result, index) => {
expect(result.type).toBe('return');
(result.value as fs.FSWatcher).on('close', () => closed.push(String(watch.mock.calls[index][0])));
});
}
expect(() => teamWatcher.stop()).not.toThrow();
expect(() => teamWatcher.stop()).not.toThrow();
await delay(200);
if (!failure) expect(closed.sort()).toEqual([teamsDir, tasksDir].sort());
expect(vi.getTimerCount()).toBe(0);
await writeTeam(teamsDir, createTeamConfig());
await writeFile(join(tasksDir, 'after-stop.json'), '{}');
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS * 3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attempts);
expect(teamWatcher.getTeams()).toEqual([]);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
}
}
);
});
describeLinuxWatch('TeamWatcher in-flight fs.watch failure', () => {
it('stays stopped when file replacement and deletion race with ENOSPC', async () => {
const teamsDir = join(tempDir, 'teams');
const tasksDir = join(tempDir, 'tasks');
const teamDir = join(teamsDir, 't');
await mkdir(teamDir, { recursive: true });
await mkdir(tasksDir);
await writeFile(join(teamDir, 'a.json'), '{}');
await writeFile(join(teamDir, 'b.json'), '{}');
const teamWatcher = new TeamWatcher(teamsDir, tasksDir);
watcher = teamWatcher;
const realWatch = fs.watch;
const listeners = new Map<string, fs.WatchListener<string | Buffer>>();
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
const handle = realWatch(...args);
if (args[2]) listeners.set(String(args[0]), args[2]);
return handle;
});
let firstFailure: NodeJS.ErrnoException | undefined;
let failingCalls = 0;
try {
teamWatcher.start();
await waitUntil(
() => listeners.has(join(teamDir, 'a.json')) && listeners.has(join(teamDir, 'b.json')),
'timed out waiting for both file watches'
);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
watch.mockImplementation((...args) => {
// Bound the unfixed retry loop so it can recover and the test can finish.
if (failingCalls >= 2000) return realWatch(...args);
failingCalls++;
const failure = watchError(FAILURES[1], String(args[0]));
firstFailure ??= failure;
throw failure;
});
fs.writeFileSync(join(teamDir, 'b.json.tmp'), '{"replaced":true}');
fs.renameSync(join(teamDir, 'b.json.tmp'), join(teamDir, 'b.json'));
await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the teams watcher warning');
// Deliver the queued deletion callback only after the replacement failure stops the watcher.
fs.unlinkSync(join(teamDir, 'a.json'));
listeners.get(join(teamDir, 'a.json'))!('rename', 'a.json');
await delay(1000);
const attempts = watch.mock.calls.length;
const failures = failingCalls;
await delay(500);
const settledAttempts = watch.mock.calls.length;
const settledFailures = failingCalls;
const warnings = warn.mock.calls.length;
teamWatcher.stop();
await delay(500);
// Check counts before arguments so a retry storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(1);
expect(warnings).toBe(1);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
expect(watch.mock.calls.length).toBe(settledAttempts);
expect(failingCalls).toBe(settledFailures);
expect(settledAttempts).toBe(attempts);
expect(settledFailures).toBe(failures);
expect(failures).toBeGreaterThanOrEqual(1);
expect(failures).toBeLessThanOrEqual(6);
expect(firstFailure?.code).toBe('ENOSPC');
expect(firstFailure?.path?.startsWith(`${teamDir}/`)).toBe(true);
expect(warn.mock.calls).toEqual([
[`[TeamWatcher] teams watcher stopped, relying on polling: ${firstFailure?.message}`],
]);
} finally {
teamWatcher.stop();
}
});
});
const PROJECT_HASH = '-home-arkon-default-claudeman';
const SESSION_UUID = '388113c8-cd01-4e80-93a8-3be66ab1519b';
const RUN_ID = 'wf_test1234-abc';
const RUN_START = 1_700_000_000_000;
function sampleRunJson() {
return {
runId: RUN_ID,
timestamp: new Date(RUN_START).toISOString(),
workflowName: 'watch-failure-test',
summary: 'Discover a run despite exhausted filesystem watches',
status: 'completed',
startTime: RUN_START,
agentCount: 0,
durationMs: 1234,
totalTokens: 0,
totalToolCalls: 0,
phases: [],
workflowProgress: [],
};
}
const { workflowProgress: _progress, ...runFields } = sampleRunJson();
const EXPECTED_RUN: WorkflowRunInfo = {
...runFields,
agents: [],
projectHash: PROJECT_HASH,
sessionUuid: SESSION_UUID,
lastActivityAt: RUN_START,
};
describeLinuxWatch('WorkflowRunWatcher fs.watch failure', () => {
let runWatcher: WorkflowRunWatcher;
let workflowsDir: string;
beforeEach(async () => {
const projectsDir = join(tempDir, 'projects');
workflowsDir = join(projectsDir, PROJECT_HASH, SESSION_UUID, 'workflows');
await mkdir(workflowsDir, { recursive: true });
await writeFile(join(workflowsDir, `${RUN_ID}.json`), JSON.stringify(sampleRunJson()));
watcher = runWatcher = new WorkflowRunWatcher(projectsDir);
// Later interval polls run only when a test explicitly advances the clock.
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
});
function firstRun(): Promise<WorkflowRunInfo> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
runWatcher.off('run_discovered', onRun);
reject(new Error('timed out waiting for run_discovered'));
}, 1500);
function onRun(info: WorkflowRunInfo) {
clearTimeout(timer);
resolve(info);
}
runWatcher.once('run_discovered', onRun);
runWatcher.start();
});
}
it.each(FAILURES)('$code discovers the run without retries, logging, or unhandled rejections', async (failure) => {
const watch = failEveryWatch(failure);
try {
const discovered = await firstRun();
await delay(500);
const attempts = watch.mock.calls.length;
await delay(500);
expect(unhandled.length).toBe(0);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(watch.mock.calls.length).toBe(attempts);
expect(attempts).toBeGreaterThanOrEqual(1);
expect(attempts).toBeLessThanOrEqual(3);
expect(discovered).toEqual(EXPECTED_RUN);
expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
expect(runWatcher.isRunning()).toBe(true);
runWatcher.stop();
expect(runWatcher.isRunning()).toBe(false);
await delay(100);
expect(unhandled.length).toBe(0);
expect(watch.mock.calls.length).toBe(attempts);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
} finally {
runWatcher.stop();
}
});
it('retries a failed directory once per poll and resumes live discovery when fs.watch recovers', async () => {
const watch = failEveryWatch(FAILURES[0]);
const discovered = vi.fn();
try {
expect(await firstRun()).toEqual(EXPECTED_RUN);
await delay(500);
const attemptsPerPoll = watch.mock.calls.length;
expect(attemptsPerPoll).toBeGreaterThanOrEqual(1);
expect(attemptsPerPoll).toBeLessThanOrEqual(3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attemptsPerPoll);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
for (const pollCount of [2, 3]) {
vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS);
await waitUntil(
() => watch.mock.calls.length > attemptsPerPoll * (pollCount - 1),
'later poll did not retry the failed workflows directory'
);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attemptsPerPoll * pollCount);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
}
watch.mockRestore();
const recoveredWatch = vi.spyOn(fs, 'watch');
vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS);
await waitUntil(() => recoveredWatch.mock.calls.length > 0, 'recovery poll did not install a watcher');
// Let watcher setup and the recovery poll settle before creating the new completion file.
await delay(500);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
const otherId = 'wf_recovered5678-def';
runWatcher.on('run_discovered', discovered);
await writeFile(join(workflowsDir, `${otherId}.json`), JSON.stringify({ ...sampleRunJson(), runId: otherId }));
// Do not advance the interval again: only the recovered watcher can discover this file.
await waitUntil(() => discovered.mock.calls.length > 0, 'recovered watcher did not discover the new run');
expect(discovered).toHaveBeenCalledTimes(1);
const expectedRun = { ...EXPECTED_RUN, runId: otherId };
expect(discovered).toHaveBeenCalledWith(expectedRun);
expect(runWatcher.getRun(otherId)).toEqual(expectedRun);
runWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
runWatcher.stop();
runWatcher.off('run_discovered', discovered);
}
});
it('discovers a run with a healthy watcher without logging or unhandled rejections', async () => {
try {
const discovered = await firstRun();
await delay(1000);
expect(discovered).toEqual(EXPECTED_RUN);
expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
runWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
runWatcher.stop();
}
});
});
+177
View File
@@ -13,6 +13,7 @@ import {
buildUpstreamRequestHeaders,
capabilityFromProxyPath,
capabilityFromReferer,
escapedWebviewAssetPath,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
@@ -238,6 +239,56 @@ describe('buildUpstreamRequestHeaders', () => {
expect(headers.authorization).toBeUndefined();
});
// `dsh web` mints its session cookie for the loopback authority the proxy
// dials, which the browser has never visited and cannot store anything for.
// The supervisor holds it instead. The managed tab is trusted, so the browser's
// other dsh cookies are still present and must be kept alongside it.
it('puts the server-held credential ahead of the filtered browser cookies', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; dash=1' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dash=1');
});
it('keeps every non-Codeman browser cookie when injecting the server credential', () => {
const headers = buildUpstreamRequestHeaders(
{ cookie: 'dsh-ui=dark; codeman_session=SECRET; dsh-settings=z' },
upstream,
{
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
}
);
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dsh-ui=dark; dsh-settings=z');
});
// A `Cookie` header may name the same cookie twice, and the first value is the
// one parsers keep. The browser can still hold a dsh cookie from an earlier
// proxied response, so the server's fresh copy has to lead or the stale one wins
// and the tab goes back to the 401 this whole path exists to prevent.
it('keeps the server credential in front of a stale browser copy of the same name', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'dsh-auth-p=STALE; dsh-ui=dark' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=FRESH',
});
// The stale copy is still forwarded behind it (dropping it would need its own
// name parsing), but the parser sees FRESH first, which is what authenticates.
expect(headers.cookie).toBe('dsh-auth-p=FRESH; dsh-auth-p=STALE; dsh-ui=dark');
});
it('sends the server-held credential even when browser cookies are not forwarded', () => {
const headers = buildUpstreamRequestHeaders({}, upstream, {
forwardCookies: false,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig');
});
it('presents Origin/Referer as if the browser talked to the dashboard directly', () => {
const headers = buildUpstreamRequestHeaders({ origin: 'https://codeman.local' }, upstream, {
forwardCookies: false,
@@ -345,6 +396,38 @@ describe('rewriteHtml', () => {
expect(out.match(/<base/g)).toHaveLength(1);
});
// A Vite build ships `<base href="./">`, and the runtime shim rewrites the
// document URL to strip the prefix — so "./" would resolve to Codeman's root
// and every module script would 404 behind an otherwise-painted page.
it('resolves a page-relative <base> against the prefix before the shim masks the URL', () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP);
expect(out).toContain(`<base href="${PREFIX}">`);
expect(out.match(/<base/g)).toHaveLength(1);
});
it('keeps a sub-path in a relative <base> inside the proxy prefix', () => {
const out = rewriteHtml('<html><head><base target="_blank" href="./sub/"></head></html>', CAP);
expect(out).toContain(`<base target="_blank" href="${PREFIX}sub/">`);
});
// A document served from a subdirectory resolves its relative base against
// ITS directory, not the proxy root: `/webview/<cap>/app/page.html` with
// `<base href="./">` must point at `/webview/<cap>/app/`.
it("resolves a relative <base> against the document's own directory", () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP, '', 'app/page.html');
expect(out).toContain(`<base href="${PREFIX}app/">`);
});
it('resolves a ../ base from the document directory', () => {
const out = rewriteHtml('<html><head><base href="../assets/"></head></html>', CAP, '', 'app/sub/page.html');
expect(out).toContain(`<base href="${PREFIX}app/assets/">`);
});
it('leaves a cross-origin <base> exactly as the author wrote it', () => {
const out = rewriteHtml('<html><head><base href="https://cdn.example/x/"></head></html>', CAP);
expect(out).toContain('<base href="https://cdn.example/x/">');
});
it('still injects the runtime shim when the page ships its own <base>', () => {
// The shim is the only layer that catches runtime-built URLs, so an early
// return on an existing <base> would silently break those pages.
@@ -358,6 +441,48 @@ describe('rewriteHtml', () => {
expect(rewriteHtml('just text', CAP)).toContain('<script>');
});
// SvelteKit's inline bootstrap does `import("/_app/…")`. A dynamic import is
// neither an attribute nor a fetch(), so `<base>` and the runtime shim both
// miss it and the module loads from Codeman's root — the app then sits on its
// own spinner forever.
it('rewrites root-absolute dynamic import() specifiers', () => {
const dq = rewriteHtml('<head><script>import("/_app/entry.js")</script></head>', CAP);
expect(dq).toContain(`import("${PREFIX}_app/entry.js")`);
const sq = rewriteHtml("<head><script>import( '/x.js' )</script></head>", CAP);
expect(sq).toContain(`import('${PREFIX}x.js' )`);
});
it('leaves relative and cross-origin import() specifiers alone', () => {
const out = rewriteHtml(
`<head><script>import("./a.js");import("//cdn.example/b.js");import("https://cdn.example/c.js")</script></head>`,
CAP
);
expect(out).toContain('import("./a.js")');
expect(out).toContain('import("//cdn.example/b.js")');
expect(out).toContain('import("https://cdn.example/c.js")');
});
// The rewrite is for specifiers a loader will execute, not for the word
// appearing in the page a reader sees.
it('leaves import() in visible text alone', () => {
const out = rewriteHtml(
`<html><body><pre>import("/example.js")</pre><code>import('/other.js')</code></body></html>`,
CAP
);
expect(out).toContain('<pre>import("/example.js")</pre>');
expect(out).toContain("<code>import('/other.js')</code>");
expect(out).not.toContain(`${PREFIX}example.js`);
});
it('rewrites imports in every script body, including one with attributes', () => {
const out = rewriteHtml(
`<head><script type="module">import("/_app/a.js")</script><script defer>import('/b.js')</script></head>`,
CAP
);
expect(out).toContain(`import("${PREFIX}_app/a.js")`);
expect(out).toContain(`import('${PREFIX}b.js')`);
});
it('rebases root-absolute src/href/action, which <base> cannot fix', () => {
const out = rewriteHtml(
`<head></head><body><script src="/static/app.js"></script><link href='/s.css'><form action="/login"></form></body>`,
@@ -858,3 +983,55 @@ describe('lost-frame recovery', () => {
expect(has({ authorization: 'Basic YWRtaW46eA==' })).toBe(true);
});
});
describe('escapedWebviewAssetPath: naming a 404 a web tab caused', () => {
const req = (over: Record<string, unknown> = {}) => ({
method: 'GET',
url: '/_app/immutable/entry/start.js',
...over,
headers: {
host: 'codeman.example:3001',
referer: 'http://codeman.example:3001/',
'sec-fetch-dest': 'script',
...((over.headers as Record<string, string | string[] | undefined> | undefined) ?? {}),
},
});
it('recognises a root-absolute module a masked frame asked for', () => {
expect(escapedWebviewAssetPath(req())).toBe('/_app/immutable/entry/start.js');
});
it('drops the query string, which carries no diagnostic value', () => {
expect(escapedWebviewAssetPath(req({ url: '/_app/x.js?v=17' }))).toBe('/_app/x.js');
});
it('ignores every shape that is not a dashboard asset', () => {
// A navigation is the lost-frame recovery's job, not this one's.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'document' } }))
).toBeNull();
// Codeman's own missing files say nothing about a web tab.
expect(
escapedWebviewAssetPath(
req({ url: '/favicon.ico', headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'image' } })
)
).toBeNull();
// A real Codeman page's assets resolve; only a masked landing (`/`) is this shape.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/settings', 'sec-fetch-dest': 'script' } }))
).toBeNull();
// Cross-origin referer, API paths, writes, and no referer at all.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://other/', 'sec-fetch-dest': 'script' } }))
).toBeNull();
expect(escapedWebviewAssetPath(req({ url: '/api/thing' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ method: 'POST' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ headers: { host: 'h' } }))).toBeNull();
});
it('accepts the array headers a proxy front end can produce', () => {
expect(
escapedWebviewAssetPath(req({ headers: { host: ['h'], referer: ['http://h/'], 'sec-fetch-dest': ['image'] } }))
).toBe('/_app/immutable/entry/start.js');
});
});