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 { export function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {
return { return {
exec: (command, cwd, { onData, signal, timeout, env }) => { exec: async (command, cwd, { onData, signal, timeout, env }) => {
return new Promise((resolve, reject) => {
void (async () => {
const { shell, args } = getShellConfig(options?.shellPath); const { shell, args } = getShellConfig(options?.shellPath);
try { try {
await fsAccess(cwd, constants.F_OK); await fsAccess(cwd, constants.F_OK);
} catch { } catch {
reject(new Error(`Working directory does not exist: ${cwd}\nCannot execute bash commands.`)); throw new Error(`Working directory does not exist: ${cwd}\nCannot execute bash commands.`);
return;
} }
if (signal?.aborted) { if (signal?.aborted) {
reject(new Error("aborted")); throw new Error("aborted");
return;
} }
const child = spawn(shell, [...args, command], { const child = spawn(shell, [...args, command], {
cwd, cwd,
detached: process.platform !== "win32", detached: process.platform !== "win32",
@@ -89,6 +86,11 @@ export function createLocalBashOperations(options?: { shellPath?: string }): Bas
if (child.pid) trackDetachedChildPid(child.pid); if (child.pid) trackDetachedChildPid(child.pid);
let timedOut = false; let timedOut = false;
let timeoutHandle: NodeJS.Timeout | undefined; let timeoutHandle: NodeJS.Timeout | undefined;
const onAbort = () => {
if (child.pid) killProcessTree(child.pid);
};
try {
// Set timeout if provided. // Set timeout if provided.
if (timeout !== undefined && timeout > 0) { if (timeout !== undefined && timeout > 0) {
timeoutHandle = setTimeout(() => { timeoutHandle = setTimeout(() => {
@@ -100,38 +102,25 @@ export function createLocalBashOperations(options?: { shellPath?: string }): Bas
child.stdout?.on("data", onData); child.stdout?.on("data", onData);
child.stderr?.on("data", onData); child.stderr?.on("data", onData);
// Handle abort signal by killing the entire process tree. // Handle abort signal by killing the entire process tree.
const onAbort = () => {
if (child.pid) killProcessTree(child.pid);
};
if (signal) { if (signal) {
if (signal.aborted) onAbort(); if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort, { once: true }); else signal.addEventListener("abort", onAbort, { once: true });
} }
// Handle shell spawn errors and wait for the process to terminate without hanging // Handle shell spawn errors and wait for the process to terminate without hanging
// on inherited stdio handles held by detached descendants. // on inherited stdio handles held by detached descendants.
waitForChildProcess(child) const exitCode = await waitForChildProcess(child);
.then((code) => {
if (child.pid) untrackDetachedChildPid(child.pid);
if (timeoutHandle) clearTimeout(timeoutHandle);
if (signal) signal.removeEventListener("abort", onAbort);
if (signal?.aborted) { if (signal?.aborted) {
reject(new Error("aborted")); throw new Error("aborted");
return;
} }
if (timedOut) { if (timedOut) {
reject(new Error(`timeout:${timeout}`)); throw new Error(`timeout:${timeout}`);
return;
} }
resolve({ exitCode: code }); return { exitCode };
}) } finally {
.catch((err) => {
if (child.pid) untrackDetachedChildPid(child.pid); if (child.pid) untrackDetachedChildPid(child.pid);
if (timeoutHandle) clearTimeout(timeoutHandle); if (timeoutHandle) clearTimeout(timeoutHandle);
if (signal) signal.removeEventListener("abort", onAbort); 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); const absolutePath = resolveToCwd(path, cwd);
return withFileMutationQueue(absolutePath, async () => { return withFileMutationQueue(absolutePath, async () => {
let aborted = signal?.aborted ?? false; // Do not reject from an abort event listener here: that would release the
const onAbort = () => { // mutation queue while an in-flight filesystem operation may still finish.
aborted = true; // Checking signal.aborted after each await observes the same aborts while
}; // keeping the queue locked until the current operation has settled.
const throwIfAborted = (): void => { const throwIfAborted = (): void => {
if (aborted || signal?.aborted) { if (signal?.aborted) throw new Error("Operation aborted");
throw new Error("Operation aborted");
}
}; };
signal?.addEventListener("abort", onAbort, { once: true });
try {
throwIfAborted(); throwIfAborted();
// Check if file exists. // Check if file exists.
@@ -341,10 +337,10 @@ export function createEditToolDefinition(
// Read the file. // Read the file.
const buffer = await ops.readFile(absolutePath); const buffer = await ops.readFile(absolutePath);
const rawContent = buffer.toString("utf-8");
throwIfAborted(); throwIfAborted();
// Strip BOM before matching. The model will not include an invisible BOM in oldText. // 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 { bom, text: content } = stripBom(rawContent);
const originalEnding = detectLineEnding(content); const originalEnding = detectLineEnding(content);
const normalizedContent = normalizeToLF(content); const normalizedContent = normalizeToLF(content);
@@ -366,9 +362,6 @@ export function createEditToolDefinition(
], ],
details: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine }, details: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine },
}; };
} finally {
signal?.removeEventListener("abort", onAbort);
}
}); });
}, },
renderCall(args, theme, context) { renderCall(args, theme, context) {