Refine async tool control flow

This commit is contained in:
Mario Zechner
2026-05-23 10:30:00 +02:00
parent e9146a5ff7
commit ba09f1c9e0
2 changed files with 97 additions and 115 deletions

View File

@@ -65,20 +65,17 @@ export interface BashOperations {
*/
export function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {
return {
exec: (command, cwd, { onData, signal, timeout, env }) => {
return new Promise((resolve, reject) => {
void (async () => {
exec: async (command, cwd, { onData, signal, timeout, env }) => {
const { shell, args } = getShellConfig(options?.shellPath);
try {
await fsAccess(cwd, constants.F_OK);
} catch {
reject(new Error(`Working directory does not exist: ${cwd}\nCannot execute bash commands.`));
return;
throw new Error(`Working directory does not exist: ${cwd}\nCannot execute bash commands.`);
}
if (signal?.aborted) {
reject(new Error("aborted"));
return;
throw new Error("aborted");
}
const child = spawn(shell, [...args, command], {
cwd,
detached: process.platform !== "win32",
@@ -89,6 +86,11 @@ export function createLocalBashOperations(options?: { shellPath?: string }): Bas
if (child.pid) trackDetachedChildPid(child.pid);
let timedOut = false;
let timeoutHandle: NodeJS.Timeout | undefined;
const onAbort = () => {
if (child.pid) killProcessTree(child.pid);
};
try {
// Set timeout if provided.
if (timeout !== undefined && timeout > 0) {
timeoutHandle = setTimeout(() => {
@@ -100,38 +102,25 @@ export function createLocalBashOperations(options?: { shellPath?: string }): Bas
child.stdout?.on("data", onData);
child.stderr?.on("data", onData);
// Handle abort signal by killing the entire process tree.
const onAbort = () => {
if (child.pid) killProcessTree(child.pid);
};
if (signal) {
if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort, { once: true });
}
// Handle shell spawn errors and wait for the process to terminate without hanging
// on inherited stdio handles held by detached descendants.
waitForChildProcess(child)
.then((code) => {
if (child.pid) untrackDetachedChildPid(child.pid);
if (timeoutHandle) clearTimeout(timeoutHandle);
if (signal) signal.removeEventListener("abort", onAbort);
const exitCode = await waitForChildProcess(child);
if (signal?.aborted) {
reject(new Error("aborted"));
return;
throw new Error("aborted");
}
if (timedOut) {
reject(new Error(`timeout:${timeout}`));
return;
throw new Error(`timeout:${timeout}`);
}
resolve({ exitCode: code });
})
.catch((err) => {
return { exitCode };
} finally {
if (child.pid) untrackDetachedChildPid(child.pid);
if (timeoutHandle) clearTimeout(timeoutHandle);
if (signal) signal.removeEventListener("abort", onAbort);
reject(err);
});
})().catch((err: unknown) => reject(err instanceof Error ? err : new Error(String(err))));
});
}
},
};
}

View File

@@ -314,18 +314,14 @@ export function createEditToolDefinition(
const absolutePath = resolveToCwd(path, cwd);
return withFileMutationQueue(absolutePath, async () => {
let aborted = signal?.aborted ?? false;
const onAbort = () => {
aborted = true;
};
// Do not reject from an abort event listener here: that would release the
// mutation queue while an in-flight filesystem operation may still finish.
// Checking signal.aborted after each await observes the same aborts while
// keeping the queue locked until the current operation has settled.
const throwIfAborted = (): void => {
if (aborted || signal?.aborted) {
throw new Error("Operation aborted");
}
if (signal?.aborted) throw new Error("Operation aborted");
};
signal?.addEventListener("abort", onAbort, { once: true });
try {
throwIfAborted();
// Check if file exists.
@@ -341,10 +337,10 @@ export function createEditToolDefinition(
// Read the file.
const buffer = await ops.readFile(absolutePath);
const rawContent = buffer.toString("utf-8");
throwIfAborted();
// Strip BOM before matching. The model will not include an invisible BOM in oldText.
const rawContent = buffer.toString("utf-8");
const { bom, text: content } = stripBom(rawContent);
const originalEnding = detectLineEnding(content);
const normalizedContent = normalizeToLF(content);
@@ -366,9 +362,6 @@ export function createEditToolDefinition(
],
details: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine },
};
} finally {
signal?.removeEventListener("abort", onAbort);
}
});
},
renderCall(args, theme, context) {