| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 |
- import { mkdtemp, mkdir, realpath, rm, symlink, truncate, writeFile } from 'node:fs/promises';
- import { tmpdir } from 'node:os';
- import { join } from 'node:path';
- import { afterEach, describe, expect, it, vi } from 'vitest';
- import {
- resolveTuiExecInvocation,
- type RawTuiExecOptions,
- } from '../../src/headless/invocation.js';
- const roots: string[] = [];
- afterEach(async () => {
- await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
- });
- async function workspace(): Promise<string> {
- const root = await mkdtemp(join(tmpdir(), 'mcode-headless-invocation-'));
- roots.push(root);
- return root;
- }
- describe('headless invocation', () => {
- it('resolves exec review as a fixed local-changes operation without stdin', async () => {
- const cwd = await workspace();
- const readStdin = vi.fn(async () => 'ignored');
- await expect(
- resolveTuiExecInvocation(
- undefined,
- {
- review: true,
- cwd,
- model: 'provider/model',
- permission: 'full',
- outputFormat: 'json',
- },
- readStdin,
- ),
- ).resolves.toMatchObject({
- prompt: 'Please review my uncommitted changes.',
- workspaceDir: await realpath(cwd),
- model: 'provider/model',
- permission: 'full',
- format: 'json',
- attachments: [],
- continueSession: false,
- reviewRequest: { scope: 'local_changes' },
- });
- expect(readStdin).not.toHaveBeenCalled();
- });
- it('carries a trimmed --effort for exec and exec review and rejects a blank level', async () => {
- const cwd = await workspace();
- const readStdin = vi.fn(async () => 'ignored');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, effort: ' xhigh ' }, readStdin),
- ).resolves.toMatchObject({ effort: 'xhigh' });
- await expect(
- resolveTuiExecInvocation(undefined, { review: true, cwd, effort: 'high' }, readStdin),
- ).resolves.toMatchObject({ effort: 'high', reviewRequest: { scope: 'local_changes' } });
- await expect(resolveTuiExecInvocation('prompt', { cwd }, readStdin)).resolves.not.toHaveProperty(
- 'effort',
- );
- for (const options of [{ cwd, effort: ' ' }, { review: true, cwd, effort: '' }]) {
- await expect(
- resolveTuiExecInvocation('prompt', options, readStdin),
- ).rejects.toMatchObject({ kind: 'invocation', message: '--effort cannot be empty.' });
- }
- });
- it('resolves a diagnostics directory against cwd and rejects empty or file paths', async () => {
- const cwd = await workspace();
- const invocation = await resolveTuiExecInvocation('review', { cwd, diagnosticsDir: 'evidence' }, async () => '');
- expect(invocation.diagnosticsDir).toBe(join(await realpath(cwd), 'evidence'));
- await expect(resolveTuiExecInvocation('review', { cwd, diagnosticsDir: '' }, async () => '')).rejects.toThrow('--diagnostics-dir');
- await writeFile(join(cwd, 'file'), 'not a directory');
- await expect(resolveTuiExecInvocation('review', { cwd, diagnosticsDir: 'file' }, async () => '')).rejects.toThrow('--diagnostics-dir');
- });
- it('never reads stdin without explicit --input -', async () => {
- const cwd = await workspace();
- let reads = 0;
- await expect(
- resolveTuiExecInvocation('prompt', { cwd }, async () => {
- reads += 1;
- return 'ignored';
- }),
- ).resolves.toMatchObject({
- prompt: 'prompt',
- workspaceDir: await realpath(cwd),
- });
- expect(reads).toBe(0);
- });
- it('defaults to smart permissions and rejects interactive ask before reading input', async () => {
- const cwd = await workspace();
- const readStdin = vi.fn(async () => 'ignored');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd }, readStdin),
- ).resolves.toMatchObject({ permission: 'smart' });
- await expect(
- resolveTuiExecInvocation(undefined, { cwd, input: '-', permission: 'ask' }, readStdin),
- ).rejects.toMatchObject({
- kind: 'invocation',
- message: expect.stringContaining('requires an interactive host'),
- });
- expect(readStdin).not.toHaveBeenCalled();
- });
- it('accepts JSON stdin and rejects prompt/source conflicts', async () => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation(
- undefined,
- { cwd, input: '-', inputFormat: 'json' },
- async () => '{"prompt":"from json"}',
- ),
- ).resolves.toMatchObject({ prompt: 'from json' });
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, input: '-' }, async () => 'from stdin'),
- ).rejects.toThrow('cannot be combined');
- });
- it('supports attachment-only input and resolves a symlinked file', async () => {
- const cwd = await workspace();
- await writeFile(join(cwd, 'actual.txt'), 'hello');
- await symlink(join(cwd, 'actual.txt'), join(cwd, 'alias.txt'));
- const invocation = await resolveTuiExecInvocation(
- undefined,
- { cwd, file: ['alias.txt'] },
- async () => {
- throw new Error('stdin must not be read');
- },
- );
- expect(invocation.prompt).toBe('');
- expect(invocation.attachments).toEqual([
- expect.objectContaining({
- fileName: 'actual.txt',
- mimeType: 'text/plain',
- sizeBytes: 5,
- }),
- ]);
- });
- it('preserves video MIME metadata for model capability selection', async () => {
- const cwd = await workspace();
- await writeFile(join(cwd, 'demo.mp4'), Buffer.from([0, 1, 2, 3]));
- await expect(
- resolveTuiExecInvocation('Review this video', { cwd, file: ['demo.mp4'] }, async () => ''),
- ).resolves.toMatchObject({
- attachments: [
- {
- type: 'file',
- fileName: 'demo.mp4',
- mimeType: 'video/mp4',
- sizeBytes: 4,
- },
- ],
- });
- });
- it('rejects missing cwd, missing input, invalid duration, and conflicting session strategies', async () => {
- const cwd = await workspace();
- await mkdir(join(cwd, 'file-dir'));
- const cases: RawTuiExecOptions[] = [
- { cwd: join(cwd, 'missing') },
- { cwd },
- { cwd, timeout: 'forever' },
- { cwd, session: 'session-1', continue: true },
- ];
- for (const options of cases) {
- await expect(
- resolveTuiExecInvocation(undefined, options, async () => ''),
- ).rejects.toThrow();
- }
- });
- it('cancels before reading files or stdin when the invocation signal is aborted', async () => {
- const cwd = await workspace();
- const controller = new AbortController();
- controller.abort('test');
- let reads = 0;
- await expect(
- resolveTuiExecInvocation(
- undefined,
- { cwd, input: '-' },
- async () => {
- reads += 1;
- return 'ignored';
- },
- controller.signal,
- ),
- ).rejects.toMatchObject({ kind: 'cancelled' });
- expect(reads).toBe(0);
- });
- it('accepts binary files and matches the client attachment limits', async () => {
- const cwd = await workspace();
- await writeFile(join(cwd, 'payload.bin'), Buffer.from([0, 1, 2, 3]));
- await writeFile(join(cwd, 'large.bin'), '');
- await truncate(join(cwd, 'large.bin'), 100 * 1024 * 1024 + 1);
- await expect(
- resolveTuiExecInvocation(undefined, { cwd, file: ['payload.bin'] }, async () => ''),
- ).resolves.toMatchObject({
- attachments: [
- {
- type: 'file',
- fileName: 'payload.bin',
- mimeType: 'application/octet-stream',
- sizeBytes: 4,
- },
- ],
- });
- await expect(
- resolveTuiExecInvocation(undefined, { cwd, file: ['missing.bin'] }, async () => ''),
- ).rejects.toThrow('Cannot attach missing.bin');
- await expect(
- resolveTuiExecInvocation(undefined, { cwd, file: ['large.bin'] }, async () => ''),
- ).rejects.toThrow('100 MB limit');
- const files = Array.from({ length: 11 }, (_, index) => `file-${String(index)}.txt`);
- await Promise.all(files.map((file) => writeFile(join(cwd, file), file)));
- await expect(
- resolveTuiExecInvocation(undefined, { cwd, file: files }, async () => ''),
- ).rejects.toThrow('up to 10 files');
- });
- it('normalizes canonical output flags and parses the result schema', async () => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation(
- 'prompt',
- {
- cwd,
- outputFormat: 'stream-json',
- outputSchema: '{"type":"object","required":["type"]}',
- },
- async () => '',
- ),
- ).resolves.toMatchObject({
- format: 'stream-json',
- outputSchema: { type: 'object', required: ['type'] },
- });
- });
- it('loads an output schema file and resolves the last-message target without creating it', async () => {
- const cwd = await workspace();
- await writeFile(
- join(cwd, 'review.schema.json'),
- JSON.stringify({ type: 'object', required: ['findings'] }),
- );
- await expect(
- resolveTuiExecInvocation(
- 'review',
- {
- cwd,
- outputSchema: 'review.schema.json',
- outputLastMessage: 'artifacts/review.json',
- },
- async () => '',
- ),
- ).rejects.toThrow('--output-last-message is invalid');
- await mkdir(join(cwd, 'artifacts'));
- await expect(
- resolveTuiExecInvocation(
- 'review',
- {
- cwd,
- outputSchema: 'review.schema.json',
- outputLastMessage: 'artifacts/review.json',
- },
- async () => '',
- ),
- ).resolves.toMatchObject({
- outputSchema: { type: 'object', required: ['findings'] },
- outputLastMessagePath: join(await realpath(cwd), 'artifacts', 'review.json'),
- });
- });
- it('resolves every optional automation control and trims owner identifiers', async () => {
- const cwd = await workspace();
- await writeFile(join(cwd, 'mcode.yaml'), 'models: {}\n');
- await writeFile(join(cwd, 'image.PNG'), Buffer.from([1, 2, 3]));
- await expect(
- resolveTuiExecInvocation(
- 'prompt',
- {
- cwd,
- file: ['image.PNG'],
- model: ' provider/model#fast ',
- session: ' session-1 ',
- config: 'mcode.yaml',
- permission: 'off',
- timeout: '2h',
- maxSteps: '12',
- outputFormat: 'json',
- },
- async () => '',
- ),
- ).resolves.toMatchObject({
- prompt: 'prompt',
- attachments: [
- expect.objectContaining({
- type: 'image',
- fileName: 'image.PNG',
- mimeType: 'image/png',
- }),
- ],
- model: 'provider/model#fast',
- sessionId: 'session-1',
- configPath: await realpath(join(cwd, 'mcode.yaml')),
- permission: 'off',
- timeoutMs: 7_200_000,
- maxSteps: 12,
- format: 'json',
- });
- });
- it.each([
- [{ input: 'file' }, '--input currently accepts only'],
- [{ inputFormat: 'yaml' }, '--input-format must be one of'],
- [{ outputFormat: 'xml' }, '--output-format must be one of'],
- [{ permission: 'root' }, '--permission must be one of'],
- ] as const)('rejects invalid enum-like option %s', async (options, message) => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, ...options }, async () => ''),
- ).rejects.toThrow(message);
- });
- it('accepts both JSON prompt shapes and rejects every other JSON input', async () => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation(
- undefined,
- { cwd, input: '-', inputFormat: 'json' },
- async () => '"string prompt"',
- ),
- ).resolves.toMatchObject({ prompt: 'string prompt' });
- await expect(
- resolveTuiExecInvocation(
- undefined,
- { cwd, input: '-', inputFormat: 'json' },
- async () => '{invalid',
- ),
- ).rejects.toThrow('requires valid JSON');
- for (const input of ['[]', '{}', '{"prompt":1}', 'null']) {
- await expect(
- resolveTuiExecInvocation(
- undefined,
- { cwd, input: '-', inputFormat: 'json' },
- async () => input,
- ),
- ).rejects.toThrow('JSON string or an object with string prompt');
- }
- });
- it.each([
- ['1', 1],
- ['500ms', 500],
- ['30s', 30_000],
- ['2m', 120_000],
- ['1H', 3_600_000],
- ] as const)('parses timeout %s as %i milliseconds', async (timeout, timeoutMs) => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, timeout }, async () => ''),
- ).resolves.toMatchObject({ timeoutMs });
- });
- it.each([
- [{ timeout: '0' }, '--timeout must resolve to a positive safe integer'],
- [{ timeout: '9007199254740992h' }, '--timeout must resolve to a positive safe integer'],
- [{ maxSteps: '0' }, '--max-steps must be a positive safe integer'],
- [{ maxSteps: '-1' }, '--max-steps must be a positive integer'],
- [{ maxSteps: '1.5' }, '--max-steps must be a positive integer'],
- [{ maxSteps: '9007199254740992' }, '--max-steps must be a positive safe integer'],
- ] as const)('rejects invalid numeric automation control %s', async (options, message) => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, ...options }, async () => ''),
- ).rejects.toThrow(message);
- });
- it.each([
- ['null', '--output-schema requires a JSON object'],
- ['[]', '--output-schema requires a JSON object'],
- ['"text"', '--output-schema requires a JSON object'],
- ['{invalid', '--output-schema requires a JSON object'],
- ['{"type":42}', '--output-schema requires a JSON object'],
- ] as const)('rejects invalid output schema %s', async (outputSchema, message) => {
- const cwd = await workspace();
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, outputSchema }, async () => ''),
- ).rejects.toThrow(message);
- });
- it('rejects non-file attachments, non-directory cwd, invalid config targets, and empty paths', async () => {
- const cwd = await workspace();
- await mkdir(join(cwd, 'directory'));
- await writeFile(join(cwd, 'file.txt'), 'file');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, file: ['directory'] }, async () => ''),
- ).rejects.toThrow('path is not a file');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd: join(cwd, 'file.txt') }, async () => ''),
- ).rejects.toThrow('--cwd must reference a directory');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, config: 'directory' }, async () => ''),
- ).rejects.toThrow('--config must reference a file');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd, config: 'missing' }, async () => ''),
- ).rejects.toThrow('--config is invalid');
- await expect(
- resolveTuiExecInvocation('prompt', { cwd: ' ' }, async () => ''),
- ).rejects.toThrow('Path value cannot be empty');
- });
- it('cancels after an in-flight stdin read before resolving attachments', async () => {
- const cwd = await workspace();
- const controller = new AbortController();
- await expect(
- resolveTuiExecInvocation(
- undefined,
- { cwd, input: '-' },
- async () => {
- controller.abort('cancelled after read');
- return 'prompt';
- },
- controller.signal,
- ),
- ).rejects.toMatchObject({ kind: 'cancelled' });
- });
- });
- describe('Prompt mode selection', () => {
- it.each([undefined, 'tui', 'coding', 'work'])(
- 'resolves %s before runtime startup',
- async (promptMode) => {
- const invocation = await resolveTuiExecInvocation('hello', { promptMode }, async () => '');
- expect(invocation.promptMode).toBe(promptMode ?? 'tui');
- },
- );
- it('rejects unknown modes', async () => {
- await expect(
- resolveTuiExecInvocation('hello', { promptMode: 'unknown' }, async () => ''),
- ).rejects.toThrow('--prompt-mode must be one of');
- });
- });
|