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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
test(executeTuiRun): cover PTY mechanics — idle-complete, timeout, missing-binary, exit/signal, env stripping
[._.]/ Adam Eivy98c0549e60e9
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 6285701afe..2d7a9e8d90 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -1,8 +1,54 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { mkdtemp, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';-import { cleanTuiResponse, resolveTuiResponseText } from './tuiPromptRunner.js';++// node-pty + runner hooks are mocked so executeTuiRun can be driven+// synchronously from the test without spawning a real terminal. fileUtils+// stays real for everything except `ensureDir` (which would otherwise create+// real run directories the SUT never needs in these tests). Mocks live+// inside vi.hoisted so the vi.mock factories (which are themselves hoisted+// to the top of the file) can reference them.+const { ptyInstances, ptySpawnMock, runnerMocks, runsTmpDirRef } = vi.hoisted(() => ({+ ptyInstances: [],+ ptySpawnMock: vi.fn(),+ runsTmpDirRef: { current: null },+ runnerMocks: {+ finalizeRunRecord: vi.fn(),+ emitRunStarted: vi.fn(),+ registerActiveRun: vi.fn(),+ unregisterActiveRun: vi.fn(),+ getRunsPath: vi.fn(),+ },+}));+runnerMocks.getRunsPath.mockImplementation(() => runsTmpDirRef.current);++vi.mock('node-pty', () => ({ spawn: (...args) => ptySpawnMock(...args) }));+vi.mock('../services/runner.js', () => runnerMocks);+vi.mock('./fileUtils.js', async () => {+ const actual = await vi.importActual('./fileUtils.js');+ return { ...actual, ensureDir: vi.fn(async () => {}) };+});++import { cleanTuiResponse, resolveTuiResponseText, executeTuiRun } from './tuiPromptRunner.js';++const makeFakePty = () => {+ const fake = {+ _dataHandler: null,+ _exitHandler: null,+ killed: false,+ onData: vi.fn((fn) => { fake._dataHandler = fn; }),+ onExit: vi.fn((fn) => { fake._exitHandler = fn; }),+ write: vi.fn(),+ kill: vi.fn(() => { fake.killed = true; }),+ emitData: (chunk) => fake._dataHandler?.(chunk),+ emitExit: (payload) => fake._exitHandler?.(payload),+ };+ ptyInstances.push(fake);+ return fake;+};++const flushAsync = () => new Promise((resolve) => setImmediate(resolve));// Targeted coverage for the cleanTuiResponse helper — it shapes what every// TUI-provider caller sees as the model response (paste-marker removal,@@ -178,3 +224,258 @@ describe('resolveTuiResponseText', () => {expect(out).toEqual({ text: 'the model reply', usedResponseFile: false });});});++// executeTuiRun owns the PTY lifecycle — spawn, ready-watch, paste, idle+// detection, hard timeout, command-not-found probe, exit/signal handling.+// The PTY is mocked so each behavior can be triggered deterministically+// from the test without spawning a real terminal.++describe('executeTuiRun', () => {+ beforeEach(async () => {+ runsTmpDirRef.current = await mkdtemp(join(tmpdir(), 'tui-runner-test-'));+ ptyInstances.length = 0;+ ptySpawnMock.mockReset();+ ptySpawnMock.mockImplementation(() => makeFakePty());+ runnerMocks.finalizeRunRecord.mockReset();+ runnerMocks.finalizeRunRecord.mockImplementation(+ async ({ runId, output, exitCode, success, error, startTime, extras }) => ({+ runId,+ output,+ exitCode,+ success,+ error,+ duration: Date.now() - startTime,+ ...extras,+ }),+ );+ runnerMocks.emitRunStarted.mockClear();+ runnerMocks.registerActiveRun.mockClear();+ runnerMocks.unregisterActiveRun.mockClear();+ runnerMocks.getRunsPath.mockClear();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(async () => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ await rm(runsTmpDirRef.current, { recursive: true, force: true }).catch(() => null);+ });++ describe('input validation', () => {+ it('throws when provider is missing', async () => {+ await expect(executeTuiRun('run-x', null, 'prompt', '/tmp'))+ .rejects.toThrow(/provider is required/);+ expect(ptySpawnMock).not.toHaveBeenCalled();+ });++ it('throws when prompt is empty', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ await expect(executeTuiRun('run-x', provider, '', '/tmp'))+ .rejects.toThrow(/non-empty string/);+ expect(ptySpawnMock).not.toHaveBeenCalled();+ });++ it('throws when prompt is non-string', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ await expect(executeTuiRun('run-x', provider, 12345, '/tmp'))+ .rejects.toThrow(/non-empty string/);+ });+ });++ describe('spawn failure', () => {+ it('wraps node-pty spawn errors with the offending command name', async () => {+ ptySpawnMock.mockImplementation(() => { throw new Error('ENOENT'); });+ const provider = { id: 'codex', type: 'tui', command: 'nonexistent-cli' };+ await expect(executeTuiRun('run-x', provider, 'do thing', '/tmp'))+ .rejects.toThrow(/Failed to spawn TUI 'nonexistent-cli': ENOENT/);+ });+ });++ describe('startup hooks', () => {+ it('registers the PTY in the active-runs map and fires emitRunStarted with provider + defaultModel', async () => {+ const provider = {+ id: 'claude', type: 'tui', command: 'echo', defaultModel: 'claude-3.5',+ };+ const promise = executeTuiRun('run-A', provider, 'do thing big enough', '/cwd', undefined, undefined, 60000);+ await flushAsync();++ expect(ptySpawnMock).toHaveBeenCalledTimes(1);+ const pty = ptyInstances[0];+ expect(runnerMocks.registerActiveRun).toHaveBeenCalledWith('run-A', pty);+ expect(runnerMocks.emitRunStarted).toHaveBeenCalledWith({+ runId: 'run-A',+ provider,+ model: 'claude-3.5',+ });++ // Drive a clean exit so the run-Promise resolves.+ pty.emitExit({ exitCode: 0 });+ await promise;+ });++ it('merges provider.envVars and strips CLAUDECODE from the child env so a nested Claude Code TUI is not detected as nested', async () => {+ process.env.CLAUDECODE = '1';+ try {+ const provider = {+ id: 'claude', type: 'tui', command: 'echo',+ envVars: { CUSTOM_PROVIDER_VAR: 'on' },+ };+ const promise = executeTuiRun('run-B', provider, 'p large enough to clear the guard', '/cwd', undefined, undefined, 60000);+ await flushAsync();++ const env = ptySpawnMock.mock.calls[0][2].env;+ expect(env.CLAUDECODE).toBeUndefined();+ expect(env.CUSTOM_PROVIDER_VAR).toBe('on');+ expect(env.TERM).toBe('xterm-256color');+ expect(env.COLORTERM).toBe('truecolor');++ ptyInstances[0].emitExit({ exitCode: 0 });+ await promise;+ } finally {+ delete process.env.CLAUDECODE;+ }+ });+ });++ describe('completion paths', () => {+ it('finishes with reason "idle-complete" once output stays idle past tuiOneShotIdleMs after the first response chunk', async () => {+ vi.useFakeTimers({+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],+ });+ const provider = {+ id: 'claude', type: 'tui', command: 'echo',+ tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500,+ };+ const onComplete = vi.fn();+ const promise = executeTuiRun('run-idle', provider, 'do thing big enough to clear the prompt guard', '/cwd', undefined, onComplete, 60000);+ await flushAsync();++ const pty = ptyInstances[0];++ // Banner output establishes firstOutputAt so the ready-watch can fire.+ pty.emitData('claude code ready> ');++ // Past tuiPromptDelayMs (50) + READY_IDLE_THRESHOLD_MS (1200) + readyTimer poll.+ await vi.advanceTimersByTimeAsync(2000);+ expect(pty.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[200~'));++ // Past PASTE_TO_ENTER_FALLBACK_MS (3500) → '\r' submitted.+ await vi.advanceTimersByTimeAsync(4000);+ expect(pty.write).toHaveBeenCalledWith('\r');++ // First post-paste chunk arms idleWatchTimer (ticks every 1000ms).+ pty.emitData('model response chunk');+ await vi.advanceTimersByTimeAsync(1100);+ await flushAsync();++ await promise;+ expect(runnerMocks.unregisterActiveRun).toHaveBeenCalledWith('run-idle');+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-idle',+ success: true,+ exitCode: 0,+ extras: expect.objectContaining({ completionReason: 'idle-complete' }),+ }));+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({+ success: true,+ exitCode: 0,+ }));+ });++ it('finishes with reason "timeout" and exitCode 124 when the hard timeout fires before any completion', async () => {+ vi.useFakeTimers({+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],+ });+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const promise = executeTuiRun('run-timeout', provider, 'a prompt long enough to clear the guard', '/cwd', undefined, undefined, 500);+ await flushAsync();++ // No data emitted → no firstOutputAt → ready-watch never triggers paste+ // before the (short) hard timeout fires.+ await vi.advanceTimersByTimeAsync(600);+ await flushAsync();++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-timeout',+ success: false,+ exitCode: 124,+ error: expect.stringContaining('timed out'),+ extras: expect.objectContaining({ completionReason: 'timeout' }),+ }));+ // PTY was killed by finish() as part of cleanup.+ expect(ptyInstances[0].kill).toHaveBeenCalled();+ });++ it('early-fails with reason "command-not-found" and exitCode 127 when "command not found" appears pre-paste', async () => {+ const provider = { id: 'codex', type: 'tui', command: 'no-such-tui' };+ const promise = executeTuiRun('run-missing', provider, 'a prompt long enough', '/cwd', undefined, undefined, 60000);+ await flushAsync();++ // Shell banner echoing the missing-command error before paste.+ ptyInstances[0].emitData('zsh: command not found: no-such-tui');++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-missing',+ success: false,+ exitCode: 127,+ error: expect.stringContaining('TUI command not found: no-such-tui'),+ extras: expect.objectContaining({ completionReason: 'command-not-found' }),+ }));+ });++ it('finishes with reason "exit" + exitCode 0 when the PTY closes cleanly', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const promise = executeTuiRun('run-exit', provider, 'a prompt long enough', '/cwd', undefined, undefined, 60000);+ await flushAsync();++ ptyInstances[0].emitExit({ exitCode: 0 });++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-exit',+ success: true,+ exitCode: 0,+ error: null,+ extras: expect.objectContaining({ completionReason: 'exit' }),+ }));+ });++ it('finishes with reason "killed" and surfaces the signal in the error when the PTY is terminated', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const promise = executeTuiRun('run-killed', provider, 'a prompt long enough', '/cwd', undefined, undefined, 60000);+ await flushAsync();++ ptyInstances[0].emitData('some screen output');+ ptyInstances[0].emitExit({ exitCode: null, signal: 'SIGTERM' });++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-killed',+ success: false,+ exitCode: 130,+ error: expect.stringContaining('SIGTERM'),+ extras: expect.objectContaining({ completionReason: 'killed' }),+ }));+ });++ it('finishes with a tail-bearing error message when the PTY exits non-zero with prior output', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const promise = executeTuiRun('run-nonzero', provider, 'a prompt long enough', '/cwd', undefined, undefined, 60000);+ await flushAsync();++ ptyInstances[0].emitData('fatal: provider config malformed at line 42');+ ptyInstances[0].emitExit({ exitCode: 2 });++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-nonzero',+ success: false,+ exitCode: 2,+ error: expect.stringMatching(/TUI exited with code 2.*malformed/),+ }));+ });+ });+});