@devries-cameron20 / t3code Mirror · read-only / commits / 19f643856e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 14:45 UTC

fix(server): interrupted checkpoint restores no longer leave files staged (#36687)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 14, 2026 at 13:04 UTC 19f643856ee36a142e8f5b6d6600374740daa669
5 files changed +125 -30
apps/server/src/processRunner.test.ts
+25
@@ -2,6 +2,8 @@ import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshot
2 import { describe, expect, it } from "@effect/vitest";
3 import * as Deferred from "effect/Deferred";
4 import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Cause from "effect/Cause";
7 import * as Layer from "effect/Layer";
8 import * as PlatformError from "effect/PlatformError";
9 import * as Sink from "effect/Sink";
@@ -143,6 +145,29 @@ describe("runProcess", () => {
145 }),
146 );
147
148 + it.effect("reports child startup before delivering cancellation during acquisition", () =>
149 + Effect.gen(function* () {
150 + let started = false;
151 + const spawner = makeSpawner(() =>
152 + Effect.withFiber((fiber) =>
153 + Effect.sync(() => {
154 + fiber.interruptUnsafe();
155 + return makeHandle({});
156 + }),
157 + ),
158 + );
159 + const result = yield* runWith(spawner)({
160 + command: "git",
161 + args: ["restore"],
162 + onSpawn: () => {
163 + started = true;
164 + },
165 + }).pipe(Effect.exit);
166 + expect(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)).toBe(true);
167 + expect(started).toBe(true);
168 + }).pipe(Effect.scoped),
169 + );
170 +
171 it.effect("fails when output exceeds max buffer in default mode", () =>
172 Effect.gen(function* () {
173 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
apps/server/src/processRunner.ts
+9 -1
@@ -26,6 +26,8 @@ export interface ProcessRunInput {
26 readonly stdin?: string | undefined;
27 /** Receives every stdout chunk, including bytes beyond the buffered output limit. */
28 readonly onStdoutChunk?: ((chunk: Uint8Array) => void) | undefined;
29 + /** Runs after successful spawn, before cancellation can interrupt acquisition. */
30 + readonly onSpawn?: (() => void) | undefined;
31 readonly maxOutputBytes?: number | undefined;
32 readonly outputMode?: "error" | "truncate" | undefined;
33 readonly truncatedMarker?: string | undefined;
@@ -290,7 +292,7 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
292 cause,
293 });
294
293 - const child = yield* spawner
295 + const spawn = spawner
296 .spawn(
297 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
298 ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
@@ -309,6 +311,12 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
311 // Synchronous spawn throws arrive as defects; recover them too so callers see typed spawn failures.
312 Effect.catchDefect((cause) => Effect.fail(toSpawnError(cause))),
313 );
314 + const child = yield* input.onSpawn === undefined
315 + ? spawn
316 + : spawn.pipe(
317 + Effect.tap(() => Effect.sync(() => input.onSpawn?.())),
318 + Effect.uninterruptible,
319 + );
320
321 const stdin = input.stdin;
322 const onStdoutChunk = input.onStdoutChunk;
apps/server/src/vcs/GitVcsDriver.test.ts
+43
@@ -400,6 +400,49 @@ it.effect.each(["failure", "interrupt"] as const)(
400 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
401 );
402
403 +it.effect.each([
404 + { stop: "before git restore spawns", gate: "restore", index: "staged", file: "later\n" },
405 + { stop: "after git restore ran", gate: "clean", index: "head", file: "unstaged\n" },
406 +] as const)(
407 + "checkpoint restore interrupted $stop leaves the $index index",
408 + ({ gate, index, file }) =>
409 + Effect.gen(function* () {
410 + const fs = yield* FileSystem.FileSystem;
411 + const path = yield* Path.Path;
412 + const driver = yield* GitVcsDriver.makeVcsDriverShape();
413 + const liveProcess = yield* VcsProcess.VcsProcess;
414 + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-restore-interrupt-" });
415 + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
416 + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
417 + yield* fs.writeFileString(path.join(cwd, "file.txt"), "later\n");
418 + yield* git(["add", "file.txt"]);
419 + const stagedTree = (yield* git(["write-tree"])).stdout;
420 + const entered = yield* Deferred.make<void>();
421 + const gatedDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
422 + Effect.provideService(VcsProcess.VcsProcess, {
423 + run: (input) =>
424 + input.operation === "GitVcsDriver.checkpoints.restoreCheckpoint" &&
425 + input.args.includes(gate)
426 + ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
427 + : liveProcess.run(input),
428 + }),
429 + );
430 + const fiber = yield* gatedDriver.checkpoints
431 + .restoreCheckpoint({ cwd, checkpointRef })
432 + .pipe(Effect.exit, Effect.forkScoped);
433 + yield* Deferred.await(entered);
434 + yield* Fiber.interrupt(fiber);
435 + const result = yield* Fiber.await(fiber);
436 + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause));
437 +
438 + assert.strictEqual(
439 + (yield* git(["write-tree"])).stdout,
440 + index === "head" ? (yield* git(["rev-parse", "HEAD^{tree}"])).stdout : stagedTree,
441 + );
442 + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "file.txt")), file);
443 + }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
444 +);
445 +
446 it.effect("checkpoint publication falls back to rename where hardlinks are unavailable", () =>
447 Effect.gen(function* () {
448 const fs = yield* FileSystem.FileSystem;
apps/server/src/vcs/GitVcsDriver.ts
+46 -29
@@ -4,6 +4,7 @@ import * as Context from "effect/Context";
4 import * as SecureRandom from "effect/crypto/SecureRandom";
5 import * as DateTime from "effect/DateTime";
6 import * as Effect from "effect/Effect";
7 +import * as Exit from "effect/Exit";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
@@ -569,6 +570,7 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")(
570 args: ReadonlyArray<string>,
571 options?: {
572 readonly stdin?: string;
573 + readonly onSpawn?: () => void;
574 readonly env?: NodeJS.ProcessEnv;
575 readonly allowNonZeroExit?: boolean;
576 readonly timeoutMs?: number;
@@ -584,6 +586,7 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")(
586 cwd,
587 spawnCwd: globalThis.process.cwd(),
588 ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
589 + ...(options?.onSpawn !== undefined ? { onSpawn: options.onSpawn } : {}),
590 ...(options?.env !== undefined ? { env: options.env } : {}),
591 ...(options?.allowNonZeroExit !== undefined
592 ? { allowNonZeroExit: options.allowNonZeroExit }
@@ -655,6 +658,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
658 const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) =>
659 gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
660 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
661 + ...(input.onSpawn !== undefined ? { onSpawn: input.onSpawn } : {}),
662 ...(input.env !== undefined ? { env: input.env } : {}),
663 ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
664 ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
@@ -1725,15 +1729,48 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1729 cwd: input.cwd,
1730 args: ["ls-files", "--cached", `--with-tree=${commitOid}`, "-z", "--", "."],
1731 });
1728 - // An empty index and checkpoint have nothing for git restore's pathspec to match.
1729 - if (tracked.stdout.length > 0) {
1730 - const sparseConfig = yield* execute({
1732 + const sparseConfig =
1733 + tracked.stdout.length > 0
1734 + ? yield* execute({
1735 + operation,
1736 + cwd: input.cwd,
1737 + args: ["config", "--bool", "core.sparseCheckout"],
1738 + allowNonZeroExit: true,
1739 + })
1740 + : null;
1741 + const sparseCheckout = sparseConfig?.stdout.trim() === "true";
1742 + // Restoring away the last tracked file can remove a nested workspace directory.
1743 + const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1744 + Effect.mapError(
1745 + (cause) =>
1746 + new VcsProcessExitError({
1747 + operation,
1748 + command: "git restore",
1749 + cwd: input.cwd,
1750 + exitCode: 0,
1751 + detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1752 + }),
1753 + ),
1754 + );
1755 + const resetIndex = Effect.gen(function* () {
1756 + // On Windows clean can remove './' and exit 0.
1757 + yield* recreateWorkspace;
1758 + yield* execute({
1759 operation,
1760 cwd: input.cwd,
1733 - args: ["config", "--bool", "core.sparseCheckout"],
1734 - allowNonZeroExit: true,
1761 + args: [...longPaths, "reset", "--quiet", "--", "."],
1762 });
1736 - const sparseCheckout = sparseConfig.stdout.trim() === "true";
1763 + });
1764 + let mutationStarted = false;
1765 + const onSpawn = () => {
1766 + mutationStarted = true;
1767 + };
1768 + // Queued commands preserve user staging; spawned children stop before this scope resets it.
1769 + yield* Effect.addFinalizer((exit) =>
1770 + mutationStarted && Exit.hasInterrupts(exit) ? resetIndex.pipe(Effect.ignore) : Effect.void,
1771 + );
1772 + // An empty index and checkpoint have nothing for git restore's pathspec to match.
1773 + if (tracked.stdout.length > 0) {
1774 const restore = [...longPaths, "restore", "--source", commitOid, "--worktree", "--staged"];
1775 // restore leaves skip-worktree paths alone. Outside a sparse checkout every such bit was
1776 // set by hand and capture recorded the file, so override them all.
@@ -1741,6 +1778,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1778 operation,
1779 cwd: input.cwd,
1780 args: [...restore, ...(sparseCheckout ? [] : ["--ignore-skip-worktree-bits"]), "--", "."],
1781 + onSpawn,
1782 });
1783 if (sparseCheckout) {
1784 // Sparse exclusions stay excluded; only skip-worktree paths the rules select are manual.
@@ -1812,28 +1850,6 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1850 }
1851 }
1852 }
1815 - // Restoring away the last tracked file can remove a nested workspace directory.
1816 - const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe(
1817 - Effect.mapError(
1818 - (cause) =>
1819 - new VcsProcessExitError({
1820 - operation,
1821 - command: "git restore",
1822 - cwd: input.cwd,
1823 - exitCode: 0,
1824 - detail: `Could not recreate the checkpoint workspace: ${cause.message}`,
1825 - }),
1826 - ),
1827 - );
1828 - const resetIndex = Effect.gen(function* () {
1829 - // On Windows clean can remove './' and exit 0.
1830 - yield* recreateWorkspace;
1831 - yield* execute({
1832 - operation,
1833 - cwd: input.cwd,
1834 - args: [...longPaths, "reset", "--quiet", "--", "."],
1835 - });
1836 - });
1853 yield* recreateWorkspace;
1854 const clean = execute({
1855 operation,
@@ -1841,6 +1857,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1857 args: [...longPaths, "clean", "-fd", "--", "."],
1858 env: { LC_ALL: "C" },
1859 allowNonZeroExit: true,
1860 + onSpawn,
1861 });
1862 let cleaned = yield* clean;
1863 // Removing a new .gitignore exposes the files it hid; clean again until nothing is left.
@@ -1894,7 +1911,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1911 yield* resetIndex;
1912
1913 return true;
1897 - }),
1914 + }, Effect.scoped),
1915
1916 diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
1917 const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
apps/server/src/vcs/VcsProcess.ts
+2
@@ -33,6 +33,7 @@ export interface VcsProcessInput {
33 readonly spawnCwd?: string;
34 readonly stdin?: string;
35 readonly onStdoutChunk?: (chunk: Uint8Array) => void;
36 + readonly onSpawn?: () => void;
37 readonly env?: NodeJS.ProcessEnv;
38 readonly allowNonZeroExit?: boolean;
39 readonly timeoutMs?: number;
@@ -232,6 +233,7 @@ export const make = Effect.gen(function* () {
233 ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
234 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
235 ...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}),
236 + ...(input.onSpawn !== undefined ? { onSpawn: input.onSpawn } : {}),
237 env: {
238 ...(input.command === "git"
239 ? unsetInheritedRepositoryEnv(process.env, hostPlatform)