Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(git-clone): wait for the killed clone to exit before cleaning up

vastsa73da9a375c3c
diff --git a/apps/desktop/electron/main/git-clone.ts b/apps/desktop/electron/main/git-clone.ts
index 8beda4206..f777ef561 100644
--- a/apps/desktop/electron/main/git-clone.ts
+++ b/apps/desktop/electron/main/git-clone.ts
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
-import { existsSync, lstatSync, rmSync, statSync, unlinkSync } from "node:fs";
+import { existsSync, lstatSync, statSync, unlinkSync } from "node:fs";
+import { rm } from "node:fs/promises";
import { isAbsolute, relative, resolve } from "node:path";
import {
isGitCloneRepoName,
@@ -24,32 +25,53 @@ export type GitCloneRunResult = {
errorCode?: string;
};
+/**
+ * How long a timed-out clone may take to exit after SIGTERM before it is
+ * force-killed. `close` fires only once git and every helper that inherited
+ * its stdio (`git-remote-https`, `index-pack`) have exited, so the
+ * destination is no longer being written when the result resolves.
+ */
+export const GIT_CLONE_KILL_GRACE_MS = 15 * 1000;
+
export function runGitClone(
cwd: string,
args: string[],
timeoutMs = GIT_CLONE_TIMEOUT_MS,
+ options: { command?: string; killGraceMs?: number } = {},
): Promise<GitCloneRunResult> {
+ const killGraceMs = options.killGraceMs ?? GIT_CLONE_KILL_GRACE_MS;
return new Promise((resolveResult) => {
- const child = spawn("git", args, {
+ const child = spawn(options.command ?? "git", args, {
cwd,
env: process.env,
windowsHide: true,
});
let stderr = "";
let settled = false;
+ let timedOut = false;
+ let graceTimer: ReturnType<typeof setTimeout> | undefined;
const finish = (result: GitCloneRunResult) => {
if (settled) return;
settled = true;
clearTimeout(timer);
+ clearTimeout(graceTimer);
resolveResult(result);
};
+ const timedOutResult = (): GitCloneRunResult => ({
+ code: 1,
+ stderr: "git clone timed out",
+ errorCode: "TIMEOUT",
+ });
const timer = setTimeout(() => {
+ timedOut = true;
child.kill("SIGTERM");
- finish({
- code: 1,
- stderr: "git clone timed out",
- errorCode: "TIMEOUT",
- });
+ // Resolving before the process tree is gone would let the caller
+ // clean the destination while git still writes to it (on Windows
+ // `kill` is TerminateProcess and leaves helpers running).
+ graceTimer = setTimeout(() => {
+ child.kill("SIGKILL");
+ finish(timedOutResult());
+ }, killGraceMs);
}, timeoutMs);
child.stderr?.on("data", (chunk) => {
stderr += String(chunk);
@@ -63,23 +85,37 @@ export function runGitClone(
});
});
child.on("close", (code) => {
- finish({ code: code ?? 1, stderr });
+ finish(timedOut ? timedOutResult() : { code: code ?? 1, stderr });
});
});
}
+function pathEntryExists(path: string): boolean {
+ try {
+ lstatSync(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
/**
* A timed-out clone leaves the half-built checkout git was killed inside;
* keeping it makes every retry of the same name hit CONFLICT until the user
- * finds and deletes the residue by hand. A symlink at the destination is
- * unlinked instead of recursed into.
+ * finds and deletes the residue by hand. Only called for a destination that
+ * was absent before git started, so everything there belongs to this clone.
+ * A symlink at the destination is unlinked instead of recursed into.
*/
-function removeIncompleteClone(dest: string): void {
+async function removeIncompleteClone(dest: string): Promise<void> {
try {
if (lstatSync(dest).isSymbolicLink()) unlinkSync(dest);
- else rmSync(dest, { recursive: true, force: true });
- } catch {
- // The clone died before creating anything; nothing to clean up.
+ else await rm(dest, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
+ } catch (error) {
+ // ENOENT: the clone died before creating anything.
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
+ console.warn("[git-clone] could not remove incomplete clone after timeout", {
+ code: (error as NodeJS.ErrnoException).code,
+ });
}
}
@@ -123,13 +159,15 @@ export async function cloneGitRepository(input: {
if (existsSync(dest)) {
throw codedError("CONFLICT", `"${name}" already exists in that folder`);
}
+ // `existsSync` follows symlinks; a dangling link still occupies the name.
+ const destPreexisted = pathEntryExists(dest);
const run = input.run ?? runGitClone;
const result = await run(parent, ["clone", "--", target.url, dest]);
if (result.errorCode === "NOT_FOUND") {
throw codedError("NOT_FOUND", "Git is not installed");
}
if (result.errorCode === "TIMEOUT") {
- removeIncompleteClone(dest);
+ if (!destPreexisted) await removeIncompleteClone(dest);
throw codedError("TIMEOUT", "git clone timed out");
}
if (result.code !== 0) {
diff --git a/apps/desktop/test/git-clone.test.mjs b/apps/desktop/test/git-clone.test.mjs
index 83644673a..e008d7d2a 100644
--- a/apps/desktop/test/git-clone.test.mjs
+++ b/apps/desktop/test/git-clone.test.mjs
@@ -1,11 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { existsSync, mkdtempSync, mkdirSync, rmSync } from "node:fs";
+import { existsSync, lstatSync, mkdtempSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
cloneGitRepository,
parseGitCloneUrl,
+ runGitClone,
} from "../electron/main/git-clone.ts";
import { applyUserEndpointPolicyFromAppSettings } from "../electron/main/endpoint-policy.ts";
@@ -292,3 +293,85 @@ test("cloneGitRepository cleans up a half-built destination after a timeout", as
rmSync(root, { recursive: true, force: true });
}
});
+
+test("runGitClone resolves a timeout only after the killed process has exited", async () => {
+ // Cleaning the destination while git (or a helper holding its stdio) still
+ // writes there races open handles; the timeout must wait for `close`.
+ const root = mkdtempSync(join(tmpdir(), "pi-clone-run-"));
+ const marker = join(root, "exited");
+ try {
+ const script = `
+ process.on("SIGTERM", () => setTimeout(() => {
+ require("node:fs").writeFileSync(${JSON.stringify(marker)}, "");
+ process.exit(1);
+ }, 300));
+ process.stderr.write("ready");
+ setInterval(() => {}, 1000);
+ `;
+ const result = await runGitClone(root, ["-e", script], 200, {
+ command: process.execPath,
+ killGraceMs: 10_000,
+ });
+ assert.equal(result.errorCode, "TIMEOUT");
+ // Windows has no SIGTERM handler (kill terminates at once), so only
+ // POSIX can observe the delayed exit.
+ if (process.platform !== "win32") assert.equal(existsSync(marker), true);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("runGitClone force-kills a timed-out process that ignores SIGTERM", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-clone-run-"));
+ try {
+ const script = `process.on("SIGTERM", () => {}); setInterval(() => {}, 1000);`;
+ const started = Date.now();
+ const result = await runGitClone(root, ["-e", script], 100, {
+ command: process.execPath,
+ killGraceMs: 200,
+ });
+ assert.equal(result.errorCode, "TIMEOUT");
+ assert.ok(Date.now() - started < 5_000);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("runGitClone reports a normal exit code and stderr", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-clone-run-"));
+ try {
+ const result = await runGitClone(
+ root,
+ ["-e", `process.stderr.write("fatal: nope"); process.exit(3);`],
+ 10_000,
+ { command: process.execPath },
+ );
+ assert.deepEqual(result, { code: 3, stderr: "fatal: nope" });
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test(
+ "cloneGitRepository keeps a destination entry that predates a timed-out clone",
+ { skip: process.platform === "win32" },
+ async () => {
+ // A dangling symlink passes `existsSync`, so git runs; the timeout path
+ // must not delete an entry this clone did not create.
+ const root = mkdtempSync(join(tmpdir(), "pi-clone-"));
+ try {
+ symlinkSync(join(root, "missing-target"), join(root, "demo"));
+ await assert.rejects(
+ cloneGitRepository({
+ url: "https://github.com/org/demo.git",
+ parentPath: root,
+ run: async () => ({ code: 1, stderr: "git clone timed out", errorCode: "TIMEOUT" }),
+ }),
+ { errorCode: "TIMEOUT" },
+ );
+ assert.equal(lstatSync(join(root, "demo")).isSymbolicLink(), true);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ },
+);