@moxxy/plugin-terminal 0.41.3 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Start files that make zsh and bash report each command they start and every
3
+ * return to their prompt, in a control sequence a terminal does not draw. The
4
+ * `terminal` tool waits for that report. It used to type a `printf` after the
5
+ * command: typed-ahead input is read by whatever is running, so an installer
6
+ * asking questions swallowed it and the call waited out its timeout.
7
+ */
8
+
9
+ import { randomBytes } from 'node:crypto';
10
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
12
+ import { basename, join } from 'node:path';
13
+
14
+ export interface ShellHooks {
15
+ /** Unpredictable, so text a command prints cannot pass for a report. */
16
+ readonly key: string;
17
+ readonly args: string[];
18
+ readonly env: NodeJS.ProcessEnv;
19
+ /** Deletes the start files; the running shell has read them already. */
20
+ remove(): void;
21
+ }
22
+
23
+ /** An operating-system command no terminal knows, so none draws it. */
24
+ const OSC = '\u001b]7717;moxxy;';
25
+ const END = '\u0007';
26
+
27
+ /**
28
+ * One report: how many commands the shell has started, and, when it is back at
29
+ * its prompt, the last one's exit code (null while that command still runs).
30
+ */
31
+ export interface ShellReport {
32
+ readonly commands: number;
33
+ readonly exitCode: number | null;
34
+ }
35
+
36
+ /** What a hooked shell prints: before a command with no exit code, before each prompt with one. */
37
+ export function shellMark(key: string, report: ShellReport): string {
38
+ return `${OSC}${key};${report.commands};${report.exitCode ?? ''}${END}`;
39
+ }
40
+
41
+ /** Finds the shell's reports in a stream that arrives in arbitrary chunks. */
42
+ export class ShellMarks {
43
+ private readonly mark: RegExp;
44
+ private readonly longest: number;
45
+ private carry = '';
46
+
47
+ constructor(key: string) {
48
+ // The key is hex, so nothing in it needs escaping.
49
+ this.mark = new RegExp(`\\u001b\\]7717;moxxy;${key};(\\d+);(\\d*)\\u0007`, 'gu');
50
+ this.longest = shellMark(key, { commands: 0, exitCode: 0 }).length + 32;
51
+ }
52
+
53
+ /** The reports in `chunk`, counting one begun in an earlier chunk. */
54
+ read(chunk: string): ShellReport[] {
55
+ const text = this.carry + chunk;
56
+ const reports: ShellReport[] = [];
57
+ let end = 0;
58
+ for (const match of text.matchAll(this.mark)) {
59
+ reports.push({ commands: Number(match[1]), exitCode: match[2] ? Number(match[2]) : null });
60
+ end = match.index + match[0].length;
61
+ }
62
+ this.carry = text.slice(Math.max(end, text.length - this.longest));
63
+ return reports;
64
+ }
65
+ }
66
+
67
+ const quoted = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`;
68
+
69
+ /** printf's own escapes, so the start files stay plain text. */
70
+ const print = (key: string): string => `builtin printf '\\033]7717;moxxy;${key};%s;%s\\007'`;
71
+
72
+ function zshFiles(key: string, userDir: string | undefined): Record<string, string> {
73
+ const restore = userDir === undefined ? 'unset ZDOTDIR' : `ZDOTDIR=${quoted(userDir)}`;
74
+ return {
75
+ '.zshenv': [
76
+ '__moxxy_start=$ZDOTDIR',
77
+ restore,
78
+ '[[ -f ${ZDOTDIR:-$HOME}/.zshenv ]] && . ${ZDOTDIR:-$HOME}/.zshenv',
79
+ // The user's own file may have moved ZDOTDIR: that is where the rest lives.
80
+ '__moxxy_user=${ZDOTDIR-}',
81
+ 'ZDOTDIR=$__moxxy_start',
82
+ ].join('\n'),
83
+ '.zshrc': [
84
+ // /etc/zshrc pointed the history at these start files; it belongs to the user.
85
+ '[[ $HISTFILE == $__moxxy_start/* ]] && HISTFILE=${__moxxy_user:-$HOME}/${HISTFILE:t}',
86
+ 'if [[ -n $__moxxy_user ]]; then ZDOTDIR=$__moxxy_user; else unset ZDOTDIR; fi',
87
+ 'unset __moxxy_start __moxxy_user',
88
+ '[[ -f ${ZDOTDIR:-$HOME}/.zshrc ]] && . ${ZDOTDIR:-$HOME}/.zshrc',
89
+ 'typeset -gi __moxxy_commands=0',
90
+ `__moxxy_command() { (( __moxxy_commands += 1 )); ${print(key)} $__moxxy_commands '' }`,
91
+ `__moxxy_prompt() { ${print(key)} $__moxxy_commands "$?" }`,
92
+ 'preexec_functions+=(__moxxy_command)',
93
+ 'precmd_functions=(__moxxy_prompt $precmd_functions)',
94
+ ].join('\n'),
95
+ };
96
+ }
97
+
98
+ /**
99
+ * bash has no hook before a command, so the reports ride on its prompt strings,
100
+ * where `\#` is the number of the command about to be read: PS1 carries the
101
+ * prompt's, PS0 (bash 4.4 and later, ignored before) the command's.
102
+ */
103
+ function bashInit(key: string): string {
104
+ const mark = (commands: string, exitCode: string): string => `\\033]7717;moxxy;${key};${commands};${exitCode}\\007`;
105
+ return [
106
+ '[ -f ~/.bashrc ] && . ~/.bashrc',
107
+ '__moxxy_code=0',
108
+ // Returns the code it read, so the user's own prompt command still sees it.
109
+ '__moxxy_prompt() { __moxxy_code=$?; return $__moxxy_code; }',
110
+ // Put back each time: a prompt command that rebuilds PS1 drops it.
111
+ `__moxxy_ps1() { case "$PS1" in *"7717;moxxy;${key}"*) ;; *) PS1='\\[${mark('$((\\#-1))', '${__moxxy_code}')}\\]'"$PS1" ;; esac; }`,
112
+ `PS0='${mark('\\#', '')}'"\${PS0-}"`,
113
+ "__moxxy_nl=$'\\n'",
114
+ 'case "$(declare -p PROMPT_COMMAND 2>/dev/null)" in',
115
+ ' "declare -a"*) PROMPT_COMMAND=(__moxxy_prompt "${PROMPT_COMMAND[@]}" __moxxy_ps1) ;;',
116
+ // Joined by newlines: the user's own may end in a `;`.
117
+ ' *) PROMPT_COMMAND="__moxxy_prompt${PROMPT_COMMAND:+$__moxxy_nl$PROMPT_COMMAND}${__moxxy_nl}__moxxy_ps1" ;;',
118
+ 'esac',
119
+ ].join('\n');
120
+ }
121
+
122
+ /** The start files for `shell`, or null for a shell there are none for (cmd, PowerShell, fish). */
123
+ export function installShellHooks(shell: string, env: NodeJS.ProcessEnv): ShellHooks | null {
124
+ if (process.platform === 'win32') return null;
125
+ const name = basename(shell);
126
+ if (name !== 'zsh' && name !== 'bash') return null;
127
+ const key = randomBytes(8).toString('hex');
128
+ const dir = mkdtempSync(join(tmpdir(), 'moxxy-shell-'));
129
+ const remove = (): void => rmSync(dir, { recursive: true, force: true });
130
+ if (name === 'zsh') {
131
+ for (const [file, text] of Object.entries(zshFiles(key, env['ZDOTDIR']))) {
132
+ writeFileSync(join(dir, file), `${text}\n`, { mode: 0o600 });
133
+ }
134
+ return { key, args: [], env: { ...env, ZDOTDIR: dir }, remove };
135
+ }
136
+ const init = join(dir, 'init.bash');
137
+ writeFileSync(init, `${bashInit(key)}\n`, { mode: 0o600 });
138
+ return { key, args: ['--init-file', init], env, remove };
139
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * runCommand against a REAL interactive zsh set up the way Oh My Zsh does it:
3
+ * `preexec` prints an OSC title sequence right before the command's own output,
4
+ * so the sentinel line does not start at a newline, and every typed character
5
+ * goes through the `url-quote-magic` widget, so zsh reads typed input slowly.
6
+ */
7
+
8
+ import { spawnSync } from 'node:child_process';
9
+ import { mkdtempSync, writeFileSync } from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
13
+ import { createTerminalProcess, type TerminalProcess } from './pty.js';
14
+ import { runCommand } from './terminal.js';
15
+ import { removeDirSync } from '@moxxy/vitest-preset/fs';
16
+
17
+ const zsh = spawnSync('zsh', ['-c', 'command -v zsh'], { encoding: 'utf8' });
18
+ const zshPath = zsh.status === 0 ? zsh.stdout.trim() : null;
19
+
20
+ /** Well under the test timeout, so a missed sentinel reads as `timedOut`. */
21
+ const COMMAND_TIMEOUT_MS = 3_000;
22
+
23
+ const TITLE_HOOKS = [
24
+ "preexec() { printf '\\e]2;%s\\a\\e]1;%s\\a' \"$1\" \"${1%% *}\"; }",
25
+ "precmd() { printf '\\e]2;%s\\a' \"$PWD\"; }",
26
+ "PROMPT='%~ %# '",
27
+ 'autoload -Uz url-quote-magic',
28
+ 'zle -N self-insert url-quote-magic',
29
+ 'unset HISTFILE',
30
+ ].join('\n');
31
+
32
+ /** Drains whatever is typed ahead for a moment, the way a prompt library reads its answers. */
33
+ const READS_INPUT = `"${process.execPath}" -e "process.stdin.resume(); setTimeout(() => process.exit(0), 300)"`;
34
+
35
+ /** What a terminal draws of a stream: its control sequences are not text. */
36
+ function shownText(raw: string): string {
37
+ return raw.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/gu, '');
38
+ }
39
+
40
+ describe.skipIf(zshPath === null)('runCommand in a zsh set up like Oh My Zsh', () => {
41
+ const saved = { SHELL: process.env.SHELL, ZDOTDIR: process.env.ZDOTDIR };
42
+ let dotdir: string;
43
+ let term: TerminalProcess;
44
+
45
+ beforeEach(async () => {
46
+ dotdir = mkdtempSync(path.join(os.tmpdir(), 'moxxy-zsh-'));
47
+ writeFileSync(path.join(dotdir, '.zshrc'), `${TITLE_HOOKS}\n`);
48
+ process.env.SHELL = zshPath ?? undefined;
49
+ process.env.ZDOTDIR = dotdir;
50
+ term = await createTerminalProcess(os.tmpdir());
51
+ });
52
+
53
+ afterEach(() => {
54
+ term.kill();
55
+ for (const [key, value] of Object.entries(saved)) {
56
+ if (value === undefined) delete process.env[key];
57
+ else process.env[key] = value;
58
+ }
59
+ removeDirSync(dotdir);
60
+ });
61
+
62
+ it('finishes as soon as the command does instead of waiting out the timeout', async () => {
63
+ const res = await runCommand(term, 'echo hi', '__MOXXY_DONE_zsh_0__', COMMAND_TIMEOUT_MS);
64
+
65
+ expect(res.timedOut).toBe(false);
66
+ expect(res.exitCode).toBe(0);
67
+ });
68
+
69
+ it('reports the exit code of a failing command', async () => {
70
+ const res = await runCommand(term, 'false', '__MOXXY_DONE_zsh_1__', COMMAND_TIMEOUT_MS);
71
+
72
+ expect(res.exitCode).toBe(1);
73
+ });
74
+
75
+ it('returns the output as plain text, without the terminal control sequences', async () => {
76
+ const res = await runCommand(term, 'echo hi', '__MOXXY_DONE_zsh_2__', COMMAND_TIMEOUT_MS);
77
+
78
+ expect(res.output.split('\n')).toContain('hi');
79
+ expect(res.output).not.toContain('\u001b');
80
+ expect(res.output).not.toContain('\u0007');
81
+ expect(res.output).not.toContain('\r');
82
+ });
83
+
84
+ it('runs a long script fed through a heredoc whole, and the shell takes the next command', async () => {
85
+ // Lines wider than the 80-column terminal: typed in, zsh redraws them while
86
+ // more input arrives and loses characters (the heredoc's end line with them).
87
+ const body = Array.from({ length: 60 }, (_, i) => `print('line ${i} ${'x'.repeat(100)}')`).join('\n');
88
+ const script = `python3 - <<'PY'\n${body}\nPY`;
89
+
90
+ const res = await runCommand(term, script, '__MOXXY_DONE_zsh_3__', COMMAND_TIMEOUT_MS);
91
+ const next = await runCommand(term, 'echo ok', '__MOXXY_DONE_zsh_4__', COMMAND_TIMEOUT_MS);
92
+
93
+ expect(res.timedOut).toBe(false);
94
+ const printed = res.output.split('\n').filter((line) => line.startsWith('line '));
95
+ expect(printed).toEqual(Array.from({ length: 60 }, (_, i) => `line ${i} ${'x'.repeat(100)}`));
96
+ expect(next.output.split('\n')).toContain('ok');
97
+ });
98
+
99
+ it('keeps what a script changes in the shell, as if it had been typed', async () => {
100
+ await runCommand(term, `cd /\nexport MOXXY_SEEN=${'y'.repeat(600)}`, '__MOXXY_DONE_zsh_5__', COMMAND_TIMEOUT_MS);
101
+ const res = await runCommand(term, 'pwd; echo ${#MOXXY_SEEN}', '__MOXXY_DONE_zsh_6__', COMMAND_TIMEOUT_MS);
102
+
103
+ expect(res.output.split('\n')).toEqual(expect.arrayContaining(['/', '600']));
104
+ });
105
+
106
+ it('finishes when the command reads the terminal input itself, like an installer asking questions', async () => {
107
+ const res = await runCommand(term, READS_INPUT, '__MOXXY_DONE_zsh_9__', COMMAND_TIMEOUT_MS);
108
+ const next = await runCommand(term, 'echo ok', '__MOXXY_DONE_zsh_10__', COMMAND_TIMEOUT_MS);
109
+
110
+ expect(res.timedOut).toBe(false);
111
+ expect(res.exitCode).toBe(0);
112
+ expect(next.output.split('\n')).toContain('ok');
113
+ });
114
+
115
+ it('shows nothing in the terminal but the command and its output', async () => {
116
+ await runCommand(term, 'echo hi', '__MOXXY_DONE_zsh_11__', COMMAND_TIMEOUT_MS);
117
+
118
+ const shown = shownText(term.scrollback());
119
+ expect(shown).toContain('echo hi');
120
+ expect(shown).not.toContain('__MOXXY_DONE');
121
+ expect(shown).not.toContain('printf');
122
+ });
123
+
124
+ it('frees a shell left waiting for the end of an unfinished command', async () => {
125
+ const stuck = await runCommand(term, "cat <<'NEVER'", '__MOXXY_DONE_zsh_7__', 1_000);
126
+ const next = await runCommand(term, 'echo ok', '__MOXXY_DONE_zsh_8__', COMMAND_TIMEOUT_MS);
127
+
128
+ expect(stuck.timedOut).toBe(true);
129
+ expect(stuck.output).toContain('waiting for the rest of an unfinished command');
130
+ expect(next.output.split('\n')).toContain('ok');
131
+ });
132
+ });
133
+
134
+ const bash = spawnSync('bash', ['-c', 'command -v bash'], { encoding: 'utf8' });
135
+ const bashPath = bash.status === 0 ? bash.stdout.trim() : null;
136
+
137
+ describe.skipIf(bashPath === null || process.platform === 'win32')('runCommand in bash', () => {
138
+ const saved = { SHELL: process.env.SHELL, HOME: process.env.HOME };
139
+ let home: string;
140
+ let term: TerminalProcess;
141
+
142
+ beforeEach(async () => {
143
+ home = mkdtempSync(path.join(os.tmpdir(), 'moxxy-bash-'));
144
+ // The user's own prompt command runs after the report and must still see `$?`.
145
+ writeFileSync(path.join(home, '.bashrc'), "PROMPT_COMMAND='MOXXY_SAW=$?'\nPS1='$ '\nunset HISTFILE\n");
146
+ process.env.SHELL = bashPath ?? undefined;
147
+ process.env.HOME = home;
148
+ term = await createTerminalProcess(os.tmpdir());
149
+ });
150
+
151
+ afterEach(() => {
152
+ term.kill();
153
+ for (const [key, value] of Object.entries(saved)) {
154
+ if (value === undefined) delete process.env[key];
155
+ else process.env[key] = value;
156
+ }
157
+ removeDirSync(home);
158
+ });
159
+
160
+ it('reports the exit code of a failing command, and leaves it to the user\'s prompt command', async () => {
161
+ const res = await runCommand(term, '(exit 3)', '__MOXXY_DONE_bash_0__', COMMAND_TIMEOUT_MS);
162
+ const seen = await runCommand(term, 'echo saw=$MOXXY_SAW', '__MOXXY_DONE_bash_1__', COMMAND_TIMEOUT_MS);
163
+
164
+ expect(res.exitCode).toBe(3);
165
+ expect(seen.output.split('\n')).toContain('saw=3');
166
+ });
167
+
168
+ it('finishes when the command reads the terminal input itself', async () => {
169
+ const res = await runCommand(term, READS_INPUT, '__MOXXY_DONE_bash_2__', COMMAND_TIMEOUT_MS);
170
+
171
+ expect(res.timedOut).toBe(false);
172
+ expect(res.exitCode).toBe(0);
173
+ });
174
+
175
+ it('shows nothing in the terminal but the command and its output', async () => {
176
+ await runCommand(term, 'echo hi', '__MOXXY_DONE_bash_3__', COMMAND_TIMEOUT_MS);
177
+
178
+ const shown = shownText(term.scrollback());
179
+ expect(shown).not.toContain('__MOXXY_DONE');
180
+ expect(shown).not.toContain('printf');
181
+ });
182
+ });
@@ -1,3 +1,4 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
1
2
  import { describe, expect, it, vi } from 'vitest';
2
3
  import { runCommand } from './terminal.js';
3
4
  import type { TerminalProcess } from './pty.js';
@@ -106,7 +107,7 @@ describe('runCommand sentinel detection (tail-scan, single RegExp compile)', ()
106
107
 
107
108
  // The shell echoes the printf command itself first (contains the marker but
108
109
  // NOT "<marker> <digits>"), then later the real sentinel value line.
109
- term.feed(`printf '%s %s\\n' "${marker}" "$?"\n`);
110
+ term.feed(`printf '\\n%s %s\\n' "${marker}" "$?"\n`);
110
111
  term.feed('echo done\n');
111
112
  term.feed('done\n');
112
113
  term.feed(`${marker} 0\n`);
@@ -243,7 +244,7 @@ describe('runCommand sentinel detection (tail-scan, single RegExp compile)', ()
243
244
 
244
245
  const all = term.writes.join('');
245
246
  // The printf line is preceded by a newline (its own write begins with "\n").
246
- expect(all).toContain(`\nprintf '%s %s\\n' "${marker}" "$?"\n`);
247
+ expect(all).toContain(`\nprintf '\\n%s %s\\n' "${marker}" "$?"\n`);
247
248
 
248
249
  // And completion still works end-to-end.
249
250
  term.feed(`${marker} 0\n`);
@@ -285,6 +286,203 @@ describe('runCommand sentinel detection (tail-scan, single RegExp compile)', ()
285
286
  });
286
287
  });
287
288
 
289
+ /** A fake terminal whose shell reports its commands and each return to its prompt. */
290
+ function promptingTerminal(): ReturnType<typeof fakeTerminal> & {
291
+ /** The shell starts a command it was typed. */
292
+ startCommand(): void;
293
+ /** The shell is back at its prompt. */
294
+ showPrompt(exitCode: number): void;
295
+ } {
296
+ const listeners = new Set<(exitCode: number, commands: number) => void>();
297
+ let seen = false;
298
+ let commands = 0;
299
+ return Object.assign(fakeTerminal(), {
300
+ prompt: {
301
+ get seen() {
302
+ return seen;
303
+ },
304
+ get commands() {
305
+ return commands;
306
+ },
307
+ onPrompt: (cb: (exitCode: number, commands: number) => void) => {
308
+ listeners.add(cb);
309
+ return () => listeners.delete(cb);
310
+ },
311
+ },
312
+ startCommand: () => {
313
+ commands += 1;
314
+ },
315
+ showPrompt: (exitCode: number) => {
316
+ seen = true;
317
+ for (const cb of [...listeners]) cb(exitCode, commands);
318
+ },
319
+ });
320
+ }
321
+
322
+ describe('runCommand in a shell that reports its prompt', () => {
323
+ it('types the command alone and finishes when the prompt is back', async () => {
324
+ const term = promptingTerminal();
325
+ term.showPrompt(0);
326
+ const p = runCommand(term, 'npm test', '__MOXXY_DONE_hook_0__', 5_000);
327
+
328
+ expect(term.writes).toEqual(['npm test\n']);
329
+ term.startCommand();
330
+ term.feed('npm test\n2 failed\n');
331
+ term.showPrompt(1);
332
+
333
+ const res = await p;
334
+ expect(res).toEqual({ output: '2 failed', exitCode: 1, timedOut: false });
335
+ });
336
+
337
+ it('is not ended by a prompt drawn again before its command started', async () => {
338
+ const term = promptingTerminal();
339
+ term.showPrompt(0);
340
+ let done = false;
341
+ const p = runCommand(term, 'npm test', '__MOXXY_DONE_hook_4__', 5_000).then((res) => {
342
+ done = true;
343
+ return res;
344
+ });
345
+
346
+ // The user pressed Enter on an empty line while the command was on its way.
347
+ term.showPrompt(0);
348
+ await Promise.resolve();
349
+ expect(done).toBe(false);
350
+
351
+ term.startCommand();
352
+ term.showPrompt(2);
353
+ expect((await p).exitCode).toBe(2);
354
+ });
355
+
356
+ it('waits out a command the user is running before counting its own', async () => {
357
+ const term = promptingTerminal();
358
+ term.showPrompt(0);
359
+ term.startCommand(); // typed in the pane by the user, still running
360
+ let done = false;
361
+ const p = runCommand(term, 'ls', '__MOXXY_DONE_hook_5__', 5_000).then((res) => {
362
+ done = true;
363
+ return res;
364
+ });
365
+
366
+ term.showPrompt(9); // the user's command ends
367
+ await Promise.resolve();
368
+ expect(done).toBe(false);
369
+
370
+ term.startCommand();
371
+ term.showPrompt(0);
372
+ expect((await p).exitCode).toBe(0);
373
+ });
374
+
375
+ it('ends a blank command at the next prompt, since the shell starts nothing for it', async () => {
376
+ const term = promptingTerminal();
377
+ term.showPrompt(0);
378
+ const p = runCommand(term, ' ', '__MOXXY_DONE_hook_6__', 5_000);
379
+
380
+ term.showPrompt(0);
381
+ expect((await p).timedOut).toBe(false);
382
+ });
383
+
384
+ it('waits for a shell that is still starting before typing', async () => {
385
+ const term = promptingTerminal();
386
+ const p = runCommand(term, 'ls', '__MOXXY_DONE_hook_1__', 5_000);
387
+
388
+ expect(term.writes).toEqual([]);
389
+ term.showPrompt(0);
390
+ await waitFor(() => term.writes.length > 0);
391
+ expect(term.writes).toEqual(['ls\n']);
392
+ term.startCommand();
393
+ term.feed('a.txt\n');
394
+ term.showPrompt(0);
395
+
396
+ expect((await p).output).toBe('a.txt');
397
+ });
398
+
399
+ it('types its own end marker when the shell never reports a prompt', async () => {
400
+ vi.useFakeTimers();
401
+ try {
402
+ const term = promptingTerminal();
403
+ const marker = '__MOXXY_DONE_hook_2__';
404
+ const p = runCommand(term, 'ls', marker, 60_000);
405
+
406
+ await vi.advanceTimersByTimeAsync(10_000);
407
+ expect(term.writes.join('')).toContain(`"${marker}" "$?"`);
408
+ term.feed(`a.txt\n${marker} 0\n`);
409
+
410
+ expect((await p).exitCode).toBe(0);
411
+ } finally {
412
+ vi.useRealTimers();
413
+ }
414
+ });
415
+
416
+ it('does not wait again for a shell that showed no prompt the first time', async () => {
417
+ vi.useFakeTimers();
418
+ try {
419
+ const term = promptingTerminal();
420
+ const first = runCommand(term, 'ls', '__MOXXY_DONE_hook_7__', 60_000);
421
+ await vi.advanceTimersByTimeAsync(10_000);
422
+ term.feed('__MOXXY_DONE_hook_7__ 0\n');
423
+ await first;
424
+
425
+ const second = runCommand(term, 'pwd', '__MOXXY_DONE_hook_8__', 60_000);
426
+ await vi.advanceTimersByTimeAsync(0);
427
+ expect(term.writes.join('')).toContain('"__MOXXY_DONE_hook_8__" "$?"');
428
+ term.feed('__MOXXY_DONE_hook_8__ 0\n');
429
+ await second;
430
+ } finally {
431
+ vi.useRealTimers();
432
+ }
433
+ });
434
+
435
+ it.skipIf(process.platform === 'win32')('runs a command that ends in a backslash from a file, so the shell is not left waiting', async () => {
436
+ const term = promptingTerminal();
437
+ term.showPrompt(0);
438
+ const p = runCommand(term, 'echo hi \\', '__MOXXY_DONE_hook_3__', 5_000);
439
+
440
+ expect(term.writes[0]).toMatch(/^\. '[^']+'\n$/);
441
+ term.startCommand();
442
+ term.showPrompt(0);
443
+ await p;
444
+ });
445
+ });
446
+
447
+ describe.skipIf(process.platform === 'win32')('runCommand with a long or multi-line command', () => {
448
+ it('types one short line that runs the command from a file, and removes the file when done', async () => {
449
+ const term = fakeTerminal();
450
+ const marker = '__MOXXY_DONE_file_0__';
451
+ const command = "python3 - <<'PY'\nprint('hi')\nPY";
452
+ const p = runCommand(term, command, marker, 5_000);
453
+
454
+ const typed = term.writes[0] ?? '';
455
+ const file = /^\. '([^']+)'\n$/.exec(typed)?.[1];
456
+ expect(file).toBeDefined();
457
+ expect(readFileSync(file ?? '', 'utf8')).toBe(`${command}\n`);
458
+
459
+ term.feed(typed);
460
+ term.feed('hi\n');
461
+ term.feed(`${marker} 0\n`);
462
+ const res = await p;
463
+ expect(res.output).toBe('hi');
464
+ expect(existsSync(file ?? '')).toBe(false);
465
+ });
466
+
467
+ it('runs a single line longer than the terminal input buffer from a file too', async () => {
468
+ const term = fakeTerminal();
469
+ const p = runCommand(term, `echo ${'x'.repeat(2_000)}`, '__MOXXY_DONE_file_1__', 5_000);
470
+
471
+ expect(term.writes[0]?.length).toBeLessThan(300);
472
+ term.feed('__MOXXY_DONE_file_1__ 0\n');
473
+ await p;
474
+ });
475
+
476
+ it('types a short one-line command as it is', async () => {
477
+ const term = fakeTerminal();
478
+ const p = runCommand(term, 'ls -la', '__MOXXY_DONE_file_2__', 5_000);
479
+
480
+ expect(term.writes[0]).toBe('ls -la\n');
481
+ term.feed('__MOXXY_DONE_file_2__ 0\n');
482
+ await p;
483
+ });
484
+ });
485
+
288
486
  describe('runCommand abort handling (turn-cancel must not hang the tool slot)', () => {
289
487
  // The turn's AbortSignal must end a running command promptly — without it the
290
488
  // call blocked the tool slot for up to the full timeout (600s) after the user