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

@@ -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)),
});