xonecas.io
64875
Mc

mini-coder / commit 19c89cd

fix: handle path selection and shell tool exits

xonecas2026-04-13 19c89cd9a38ea63aff41bdac95581556b14cdcfa parent 1d30d9a

6 files changed

src/tools.test.ts+86−0
@@ -1,5 +1,6 @@
11 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import {
3+ existsSync,
34 mkdirSync,
45 mkdtempSync,
56 readFileSync,
@@ -91,6 +92,29 @@ function hasUnpairedSurrogate(input: string): boolean {
9192 return false;
9293 }
9394
95+async function waitFor(
96+ predicate: () => boolean,
97+ timeoutMs = 1_000,
98+): Promise<void> {
99+ const deadline = Date.now() + timeoutMs;
100+ while (Date.now() < deadline) {
101+ if (predicate()) {
102+ return;
103+ }
104+ await new Promise<void>((resolve) => setTimeout(resolve, 10));
105+ }
106+ throw new Error("Timed out waiting for condition");
107+}
108+
109+function isProcessAlive(pid: number): boolean {
110+ try {
111+ process.kill(pid, 0);
112+ return true;
113+ } catch {
114+ return false;
115+ }
116+}
117+
94118 // ---------------------------------------------------------------------------
95119 // edit
96120 // ---------------------------------------------------------------------------
@@ -430,6 +454,68 @@ describe("shell", () => {
430454 expect(result.isError).toBe(true);
431455 });
432456
457+ test("returns after the shell exits even when a background child keeps stdout and stderr open", async () => {
458+ const pidFile = join(tmp, "child.pid");
459+ const command = `sleep 30 & pid=$!; echo "$pid" > '${pidFile}'; echo ready`;
460+ let childPid: number | null = null;
461+
462+ try {
463+ const result = await Promise.race([
464+ executeShell({ command }, tmp),
465+ new Promise<never>((_, reject) => {
466+ setTimeout(() => {
467+ reject(new Error("Shell command did not return promptly"));
468+ }, 1_000);
469+ }),
470+ ]);
471+
472+ childPid = Number(readFileSync(pidFile, "utf-8").trim());
473+
474+ expect(result.isError).toBe(false);
475+ expect(resultText(result)).toContain("Exit code: 0");
476+ expect(resultText(result)).toContain("ready");
477+ expect(isProcessAlive(childPid)).toBe(true);
478+ } finally {
479+ if (childPid !== null && isProcessAlive(childPid)) {
480+ process.kill(childPid, "SIGKILL");
481+ }
482+ }
483+ });
484+
485+ test("abort signal kills spawned child processes that keep the shell pipes open", async () => {
486+ const controller = new AbortController();
487+ const pidFile = join(tmp, "child.pid");
488+ const command = `sleep 30 & echo $! > '${pidFile}' && wait`;
489+ const resultPromise = executeShell({ command }, tmp, {
490+ signal: controller.signal,
491+ });
492+
493+ let childPid: number | null = null;
494+ try {
495+ await waitFor(() => existsSync(pidFile));
496+ childPid = Number(readFileSync(pidFile, "utf-8").trim());
497+ const startedChildPid = childPid;
498+
499+ controller.abort();
500+
501+ const result = await Promise.race([
502+ resultPromise,
503+ new Promise<never>((_, reject) => {
504+ setTimeout(() => {
505+ reject(new Error("Shell command did not abort promptly"));
506+ }, 1_000);
507+ }),
508+ ]);
509+
510+ expect(result.isError).toBe(true);
511+ await waitFor(() => !isProcessAlive(startedChildPid), 1_000);
512+ } finally {
513+ if (childPid !== null && isProcessAlive(childPid)) {
514+ process.kill(childPid, "SIGKILL");
515+ }
516+ }
517+ });
518+
433519 test("combines stdout and stderr in output", async () => {
434520 const result = await executeShell(
435521 { command: "echo out && echo err >&2" },
src/tools.ts+127−80
@@ -9,7 +9,15 @@
99 * @module
1010 */
1111
12-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12+import {
13+ existsSync,
14+ mkdirSync,
15+ mkdtempSync,
16+ readFileSync,
17+ rmSync,
18+ writeFileSync,
19+} from "node:fs";
20+import { tmpdir } from "node:os";
1321 import { dirname, extname, isAbsolute, join } from "node:path";
1422 import type { ImageContent, TextContent, Tool } from "@mariozechner/pi-ai";
1523 import { Type } from "@mariozechner/pi-ai";
@@ -490,6 +498,8 @@ interface ShellOpts {
490498 onUpdate?: ToolUpdateCallback;
491499 }
492500
501+type ShellProcess = ReturnType<typeof Bun.spawn>;
502+
493503 const DEFAULT_MAX_LINES = 1000;
494504 const DEFAULT_MAX_BYTES = 50_000;
495505 const SHELL_UPDATE_INTERVAL_MS = 75;
@@ -837,26 +847,94 @@ function normalizeShellCommand(command: string): string {
837847 }
838848 }
839849
840-/** Read a spawned shell stream into a string, reporting progressive updates. */
841-async function consumeShellStream(
842- stream: ReadableStream<Uint8Array>,
843- onChunk: (chunk: string) => void,
844-): Promise<string> {
845- const reader = stream.getReader();
846- const decoder = new TextDecoder();
847- let output = "";
850+interface ShellCaptureFiles {
851+ stdoutPath: string;
852+ stderrPath: string;
853+ cleanup: () => void;
854+}
848855
849- while (true) {
850- const { done, value } = await reader.read();
851- if (done) {
852- output += decoder.decode();
853- return output;
856+function createShellCaptureFiles(): ShellCaptureFiles {
857+ const dir = mkdtempSync(join(tmpdir(), "mini-coder-shell-"));
858+ return {
859+ stdoutPath: join(dir, "stdout.log"),
860+ stderrPath: join(dir, "stderr.log"),
861+ cleanup: () => {
862+ try {
863+ rmSync(dir, { recursive: true, force: true });
864+ } catch {
865+ // Best-effort cleanup. Background processes may still hold the files open.
866+ }
867+ },
868+ };
869+}
870+
871+function readShellCapture(path: string): string {
872+ try {
873+ return readFileSync(path, "utf-8");
874+ } catch {
875+ return "";
876+ }
877+}
878+
879+function readShellCaptureOutput(
880+ capture: Pick<ShellCaptureFiles, "stdoutPath" | "stderrPath">,
881+): { stdout: string; stderr: string } {
882+ return {
883+ stdout: readShellCapture(capture.stdoutPath),
884+ stderr: readShellCapture(capture.stderrPath),
885+ };
886+}
887+
888+function buildShellSpawnOptions(
889+ cwd: string,
890+ capture: Pick<ShellCaptureFiles, "stdoutPath" | "stderrPath">,
891+): Parameters<typeof Bun.spawn>[1] {
892+ return {
893+ cwd,
894+ stdout: Bun.file(capture.stdoutPath),
895+ stderr: Bun.file(capture.stderrPath),
896+ ...(process.platform === "win32" ? {} : { detached: true }),
897+ };
898+}
899+
900+function abortShellProcess(proc: ShellProcess): void {
901+ if (proc.killed || proc.exitCode !== null) {
902+ return;
903+ }
904+
905+ if (process.platform !== "win32") {
906+ try {
907+ process.kill(-proc.pid, "SIGTERM");
908+ return;
909+ } catch {
910+ // Fall through to a direct kill when the process group is unavailable.
854911 }
912+ }
913+
914+ proc.kill("SIGTERM");
915+}
855916
856- const chunk = decoder.decode(value, { stream: true });
857- output += chunk;
858- onChunk(chunk);
917+function registerShellAbort(
918+ signal: AbortSignal | undefined,
919+ proc: ShellProcess,
920+): (() => void) | null {
921+ if (!signal) {
922+ return null;
859923 }
924+
925+ const abortListener = (): void => {
926+ abortShellProcess(proc);
927+ };
928+
929+ if (signal.aborted) {
930+ abortShellProcess(proc);
931+ return null;
932+ }
933+
934+ signal.addEventListener("abort", abortListener, { once: true });
935+ return () => {
936+ signal.removeEventListener("abort", abortListener);
937+ };
860938 }
861939
862940 /**
@@ -879,93 +957,59 @@ export async function executeShell(
879957 const shell = process.env.SHELL || "/bin/sh";
880958 const maxLines = opts?.maxLines ?? DEFAULT_MAX_LINES;
881959 const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
882- let updateTimer: ReturnType<typeof setTimeout> | null = null;
960+ const capture = createShellCaptureFiles();
961+ let updateTimer: ReturnType<typeof setInterval> | null = null;
962+ let cleanupAbort: (() => void) | null = null;
963+ let lastReportedOutput = "";
883964
884965 try {
885- const spawnOpts: Parameters<typeof Bun.spawn>[1] = {
886- cwd,
887- stdout: "pipe",
888- stderr: "pipe",
889- };
890- if (opts?.signal) spawnOpts.signal = opts.signal;
891- const command = normalizeShellCommand(args.command);
892- const proc = Bun.spawn([shell, "-c", command], spawnOpts);
893-
894- let stdoutBuf = "";
895- let stderrBuf = "";
896- let lastReportedOutput = "";
897- let lastReportAt = 0;
898-
899- const clearPendingUpdate = (): void => {
900- if (updateTimer) {
901- clearTimeout(updateTimer);
902- updateTimer = null;
903- }
904- };
905-
906- const buildProgressOutput = (): string => {
966+ const buildOutput = (trimEnd: boolean): string => {
967+ const { stdout, stderr } = readShellCaptureOutput(capture);
907968 return truncateOutput(
908- formatShellOutput(stdoutBuf, stderrBuf),
969+ formatShellOutput(
970+ trimEnd ? stdout.trimEnd() : stdout,
971+ trimEnd ? stderr.trimEnd() : stderr,
972+ ),
909973 maxLines,
910974 maxBytes,
911975 );
912976 };
913977
914978 const emitUpdate = (): void => {
915- clearPendingUpdate();
916979 if (!opts?.onUpdate) {
917980 return;
918981 }
919982
920- const output = buildProgressOutput();
983+ const output = buildOutput(false);
921984 if (!output || output === lastReportedOutput) {
922985 return;
923986 }
924987
925988 lastReportedOutput = output;
926- lastReportAt = Date.now();
927989 opts.onUpdate(textResult(output, false));
928990 };
929991
930- const scheduleUpdate = (): void => {
931- if (!opts?.onUpdate) {
932- return;
933- }
992+ const command = normalizeShellCommand(args.command);
993+ const proc = Bun.spawn(
994+ [shell, "-c", command],
995+ buildShellSpawnOptions(cwd, capture),
996+ );
997+ cleanupAbort = registerShellAbort(opts?.signal, proc);
934998
935- const elapsed = Date.now() - lastReportAt;
936- if (elapsed >= SHELL_UPDATE_INTERVAL_MS) {
937- emitUpdate();
938- return;
939- }
940- if (updateTimer) {
941- return;
942- }
999+ if (opts?.onUpdate) {
1000+ updateTimer = setInterval(emitUpdate, SHELL_UPDATE_INTERVAL_MS);
1001+ }
9431002
944- updateTimer = setTimeout(() => {
945- emitUpdate();
946- }, SHELL_UPDATE_INTERVAL_MS - elapsed);
947- };
1003+ const exitCode = await proc.exited;
9481004
949- const [stdout, stderr, exitCode] = await Promise.all([
950- consumeShellStream(proc.stdout as ReadableStream<Uint8Array>, (chunk) => {
951- stdoutBuf += chunk;
952- scheduleUpdate();
953- }),
954- consumeShellStream(proc.stderr as ReadableStream<Uint8Array>, (chunk) => {
955- stderrBuf += chunk;
956- scheduleUpdate();
957- }),
958- proc.exited,
959- ]);
960-
961- clearPendingUpdate();
962- const output = truncateOutput(
963- formatShellOutput(stdout.trimEnd(), stderr.trimEnd()),
964- maxLines,
965- maxBytes,
966- );
1005+ if (updateTimer) {
1006+ clearInterval(updateTimer);
1007+ updateTimer = null;
1008+ }
1009+ cleanupAbort?.();
1010+
1011+ const output = buildOutput(true);
9671012 if (opts?.onUpdate && output && output !== lastReportedOutput) {
968- lastReportedOutput = output;
9691013 opts.onUpdate(textResult(output, false));
9701014 }
9711015
@@ -973,12 +1017,15 @@ export async function executeShell(
9731017 const body = output || "(no output)";
9741018 return textResult(`Exit code: ${exitCode}\n${body}`, isError);
9751019 } catch (err) {
1020+ cleanupAbort?.();
9761021 if (updateTimer) {
977- clearTimeout(updateTimer);
1022+ clearInterval(updateTimer);
9781023 updateTimer = null;
9791024 }
9801025 const message = err instanceof Error ? err.message : String(err);
9811026 return textResult(`Shell error: ${message}`, true);
1027+ } finally {
1028+ capture.cleanup();
9821029 }
9831030 }
9841031
src/ui.test.ts+165−1
@@ -1,5 +1,12 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+import {
3+ existsSync,
4+ mkdirSync,
5+ mkdtempSync,
6+ readFileSync,
7+ rmSync,
8+ writeFileSync,
9+} from "node:fs";
310 import { tmpdir } from "node:os";
411 import { join } from "node:path";
512 import { cel, MockTerminal, measureContentHeight, VStack } from "@cel-tui/core";
@@ -280,6 +287,15 @@ async function stopRunningTurn(
280287 }
281288 }
282289
290+function isProcessAlive(pid: number): boolean {
291+ try {
292+ process.kill(pid, 0);
293+ return true;
294+ } catch {
295+ return false;
296+ }
297+}
298+
283299 describe("ui rendering", () => {
284300 test("reasoning defaults on and verbose defaults off", () => {
285301 expect(DEFAULT_SHOW_REASONING).toBe(true);
@@ -1812,6 +1828,72 @@ describe("ui rendering", () => {
18121828 }
18131829 });
18141830
1831+ test("Escape aborts a running shell tool even when the shell command spawned a child process", async () => {
1832+ const state = createTestState();
1833+ const faux = registerFauxProvider();
1834+ const cwd = createTempDir();
1835+ const terminal = new MockTerminal(80, 20);
1836+ const pidFile = join(cwd, "child.pid");
1837+ let childPid: number | null = null;
1838+ state.model = faux.getModel();
1839+ state.cwd = cwd;
1840+ state.canonicalCwd = cwd;
1841+ faux.setResponses([
1842+ fauxAssistantMessage(
1843+ [
1844+ fauxToolCall("shell", {
1845+ command: `sleep 30 & echo $! > '${pidFile}' && wait`,
1846+ }),
1847+ ],
1848+ {
1849+ stopReason: "toolUse",
1850+ },
1851+ ),
1852+ ]);
1853+
1854+ try {
1855+ const controller = createInputController(state);
1856+ startUiViewport(state, terminal, controller);
1857+ await waitForCelRender();
1858+
1859+ handleInput("interrupt the spawned tool", state);
1860+
1861+ await waitFor(
1862+ () =>
1863+ state.running &&
1864+ state.activeTurnPromise !== null &&
1865+ existsSync(pidFile),
1866+ );
1867+ childPid = Number(readFileSync(pidFile, "utf-8").trim());
1868+
1869+ terminal.sendInput("\x1b");
1870+ await waitFor(() => !state.running, 1_000);
1871+
1872+ const activeTurnPromise = state.activeTurnPromise;
1873+ if (activeTurnPromise) {
1874+ await activeTurnPromise;
1875+ }
1876+
1877+ expect(state.messages.map((message) => message.role)).toEqual([
1878+ "user",
1879+ "assistant",
1880+ "toolResult",
1881+ ]);
1882+ await waitFor(
1883+ () => childPid !== null && !isProcessAlive(childPid),
1884+ 1_000,
1885+ );
1886+ } finally {
1887+ if (childPid !== null && isProcessAlive(childPid)) {
1888+ process.kill(childPid, "SIGKILL");
1889+ }
1890+ await stopRunningTurn(state);
1891+ cel.stop();
1892+ faux.unregister();
1893+ state.db.close();
1894+ }
1895+ });
1896+
18151897 test("Tab autocompletes the last file path in normal input mode", () => {
18161898 const state = createTestState();
18171899 const cwd = createTempDir();
@@ -1834,6 +1916,88 @@ describe("ui rendering", () => {
18341916 }
18351917 });
18361918
1919+ test("Tab opens a path picker when multiple file path matches are available", () => {
1920+ const state = createTestState();
1921+ const cwd = createTempDir();
1922+ mkdirSync(join(cwd, "src"), { recursive: true });
1923+ writeFileSync(join(cwd, "src", "ui.ts"), "", "utf-8");
1924+ writeFileSync(join(cwd, "src", "utils.ts"), "", "utf-8");
1925+ state.cwd = cwd;
1926+ state.canonicalCwd = cwd;
1927+
1928+ try {
1929+ const controller = createInputController(state);
1930+ controller.onChange("inspect src/u");
1931+
1932+ expect(controller.onKeyPress("tab")).toBe(false);
1933+
1934+ const overlay = renderActiveOverlay(state);
1935+ if (!overlay || overlay.type !== "vstack") {
1936+ throw new Error("Expected an active path picker overlay");
1937+ }
1938+ const overlayText = collectText(overlay);
1939+ expect(overlayText.some((line) => line.includes("src/ui.ts"))).toBe(true);
1940+ expect(overlayText.some((line) => line.includes("src/utils.ts"))).toBe(
1941+ true,
1942+ );
1943+ expect(
1944+ expectTextInput(renderInputArea(state.theme, controller)).props.value,
1945+ ).toBe("inspect src/u");
1946+ expect(
1947+ expectTextInput(renderInputArea(state.theme, controller)).props.focused,
1948+ ).toBe(false);
1949+
1950+ const modal = expectVStack(overlay.children[0]!);
1951+ const selectNode = expectVStack(modal.children[1]!);
1952+ selectNode.props.onKeyPress?.("down");
1953+ selectNode.props.onKeyPress?.("enter");
1954+
1955+ const input = expectTextInput(renderInputArea(state.theme, controller));
1956+ expect(input.props.value).toBe("inspect src/utils.ts");
1957+ expect(input.props.focused).toBe(true);
1958+ expect(renderActiveOverlay(state)).toBeNull();
1959+ } finally {
1960+ state.db.close();
1961+ }
1962+ });
1963+
1964+ test("Escape cancels the path picker and leaves the draft unchanged", async () => {
1965+ const state = createTestState();
1966+ const cwd = createTempDir();
1967+ const terminal = new MockTerminal(80, 20);
1968+ mkdirSync(join(cwd, "src"), { recursive: true });
1969+ writeFileSync(join(cwd, "src", "ui.ts"), "", "utf-8");
1970+ writeFileSync(join(cwd, "src", "utils.ts"), "", "utf-8");
1971+ state.cwd = cwd;
1972+ state.canonicalCwd = cwd;
1973+
1974+ try {
1975+ const controller = createInputController(state);
1976+ startUiViewport(state, terminal, controller);
1977+ await waitForCelRender();
1978+
1979+ controller.onChange("inspect src/u");
1980+ controller.onKeyPress("tab");
1981+ await waitForCelRender();
1982+
1983+ expect(renderActiveOverlay(state)).not.toBeNull();
1984+ expect(
1985+ expectTextInput(renderInputArea(state.theme, controller)).props.focused,
1986+ ).toBe(false);
1987+
1988+ terminal.sendInput("\x1b");
1989+ await waitForCelRender();
1990+
1991+ expect(renderActiveOverlay(state)).toBeNull();
1992+ const input = expectTextInput(renderInputArea(state.theme, controller));
1993+ expect(input.props.value).toBe("inspect src/u");
1994+ expect(input.props.focused).toBe(true);
1995+ } finally {
1996+ cel.stop();
1997+ state.db.close();
1998+ }
1999+ });
2000+
18372001 test("Ctrl+R opens input history with newest prompts first", () => {
18382002 const state = createTestState();
18392003
src/ui.ts+50−10
@@ -10,6 +10,7 @@
1010
1111 import { spawn } from "node:child_process";
1212 import { platform } from "node:os";
13+import { Select } from "@cel-tui/components";
1314 import {
1415 cel,
1516 HStack,
@@ -37,9 +38,14 @@ import {
3738 import type { InputController } from "./ui/input.ts";
3839 import {
3940 autocompleteInputPath,
41+ findInputPathMatches,
4042 renderInputArea as renderInputAreaNode,
4143 } from "./ui/input.ts";
42-import { type ActiveOverlay, renderOverlay } from "./ui/overlay.ts";
44+import {
45+ type ActiveOverlay,
46+ OVERLAY_MAX_VISIBLE,
47+ renderOverlay,
48+} from "./ui/overlay.ts";
4349 import { renderStatusBar } from "./ui/status.ts";
4450
4551 export type { InputController } from "./ui/input.ts";
@@ -286,6 +292,48 @@ function dismissOverlay(): void {
286292 cel.render();
287293 }
288294
295+function openPathAutocompleteOverlay(state: AppState): void {
296+ const matches = findInputPathMatches(inputValue, state.cwd);
297+ if (matches.length <= 1) {
298+ return;
299+ }
300+
301+ const select = Select({
302+ items: matches.map((match) => ({
303+ label: match.label,
304+ value: match.value,
305+ filterText: match.label,
306+ })),
307+ maxVisible: OVERLAY_MAX_VISIBLE,
308+ placeholder: "type to filter paths...",
309+ focused: true,
310+ highlightColor: state.theme.accentText,
311+ onSelect: (value) => {
312+ inputValue = value;
313+ dismissOverlay();
314+ },
315+ onBlur: dismissOverlay,
316+ });
317+
318+ openOverlay({ select, title: "Path matches" });
319+}
320+
321+function handleTabKeyPress(state: AppState): void {
322+ if (inputValue.startsWith("/")) {
323+ commandController.showCommandAutocomplete(state);
324+ return;
325+ }
326+
327+ const completedInput = autocompleteInputPath(inputValue, state.cwd);
328+ if (completedInput) {
329+ inputValue = completedInput;
330+ cel.render();
331+ return;
332+ }
333+
334+ openPathAutocompleteOverlay(state);
335+}
336+
289337 /**
290338 * Render the active overlay when one is open.
291339 *
@@ -344,15 +392,7 @@ export function createInputController(state: AppState): InputController {
344392 return false;
345393 }
346394 if (key === "tab") {
347- if (inputValue.startsWith("/")) {
348- commandController.showCommandAutocomplete(state);
349- } else {
350- const completedInput = autocompleteInputPath(inputValue, state.cwd);
351- if (completedInput) {
352- inputValue = completedInput;
353- cel.render();
354- }
355- }
395+ handleTabKeyPress(state);
356396 return false;
357397 }
358398 },
src/ui/input.test.ts+29−1
@@ -5,6 +5,7 @@ import { join } from "node:path";
55 import { DEFAULT_THEME } from "../theme.ts";
66 import {
77 autocompleteInputPath,
8+ findInputPathMatches,
89 type InputController,
910 renderInputArea,
1011 } from "./input.ts";
@@ -60,7 +61,7 @@ describe("ui/input", () => {
6061 expect(placeholder.props.italic).toBe(true);
6162 });
6263
63- test("autocompleteInputPath completes the last file path token", () => {
64+ test("autocompleteInputPath completes the last file path token when exactly one match is available", () => {
6465 const cwd = createTempDir();
6566 mkdirSync(join(cwd, "src"), { recursive: true });
6667 writeFileSync(join(cwd, "src", "ui.ts"), "", "utf-8");
@@ -70,6 +71,33 @@ describe("ui/input", () => {
7071 );
7172 });
7273
74+ test("autocompleteInputPath returns null when multiple matches are available", () => {
75+ const cwd = createTempDir();
76+ mkdirSync(join(cwd, "src"), { recursive: true });
77+ writeFileSync(join(cwd, "src", "ui.ts"), "", "utf-8");
78+ writeFileSync(join(cwd, "src", "utils.ts"), "", "utf-8");
79+
80+ expect(autocompleteInputPath("inspect src/u", cwd)).toBeNull();
81+ });
82+
83+ test("findInputPathMatches returns sorted selectable matches for the last file path token", () => {
84+ const cwd = createTempDir();
85+ mkdirSync(join(cwd, "src"), { recursive: true });
86+ writeFileSync(join(cwd, "src", "alpine.ts"), "", "utf-8");
87+ writeFileSync(join(cwd, "src", "alpha.ts"), "", "utf-8");
88+
89+ expect(findInputPathMatches("inspect src/al", cwd)).toEqual([
90+ {
91+ label: "src/alpha.ts",
92+ value: "inspect src/alpha.ts",
93+ },
94+ {
95+ label: "src/alpine.ts",
96+ value: "inspect src/alpine.ts",
97+ },
98+ ]);
99+ });
100+
73101 test("autocompleteInputPath returns null when no completion is available", () => {
74102 const cwd = createTempDir();
75103
src/ui/input.ts+45−51
@@ -25,39 +25,18 @@ export interface InputController {
2525 onKeyPress: (key: string) => boolean | undefined;
2626 }
2727
28-/** Find the longest common prefix across a list of strings. */
29-function getLongestCommonPrefix(values: readonly string[]): string {
30- if (values.length === 0) {
31- return "";
32- }
33-
34- let prefix = values[0]!;
35- for (let i = 1; i < values.length && prefix.length > 0; i++) {
36- const value = values[i]!;
37- let j = 0;
38- while (j < prefix.length && j < value.length && prefix[j] === value[j]) {
39- j++;
40- }
41- prefix = prefix.slice(0, j);
42- }
43-
44- return prefix;
28+/** A selectable path-autocomplete match for the current input draft. */
29+export interface InputPathMatch {
30+ /** Path label shown in the overlay. */
31+ label: string;
32+ /** Full draft value to apply when this match is selected. */
33+ value: string;
4534 }
4635
47-/**
48- * Attempt to autocomplete the final path token in the current draft.
49- *
50- * @param value - Current input draft.
51- * @param cwd - Working directory used to resolve relative paths.
52- * @returns The completed input value, or `null` when no completion is available.
53- */
54-export function autocompleteInputPath(
55- value: string,
56- cwd: string,
57-): string | null {
36+function listInputPathMatches(value: string, cwd: string): InputPathMatch[] {
5837 const tokenMatch = /(^|\s)(\S+)$/.exec(value);
5938 if (!tokenMatch?.[2]) {
60- return null;
39+ return [];
6140 }
6241
6342 const token = tokenMatch[2];
@@ -80,35 +59,50 @@ export function autocompleteInputPath(
8059 }
8160 })();
8261 if (!entries) {
83- return null;
62+ return [];
8463 }
8564
8665 const showHidden = partial.startsWith(".");
87- const matches = entries
66+ return entries
8867 .filter((entry) => (showHidden ? true : !entry.name.startsWith(".")))
8968 .filter((entry) => entry.name.startsWith(partial))
90- .sort((a, b) => a.name.localeCompare(b.name));
91-
92- if (matches.length === 0) {
93- return null;
94- }
95-
96- let completedName: string | null = null;
97- if (matches.length === 1) {
98- const match = matches[0]!;
99- completedName = `${match.name}${match.isDirectory() ? "/" : ""}`;
100- } else {
101- const prefix = getLongestCommonPrefix(matches.map((entry) => entry.name));
102- if (prefix.length > partial.length) {
103- completedName = prefix;
104- }
105- }
69+ .sort((a, b) => a.name.localeCompare(b.name))
70+ .map((entry) => {
71+ const completedPath = `${dirToken}${entry.name}${entry.isDirectory() ? "/" : ""}`;
72+ return {
73+ label: completedPath,
74+ value: `${value.slice(0, tokenStart)}${completedPath}`,
75+ };
76+ });
77+}
10678
107- if (!completedName) {
108- return null;
109- }
79+/**
80+ * Find selectable path matches for the final path token in the current draft.
81+ *
82+ * @param value - Current input draft.
83+ * @param cwd - Working directory used to resolve relative paths.
84+ * @returns Matching path completions with their applied draft values.
85+ */
86+export function findInputPathMatches(
87+ value: string,
88+ cwd: string,
89+): InputPathMatch[] {
90+ return listInputPathMatches(value, cwd);
91+}
11092
111- return `${value.slice(0, tokenStart)}${dirToken}${completedName}`;
93+/**
94+ * Attempt to autocomplete the final path token in the current draft.
95+ *
96+ * @param value - Current input draft.
97+ * @param cwd - Working directory used to resolve relative paths.
98+ * @returns The completed input value, or `null` when direct completion is unavailable.
99+ */
100+export function autocompleteInputPath(
101+ value: string,
102+ cwd: string,
103+): string | null {
104+ const matches = listInputPathMatches(value, cwd);
105+ return matches.length === 1 ? matches[0]!.value : null;
112106 }
113107
114108 /**