Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

test([med-tests-no-tests-for-server-lib-ansistrip-js]): cover ansiStrip + tuiHandshake

[._.]/ Adam Eivy7e4369f72da4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0f369b75cc..dcbfa4b398 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,8 @@
## Added
+- **[med-tests-no-tests-for-server-lib-ansistrip-js] Tests for `server/lib/ansiStrip.js` and `server/lib/tuiHandshake.js`.** New `ansiStrip.test.js` (25 tests) covers `stripAnsi` one-shot behavior, the `createStreamingAnsiStripper` chunk-boundary buffering (CSI/OSC split across chunks, bare `\x1B` at chunk end resolved as either single-byte or CSI on the next chunk, OSC body leak when terminator never arrives within the 4096-byte window, older unterminated bytes past the window). New `tuiHandshake.test.js` (29 tests) pins every paste-timing constant both production paths (`tuiPromptRunner.js`, `agentTuiSpawning.js`) depend on, plus `PASTE_MARKER_PATTERN`, `inferTuiCommand`, `applyCommandDefaults` (codex `--ask-for-approval never` injection), `buildTuiInvocation` (model-flag baked-in suppression for `--model`/`-m`/`=` forms + codex sentinel), and `detectMissingTuiBinary`. A latent OSC-stripping bug surfaced during the write — `ANSI_PATTERN`'s OSC alternative is dead code because the single-byte alternative `[@-Z\\-_]` matches `\x1B]` first, so OSC bodies leak into the cleaned stream; tests document the current behavior and the issue is logged as [ansistrip-osc-alternative-unreachable] in PLAN.md for a separate fix.
+
- **Network Exposure dashboard widget.** New widget surfaces how PortOS is actually exposed on the network: HTTPS vs HTTP, bind address + audience (loopback-only / all-interfaces / specific-interface), cert mode (Tailscale-trusted hostname vs self-signed), the loopback HTTP mirror port when HTTPS is on, and a mic-availability hint computed from the browser origin (HTTPS or loopback ⇒ available; HTTP on a Tailscale IP ⇒ blocked by the browser's secure-context rule). Renders a warning banner when bound on all interfaces over plain HTTP. Seeded into the `default` (Everything) and `ops` built-in dashboard layouts so the security posture is visible product UX, not a docs-only invariant. Backed by `GET /api/network-exposure/status`.
- **CoS task form: pick the reviewer for the Review Loop (`--review-with`).** A new compact dropdown appears next to the Review Loop checkbox in `TaskAddForm.jsx` (copilot / claude / gemini / codex; default copilot). The choice is persisted on the task as `metadata.reviewer` and flows through the agent prompt, the follow-up agent's prompt (`/do:rpr --review-with <reviewer>`), and the worktree cleanup hook — for non-copilot reviewers, PortOS skips the GitHub Copilot reviewer-API pre-request and instructs the follow-up to invoke the chosen CLI against the PR diff instead. AgentCard chips show the selected reviewer when it isn't the default.
diff --git a/PLAN.md b/PLAN.md
index 83922f9248..ed8cf91ee9 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -36,7 +36,6 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [med-sharing-server-services-sharing-version-js] **[MED][SHARING]** `server/services/sharing/version.js` — `SHARING_SCHEMA_VERSION` not bumped despite series-schema canon-field removal. Cross-peer share-bucket import from a pre-B.4 install silently loses series-side canon. Either bump the version (force refusal) or mirror migration logic in the importer for legacy canon fields.
- [ ] [med-ai-dispatch-server-services-digital-twin] **[MED][AI-DISPATCH]** `server/services/digital-twin-helpers.js:56-130` — `callProviderAI` still has ad-hoc CLI/API split with TUI falling into the CLI branch (will hang or render banner into pipe). Migrate to `runPromptThroughProvider`.
- [ ] [med-ai-dispatch-server-lib-tuipromptrunner-js-198] **[MED][AI-DISPATCH]** `server/lib/tuiPromptRunner.js:198-200` — `OUTPUT_BUFFER_CAP = 1MB` silently truncates the _head_ of TUI responses >1.25MB mid-token. Persists to disk AND returns truncated. Either stream incrementally to `output.txt` (like agentTuiSpawning does) or raise the cap + log a warning.
-- [ ] [med-tests-no-tests-for-server-lib-ansistrip-js] **[MED][TESTS]** No tests for `server/lib/ansiStrip.js` (streaming escape-split-across-chunks logic) or `server/lib/tuiHandshake.js` (paste timing constants both production paths depend on). Add coverage for: escape split across two chunks, bare `\x1B` at chunk end, OSC sequences, unterminated bytes past the 4096-byte window.
- [ ] [med-tests-no-direct-tests-for-executetuirun-pty] **[MED][TESTS]** No direct tests for `executeTuiRun` PTY mechanics — idle-complete, hard-timeout, missing-binary early-fail, `emitRunStarted` shape, CLAUDECODE env stripping. The new `tuiPromptRunner.test.js` only covers `cleanTuiResponse`.
- [ ] [med-importer-server-routes-importer-test-js-no] **[MED][IMPORTER]** `server/routes/importer.test.js` — no test pins `ERR_PARTIAL_COMMIT_ISSUES → 207` status mapping. Future refactor that drops the entry from `SERVICE_ERROR_STATUS` would 500 on partial commits and trigger pager alerts (the in-code comment's stated regression).
- [ ] [med-importer-server-services-importer-test-js-no] **[MED][IMPORTER]** `server/services/importer.test.js` — no test exercises `existingCanonBlock` dedupe wiring. A regression that wires `null` would silently degrade second-pass imports. Assert `mockRunStagedLLM.mock.calls[0][1].existingCanonBlock` contains a seeded character name.
@@ -73,6 +72,8 @@ The 2026-04-25 CODEX 5.5 review's concrete bugs (Brain Feeds nav, Time Capsule n
### Deferred from better/2026-05-19
+- [ ] [ansistrip-osc-alternative-unreachable] **[MED][TUI]** `server/lib/ansiStrip.js:14` — the OSC alternative in `ANSI_PATTERN` (`\][^\x07]*(?:\x07|\x1B\\)`) is dead code. Alternation order matches the single-byte alternative `[@-Z\\-_]` against `\x1B]` (0x5D is in 0x5C-0x5F) before the OSC alt is tried. Effect: only `\x1B]` is stripped from OSC sequences; the body+terminator leak into the cleaned stream (e.g. `\x1B]0;title\x07after` → `0;title\x07after`). Callers (`tuiPromptRunner.js:237`, `agentTuiSpawning.js:292`) consume the result without further filtering. Fix by either reordering alternatives (OSC before single-byte) or excluding `]` from the single-byte class (`[@-Z\\^_]` or similar). The new `ansiStrip.test.js` pins the current buggy behavior so a fix has an unambiguous before/after baseline. Surfaced 2026-05-20 during the test-coverage PR for med-tests-no-tests-for-server-lib-ansistrip-js; deferred to keep that PR scoped to tests.
+
- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.
### Voice agent
diff --git a/server/lib/ansiStrip.test.js b/server/lib/ansiStrip.test.js
new file mode 100644
index 0000000000..79bcc04020
--- /dev/null
+++ b/server/lib/ansiStrip.test.js
@@ -0,0 +1,189 @@
+import { describe, it, expect } from 'vitest';
+import { stripAnsi, createStreamingAnsiStripper, ANSI_PATTERN } from './ansiStrip.js';
+
+// These tests pin the *current* behavior of the streaming stripper. Anything
+// surprising (e.g. OSC bodies leaking because `[@-Z\\-_]` matches `\x1B]`
+// before the OSC alternative can fire) is called out inline so a future
+// regex rewrite has explicit before/after evidence to work against.
+
+describe('stripAnsi (one-shot)', () => {
+ it('returns empty string for non-string input', () => {
+ expect(stripAnsi(null)).toBe('');
+ expect(stripAnsi(undefined)).toBe('');
+ expect(stripAnsi(42)).toBe('');
+ expect(stripAnsi({})).toBe('');
+ expect(stripAnsi([])).toBe('');
+ });
+
+ it('passes plain text through unchanged', () => {
+ expect(stripAnsi('hello world')).toBe('hello world');
+ expect(stripAnsi('line1\nline2\tcol2')).toBe('line1\nline2\tcol2');
+ });
+
+ it('strips a complete CSI sequence', () => {
+ expect(stripAnsi('\x1B[2Jcleared')).toBe('cleared');
+ expect(stripAnsi('\x1B[31mred\x1B[0m')).toBe('red');
+ expect(stripAnsi('\x1B[1;31;47mfoo\x1B[0m')).toBe('foo');
+ });
+
+ it('strips the `\\x1B]` OSC opener but leaves the body when BEL-terminated', () => {
+ // The OSC alternative in ANSI_PATTERN is unreachable because the
+ // single-byte alternative `[@-Z\\-_]` matches `]` (0x5D) first. So an
+ // OSC sequence loses its `\x1B]` prefix and keeps the body+BEL. This is
+ // a latent bug — callers in tuiPromptRunner/agentTuiSpawning consume
+ // the result as-is. Documented here so a future fix has a baseline.
+ expect(stripAnsi('\x1B]0;title\x07after')).toBe('0;title\x07after');
+ });
+
+ it('strips both `\\x1B]` opener AND `\\x1B\\\\` ST terminator when OSC is ST-terminated', () => {
+ // Same alt-order quirk strips `\x1B\\` (backslash, 0x5C, in 0x5C-0x5F),
+ // so the body remains but both ESC bytes vanish.
+ expect(stripAnsi('\x1B]0;title\x1B\\after')).toBe('0;titleafter');
+ });
+
+ it('strips a bare `\\x1B]` (single-byte path) when nothing follows', () => {
+ expect(stripAnsi('a\x1B]b')).toBe('ab');
+ });
+
+ it('strips single-byte escape forms (\\x1B@ ... \\x1B_)', () => {
+ expect(stripAnsi('a\x1B@b')).toBe('ab');
+ expect(stripAnsi('a\x1BDb')).toBe('ab');
+ expect(stripAnsi('a\x1B_b')).toBe('ab');
+ });
+
+ it('strips a bare \\x1B not followed by 0x40-0x5F (lookahead branch)', () => {
+ // `(` is 0x28, not in [@-_], so the bare-ESC catch-all fires and only
+ // the ESC is removed.
+ expect(stripAnsi('\x1B(plain')).toBe('(plain');
+ });
+
+ it('strips NUL bytes', () => {
+ expect(stripAnsi('a\x00b\x00c')).toBe('abc');
+ });
+
+ it('handles mixed content in one pass', () => {
+ expect(stripAnsi('\x1B[2J\x1B[Hhi\x00\x1B[31mthere\x1B[0m')).toBe('hithere');
+ });
+
+ it('exports an ANSI_PATTERN regex that matches CSI starts', () => {
+ expect(ANSI_PATTERN).toBeInstanceOf(RegExp);
+ expect('\x1B[31m'.replace(ANSI_PATTERN, '')).toBe('');
+ });
+});
+
+describe('createStreamingAnsiStripper', () => {
+ it('returns independent stateful stripper instances', () => {
+ const a = createStreamingAnsiStripper();
+ const b = createStreamingAnsiStripper();
+ // Feed an incomplete escape into A only; B should still pass plain text through.
+ a('hi\x1B[');
+ expect(b('hello')).toBe('hello');
+ // A continues to buffer until the sequence completes.
+ expect(a('31mworld')).toBe('world');
+ });
+
+ it('passes clean text through unchanged minus NUL', () => {
+ const strip = createStreamingAnsiStripper();
+ expect(strip('hello\nworld\x00')).toBe('hello\nworld');
+ });
+
+ it('resolves a CSI sequence split across two chunks', () => {
+ const strip = createStreamingAnsiStripper();
+ expect(strip('hi\x1B[')).toBe('hi');
+ expect(strip('31mworld')).toBe('world');
+ });
+
+ it('resolves a CSI sequence split with parameter bytes already in chunk1', () => {
+ // `\x1B[01;` is still incomplete (no final byte yet); chunk2 closes it.
+ const strip = createStreamingAnsiStripper();
+ expect(strip('pre\x1B[01;')).toBe('pre');
+ expect(strip('33mtext')).toBe('text');
+ });
+
+ it('buffers a bare \\x1B at chunk end and resolves on the next chunk', () => {
+ const strip = createStreamingAnsiStripper();
+ // Bare ESC could become a CSI/OSC/single-byte escape — must buffer.
+ expect(strip('abc\x1B')).toBe('abc');
+ // Next chunk completes a single-byte escape form (`\x1B@`).
+ expect(strip('@xyz')).toBe('xyz');
+ });
+
+ it('buffers a bare \\x1B at chunk end and resolves into a CSI on the next chunk', () => {
+ const strip = createStreamingAnsiStripper();
+ expect(strip('abc\x1B')).toBe('abc');
+ expect(strip('[2Jxyz')).toBe('xyz');
+ });
+
+ it('buffers an OSC opener split across chunks (BEL terminator) — body still leaks on flush', () => {
+ // Streaming correctly *defers* the chunk boundary inside an OSC opener
+ // — the trailing `\x1B]0;ti` is held until the next chunk arrives. But
+ // when the terminator chunk lands and the full sequence is re-strip'd,
+ // the regex's dead OSC alternative means only `\x1B]` is consumed and
+ // the `0;title\x07` body leaks. Future-fix baseline.
+ const strip = createStreamingAnsiStripper();
+ expect(strip('pre\x1B]0;ti')).toBe('pre');
+ expect(strip('tle\x07post')).toBe('0;title\x07post');
+ });
+
+ it('buffers an OSC opener split across three chunks then leaks the body', () => {
+ const strip = createStreamingAnsiStripper();
+ expect(strip('A\x1B]')).toBe('A');
+ expect(strip('8;;https://example.com')).toBe('');
+ // BEL terminator survives because the OSC alternative is dead — only
+ // the `\x1B]` prefix is consumed, body+BEL stay.
+ expect(strip('\x07Z')).toBe('8;;https://example.com\x07Z');
+ });
+
+ it('does NOT buffer an OSC body longer than 4096 bytes — it leaks instead of pinning memory', () => {
+ const strip = createStreamingAnsiStripper();
+ // OSC opens, then 4097 chars of body with no terminator. The 4096-byte
+ // window guard (`combined.length - lastEsc <= 4096`) is exceeded so we
+ // fall through to STRIP without buffering. Body leaks rather than
+ // pinning memory waiting for a terminator that may never come.
+ const longBody = 'x'.repeat(4097);
+ const out = strip(`\x1B]0;${longBody}`);
+ expect(out).toContain(longBody);
+ // No tail held over — the next chunk is uncorrupted.
+ expect(strip('next')).toBe('next');
+ });
+
+ it('treats an older unterminated ESC as resolved when newer plain text pushes it past the 4096-byte window', () => {
+ const strip = createStreamingAnsiStripper();
+ // A bare `\x1B` followed by enough plain text that lastEsc lives outside
+ // the 4096-byte trailing window. The buffer-candidate branch is skipped
+ // and we fall through to STRIP. The bare-ESC lookahead branch removes
+ // the lone `\x1B` (since `y` is 0x79, not in [@-_]) leaving plain text.
+ const padding = 'y'.repeat(5000);
+ expect(strip(`\x1B${padding}`)).toBe(padding);
+ // Nothing held over.
+ expect(strip('done')).toBe('done');
+ });
+
+ it('flushes completed sequences while buffering a trailing incomplete one', () => {
+ const strip = createStreamingAnsiStripper();
+ // First chunk: one completed CSI + a trailing incomplete CSI.
+ expect(strip('\x1B[31mhi\x1B[')).toBe('hi');
+ // Trailer closes — buffered fragment merges and gets stripped.
+ expect(strip('32mthere')).toBe('there');
+ });
+
+ it('handles consecutive complete chunks independently', () => {
+ const strip = createStreamingAnsiStripper();
+ expect(strip('\x1B[31mfoo\x1B[0m')).toBe('foo');
+ expect(strip('\x1B[32mbar\x1B[0m')).toBe('bar');
+ });
+
+ it('safely handles an empty chunk', () => {
+ const strip = createStreamingAnsiStripper();
+ expect(strip('')).toBe('');
+ // Then a normal chunk still works.
+ expect(strip('plain')).toBe('plain');
+ });
+
+ it('does not corrupt the next chunk after a clean (no-tail) flush', () => {
+ const strip = createStreamingAnsiStripper();
+ // No trailing escape at all → no tail buffered.
+ expect(strip('plain text')).toBe('plain text');
+ expect(strip('more')).toBe('more');
+ });
+});
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
new file mode 100644
index 0000000000..d1b4574233
--- /dev/null
+++ b/server/lib/tuiHandshake.test.js
@@ -0,0 +1,215 @@
+import { describe, it, expect } from 'vitest';
+import {
+ READY_POLL_INTERVAL_MS,
+ READY_IDLE_THRESHOLD_MS,
+ PASTE_DEADLINE_MS,
+ PASTE_MARKER_POLL_MS,
+ PASTE_MARKER_PATTERN,
+ PASTE_TO_ENTER_MIN_DELAY_MS,
+ PASTE_TO_ENTER_FALLBACK_MS,
+ DEFAULT_TUI_PROMPT_DELAY_MS,
+ DEFAULT_TUI_IDLE_TIMEOUT_MS,
+ RAW_BUFFER_CAP,
+ RAW_BUFFER_HEADROOM,
+ OUTPUT_BUFFER_CAP,
+ OUTPUT_BUFFER_HEADROOM,
+ inferTuiCommand,
+ applyCommandDefaults,
+ buildTuiInvocation,
+ detectMissingTuiBinary,
+} from './tuiHandshake.js';
+import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';
+
+// The exported constants are load-bearing for both production callers
+// (`tuiPromptRunner.js`, `agentTuiSpawning.js`). Pin every value so an
+// inadvertent edit on one timing knob trips a test instead of silently
+// drifting the paste handshake.
+describe('tuiHandshake — paste timing constants', () => {
+ it('pins ready-poll constants', () => {
+ expect(READY_POLL_INTERVAL_MS).toBe(300);
+ expect(READY_IDLE_THRESHOLD_MS).toBe(1200);
+ expect(PASTE_DEADLINE_MS).toBe(10000);
+ // The idle threshold must remain larger than the poll interval —
+ // otherwise the first idle window is observed before the banner
+ // has finished its second paint.
+ expect(READY_IDLE_THRESHOLD_MS).toBeGreaterThan(READY_POLL_INTERVAL_MS);
+ // The deadline must outrun the idle threshold by enough headroom to
+ // catch a slow spawn + initial paint.
+ expect(PASTE_DEADLINE_MS).toBeGreaterThan(READY_IDLE_THRESHOLD_MS);
+ });
+
+ it('pins paste-marker constants', () => {
+ expect(PASTE_MARKER_POLL_MS).toBe(150);
+ expect(PASTE_TO_ENTER_MIN_DELAY_MS).toBe(200);
+ expect(PASTE_TO_ENTER_FALLBACK_MS).toBe(3500);
+ // Fallback only fires when no marker appears; it must be longer than
+ // the min delay or the min delay never gates anything.
+ expect(PASTE_TO_ENTER_FALLBACK_MS).toBeGreaterThan(PASTE_TO_ENTER_MIN_DELAY_MS);
+ });
+
+ it('PASTE_MARKER_PATTERN matches Claude Code paste markers', () => {
+ expect(PASTE_MARKER_PATTERN.test('[Pasted text #1 +3 lines]')).toBe(true);
+ expect(PASTE_MARKER_PATTERN.test('[Pasted text #42 +120 lines]')).toBe(true);
+ // Embedded inside a banner of escape-stripped output.
+ expect(PASTE_MARKER_PATTERN.test('banner stuff [Pasted text #7 +1 lines] trailer')).toBe(true);
+ });
+
+ it('PASTE_MARKER_PATTERN does NOT match similar-looking but distinct text', () => {
+ expect(PASTE_MARKER_PATTERN.test('[Pasted text]')).toBe(false);
+ expect(PASTE_MARKER_PATTERN.test('[Pasted #1]')).toBe(false);
+ expect(PASTE_MARKER_PATTERN.test('Pasted text #1')).toBe(false);
+ expect(PASTE_MARKER_PATTERN.test('')).toBe(false);
+ });
+
+ it('pins provider-default constants', () => {
+ expect(DEFAULT_TUI_PROMPT_DELAY_MS).toBe(2500);
+ expect(DEFAULT_TUI_IDLE_TIMEOUT_MS).toBe(180000);
+ });
+
+ it('pins buffer caps with headroom > cap (defensive growth allowance)', () => {
+ expect(RAW_BUFFER_CAP).toBe(512 * 1024);
+ expect(RAW_BUFFER_HEADROOM).toBe(640 * 1024);
+ expect(OUTPUT_BUFFER_CAP).toBe(1024 * 1024);
+ expect(OUTPUT_BUFFER_HEADROOM).toBe(1280 * 1024);
+ // Headroom must exceed cap so the slice-tail-after-overflow logic in
+ // the callers actually keeps recent bytes instead of dropping them.
+ expect(RAW_BUFFER_HEADROOM).toBeGreaterThan(RAW_BUFFER_CAP);
+ expect(OUTPUT_BUFFER_HEADROOM).toBeGreaterThan(OUTPUT_BUFFER_CAP);
+ });
+});
+
+describe('tuiHandshake.inferTuiCommand', () => {
+ // Catch-all default also returns claude; the claude rows just confirm
+ // an explicit match isn't accidentally tagged codex/gemini.
+ it.each([
+ ['', 'claude'],
+ [null, 'claude'],
+ [undefined, 'claude'],
+ ['mystery-provider', 'claude'],
+ ['codex', 'codex'],
+ ['openai-codex', 'codex'],
+ ['codex-cloud', 'codex'],
+ ['gemini', 'gemini'],
+ ['google-gemini-2', 'gemini'],
+ ['claude', 'claude'],
+ ['anthropic-claude-code', 'claude'],
+ ])('inferTuiCommand(%p) → %p', (id, expected) => {
+ expect(inferTuiCommand(id)).toBe(expected);
+ });
+});
+
+describe('tuiHandshake.applyCommandDefaults', () => {
+ it('injects `--ask-for-approval never` for codex when not already present', () => {
+ expect(applyCommandDefaults('codex', ['exec', '-'])).toEqual([
+ '--ask-for-approval', 'never', 'exec', '-',
+ ]);
+ });
+
+ it('passes codex args through unchanged when --ask-for-approval is already present', () => {
+ const args = ['--ask-for-approval', 'auto-edit', 'exec', '-'];
+ expect(applyCommandDefaults('codex', args)).toBe(args);
+ });
+
+ it('passes non-codex commands through unchanged', () => {
+ const args = ['-p', '-'];
+ expect(applyCommandDefaults('claude', args)).toBe(args);
+ expect(applyCommandDefaults('gemini', args)).toBe(args);
+ expect(applyCommandDefaults('something-else', args)).toBe(args);
+ });
+
+ it('preserves the original arg list when injecting (caller can still mutate before spawn)', () => {
+ const args = ['exec', '-'];
+ const result = applyCommandDefaults('codex', args);
+ // The injection produces a new array; original is untouched.
+ expect(result).not.toBe(args);
+ expect(args).toEqual(['exec', '-']);
+ });
+});
+
+describe('tuiHandshake.buildTuiInvocation', () => {
+ it('uses provider.command when present and skips codex defaults for non-literal-codex command names', () => {
+ const provider = { id: 'codex', command: 'my-codex-wrapper', args: ['exec', '-'] };
+ const out = buildTuiInvocation(provider, null);
+ expect(out.command).toBe('my-codex-wrapper');
+ // `applyCommandDefaults` checks `command === 'codex'` (strict). A
+ // wrapper name escapes the auto-inject — caller-controlled commands
+ // own their argv entirely.
+ expect(out.args).toEqual(['exec', '-']);
+ });
+
+ it('infers command from id when provider.command is missing', () => {
+ const provider = { id: 'codex' };
+ const out = buildTuiInvocation(provider, null);
+ expect(out.command).toBe('codex');
+ expect(out.args).toEqual(['--ask-for-approval', 'never']);
+ });
+
+ it('appends --model when caller passes a model and provider.args has no model flag', () => {
+ const provider = { id: 'claude', args: ['-p', '-'] };
+ const out = buildTuiInvocation(provider, 'claude-opus-4-7');
+ expect(out.command).toBe('claude');
+ expect(out.args).toEqual(['-p', '-', '--model', 'claude-opus-4-7']);
+ });
+
+ it.each([
+ { form: '--model X', bakedArgs: ['--model', 'baked-in'] },
+ { form: '--model=X', bakedArgs: ['--model=baked-in'] },
+ { form: '-m X', bakedArgs: ['-m', 'baked-in'] },
+ ])('does NOT append --model when provider.args pins one ($form form)', ({ bakedArgs }) => {
+ const provider = { id: 'claude', args: ['-p', '-', ...bakedArgs] };
+ const out = buildTuiInvocation(provider, 'caller-model');
+ expect(out.args).toEqual(['-p', '-', ...bakedArgs]);
+ });
+
+ it('skips --model injection when caller passes the codex sentinel (configured default)', () => {
+ // resolveCliModel(CODEX_CONFIGURED_DEFAULT) returns null → no flag.
+ const provider = { id: 'codex', args: ['exec', '-'] };
+ const out = buildTuiInvocation(provider, CODEX_CONFIGURED_DEFAULT);
+ expect(out.args).toEqual(['--ask-for-approval', 'never', 'exec', '-']);
+ });
+
+ it('skips --model injection when model is null/undefined/empty', () => {
+ const provider = { id: 'claude', args: ['-p', '-'] };
+ expect(buildTuiInvocation(provider, null).args).toEqual(['-p', '-']);
+ expect(buildTuiInvocation(provider, undefined).args).toEqual(['-p', '-']);
+ expect(buildTuiInvocation(provider, '').args).toEqual(['-p', '-']);
+ });
+
+ it('handles a provider with no args (treats as empty array)', () => {
+ const out = buildTuiInvocation({ id: 'claude' }, 'opus-x');
+ expect(out.command).toBe('claude');
+ expect(out.args).toEqual(['--model', 'opus-x']);
+ });
+
+ it('handles a missing provider with no id (falls back to claude)', () => {
+ const out = buildTuiInvocation(undefined, 'opus-x');
+ expect(out.command).toBe('claude');
+ expect(out.args).toEqual(['--model', 'opus-x']);
+ });
+});
+
+describe('tuiHandshake.detectMissingTuiBinary', () => {
+ it('detects bash-style not-found for the spawned command', () => {
+ expect(detectMissingTuiBinary('bash: codex: command not found', 'codex')).toBe(true);
+ expect(detectMissingTuiBinary('zsh: command not found: claude', 'claude')).toBe(true);
+ });
+
+ it('is case-insensitive on both sides', () => {
+ expect(detectMissingTuiBinary('Codex: COMMAND NOT FOUND', 'codex')).toBe(true);
+ expect(detectMissingTuiBinary('command not found CODEX', 'CoDeX')).toBe(true);
+ });
+
+ it('rejects unrelated errors that mention the command but not "command not found"', () => {
+ expect(detectMissingTuiBinary('codex: permission denied', 'codex')).toBe(false);
+ expect(detectMissingTuiBinary('codex panicked at line 42', 'codex')).toBe(false);
+ });
+
+ it('rejects "command not found" for a different command', () => {
+ expect(detectMissingTuiBinary('bash: gemini: command not found', 'codex')).toBe(false);
+ });
+
+ it('rejects empty / whitespace strings', () => {
+ expect(detectMissingTuiBinary('', 'codex')).toBe(false);
+ expect(detectMissingTuiBinary(' ', 'codex')).toBe(false);
+ });
+});