|
| 1 | +import fs from 'node:fs'; |
| 2 | +import os from 'node:os'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { afterEach, test, vi } from 'vitest'; |
| 5 | +import assert from 'node:assert/strict'; |
| 6 | + |
| 7 | +vi.mock('../cli/commands/web.ts', async (importOriginal) => { |
| 8 | + const actual = await importOriginal<typeof import('../cli/commands/web.ts')>(); |
| 9 | + return { ...actual, runWebCommand: vi.fn(async () => 0) }; |
| 10 | +}); |
| 11 | + |
| 12 | +import { runCli } from '../cli.ts'; |
| 13 | +import { runWebCommand } from '../cli/commands/web.ts'; |
| 14 | +import { installIsolatedCliTestEnv } from './cli-test-env.ts'; |
| 15 | +import { resolveDaemonPaths } from '../daemon/config.ts'; |
| 16 | +import type { DaemonResponse } from '../daemon/client/daemon-client.ts'; |
| 17 | + |
| 18 | +afterEach(() => { |
| 19 | + vi.clearAllMocks(); |
| 20 | +}); |
| 21 | + |
| 22 | +function installExitSpy(): { calls: number[]; restore: () => void } { |
| 23 | + const originalExit = process.exit; |
| 24 | + const calls: number[] = []; |
| 25 | + (process as any).exit = ((code?: number) => { |
| 26 | + calls.push(code ?? 0); |
| 27 | + }) as typeof process.exit; |
| 28 | + return { calls, restore: () => (process.exit = originalExit) }; |
| 29 | +} |
| 30 | + |
| 31 | +class ProcessExitSentinel extends Error { |
| 32 | + code: number; |
| 33 | + constructor(code: number) { |
| 34 | + super(`process.exit(${code})`); |
| 35 | + this.code = code; |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +// `parseCliInputOrExit`'s early-exit branches run before `runCli`'s own |
| 40 | +// try/catch, so — unlike `installExitSpy` above — the mock here must behave |
| 41 | +// like a real `process.exit()` and actually stop execution (by throwing), |
| 42 | +// or the function falls through past its `return exitAfterFlush(...)` into |
| 43 | +// code that assumes a command was parsed. |
| 44 | +function installTerminatingExitSpy(): { restore: () => void } { |
| 45 | + const originalExit = process.exit; |
| 46 | + (process as any).exit = ((code?: number) => { |
| 47 | + throw new ProcessExitSentinel(code ?? 0); |
| 48 | + }) as typeof process.exit; |
| 49 | + return { restore: () => (process.exit = originalExit) }; |
| 50 | +} |
| 51 | + |
| 52 | +async function runCliExpectingExit( |
| 53 | + argv: string[], |
| 54 | + deps: { sendToDaemon: (...args: any[]) => Promise<DaemonResponse> }, |
| 55 | +): Promise<number> { |
| 56 | + try { |
| 57 | + await runCli(argv, deps as any); |
| 58 | + } catch (error) { |
| 59 | + if (error instanceof ProcessExitSentinel) return error.code; |
| 60 | + throw error; |
| 61 | + } |
| 62 | + throw new Error('expected runCli to exit'); |
| 63 | +} |
| 64 | + |
| 65 | +function captureStdout(): { read: () => string; restore: () => void } { |
| 66 | + const originalWrite = process.stdout.write.bind(process.stdout); |
| 67 | + let captured = ''; |
| 68 | + (process.stdout as { write: typeof process.stdout.write }).write = ((chunk: unknown) => { |
| 69 | + captured += String(chunk); |
| 70 | + return true; |
| 71 | + }) as typeof process.stdout.write; |
| 72 | + return { |
| 73 | + read: () => captured, |
| 74 | + restore: () => { |
| 75 | + process.stdout.write = originalWrite; |
| 76 | + }, |
| 77 | + }; |
| 78 | +} |
| 79 | + |
| 80 | +function captureStderr(): { read: () => string; restore: () => void } { |
| 81 | + const originalWrite = process.stderr.write.bind(process.stderr); |
| 82 | + let captured = ''; |
| 83 | + (process.stderr as { write: typeof process.stderr.write }).write = ((chunk: unknown) => { |
| 84 | + captured += String(chunk); |
| 85 | + return true; |
| 86 | + }) as typeof process.stderr.write; |
| 87 | + return { |
| 88 | + read: () => captured, |
| 89 | + restore: () => { |
| 90 | + process.stderr.write = originalWrite; |
| 91 | + }, |
| 92 | + }; |
| 93 | +} |
| 94 | + |
| 95 | +test('--version exits 0 and prints the version, without touching the daemon', async () => { |
| 96 | + const restoreEnv = installIsolatedCliTestEnv(); |
| 97 | + const exitSpy = installTerminatingExitSpy(); |
| 98 | + const stdout = captureStdout(); |
| 99 | + const sendToDaemon = async (): Promise<DaemonResponse> => { |
| 100 | + throw new Error('sendToDaemon should not be called for --version'); |
| 101 | + }; |
| 102 | + |
| 103 | + let exitCode: number; |
| 104 | + try { |
| 105 | + exitCode = await runCliExpectingExit(['--version'], { sendToDaemon }); |
| 106 | + } finally { |
| 107 | + stdout.restore(); |
| 108 | + exitSpy.restore(); |
| 109 | + restoreEnv(); |
| 110 | + } |
| 111 | + |
| 112 | + assert.equal(exitCode, 0); |
| 113 | + assert.ok(stdout.read().trim().length > 0); |
| 114 | +}); |
| 115 | + |
| 116 | +test('bare `help` with no target exits 0 and prints usage', async () => { |
| 117 | + const restoreEnv = installIsolatedCliTestEnv(); |
| 118 | + const exitSpy = installTerminatingExitSpy(); |
| 119 | + const stdout = captureStdout(); |
| 120 | + const sendToDaemon = async (): Promise<DaemonResponse> => { |
| 121 | + throw new Error('sendToDaemon should not be called for help'); |
| 122 | + }; |
| 123 | + |
| 124 | + let exitCode: number; |
| 125 | + try { |
| 126 | + exitCode = await runCliExpectingExit(['help'], { sendToDaemon }); |
| 127 | + } finally { |
| 128 | + stdout.restore(); |
| 129 | + exitSpy.restore(); |
| 130 | + restoreEnv(); |
| 131 | + } |
| 132 | + |
| 133 | + assert.equal(exitCode, 0); |
| 134 | + assert.ok(stdout.read().includes('agent-device')); |
| 135 | +}); |
| 136 | + |
| 137 | +test('no command exits 1 and prints usage', async () => { |
| 138 | + const restoreEnv = installIsolatedCliTestEnv(); |
| 139 | + const exitSpy = installTerminatingExitSpy(); |
| 140 | + const stdout = captureStdout(); |
| 141 | + const sendToDaemon = async (): Promise<DaemonResponse> => { |
| 142 | + throw new Error('sendToDaemon should not be called with no command'); |
| 143 | + }; |
| 144 | + |
| 145 | + let exitCode: number; |
| 146 | + try { |
| 147 | + exitCode = await runCliExpectingExit([], { sendToDaemon }); |
| 148 | + } finally { |
| 149 | + stdout.restore(); |
| 150 | + exitSpy.restore(); |
| 151 | + restoreEnv(); |
| 152 | + } |
| 153 | + |
| 154 | + assert.equal(exitCode, 1); |
| 155 | + assert.ok(stdout.read().length > 0); |
| 156 | +}); |
| 157 | + |
| 158 | +test("web command exits with runWebCommand's status code", async () => { |
| 159 | + const restoreEnv = installIsolatedCliTestEnv(); |
| 160 | + const exitSpy = installExitSpy(); |
| 161 | + const sendToDaemon = async (): Promise<DaemonResponse> => { |
| 162 | + throw new Error('sendToDaemon should not be called for web'); |
| 163 | + }; |
| 164 | + vi.mocked(runWebCommand).mockResolvedValueOnce(0); |
| 165 | + |
| 166 | + try { |
| 167 | + await runCli(['web', 'status'], { sendToDaemon }); |
| 168 | + } finally { |
| 169 | + exitSpy.restore(); |
| 170 | + restoreEnv(); |
| 171 | + } |
| 172 | + |
| 173 | + assert.deepEqual(exitSpy.calls, [0]); |
| 174 | + assert.equal(vi.mocked(runWebCommand).mock.calls.length, 1); |
| 175 | + assert.deepEqual(vi.mocked(runWebCommand).mock.calls[0]?.[0], ['status']); |
| 176 | +}); |
| 177 | + |
| 178 | +// #1596: printDaemonLogTailOnError's --debug dump must stay bounded even when |
| 179 | +// the daemon log itself is large — otherwise the dump risks the same |
| 180 | +// process.exit()-truncates-a-pipe-write failure exitAfterFlush exists to fix. |
| 181 | +test('a --debug failure caps the daemon-log-tail dump instead of printing it unbounded', async () => { |
| 182 | + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-cli-log-tail-')); |
| 183 | + const stateDir = path.join(tempRoot, 'state'); |
| 184 | + fs.mkdirSync(stateDir, { recursive: true }); |
| 185 | + const { logPath } = resolveDaemonPaths(stateDir); |
| 186 | + |
| 187 | + // 200 lines * 500 bytes = 100,000 bytes: within the existing 200-line cap, |
| 188 | + // but past the 64,000-byte cap this change adds — so only the byte cap can |
| 189 | + // explain the head line being absent from the captured output below. |
| 190 | + const headMarker = 'HEAD_OF_SEEDED_LOG_LINE_0000'; |
| 191 | + const tailMarker = 'TAIL_OF_SEEDED_LOG_LINE_0199'; |
| 192 | + const lines: string[] = []; |
| 193 | + for (let i = 0; i < 200; i += 1) { |
| 194 | + const marker = i === 0 ? headMarker : i === 199 ? tailMarker : `line-${i}`; |
| 195 | + lines.push(`${marker}-${'x'.repeat(500 - marker.length - 1)}`); |
| 196 | + } |
| 197 | + fs.writeFileSync(logPath, `${lines.join('\n')}\n`); |
| 198 | + |
| 199 | + const restoreEnv = installIsolatedCliTestEnv(); |
| 200 | + const exitSpy = installExitSpy(); |
| 201 | + const stderr = captureStderr(); |
| 202 | + const sendToDaemon = async (): Promise<DaemonResponse> => ({ |
| 203 | + ok: false, |
| 204 | + error: { code: 'SESSION_NOT_FOUND', message: 'No active session' }, |
| 205 | + }); |
| 206 | + |
| 207 | + try { |
| 208 | + await runCli(['session', 'list', '--state-dir', stateDir, '--debug'], { sendToDaemon }); |
| 209 | + } finally { |
| 210 | + stderr.restore(); |
| 211 | + exitSpy.restore(); |
| 212 | + restoreEnv(); |
| 213 | + fs.rmSync(tempRoot, { recursive: true, force: true }); |
| 214 | + } |
| 215 | + |
| 216 | + assert.deepEqual(exitSpy.calls, [1]); |
| 217 | + const output = stderr.read(); |
| 218 | + assert.ok(output.includes('[daemon log]'), 'expected the daemon-log-tail block to be printed'); |
| 219 | + assert.ok(output.includes(tailMarker), 'expected the most recent line to survive the byte cap'); |
| 220 | + assert.ok( |
| 221 | + !output.includes(headMarker), |
| 222 | + 'expected the byte cap to drop the oldest lines, not just the 200-line cap', |
| 223 | + ); |
| 224 | +}); |
0 commit comments