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

main
ts 991 lines 36.5 KB
Raw
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import * as NodePath from "@effect/platform-node/NodePath";
3 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { assert, it } from "@effect/vitest";
6 import * as Deferred from "effect/Deferred";
7 import * as Effect from "effect/Effect";
8 import * as Fiber from "effect/Fiber";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Path from "effect/Path";
11 import * as Layer from "effect/Layer";
12 import * as PlatformError from "effect/PlatformError";
13 import * as Queue from "effect/Queue";
14 import { ChildProcessSpawner } from "effect/process";
15 import * as TestClock from "effect/testing/TestClock";
16
17 import {
18 GitCommandError,
19 SourceControlProviderError,
20 type SourceControlCloneRepositoryInput,
21 } from "@t3tools/contracts";
22
23 import * as ServerConfig from "../config.ts";
24 import type { GitCloneProgressLine } from "../project/gitCloneProgress.ts";
25 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
26 import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
27 import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
28 import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
29
30 const CLONE_URLS = {
31 nameWithOwner: "octocat/t3code",
32 url: "https://github.com/octocat/t3code",
33 sshUrl: "git@github.com:octocat/t3code.git",
34 };
35
36 function makeProvider(
37 overrides: Partial<SourceControlProvider.SourceControlProvider["Service"]> = {},
38 ): SourceControlProvider.SourceControlProvider["Service"] {
39 const unsupported = (operation: string) =>
40 Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
41 never,
42 SourceControlProviderError
43 >;
44
45 return {
46 kind: SourceControlProviderKind.make("github"),
47 listChangeRequests: () => unsupported("listChangeRequests"),
48 getChangeRequest: () => unsupported("getChangeRequest"),
49 createChangeRequest: () => unsupported("createChangeRequest"),
50 getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
51 createRepository: () => Effect.succeed(CLONE_URLS),
52 getDefaultBranch: () => Effect.succeed(null),
53 checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
54 ...overrides,
55 };
56 }
57
58 function processOutput(): GitVcsDriver.ExecuteGitResult {
59 return {
60 exitCode: ChildProcessSpawner.ExitCode(0),
61 stdout: "",
62 stderr: "",
63 stdoutTruncated: false,
64 stderrTruncated: false,
65 };
66 }
67
68 function layer(input: {
69 readonly provider?: SourceControlProvider.SourceControlProvider["Service"];
70 readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
71 readonly fileSystem?: FileSystem.FileSystem;
72 }) {
73 const layerService = SourceControlRepositoryService.layer.pipe(
74 Layer.provide(
75 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
76 resolveLink: () => undefined,
77 get: () => Effect.succeed(input.provider ?? makeProvider()),
78 }),
79 ),
80 Layer.provide(
81 Layer.mock(GitVcsDriver.GitVcsDriver)({
82 execute: () => Effect.succeed(processOutput()),
83 invalidateRefs: () => Effect.void,
84 ensureRemote: () => Effect.succeed("origin"),
85 pushCurrentBranch: () =>
86 Effect.succeed({
87 status: "pushed" as const,
88 branch: "feature/remote-v1",
89 upstreamBranch: "origin/feature/remote-v1",
90 setUpstream: true,
91 }),
92 ...input.git,
93 }),
94 ),
95 Layer.provide(
96 ServerConfig.layerTest(
97 process.cwd(),
98 input.fileSystem ? "/tmp/t3-source-control-repos" : { prefix: "t3-source-control-repos-" },
99 ),
100 ),
101 );
102
103 return input.fileSystem
104 ? layerService.pipe(
105 Layer.provide(Layer.succeed(FileSystem.FileSystem, input.fileSystem)),
106 Layer.provideMerge(NodePath.layer),
107 )
108 : layerService.pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
109 }
110
111 const lookupFailingWith = (cause: unknown, detail: string) =>
112 Effect.gen(function* () {
113 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
114 return yield* service
115 .lookupRepository({ provider: SourceControlProviderKind.make("bitbucket"), repository: "x" })
116 .pipe(Effect.flip);
117 }).pipe(
118 Effect.provide(
119 layer({
120 provider: makeProvider({
121 getRepositoryCloneUrls: (input) =>
122 Effect.fail(
123 new SourceControlProviderError({
124 provider: SourceControlProviderKind.make("bitbucket"),
125 operation: "getRepositoryCloneUrls",
126 cwd: input.cwd,
127 detail,
128 cause,
129 }),
130 ),
131 }),
132 }),
133 ),
134 );
135
136 it.effect("tells the user a host's fixed explanation of a failed repository lookup", () =>
137 Effect.gen(function* () {
138 const error = yield* lookupFailingWith(
139 { userFacingDetail: "Repositories are named workspace/repository." },
140 "Repositories are named workspace/repository.",
141 );
142 assert.strictEqual(error.detail, "Repositories are named workspace/repository.");
143 }),
144 );
145
146 it.effect("keeps a host's raw response text out of a failed repository lookup", () =>
147 Effect.gen(function* () {
148 const error = yield* lookupFailingWith(
149 new Error("upstream"),
150 "<html>internal token=abc</html>",
151 );
152 assert.strictEqual(error.detail, "The source control operation could not be completed.");
153 }),
154 );
155
156 it.effect("clones a looked-up repository after creating missing parent directories", () =>
157 Effect.gen(function* () {
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
161 prefix: "t3-source-control-clone-parent-",
162 });
163 const parent = path.join(temporaryDirectory, "missing", "nested");
164 const destinationPath = path.join(parent, "t3code");
165 const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
166
167 yield* Effect.gen(function* () {
168 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
169 const result = yield* service.cloneRepository({
170 provider: SourceControlProviderKind.make("github"),
171 repository: "octocat/t3code",
172 destinationPath,
173 protocol: "https",
174 });
175
176 assert.deepStrictEqual(result, {
177 cwd: destinationPath,
178 remoteUrl: CLONE_URLS.url,
179 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
180 });
181 assert.deepStrictEqual(cloneCalls, [
182 {
183 cwd: parent,
184 args: ["clone", "--progress", "--", CLONE_URLS.url, "t3code"],
185 },
186 ]);
187 }).pipe(
188 Effect.provide(
189 layer({
190 git: {
191 execute: (input) =>
192 Effect.gen(function* () {
193 assert.isTrue(yield* fs.exists(parent).pipe(Effect.orDie));
194 cloneCalls.push({ cwd: input.cwd, args: input.args });
195 return processOutput();
196 }),
197 },
198 }),
199 ),
200 );
201 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
202 );
203
204 it.effect.each(["--bare", "source.git"])(
205 "clones a local repository named %s as a working tree",
206 (repositoryName) =>
207 Effect.gen(function* () {
208 const fs = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const git = yield* GitVcsDriver.GitVcsDriver;
211 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-options-" });
212 yield* git.execute({
213 operation: "test.init",
214 cwd: parent,
215 args: ["init", "--bare", path.join(parent, repositoryName)],
216 });
217 const destinationPath = path.join(parent, "checkout");
218 yield* Effect.gen(function* () {
219 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
220 const result = yield* service.cloneRepository({
221 remoteUrl: repositoryName,
222 destinationPath,
223 });
224 assert.strictEqual(result.cwd, destinationPath);
225 assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git")));
226 }).pipe(Effect.provide(layer({ git })));
227 }).pipe(
228 Effect.provide(
229 GitVcsDriver.layer.pipe(
230 Layer.provide(
231 ServerConfig.layerTest(process.cwd(), {
232 prefix: "t3-clone-options-config-",
233 }),
234 ),
235 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
236 ),
237 ),
238 ),
239 );
240
241 it.effect.each([
242 { readsWhen: "before git creates the repository", readBeforeInit: true },
243 { readsWhen: "while HEAD is unborn", readBeforeInit: false },
244 ])("lists the cloned branches after a ref list was read $readsWhen", ({ readBeforeInit }) =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const git = yield* GitVcsDriver.GitVcsDriver;
249 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-refs-" });
250 const source = path.join(parent, "source");
251 const destinationPath = path.join(parent, "checkout");
252 const run = (cwd: string, args: ReadonlyArray<string>) =>
253 git.execute({ operation: "test.git", cwd, args });
254 yield* run(parent, ["init", "--initial-branch=staging", source]);
255 yield* run(source, [
256 "-c",
257 "user.name=Test",
258 "-c",
259 "user.email=test@example.com",
260 "commit",
261 "--allow-empty",
262 "-m",
263 "init",
264 ]);
265 const refNames = git
266 .listRefs({ cwd: destinationPath })
267 .pipe(Effect.map((result) => result.refs.map((ref) => ref.name)));
268 let duringClone: ReadonlyArray<string> | null = null;
269 // Stands in for git clone so the read lands at a chosen point inside it.
270 const cloneInTwoSteps = Effect.gen(function* () {
271 yield* fs.makeDirectory(destinationPath).pipe(Effect.orDie);
272 if (readBeforeInit) duringClone = yield* refNames;
273 yield* run(parent, ["init", "--initial-branch=staging", destinationPath]);
274 if (!readBeforeInit) duringClone = yield* refNames;
275 return yield* run(destinationPath, ["pull", source, "staging"]);
276 });
277 yield* Effect.gen(function* () {
278 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
279 yield* service.cloneRepository({ remoteUrl: source, destinationPath });
280 }).pipe(
281 Effect.provide(
282 layer({
283 git: {
284 ...git,
285 execute: (input) => (input.args[0] === "clone" ? cloneInTwoSteps : git.execute(input)),
286 },
287 }),
288 ),
289 );
290
291 assert.deepStrictEqual(duringClone, []);
292 assert.deepStrictEqual(yield* refNames, ["staging"]);
293 }).pipe(
294 Effect.provide(
295 GitVcsDriver.layer.pipe(
296 Layer.provide(
297 ServerConfig.layerTest(process.cwd(), {
298 prefix: "t3-clone-refs-config-",
299 }),
300 ),
301 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
302 ),
303 ),
304 ),
305 );
306
307 it.effect("reports clone progress from git's stderr and keeps its error text on failure", () =>
308 Effect.gen(function* () {
309 const fs = yield* FileSystem.FileSystem;
310 const path = yield* Path.Path;
311 const parent = yield* fs.makeTempDirectoryScoped({
312 prefix: "t3-source-control-clone-progress-",
313 });
314 const destinationPath = path.join(parent, "t3code");
315 const progress: Array<{ stage: string; percent: number | null; detail: string | null }> = [];
316
317 const stderrLines = [
318 "Cloning into 't3code'...",
319 "remote: Enumerating objects: 10, done.",
320 "Receiving objects: 40% (4/10), 1.00 MiB | 2.00 MiB/s",
321 "Receiving objects: 100% (10/10), 2.50 MiB | 2.00 MiB/s, done.",
322 "fatal: early EOF",
323 "fatal: unable to access 'https://user:s3c@ret@github.com/octocat/t3code.git/': could not resolve host",
324 ];
325 const error = yield* Effect.gen(function* () {
326 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
327 return yield* Effect.flip(
328 service.cloneRepository(
329 { remoteUrl: CLONE_URLS.sshUrl, destinationPath },
330 { onProgress: (line) => Effect.sync(() => void progress.push(line)) },
331 ),
332 );
333 }).pipe(
334 Effect.provide(
335 layer({
336 git: {
337 execute: (input) =>
338 Effect.gen(function* () {
339 for (const line of stderrLines) {
340 yield* input.progress?.onStderrLine?.(line) ?? Effect.void;
341 }
342 return yield* new GitCommandError({
343 operation: input.operation,
344 command: "git",
345 cwd: input.cwd,
346 detail: "Git command exited with a non-zero status.",
347 exitCode: 128,
348 });
349 }),
350 },
351 }),
352 ),
353 );
354
355 assert.deepStrictEqual(progress, [
356 { stage: "counting", percent: null, detail: null },
357 { stage: "receiving", percent: 40, detail: "1.00 MiB | 2.00 MiB/s" },
358 { stage: "receiving", percent: 100, detail: "2.50 MiB | 2.00 MiB/s" },
359 ]);
360 assert.strictEqual(
361 error.detail,
362 "fatal: early EOF fatal: unable to access 'https://github.com/octocat/t3code.git/': could not resolve host",
363 );
364 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
365 );
366
367 it.effect("reports a Git LFS download as progress only while its partial files change", () =>
368 Effect.gen(function* () {
369 const fs = yield* FileSystem.FileSystem;
370 const path = yield* Path.Path;
371 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-clone-lfs-" });
372 const destinationPath = path.join(parent, "t3code");
373 const incomplete = path.join(destinationPath, ".git", "lfs", "incomplete");
374 const progress = yield* Queue.unbounded<GitCloneProgressLine>();
375 const firstDownloading = yield* Deferred.make<void>();
376 const firstLanded = yield* Deferred.make<void>();
377 const secondDownloading = yield* Deferred.make<void>();
378 const secondLanded = yield* Deferred.make<void>();
379 const filtering = "Filtering content: 50% (1/2), 1.50 MiB | 1.00 MiB/s";
380
381 const clone = yield* Effect.gen(function* () {
382 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
383 return yield* service.cloneRepository(
384 { remoteUrl: CLONE_URLS.url, destinationPath },
385 { onProgress: (line) => Queue.offer(progress, line), timeoutMs: null },
386 );
387 }).pipe(
388 Effect.provide(
389 layer({
390 git: {
391 execute: (input) =>
392 Effect.gen(function* () {
393 yield* (
394 input.progress?.onStderrLine?.("Updating files: 100% (3/3), done.") ?? Effect.void
395 );
396 yield* fs.makeDirectory(incomplete, { recursive: true });
397 yield* fs.writeFile(path.join(incomplete, "a.part"), new Uint8Array(1536 * 1024));
398 yield* Deferred.succeed(firstDownloading, undefined);
399 yield* Deferred.await(firstLanded);
400 yield* fs.remove(path.join(incomplete, "a.part"));
401 yield* fs.writeFile(path.join(incomplete, "b.part"), new Uint8Array(512 * 1024));
402 yield* input.progress?.onStderrLine?.(filtering) ?? Effect.void;
403 yield* Deferred.succeed(secondDownloading, undefined);
404 yield* Deferred.await(secondLanded);
405 yield* fs.remove(path.join(incomplete, "b.part"));
406 return processOutput();
407 }).pipe(Effect.orDie),
408 },
409 }),
410 ),
411 Effect.forkChild,
412 );
413
414 yield* Deferred.await(firstDownloading);
415 yield* TestClock.adjust("2 seconds");
416 assert.deepStrictEqual(yield* Queue.takeN(progress, 2), [
417 { stage: "checkout", percent: 100, detail: null },
418 {
419 stage: "checkout",
420 percent: null,
421 detail: "Downloading Git LFS objects: 1.5 MiB in progress",
422 },
423 ]);
424
425 yield* Deferred.succeed(firstLanded, undefined);
426 yield* Deferred.await(secondDownloading);
427 yield* TestClock.adjust("2 seconds");
428 assert.deepStrictEqual(yield* Queue.takeN(progress, 2), [
429 { stage: "checkout", percent: 50, detail: "1.50 MiB | 1.00 MiB/s" },
430 {
431 stage: "checkout",
432 percent: 50,
433 detail: "Downloading Git LFS objects: 0.5 MiB in progress",
434 },
435 ]);
436
437 // The second object stops growing: a transfer that really stalled must stay silent.
438 yield* TestClock.adjust("2 seconds");
439 yield* Deferred.succeed(secondLanded, undefined);
440 yield* Fiber.join(clone);
441 assert.strictEqual(yield* Queue.size(progress), 0);
442 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
443 );
444
445 it.effect("says a clone that ran out of time timed out, not git's last remote line", () =>
446 Effect.gen(function* () {
447 const fs = yield* FileSystem.FileSystem;
448 const path = yield* Path.Path;
449 const parent = yield* fs.makeTempDirectoryScoped({
450 prefix: "t3-source-control-clone-timeout-",
451 });
452 const started = yield* Deferred.make<void>();
453 const clone = yield* Effect.gen(function* () {
454 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
455 return yield* Effect.flip(
456 service.cloneRepository({
457 remoteUrl: CLONE_URLS.url,
458 destinationPath: path.join(parent, "t3code"),
459 }),
460 );
461 }).pipe(
462 Effect.provide(
463 layer({
464 git: {
465 // Like the real driver: the transfer outlives its deadline and git's last line is
466 // a remote summary.
467 execute: (input) =>
468 Effect.gen(function* () {
469 yield* (
470 input.progress?.onStderrLine?.(
471 "remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0",
472 ) ?? Effect.void
473 );
474 yield* Deferred.succeed(started, undefined);
475 return yield* Effect.never;
476 }).pipe(
477 Effect.timeoutOrElse({
478 duration: input.timeoutMs ?? Infinity,
479 orElse: () =>
480 Effect.fail(
481 new GitCommandError({
482 operation: input.operation,
483 command: "git",
484 cwd: input.cwd,
485 detail: "Git command timed out.",
486 }),
487 ),
488 }),
489 ),
490 },
491 }),
492 ),
493 Effect.forkChild,
494 );
495
496 yield* Deferred.await(started);
497 yield* TestClock.adjust("2 minutes");
498 const error = yield* Fiber.join(clone);
499
500 assert.match(error.detail, /timed out/i);
501 }).pipe(Effect.provide(NodeServices.layer)),
502 );
503
504 function rejectingSsh(
505 urls: Array<string>,
506 httpsFails: boolean,
507 reason: GitCommandError["reason"] = "authentication_failed",
508 ) {
509 return {
510 execute: (input: GitVcsDriver.ExecuteGitInput) =>
511 Effect.gen(function* () {
512 const url = input.args.at(-2)!;
513 urls.push(url);
514 if (url.startsWith("https://") && !httpsFails) return processOutput();
515 yield* (
516 input.progress?.onStderrLine?.(
517 url.startsWith("https://")
518 ? "fatal: could not read Username for 'https://github.com': terminal prompts disabled"
519 : "git@github.com: Permission denied (publickey).",
520 ) ?? Effect.void
521 );
522 return yield* new GitCommandError({
523 operation: input.operation,
524 command: "git",
525 cwd: input.cwd,
526 reason,
527 detail: "Git command exited with a non-zero status.",
528 });
529 }),
530 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
531 }
532
533 const cloneInTemporaryDirectory = (
534 git: Partial<GitVcsDriver.GitVcsDriver["Service"]>,
535 input: Omit<SourceControlCloneRepositoryInput, "destinationPath">,
536 ) =>
537 Effect.gen(function* () {
538 const fs = yield* FileSystem.FileSystem;
539 const path = yield* Path.Path;
540 const parent = yield* fs
541 .makeTempDirectoryScoped({ prefix: "t3-clone-fallback-" })
542 .pipe(Effect.orDie);
543 return yield* Effect.gen(function* () {
544 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
545 return yield* service.cloneRepository({
546 ...input,
547 destinationPath: path.join(parent, "t3code"),
548 });
549 }).pipe(Effect.provide(layer({ git }).pipe(Layer.orDie)));
550 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
551
552 it.effect("retries a clone over HTTPS when the SSH login is refused", () =>
553 Effect.gen(function* () {
554 const urls: Array<string> = [];
555 const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), {
556 remoteUrl: CLONE_URLS.sshUrl,
557 });
558
559 assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl, "https://github.com/octocat/t3code.git"]);
560 assert.strictEqual(result.remoteUrl, "https://github.com/octocat/t3code.git");
561 }),
562 );
563
564 it.effect("reports both failures when the HTTPS retry fails too", () =>
565 Effect.gen(function* () {
566 const urls: Array<string> = [];
567 const error = yield* Effect.flip(
568 cloneInTemporaryDirectory(rejectingSsh(urls, true), { remoteUrl: CLONE_URLS.sshUrl }),
569 );
570
571 assert.strictEqual(urls.length, 2);
572 assert.strictEqual(
573 error.detail,
574 "git@github.com: Permission denied (publickey). Cloning over HTTPS instead also failed: fatal: could not read Username for 'https://github.com': terminal prompts disabled",
575 );
576 }),
577 );
578
579 it.effect.each([
580 "git@ssh.dev.azure.com:v3/Fabrikam/Project1/fab_repo",
581 "ssh://user:pa@rt@ssh.dev.azure.com/v3/Fabrikam/Project1/fab_repo",
582 "ssh://us%40er:pa%40ss@ssh.dev.azure.com/v3/Fabrikam/Project1/fab_repo",
583 ])("retries Azure SSH URL %s using its HTTPS host and repository path", (remoteUrl) =>
584 Effect.gen(function* () {
585 const urls: Array<string> = [];
586 const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), {
587 remoteUrl,
588 });
589
590 assert.deepStrictEqual(urls, [
591 remoteUrl,
592 "https://dev.azure.com/Fabrikam/Project1/_git/fab_repo",
593 ]);
594 assert.strictEqual(result.remoteUrl, "https://dev.azure.com/Fabrikam/Project1/_git/fab_repo");
595 }),
596 );
597
598 it.effect.each([
599 ["the caller asked for SSH", "ssh", "authentication_failed"],
600 ["git failed for another reason", undefined, "remote_unreachable"],
601 ] as const)("does not retry over HTTPS when %s", ([, protocol, reason]) =>
602 Effect.gen(function* () {
603 const urls: Array<string> = [];
604 yield* Effect.flip(
605 cloneInTemporaryDirectory(rejectingSsh(urls, false, reason), {
606 remoteUrl: CLONE_URLS.sshUrl,
607 ...(protocol === undefined ? {} : { protocol }),
608 }),
609 );
610
611 assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl]);
612 }),
613 );
614
615 it.effect.each([
616 ["a plain token", "s3cret"],
617 ["a token with an apostrophe", "s3'cret"],
618 ["a token with a double quote", 's3"cret'],
619 ["a host-only token with an at sign", "abc@secret"],
620 ["an unquoted token with an apostrophe", "s3'cret", true],
621 ["an unquoted token with a double quote", 's3"cret', true],
622 ["an unquoted URL with an apostrophe in its path", "path-token", true],
623 ] as const)("keeps %s in the query out of a failed clone's error text", ([, token, unquoted]) =>
624 Effect.gen(function* () {
625 const remote =
626 token === "abc@secret"
627 ? "https://github.com"
628 : token === "path-token"
629 ? "https://github.com/octocat/t3code's.git"
630 : "https://github.com/octocat/t3code.git";
631 const error = yield* Effect.flip(
632 cloneInTemporaryDirectory(
633 {
634 execute: (input) =>
635 Effect.gen(function* () {
636 const cloneUrl = input.args.at(-2)!;
637 // Git treats @ in a pathless URL's query as userinfo, losing the query delimiter.
638 const diagnosticUrl =
639 cloneUrl === "https://github.com?access_token=abc@secret"
640 ? "https://secret"
641 : cloneUrl;
642 yield* (
643 input.progress?.onStderrLine?.(
644 unquoted
645 ? `fatal: ${diagnosticUrl}/info/refs not valid: is this a git repository?`
646 : `fatal: unable to access '${diagnosticUrl}/': Could not resolve host: github.com`,
647 ) ?? Effect.void
648 );
649 return yield* new GitCommandError({
650 operation: input.operation,
651 command: "git",
652 cwd: input.cwd,
653 detail: "Git command exited with a non-zero status.",
654 exitCode: 128,
655 });
656 }),
657 },
658 { remoteUrl: `${remote}?access_token=${token}` },
659 ),
660 );
661
662 assert.strictEqual(
663 error.detail,
664 unquoted
665 ? `fatal: ${remote} not valid: is this a git repository?`
666 : `fatal: unable to access '${remote}${token === "abc@secret" ? "/" : ""}': Could not resolve host: github.com`,
667 );
668 }),
669 );
670
671 it.effect("strips embedded credentials from the remote URL it reports", () =>
672 Effect.gen(function* () {
673 const fs = yield* FileSystem.FileSystem;
674 const path = yield* Path.Path;
675 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact-" });
676 const destinationPath = path.join(parent, "t3code");
677 const cloneArgs: Array<ReadonlyArray<string>> = [];
678 const result = yield* Effect.gen(function* () {
679 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
680 return yield* service.prepareClone({
681 remoteUrl: "https://user:s3cret@github.com/octocat/t3code.git",
682 destinationPath,
683 });
684 }).pipe(
685 Effect.provide(
686 layer({
687 git: {
688 execute: (input) =>
689 Effect.sync(() => {
690 cloneArgs.push(input.args);
691 return processOutput();
692 }),
693 },
694 }),
695 ),
696 );
697 assert.equal(result.remoteUrl, "https://github.com/octocat/t3code.git");
698 assert.equal(result.cloneUrl, "https://user:s3cret@github.com/octocat/t3code.git");
699 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
700 );
701
702 it.effect("discards only a directory git wrote to", () =>
703 Effect.gen(function* () {
704 const fs = yield* FileSystem.FileSystem;
705 const path = yield* Path.Path;
706 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-discard-" });
707 const partial = path.join(parent, "partial");
708 yield* fs.makeDirectory(path.join(partial, ".git"), { recursive: true });
709 yield* fs.writeFileString(path.join(partial, "README.md"), "half");
710 const foreign = path.join(parent, "foreign");
711 yield* fs.makeDirectory(foreign);
712 yield* fs.writeFileString(path.join(foreign, "notes.txt"), "mine");
713
714 const replaced = path.join(parent, "replaced");
715 yield* fs.writeFileString(replaced, "not a directory");
716
717 yield* Effect.gen(function* () {
718 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
719 yield* service.discardClone(partial);
720 const error = yield* Effect.flip(service.discardClone(foreign));
721 assert.include(error.detail, "not from the clone");
722 const replacedError = yield* Effect.flip(service.discardClone(replaced));
723 assert.include(replacedError.detail, "could not be inspected");
724 yield* service.discardClone(path.join(parent, "missing"));
725 }).pipe(Effect.provide(layer({})));
726
727 assert.deepStrictEqual(yield* fs.readDirectory(partial), []);
728 assert.deepStrictEqual(yield* fs.readDirectory(foreign), ["notes.txt"]);
729 assert.strictEqual(yield* fs.readFileString(replaced), "not a directory");
730 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
731 );
732
733 it.effect("redacts query tokens and userinfo containing '@' from reported URLs", () =>
734 Effect.gen(function* () {
735 const fs = yield* FileSystem.FileSystem;
736 const path = yield* Path.Path;
737 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-redact2-" });
738 yield* Effect.gen(function* () {
739 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
740 const query = yield* service.prepareClone({
741 remoteUrl: "https://github.com/octocat/t3code.git?access_token=s3cret",
742 destinationPath: path.join(parent, "a"),
743 });
744 assert.equal(query.remoteUrl, "https://github.com/octocat/t3code.git");
745 const nested = yield* service.prepareClone({
746 remoteUrl: "https://user:pa@rt@github.com/octocat/t3code.git",
747 destinationPath: path.join(parent, "b"),
748 });
749 assert.equal(nested.remoteUrl, "https://github.com/octocat/t3code.git");
750 }).pipe(Effect.provide(layer({})));
751 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
752 );
753
754 it.effect("preserves destination probe failures instead of treating them as missing paths", () => {
755 const fileSystemCause = PlatformError.systemError({
756 _tag: "PermissionDenied",
757 module: "FileSystem",
758 method: "exists",
759 pathOrDescriptor: "/restricted/t3code",
760 });
761
762 return Effect.gen(function* () {
763 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
764 const error = yield* Effect.flip(
765 service.cloneRepository({
766 remoteUrl: CLONE_URLS.sshUrl,
767 destinationPath: "/restricted/t3code",
768 }),
769 );
770
771 assert.strictEqual(error.provider, "unknown");
772 assert.strictEqual(error.operation, "cloneRepository");
773 assert.strictEqual(error.cause, fileSystemCause);
774 }).pipe(
775 Effect.provide(
776 layer({
777 fileSystem: FileSystem.makeNoop({
778 exists: () => Effect.fail(fileSystemCause),
779 makeDirectory: () => Effect.void,
780 }),
781 }),
782 ),
783 );
784 });
785
786 it.effect("publishes to the remote name returned by ensureRemote", () => {
787 const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
788
789 return Effect.gen(function* () {
790 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
791 const result = yield* service.publishRepository({
792 cwd: "/workspace",
793 provider: SourceControlProviderKind.make("github"),
794 repository: "octocat/t3code",
795 visibility: "private",
796 remoteName: "origin",
797 protocol: "ssh",
798 });
799
800 assert.equal(result.remoteName, "origin-1");
801 assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
802 }).pipe(
803 Effect.provide(
804 layer({
805 git: {
806 ensureRemote: () => Effect.succeed("origin-1"),
807 pushCurrentBranch: (cwd, _fallbackBranch, options) =>
808 Effect.sync(() => {
809 pushCalls.push({ cwd, remoteName: options?.remoteName });
810 return {
811 status: "pushed" as const,
812 branch: "feature/remote-v1",
813 upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
814 setUpstream: true,
815 };
816 }),
817 },
818 }),
819 ),
820 );
821 });
822
823 function failingPush(reason?: GitCommandError["reason"]) {
824 return {
825 pushCurrentBranch: (cwd: string) =>
826 Effect.fail(
827 new GitCommandError({
828 operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",
829 command: "git",
830 cwd,
831 ...(reason === undefined ? {} : { reason }),
832 detail: "Git command exited with a non-zero status.",
833 }),
834 ),
835 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
836 }
837
838 it.effect("explains a rejected SSH push after creating the repository", () =>
839 Effect.gen(function* () {
840 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
841 const error = yield* Effect.flip(
842 service.publishRepository({
843 cwd: "/workspace",
844 provider: SourceControlProviderKind.make("github"),
845 repository: "octocat/t3code",
846 visibility: "private",
847 protocol: "ssh",
848 }),
849 );
850
851 assert.strictEqual(error.operation, "publishRepository");
852 assert.strictEqual(
853 error.detail,
854 'Created octocat/t3code and added it as remote "origin", but the push failed because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "git remote set-url origin https://github.com/octocat/t3code", then push again.',
855 );
856 assert.instanceOf(error.cause, GitCommandError);
857 }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))),
858 );
859
860 // regression: an auto-selected SSH remote kept failing every later fetch after a refused push
861 it.effect("switches an auto-selected remote to HTTPS when the SSH push is refused", () => {
862 const gitArgs: Array<ReadonlyArray<string>> = [];
863 let pushAttempts = 0;
864 return Effect.gen(function* () {
865 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
866 const result = yield* service.publishRepository({
867 cwd: "/workspace",
868 provider: SourceControlProviderKind.make("github"),
869 repository: "octocat/t3code",
870 visibility: "private",
871 });
872
873 assert.strictEqual(result.status, "pushed");
874 assert.strictEqual(result.remoteUrl, CLONE_URLS.url);
875 assert.strictEqual(pushAttempts, 2);
876 assert.deepStrictEqual(gitArgs, [
877 ["rev-parse", "--verify", "HEAD"],
878 ["remote", "set-url", "origin", CLONE_URLS.url],
879 ]);
880 }).pipe(
881 Effect.provide(
882 layer({
883 git: {
884 execute: (input) =>
885 Effect.sync(() => {
886 gitArgs.push(input.args);
887 return processOutput();
888 }),
889 pushCurrentBranch: (cwd) => {
890 pushAttempts += 1;
891 return pushAttempts === 1
892 ? failingPush("authentication_failed").pushCurrentBranch(cwd)
893 : Effect.succeed({
894 status: "pushed" as const,
895 branch: "main",
896 upstreamBranch: "origin/main",
897 setUpstream: true,
898 });
899 },
900 },
901 }),
902 ),
903 );
904 });
905
906 // regression: #19219 publishing did not explain why the first push failed
907 it.effect("says the repository exists when an unclassified publish push fails", () =>
908 Effect.gen(function* () {
909 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
910 const error = yield* Effect.flip(
911 service.publishRepository({
912 cwd: "/workspace",
913 provider: SourceControlProviderKind.make("github"),
914 repository: "octocat/t3code",
915 visibility: "private",
916 protocol: "https",
917 }),
918 );
919
920 assert.strictEqual(
921 error.detail,
922 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.',
923 );
924 }).pipe(Effect.provide(layer({ git: failingPush() }))),
925 );
926
927 it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
928 let pushCalls = 0;
929 return Effect.gen(function* () {
930 const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
931 const result = yield* service.publishRepository({
932 cwd: "/workspace",
933 provider: SourceControlProviderKind.make("github"),
934 repository: "octocat/t3code",
935 visibility: "private",
936 remoteName: "origin",
937 protocol: "ssh",
938 });
939
940 assert.deepStrictEqual(result, {
941 repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS },
942 remoteName: "origin",
943 remoteUrl: CLONE_URLS.sshUrl,
944 branch: "main",
945 status: "remote_added",
946 });
947 assert.strictEqual(pushCalls, 0);
948 }).pipe(
949 Effect.provide(
950 layer({
951 git: {
952 execute: (input) =>
953 input.args[0] === "rev-parse"
954 ? Effect.fail(
955 new GitCommandError({
956 operation: input.operation,
957 command: "git rev-parse --verify HEAD",
958 cwd: input.cwd,
959 detail: "fatal: Needed a single revision",
960 }),
961 )
962 : Effect.succeed(processOutput()),
963 statusDetails: () =>
964 Effect.succeed({
965 isRepo: true,
966 hasOriginRemote: true,
967 isDefaultBranch: true,
968 branch: "main",
969 upstreamRef: null,
970 hasWorkingTreeChanges: false,
971 workingTree: { files: [], insertions: 0, deletions: 0 },
972 hasUpstream: false,
973 aheadCount: 0,
974 behindCount: 0,
975 aheadOfDefaultCount: 0,
976 }),
977 pushCurrentBranch: () =>
978 Effect.sync(() => {
979 pushCalls += 1;
980 return {
981 status: "pushed" as const,
982 branch: "main",
983 upstreamBranch: "origin/main",
984 setUpstream: true,
985 };
986 }),
987 },
988 }),
989 ),
990 );
991 });