feat(web): clone repositories in the background instead of holding the palette open (#11762)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-09-14 13:00:28 -07:00
1 parent 112a7088da
commit 8d7c700c17
28 files changed
+2206 -25

No files matched your search

@@ -178,7 +178,7 @@ it.effect("clones a looked-up repository into the requested destination", () =>
assert.deepStrictEqual(cloneCalls, [
{
cwd: parent,
args: ["clone", CLONE_URLS.url, "t3code"],
args: ["clone", "--progress", CLONE_URLS.url, "t3code"],
},
]);
}).pipe(
@@ -197,6 +197,154 @@ it.effect("clones a looked-up repository into the requested destination", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parent = yield* fs.makeTempDirectoryScoped({
prefix: "t3-source-control-clone-progress-",
});
const destinationPath = path.join(parent, "t3code");
const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
const stderrLines = [
"Cloning into 't3code'...",
"remote: Enumerating objects: 10, done.",
"Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
"Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
"fatal: early EOF",
"fatal: unable to access 'https://user:s3c@[email protected]/octocat/t3code.git/': could not resolve host",
];
const error = yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
return yield* Effect.flip(
service.cloneRepository(
{ remoteUrl: CLONE_URLS.sshUrl, destinationPath },
{ onProgress: (line) => Effect.sync(() => void progress.push(line)) },
),
);
}).pipe(
Effect.provide(
makeLayer({
git: {
execute: (input) =>
Effect.gen(function* () {
for (const line of stderrLines) {
yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
}
return yield* new GitCommandError({
operation: input.operation,
command: "git",
cwd: input.cwd,
detail: "Git command exited with a non-zero status.",
exitCode: 128,
});
}),
},
}),
),
);
assert.deepStrictEqual(progress, [
{ stage: "counting", percent: null, detail: null },
{ stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
{ stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
]);
// Git echoes the remote in some failures; the credentials must not follow.
assert.strictEqual(
error.detail,
"fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("strips embedded credentials from the remote URL it reports", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
const destinationPath = path.join(parent, "t3code");
const cloneArgs: Array<ReadonlyArray<string>> = [];
const result = yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
return yield* service.prepareClone({
remoteUrl: "https://user:[email protected]/octocat/t3code.git",
destinationPath,
});
}).pipe(
Effect.provide(
makeLayer({
git: {
execute: (input) =>
Effect.sync(() => {
cloneArgs.push(input.args);
return processOutput();
}),
},
}),
),
);
assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
// Git itself still receives the credentials.
assert.equal(result.cloneUrl, "https://user:[email protected]/octocat/t3code.git");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("discards only a directory git wrote to", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
const partial = path.join(parent, "partial");
yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
yield* fs.writeFileString(path.join(partial, "README.md"), "half");
const foreign = path.join(parent, "foreign");
yield* fs.makeDirectory(foreign);
yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
// A file where the directory should be must not be removed either.
const replaced = path.join(parent, "replaced");
yield* fs.writeFileString(replaced, "not a directory");
yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
yield* service.discardClone(partial);
const error = yield* Effect.flip(service.discardClone(foreign));
assert.include(error.detail, "not from the clone");
const replacedError = yield* Effect.flip(service.discardClone(replaced));
assert.include(replacedError.detail, "could not be inspected");
// A destination that never got created is nothing to discard.
yield* service.discardClone(path.join(parent, "missing"));
}).pipe(Effect.provide(makeLayer({})));
// The partial clone is emptied but its directory (the workspace root) stays.
assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const query = yield* service.prepareClone({
remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
destinationPath: path.join(parent, "a"),
});
assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
const nested = yield* service.prepareClone({
remoteUrl: "https://user:pa@[email protected]/octocat/t3code.git",
destinationPath: path.join(parent, "b"),
});
assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
}).pipe(Effect.provide(makeLayer({})));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
const fileSystemCause = PlatformError.systemError({
_tag: "PermissionDenied",
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import {
@@ -20,6 +21,10 @@ import {
import { ServerConfig } from "../config.ts";
import { expandHomePathWith } from "../pathExpansion.ts";
import {
parseGitCloneProgressLine,
type GitCloneProgressLine,
} from "../project/gitCloneProgress.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
@@ -30,15 +35,56 @@ export class SourceControlRepositoryService extends Context.Service<
readonly lookupRepository: (
input: SourceControlRepositoryLookupInput,
) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
/**
* Everything `cloneRepository` checks before running git: the resolved
* remote, the normalized destination, and that the destination is empty.
* Lets a caller create the project first and clone afterwards.
*/
readonly prepareClone: (
input: SourceControlCloneRepositoryInput,
) => Effect.Effect<SourceControlPreparedClone, SourceControlRepositoryError>;
readonly cloneRepository: (
input: SourceControlCloneRepositoryInput,
options?: SourceControlCloneOptions,
) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
/** Removes a partial or failed clone so the destination is empty again. */
readonly discardClone: (
destinationPath: string,
) => Effect.Effect<void, SourceControlRepositoryError>;
readonly publishRepository: (
input: SourceControlPublishRepositoryInput,
) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
}
>()("t3/sourceControl/SourceControlRepositoryService") {}
export interface SourceControlPreparedClone {
readonly destinationPath: string;
/** Credential-free; safe to show and to store in snapshots. */
readonly remoteUrl: string;
/** What git is given; may carry embedded credentials. */
readonly cloneUrl: string;
readonly repository: SourceControlRepositoryInfo | null;
}
export interface SourceControlCloneOptions {
readonly onProgress?: (line: GitCloneProgressLine) => Effect.Effect<void>;
/** Overrides the default clone budget; `null` disables the deadline. */
readonly timeoutMs?: number | null;
}
// The synchronous RPC (older clients, mobile) keeps a deadline: nothing else
// tells the user a clone stalled. The tracked path passes null and relies on
// progress and Cancel instead.
const CLONE_TIMEOUT_MS = 120_000;
const CLONE_ENV = {
// `--progress` forces the transfer counters through the pipe; the delay env
// makes the checkout counter start immediately. No tty means a credential
// prompt would hang forever, so tell git to fail instead.
GIT_PROGRESS_DELAY: "0",
GIT_TERMINAL_PROMPT: "0",
LC_ALL: "C",
} satisfies NodeJS.ProcessEnv;
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
return Effect.mapError((cause: unknown) =>
isSourceControlRepositoryError(cause)
@@ -64,6 +110,36 @@ function toRepositoryInfo(
};
}
/**
* The URL clients see. A pasted `https://user:token@host/…` must not travel
* back over `subscribeProjectClones` to every reader; git still gets the
* original.
*/
function redactRemoteUrl(remoteUrl: string): string {
try {
const url = new URL(remoteUrl);
// Clone URLs have no legitimate query; when one is present it is a token.
if (url.username.length === 0 && url.password.length === 0 && url.search.length === 0) {
return remoteUrl;
}
url.username = "";
url.password = "";
url.search = "";
return url.toString();
} catch {
return remoteUrl;
}
}
// Userinfo may itself contain `@`; everything up to the last one before the
// host boundary goes.
const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/]+@/gi;
/** Drops `user:token@` from any URL embedded in free text. */
function redactUrlCredentials(text: string): string {
return text.replace(URL_WITH_USERINFO, "$1");
}
function selectRemoteUrl(
urls: SourceControlRepositoryCloneUrls,
protocol: SourceControlCloneProtocol | undefined,
@@ -168,7 +244,7 @@ export const make = Effect.gen(function* () {
},
);
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
input: SourceControlCloneRepositoryInput,
) {
const preparedDestination = yield* prepareDestination(input.destinationPath);
@@ -194,21 +270,121 @@ export const make = Effect.gen(function* () {
});
}
yield* git.execute({
operation: "SourceControlRepositoryService.cloneRepository",
cwd: preparedDestination.parentPath,
args: ["clone", remoteUrl, preparedDestination.directoryName],
timeoutMs: 120_000,
maxOutputBytes: 256 * 1024,
});
return {
destinationPath: preparedDestination.destinationPath,
remoteUrl: redactRemoteUrl(remoteUrl),
cloneUrl: remoteUrl,
repository,
} satisfies SourceControlPreparedClone;
});
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
input: SourceControlCloneRepositoryInput,
options?: SourceControlCloneOptions,
) {
const prepared = yield* prepareClone(input);
const onProgress = options?.onProgress;
// Git interleaves progress redraws with its real messages on stderr. The
// last non-progress lines are what explain a failure ("Repository not
// found", "Permission denied"), so keep them for the error detail.
const stderrTail: Array<string> = [];
const onStderrLine = (line: string) => {
const parsed = parseGitCloneProgressLine(line);
if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
return Effect.sync(() => {
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
// Git echoes the remote in some failures; the tail becomes user-facing text.
stderrTail.push(redactUrlCredentials(trimmed));
if (stderrTail.length > 4) stderrTail.shift();
});
};
yield* git
.execute({
operation: "SourceControlRepositoryService.cloneRepository",
cwd: path.dirname(prepared.destinationPath),
args: ["clone", "--progress", prepared.cloneUrl, path.basename(prepared.destinationPath)],
timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
// Progress redraws add up on a slow multi-GB clone. The buffered copy
// is never read (the tail is kept by hand above), so keep it small
// and let the line callbacks keep flowing past the cap.
maxOutputBytes: 256 * 1024,
appendTruncationMarker: true,
keepLineCallbacksAfterTruncation: true,
env: CLONE_ENV,
progress: { onStderrLine },
})
.pipe(
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "cloneRepository",
provider: input.provider ?? "unknown",
detail:
stderrTail.length > 0
? stderrTail.join(" ")
: "The repository could not be cloned.",
cause,
}),
),
);
return {
cwd: preparedDestination.destinationPath,
remoteUrl,
repository,
cwd: prepared.destinationPath,
remoteUrl: prepared.remoteUrl,
repository: prepared.repository,
};
});
const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
destinationPath: string,
) {
const normalized = yield* normalizeDestinationPath(destinationPath);
// Only what git left behind may go. The destination was empty when the
// clone started, so anything without a `.git` inside was put there by
// someone else since; refuse rather than delete their files.
// A missing destination is already discarded; any other read failure
// (a file in its place, permissions) is not something to remove through.
const entries = yield* fileSystem.readDirectory(normalized).pipe(
Effect.catchIf(
(cause) => cause.reason._tag === "NotFound",
() => Effect.succeed<ReadonlyArray<string>>([]),
),
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "discardClone",
provider: "unknown",
detail: "The clone destination could not be inspected.",
cause,
}),
),
);
if (entries.length > 0 && !entries.includes(".git")) {
return yield* new SourceControlRepositoryError({
operation: "discardClone",
provider: "unknown",
detail: "Destination path contains files that are not from the clone.",
});
}
// The directory itself is the project's workspace root and must stay;
// only git's partial contents go. An interrupted git may still be closing
// files, so removal retries briefly.
yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
Effect.mapError(
(cause) =>
new SourceControlRepositoryError({
operation: "discardClone",
provider: "unknown",
detail: "The partial clone could not be removed.",
cause,
}),
),
);
});
const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
function* (input: SourceControlPublishRepositoryInput) {
const providerKind = yield* ensureConcreteProvider({
@@ -269,10 +445,14 @@ export const make = Effect.gen(function* () {
return SourceControlRepositoryService.of({
lookupRepository: (input) =>
lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
cloneRepository: (input) =>
cloneRepository(input).pipe(
prepareClone: (input) =>
prepareClone(input).pipe(mapRepositoryError("cloneRepository", input.provider ?? "unknown")),
cloneRepository: (input, options) =>
cloneRepository(input, options).pipe(
mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
),
discardClone: (destinationPath) =>
discardClone(destinationPath).pipe(mapRepositoryError("discardClone", "unknown")),
publishRepository: (input) =>
publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
});