@devries-cameron20 / t3code Mirror · read-only / commits / c03b240265
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 24, 00:15 UTC

fix(git): explain fetch failures without exposing remote output (#12485)

Julius Marminge committed Sep 18, 2026 at 11:14 UTC c03b240265a1d4954536c5c0758ac2b7fa762ba8
2 files changed +231 -12
apps/server/src/vcs/GitVcsDriverCore.test.ts
+156 -8
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Fiber from "effect/Fiber";
10 import * as Layer from "effect/Layer";
11 +import * as Logger from "effect/Logger";
12 import * as Metric from "effect/Metric";
13 import * as Path from "effect/Path";
14 import * as PlatformError from "effect/PlatformError";
@@ -35,6 +36,8 @@ import {
36 } from "./GitVcsDriverCore.ts";
37 import * as GitVcsDriver from "./GitVcsDriver.ts";
38
39 +const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));
40 +
41 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
42 prefix: "t3-git-vcs-driver-test-",
43 });
@@ -718,7 +721,7 @@ it.effect("refreshes the current branch after an external checkout", () =>
721 ).pipe(Effect.provide(TestLayer)),
722 );
723
721 -it.effect("backs off failed upstream refreshes across linked worktrees", () =>
724 +it.effect("backs off and logs failed fetch attempts across linked worktrees", () =>
725 Effect.scoped(
726 Effect.gen(function* () {
727 const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -738,6 +741,14 @@ it.effect("backs off failed upstream refreshes across linked worktrees", () =>
741 const driver = yield* makeGitVcsDriverCore().pipe(
742 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingFetchSpawner),
743 );
744 + const warnings: string[] = [];
745 + const logger = Logger.make<unknown, void>(({ message }) => {
746 + warnings.push(String(message));
747 + });
748 + const readRemoteStatus = (workingDirectory: string) =>
749 + driver
750 + .statusDetailsRemote(workingDirectory)
751 + .pipe(Effect.provideService(Logger.CurrentLoggers, new Set([logger])));
752 const cwd = yield* makeTmpDir();
753 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
754 const worktreesRoot = yield* makeTmpDir("git-vcs-driver-worktrees-");
@@ -781,29 +792,146 @@ it.effect("backs off failed upstream refreshes across linked worktrees", () =>
792 );
793 yield* Ref.set(fetchAttempts, 0);
794
784 - yield* driver.statusDetailsRemote(cwd);
785 - yield* driver.statusDetailsRemote(worktreePath);
795 + yield* readRemoteStatus(cwd);
796 + yield* readRemoteStatus(worktreePath);
797 assert.equal(yield* Ref.get(fetchAttempts), 1);
798 + assert.lengthOf(warnings, 1);
799 + assert.include(warnings[0], "Background Git fetch failed");
800
801 yield* TestClock.adjust("29 seconds");
789 - yield* driver.statusDetailsRemote(worktreePath);
802 + yield* readRemoteStatus(worktreePath);
803 assert.equal(yield* Ref.get(fetchAttempts), 1);
804 + assert.lengthOf(warnings, 1);
805
806 yield* TestClock.adjust("1 second");
793 - yield* driver.statusDetailsRemote(cwd);
807 + yield* readRemoteStatus(cwd);
808 assert.equal(yield* Ref.get(fetchAttempts), 2);
809 + assert.lengthOf(warnings, 2);
810
811 yield* TestClock.adjust("59 seconds");
797 - yield* driver.statusDetailsRemote(worktreePath);
812 + yield* readRemoteStatus(worktreePath);
813 assert.equal(yield* Ref.get(fetchAttempts), 2);
814 + assert.lengthOf(warnings, 2);
815
816 yield* TestClock.adjust("1 second");
801 - yield* driver.statusDetailsRemote(cwd);
817 + yield* readRemoteStatus(cwd);
818 assert.equal(yield* Ref.get(fetchAttempts), 3);
819 + assert.lengthOf(warnings, 3);
820 }),
821 ).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
822 );
823
824 +for (const scenario of [
825 + {
826 + name: "HTTPS credentials",
827 + stderr: "fatal: Authentication failed for",
828 + expected: "could not authenticate",
829 + },
830 + {
831 + name: "SSH credentials",
832 + stderr: "git@example.com: Permission denied (publickey).",
833 + expected: "could not authenticate",
834 + },
835 + {
836 + name: "disabled prompts",
837 + stderr: "fatal: could not read Username: terminal prompts disabled",
838 + expected: "could not authenticate",
839 + },
840 + {
841 + name: "DNS failure",
842 + stderr: "fatal: Could not resolve host: example.com",
843 + expected: "could not reach the remote",
844 + },
845 + {
846 + name: "connection failure",
847 + stderr: "ssh: connect to host example.com port 22: Connection refused",
848 + expected: "could not reach the remote",
849 + },
850 + {
851 + name: "missing remote",
852 + stderr: "remote: Repository not found.",
853 + expected: "could not access the remote repository",
854 + },
855 + {
856 + name: "invalid remote",
857 + stderr: "fatal: remote does not appear to be a git repository",
858 + expected: "could not access the remote repository",
859 + },
860 + {
861 + name: "reference lock",
862 + stderr: "error: cannot lock ref 'refs/remotes/origin/main': is at abc but expected def",
863 + expected: "could not update a local reference",
864 + },
865 + {
866 + name: "lock file",
867 + stderr: "fatal: Unable to create '/repo/.git/FETCH_HEAD.lock': File exists.",
868 + expected: "could not update a local reference",
869 + },
870 + {
871 + name: "unrelated remote chatter",
872 + stderr:
873 + "remote: Help: authentication failed, connection refused, cannot lock ref\nremote: unrelated service error",
874 + expected: "git fetch origin failed",
875 + },
876 + {
877 + name: "HTTPS DNS failure",
878 + stderr:
879 + "fatal: unable to access 'https://example.com/repo.git/': Could not resolve host: example.com",
880 + expected: "could not reach the remote",
881 + },
882 + {
883 + name: "unknown failure",
884 + stderr: "fatal: unexpected remote failure",
885 + expected: "git fetch origin failed",
886 + },
887 +] as const) {
888 + it.effect(`reports ${scenario.name} during fetch without retaining remote output`, () =>
889 + Effect.gen(function* () {
890 + const secret = "secret-fetch-token";
891 + const stderr = `${scenario.stderr}\nhttps://user:${secret}@example.com/private?token=${secret}`;
892 + const attempts = yield* Ref.make(0);
893 + const spawner = ChildProcessSpawner.make((command) =>
894 + Effect.gen(function* () {
895 + if (!ChildProcess.isStandardCommand(command))
896 + return yield* Effect.die("expected Git command");
897 + if (command.args[0] !== "fetch") return makeNonRepositoryHandle();
898 + assert.deepEqual(command.args, ["fetch", "--quiet", "origin"]);
899 + assert.equal(command.options.env?.LC_ALL, "C");
900 + assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0");
901 + yield* Ref.update(attempts, (count) => count + 1);
902 + return ChildProcessSpawner.makeHandle({
903 + pid: ChildProcessSpawner.ProcessId(1),
904 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
905 + isRunning: Effect.succeed(false),
906 + kill: () => Effect.void,
907 + unref: Effect.succeed(Effect.void),
908 + stdin: Sink.drain,
909 + stdout: Stream.encodeText(Stream.make(secret)),
910 + stderr: Stream.encodeText(Stream.make(stderr)),
911 + all: Stream.empty,
912 + getInputFd: () => Sink.drain,
913 + getOutputFd: () => Stream.empty,
914 + });
915 + }),
916 + );
917 + const driver = yield* makeGitVcsDriverCore().pipe(
918 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
919 + );
920 + const cwd = yield* makeTmpDir();
921 + const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);
922 + assert.include(error.detail, scenario.expected);
923 + assert.equal(error.exitCode, 128);
924 + assert.equal(error.stderrLength, stderr.length);
925 + assert.equal(error.stdoutLength, secret.length);
926 + assert.notInclude(error.message, secret);
927 + assert.notInclude(yield* encodeGitCommandError(error), secret);
928 + assert.notProperty(error, "stderr");
929 + assert.notProperty(error, "args");
930 + assert.equal(yield* Ref.get(attempts), 1);
931 + }).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
932 + );
933 +}
934 +
935 it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
936 describe("process environment", () => {
937 it.effect("preserves the caller locale for general Git subprocesses", () =>
@@ -2398,6 +2526,22 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
2526 });
2527
2528 describe("remote operations", () => {
2529 + it.effect("explains a real fetch failure for a missing local remote", () =>
2530 + Effect.gen(function* () {
2531 + const cwd = yield* makeTmpDir();
2532 + yield* initRepoWithCommit(cwd);
2533 + const driver = yield* GitVcsDriver.GitVcsDriver;
2534 + const missingRemote = `${cwd}/private-missing-remote`;
2535 + yield* git(cwd, ["remote", "add", "origin", missingRemote]);
2536 + const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);
2537 + assert.include(error.detail, "could not access the remote repository");
2538 + assert.equal(error.exitCode, 128);
2539 + assert.isAbove(error.stderrLength ?? 0, 0);
2540 + assert.notInclude(error.detail, missingRemote);
2541 + assert.notProperty(error, "stderr");
2542 + }),
2543 + );
2544 +
2545 it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>
2546 Effect.gen(function* () {
2547 const cwd = yield* makeTmpDir();
@@ -2544,7 +2688,11 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
2688 if (Result.isFailure(result)) {
2689 assert.equal(
2690 result.failure.detail,
2547 - failure === "timeout" ? "Git command timed out." : "git fetch origin failed",
2691 + failure === "timeout"
2692 + ? "Git command timed out."
2693 + : failure === "offline"
2694 + ? "Git could not reach the remote. Check the server's network connection and remote host, then retry."
2695 + : "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.",
2696 );
2697 }
2698 }),
apps/server/src/vcs/GitVcsDriverCore.ts
+75 -4
@@ -469,6 +469,49 @@ function isMissingWorktreeStderr(stderr: string): boolean {
469 );
470 }
471
472 +// Fetch stderr can contain remote credentials. Only fixed diagnoses may enter
473 +// persisted errors; unrecognized output keeps the generic failure message.
474 +function fetchFailureDetail(stderr: string): string | undefined {
475 + const lines = stderr.split(/\r?\n/).map((line) => line.trim());
476 + if (
477 + lines.some((line) =>
478 + /^(?:fatal: (?:Authentication failed|could not read (?:Username|Password))\b|\S+: Permission denied \(publickey)/i.test(
479 + line,
480 + ),
481 + )
482 + ) {
483 + return "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.";
484 + }
485 + if (
486 + lines.some((line) =>
487 + /^(?:(?:fatal: |ssh: )?Could not resolve host(?:name)?\b|fatal: unable to access .+: (?:Could not resolve host|Failed to connect)\b|ssh: connect to host \S+ port \d+: (?:Connection timed out|Connection refused|Network is unreachable)\b)/i.test(
488 + line,
489 + ),
490 + )
491 + ) {
492 + return "Git could not reach the remote. Check the server's network connection and remote host, then retry.";
493 + }
494 + if (
495 + lines.some((line) =>
496 + /^(?:remote: Repository not found\.?$|fatal: repository .+ not found$|fatal: .+ does not appear to be a git repository$)/i.test(
497 + line,
498 + ),
499 + )
500 + ) {
501 + return "Git could not access the remote repository. Check the remote URL and repository permissions on the server.";
502 + }
503 + if (
504 + lines.some((line) =>
505 + /^(?:(?:error|fatal): cannot lock ref\b|fatal: Unable to create ['"].+\.lock['"]:)/i.test(
506 + line,
507 + ),
508 + )
509 + ) {
510 + return "Git could not update a local reference. Another Git operation or a stale lock may be blocking the fetch; check the repository on the server, then retry.";
511 + }
512 + return undefined;
513 +}
514 +
515 interface Trace2Monitor {
516 readonly env: NodeJS.ProcessEnv;
517 readonly flush: Effect.Effect<void, never>;
@@ -1307,6 +1350,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1350 return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(
1351 Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),
1352 Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),
1353 + Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)),
1354 Effect.as(true as const),
1355 );
1356 });
@@ -1331,13 +1375,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1375 const upstream = yield* resolveCurrentUpstream(cwd);
1376 if (!upstream) return;
1377 const gitCommonDir = yield* resolveGitCommonDir(cwd);
1378 + // The cache loader logs failed attempts; cache hits keep using the last fetched refs.
1379 yield* Cache.get(
1380 statusRemoteRefreshCache,
1381 new StatusRemoteRefreshCacheKey({
1382 gitCommonDir,
1383 remoteName: upstream.remoteName,
1384 }),
1340 - );
1385 + ).pipe(Effect.ignore);
1386 });
1387
1388 const resolveDefaultBranchName = (
@@ -3224,7 +3269,33 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3269 env: STATUS_UPSTREAM_REFRESH_ENV,
3270 fallbackErrorDetail: `git fetch ${input.remoteName} failed`,
3271 };
3227 - const fetchAll = executeGit("GitVcsDriver.fetchRemote", input.cwd, args, options);
3272 + const fetchAll = executeGitWithStableDiagnostics(
3273 + "GitVcsDriver.fetchRemote",
3274 + input.cwd,
3275 + args,
3276 + {
3277 + ...options,
3278 + allowNonZeroExit: true,
3279 + },
3280 + ).pipe(
3281 + Effect.flatMap((result) =>
3282 + result.exitCode === 0
3283 + ? Effect.void
3284 + : Effect.fail(
3285 + new GitCommandError({
3286 + ...gitCommandContext({
3287 + operation: "GitVcsDriver.fetchRemote",
3288 + cwd: input.cwd,
3289 + args,
3290 + }),
3291 + detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3292 + ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3293 + stdoutLength: result.stdout.length,
3294 + stderrLength: result.stderr.length,
3295 + }),
3296 + ),
3297 + ),
3298 + );
3299 if (input.refName === undefined) {
3300 return yield* fetchAll.pipe(Effect.asVoid);
3301 }
@@ -3255,8 +3326,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3326 cwd: input.cwd,
3327 args: scopedArgs,
3328 }),
3258 - detail: options.fallbackErrorDetail,
3259 - exitCode: result.exitCode,
3329 + detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3330 + ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3331 stdoutLength: result.stdout.length,
3332 stderrLength: result.stderr.length,
3333 });