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

main
ts 1,342 lines 44.6 KB
Raw
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import * as HostProcess from "@t3tools/shared/HostProcess";
3 import { assert, describe, it } from "@effect/vitest";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as Redacted from "effect/Redacted";
11 import * as Schema from "effect/Schema";
12 import { HttpClient, HttpClientResponse } from "effect/http";
13 import { ChildProcessSpawner } from "effect/process";
14 import * as TestClock from "effect/testing/TestClock";
15 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
16
17 import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
18 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
19 import * as GitHubRest from "./GitHubRest.ts";
20 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
21 import * as GitHubCredentials from "./GitHubCredentials.ts";
22 import * as GitHubQuota from "./GitHubQuota.ts";
23 import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
24 import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
25 import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
26
27 const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
28 enabled: false,
29 token: () => Effect.succeedNone,
30 invalidate: () => Effect.void,
31 });
32
33 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
34
35 const processResult = (
36 stdout: string,
37 options?: {
38 readonly stderr?: string;
39 readonly exitCode?: ChildProcessSpawner.ExitCode;
40 },
41 ): SourceControlHost.SourceControlProcessOutput => ({
42 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
43 stdout,
44 stderr: options?.stderr ?? "",
45 stdoutTruncated: false,
46 stderrTruncated: false,
47 });
48
49 const processOutput = (
50 stdout: string,
51 exitCode = 0,
52 ): SourceControlHost.SourceControlProcessOutput => ({
53 exitCode: ChildProcessSpawner.ExitCode(exitCode),
54 stdout,
55 stderr: "",
56 stdoutTruncated: false,
57 stderrTruncated: false,
58 });
59
60 const remotesOutput = (...entries: ReadonlyArray<readonly [string, string]>) =>
61 entries
62 .flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
63 .join("\n");
64
65 const restResponse = (body: unknown, status = 200): GitHubRest.GitHubRestResponse => ({
66 status,
67 headers: {},
68 body: body === undefined ? "" : encodeJson(body),
69 truncated: false,
70 invalidUtf8: false,
71 });
72
73 const node = (number: number, headRefName: string, owner = "acme") => ({
74 number,
75 title: `PR ${number}`,
76 url: `https://github.com/acme/web/pull/${number}`,
77 baseRefName: "main",
78 headRefName,
79 headRefOid: "f".repeat(40),
80 state: "OPEN",
81 isDraft: false,
82 mergedAt: null,
83 closedAt: null,
84 isCrossRepository: owner !== "acme",
85 updatedAt: "2026-01-02T00:00:00Z",
86 headRepository: { name: "web", nameWithOwner: `${owner}/web` },
87 headRepositoryOwner: { __typename: "User", login: owner },
88 });
89
90 interface GraphQlCall {
91 readonly host: string;
92 readonly operationName: string;
93 readonly query: string;
94 readonly lookups: ReadonlyArray<Readonly<Record<string, unknown>>>;
95 }
96
97 type GraphQlAnswer = unknown;
98 type GraphQlRespond = (
99 lookup: Readonly<Record<string, unknown>>,
100 call: GraphQlCall,
101 ) => GraphQlAnswer | Response;
102
103 function graphQlHttp(respond: GraphQlRespond, calls: Array<GraphQlCall>) {
104 return HttpClient.make((request) =>
105 Effect.sync(() => {
106 const sent =
107 request.body._tag === "Uint8Array"
108 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
109 readonly query: string;
110 readonly operationName: string;
111 readonly variables: Readonly<Record<string, unknown>>;
112 })
113 : { query: "", operationName: "", variables: {} };
114 const prefixes = [
115 ...new Set(Object.keys(sent.variables).flatMap((key) => /^_\d+_/.exec(key) ?? [])),
116 ];
117 const lookups =
118 prefixes.length === 0
119 ? [sent.variables]
120 : prefixes.map((prefix) =>
121 Object.fromEntries(
122 Object.entries(sent.variables)
123 .filter(([key]) => key.startsWith(prefix))
124 .map(([key, value]) => [key.slice(prefix.length), value]),
125 ),
126 );
127 const call: GraphQlCall = {
128 host: new URL(request.url).hostname.replace(/^api\./, ""),
129 operationName: sent.operationName,
130 query: sent.query,
131 lookups,
132 };
133 calls.push(call);
134 const answers = lookups.map((lookup) => respond(lookup, call));
135 const refusal = answers.find((answer) => answer instanceof Response);
136 const response =
137 refusal ??
138 new Response(
139 encodeJson({
140 data: Object.fromEntries(
141 answers.map((answer, index) => [
142 prefixes.length === 0 ? "repository" : `${prefixes[index]}repository`,
143 answer,
144 ]),
145 ),
146 }),
147 { headers: { "content-type": "application/json" } },
148 );
149 return HttpClientResponse.fromWeb(request, response);
150 }),
151 );
152 }
153
154 function harness(input: {
155 readonly remotes: string;
156 readonly api?: Partial<GitHubRest.GitHubRest["Service"]>;
157 readonly graphql?: GraphQlRespond;
158 readonly credential?: (
159 host: string,
160 ) => Effect.Effect<
161 GitHubCredentials.GitHubCredential,
162 GitHubCredentials.GitHubCredentialUnavailableError
163 >;
164 readonly localBranches?: ReadonlyArray<string>;
165 readonly resolved?: string;
166 readonly gitFailure?: unknown;
167 readonly originUrls?: string;
168 }) {
169 const git: Array<readonly [string, unknown]> = [];
170 const graphqlCalls: Array<GraphQlCall> = [];
171 const record =
172 <A>(name: string, value: A) =>
173 (args: unknown) =>
174 Effect.sync(() => {
175 git.push([name, args]);
176 return value;
177 });
178 const hostGit: Partial<SourceControlHost.SourceControlHost["Service"]["git"]> = {
179 execute: (args) =>
180 Effect.sync(() => {
181 git.push(["execute", args.args]);
182 return processOutput(
183 args.args[0] === "config" ? (input.originUrls ?? "git@github.com:acme/web.git\n") : "",
184 );
185 }),
186 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
187 readConfigValue: () => Effect.succeed("git@github.com:acme/web.git"),
188 ensureRemote: (args) =>
189 Effect.sync(() => {
190 git.push(["ensureRemote", args]);
191 return args.preferredName;
192 }),
193 fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),
194 setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),
195 createBranch: (args) => record("createBranch", undefined)(args),
196 writeConfigValue: (args) => record("writeConfigValue", undefined)(args),
197 switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,
198 listLocalBranchNames: () =>
199 input.gitFailure === undefined
200 ? Effect.succeed([...(input.localBranches ?? [])])
201 : Effect.fail(input.gitFailure as never),
202 resolveCommit: () => Effect.succeed({ commitSha: "abc123" }),
203 };
204 const host = TestSourceControlHost.layer({
205 git: hostGit,
206 process: {
207 run: (args) =>
208 Effect.succeed(
209 args.args[0] === "remote"
210 ? processOutput(input.remotes)
211 : processOutput(input.resolved ?? "", input.resolved ? 0 : 1),
212 ),
213 },
214 });
215 const graphql =
216 input.graphql ??
217 (() => {
218 throw new Error("Unexpected GraphQL read");
219 });
220 const policy = GitHubRequestPolicy.layer.pipe(
221 Layer.provide(
222 Layer.mergeAll(
223 Layer.succeed(GitHubCredentials.GitHubCredentials, {
224 get:
225 input.credential ??
226 ((host) =>
227 Effect.succeed({
228 host,
229 token: Redacted.make("token"),
230 source: "gh" as const,
231 fingerprint: `${host}:token`,
232 })),
233 saved: () => Effect.succeedNone,
234 fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
235 invalidate: () => Effect.void,
236 }),
237 GitHubQuota.layer,
238 SourceControlRateLimit.layer,
239 appSignedOut,
240 ),
241 ),
242 );
243 const layer = Layer.mergeAll(
244 host,
245 appSignedOut,
246 Layer.mock(GitHubRest.GitHubRest)(input.api ?? {}),
247 policy,
248 Layer.succeed(HttpClient.HttpClient, graphQlHttp(graphql, graphqlCalls)),
249 NodeServices.layer,
250 );
251 return { layer, git, graphqlCalls };
252 }
253
254 const makeProvider = (api: Partial<GitHubRest.GitHubRest["Service"]>) =>
255 GitHubSourceControlProvider.make.pipe(Effect.provide(harness({ remotes: "", api }).layer));
256
257 const githubContext = (host: string) => ({
258 provider: {
259 kind: SourceControlProviderKind.make("github"),
260 name: "GitHub",
261 baseUrl: `https://${host}`,
262 },
263 remoteName: "origin",
264 remoteUrl: `git@${host}:acme/web.git`,
265 });
266
267 describe("GitHubSourceControlProvider repository resolution", () => {
268 // regression: #38251 an Enterprise Server's hostname need not say "github"; a gh login vouches for it
269 it.effect.each([
270 ["github", "github"],
271 ["unknown", "unknown"],
272 ] as const)("refines a remote on an unknown host the gh login reads as %s", ([seen, expected]) =>
273 Effect.gen(function* () {
274 const provider = yield* makeProvider({});
275 const remoteUrl = "https://code.acme.test/acme/web.git";
276 const identity = {
277 canonicalKey: "code.acme.test/acme/web",
278 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
279 rootPath: "/repo",
280 provider: SourceControlProviderKind.make("unknown"),
281 };
282 const refined = yield* provider.refineRepositoryIdentity!({
283 identity,
284 resolveContext: ({ context }) =>
285 Effect.succeed({
286 ...context,
287 provider: { ...context.provider, kind: SourceControlProviderKind.make(seen) },
288 }),
289 });
290 assert.deepStrictEqual(refined, {
291 ...identity,
292 provider: SourceControlProviderKind.make(expected),
293 });
294 }),
295 );
296
297 it.effect("reads the repository gh would pick from the remotes", () => {
298 const paths: string[] = [];
299 const { layer } = harness({
300 remotes: remotesOutput(
301 ["origin", "git@github.com:me/web.git"],
302 ["upstream", "https://github.com/acme/web.git"],
303 ),
304 api: {
305 rest: (input) =>
306 Effect.sync(() => {
307 paths.push(`${input.host} ${input.path}`);
308 return restResponse({
309 full_name: "acme/web",
310 html_url: "https://github.com/acme/web",
311 ssh_url: "git@github.com:acme/web.git",
312 default_branch: "trunk",
313 });
314 }),
315 },
316 });
317 return Effect.gen(function* () {
318 const gh = yield* GitHubSourceControlProvider.make;
319 assert.strictEqual(yield* gh.getDefaultBranch({ cwd: "/repo" }), "trunk");
320 assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);
321 }).pipe(Effect.provide(layer));
322 });
323
324 it.effect("reads clone URLs on the given host before the checkout's", () => {
325 const paths: string[] = [];
326 const { layer } = harness({
327 remotes: remotesOutput(["origin", "https://github.com/acme/web.git"]),
328 api: {
329 rest: (input) =>
330 Effect.sync(() => {
331 paths.push(`${input.host} ${input.path}`);
332 return restResponse({
333 full_name: "acme/web",
334 html_url: `https://${input.host}/acme/web`,
335 ssh_url: `git@${input.host}:acme/web.git`,
336 });
337 }),
338 },
339 });
340 return Effect.gen(function* () {
341 const gh = yield* GitHubSourceControlProvider.make;
342 const cloneUrls = yield* gh.getRepositoryCloneUrls({
343 cwd: "/repo",
344 repository: "acme/web",
345 host: "GitHub.Enterprise.test",
346 });
347 yield* gh.getRepositoryCloneUrls({ cwd: "/repo", repository: "acme/web" });
348 assert.strictEqual(cloneUrls.url, "https://github.enterprise.test/acme/web");
349 assert.deepStrictEqual(paths, [
350 "github.enterprise.test repos/acme/web",
351 "github.com repos/acme/web",
352 ]);
353 }).pipe(Effect.provide(layer));
354 });
355
356 it.effect.each([
357 ["github", "git@github:acme/web.git"],
358 ["github.com-scale", "git@github.com-scale:acme/web.git"],
359 ["github.com-scale", "ssh://git@github.com-scale:22/acme/web.git"],
360 ] as const)("reads an SSH alias on %s through github.com (%s)", ([host, remoteUrl]) => {
361 const hosts: string[] = [];
362 const { layer } = harness({
363 remotes: remotesOutput(["origin", remoteUrl]),
364 api: {
365 rest: (input) =>
366 Effect.sync(() => {
367 hosts.push(`${input.host} ${input.path}`);
368 return restResponse({
369 full_name: "acme/web",
370 html_url: "https://github.com/acme/web",
371 ssh_url: "git@github.com:acme/web.git",
372 default_branch: "main",
373 });
374 }),
375 },
376 });
377 return Effect.gen(function* () {
378 const gh = yield* GitHubSourceControlProvider.make;
379 const resolveWebHost = gh.resolveRemoteWebHost;
380 assert.ok(resolveWebHost);
381 assert.strictEqual(
382 yield* resolveWebHost({
383 cwd: "/repo",
384 context: { ...githubContext(host), remoteUrl },
385 resolveContext: () => Effect.succeed(null),
386 }),
387 "github.com",
388 );
389 yield* gh.getDefaultBranch({ cwd: "/repo" });
390 yield* gh.getDefaultBranch({
391 cwd: "/repo",
392 context: { ...githubContext(host), remoteUrl },
393 });
394 assert.deepStrictEqual(hosts, ["github.com repos/acme/web", "github.com repos/acme/web"]);
395 }).pipe(Effect.provide(layer));
396 });
397
398 it.effect.each(["sole", "upstream", "missing"])(
399 "preserves an HTTPS context host with %s remotes",
400 (mode) => {
401 const paths: string[] = [];
402 const remoteUrl = "https://github.com-scale/me/web.git";
403 const { layer } = harness({
404 remotes:
405 mode === "missing"
406 ? ""
407 : remotesOutput(
408 ["origin", remoteUrl],
409 ...(mode === "upstream"
410 ? ([["upstream", "https://github.com/acme/web.git"]] as const)
411 : []),
412 ),
413 api: {
414 rest: (input) =>
415 Effect.sync(() => {
416 paths.push(`${input.host} ${input.path}`);
417 return restResponse({
418 full_name: "me/web",
419 html_url: "https://github.com-scale/me/web",
420 ssh_url: "git@github.com-scale:me/web.git",
421 default_branch: "trunk",
422 });
423 }),
424 },
425 });
426 return Effect.gen(function* () {
427 const gh = yield* GitHubSourceControlProvider.make;
428 const resolveWebHost = gh.resolveRemoteWebHost;
429 assert.ok(resolveWebHost);
430 for (const url of [remoteUrl, "git@github.com-evil.example:me/web.git"]) {
431 assert.strictEqual(
432 yield* resolveWebHost({
433 cwd: "/repo",
434 context: { ...githubContext("github.com-scale"), remoteUrl: url },
435 resolveContext: () => Effect.succeed(null),
436 }),
437 url === remoteUrl ? "github.com-scale" : "github.com-evil.example",
438 );
439 }
440 assert.strictEqual(
441 yield* gh.getDefaultBranch({
442 cwd: "/repo",
443 context: { ...githubContext("github.com-scale"), remoteUrl },
444 }),
445 "trunk",
446 );
447 assert.deepStrictEqual(paths, ["github.com-scale repos/me/web"]);
448 }).pipe(Effect.provide(layer));
449 },
450 );
451 });
452
453 describe("GitHubSourceControlProvider change request lookups by head", () => {
454 const remotes = remotesOutput(["origin", "git@github.com:acme/web.git"]);
455
456 it.effect("filters an owner:branch selector by owner through REST", () => {
457 const paths: string[] = [];
458 const restNode = (number: number, mergedAt: string | null) => ({
459 number,
460 title: `PR ${number}`,
461 html_url: `https://github.com/acme/web/pull/${number}`,
462 state: mergedAt === null ? "open" : "closed",
463 merged_at: mergedAt,
464 closed_at: mergedAt,
465 updated_at: "2026-01-02T00:00:00Z",
466 base: { ref: "main", repo: { full_name: "acme/web" } },
467 head: {
468 ref: "main",
469 sha: "f".repeat(40),
470 repo: { name: "web", full_name: "me/web", owner: { login: "me", type: "User" } },
471 },
472 });
473 const { layer, graphqlCalls } = harness({
474 remotes,
475 api: {
476 rest: (input) =>
477 Effect.sync(() => {
478 paths.push(input.path);
479 return restResponse([restNode(8, null), restNode(7, "2026-01-01T00:00:00Z")]);
480 }),
481 },
482 });
483 return Effect.gen(function* () {
484 const gh = yield* GitHubSourceControlProvider.make;
485 const probe = (ownerHeadSelector?: string) =>
486 gh.headBranchProbe?.({
487 headSelectors: ["me:main", "main"],
488 state: "all",
489 ownerHeadSelector,
490 }).headSelectors;
491 assert.deepStrictEqual([probe(), probe("me:main")], [["main"], ["me:main"]]);
492 const read = (state: "open" | "merged") =>
493 gh.listChangeRequests({ cwd: "/repo", headSelector: "me:main", state, limit: 1 });
494 const [open] = yield* read("open");
495 const [merged] = yield* read("merged");
496 assert.deepStrictEqual(
497 [open, merged].map((pr) => [pr?.number, pr?.state, pr?.headRepositoryOwnerLogin]),
498 [
499 [8, "open", "me"],
500 [7, "merged", "me"],
501 ],
502 );
503 assert.deepStrictEqual(
504 paths.map((path) => new URL(path, "https://api.test/").searchParams.get("state")),
505 ["open", "closed"],
506 );
507 assert.include(paths[0], "repos/acme/web/pulls?head=me%3Amain");
508 assert.lengthOf(graphqlCalls, 0);
509 }).pipe(Effect.provide(layer));
510 });
511
512 it.effect("maps API failures onto the errors callers handle", () => {
513 let signedIn = false;
514 const { layer } = harness({
515 remotes,
516 credential: (host) =>
517 signedIn
518 ? Effect.succeed({
519 host,
520 token: Redacted.make("token"),
521 source: "gh" as const,
522 fingerprint: "fp",
523 })
524 : Effect.fail(new GitHubCredentials.GitHubCliMissingError({ host })),
525 graphql: () =>
526 new Response(encodeJson({ message: "API rate limit exceeded" }), {
527 status: 403,
528 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "123" },
529 }),
530 });
531 return Effect.gen(function* () {
532 const gh = yield* GitHubSourceControlProvider.make;
533 const read = (headSelector: string) =>
534 gh
535 .listChangeRequests({ cwd: "/repo", headSelector, state: "open", limit: 1 })
536 .pipe(Effect.flip, Effect.forkChild);
537 const missing = yield* read("missing");
538 yield* TestClock.adjust("500 millis");
539 assert.include((yield* Fiber.join(missing)).detail, "No GitHub credential on the server");
540 signedIn = true;
541 const limited = yield* read("limited");
542 yield* TestClock.adjust("500 millis");
543 const error = yield* Fiber.join(limited);
544 assert.include(error.detail, "rate limit exceeded");
545 assert.propertyVal(error.cause, "retryAt", 123_000);
546 }).pipe(Effect.provide(layer));
547 });
548 });
549
550 describe("GitHubSourceControlProvider.getChangeRequest", () => {
551 it.effect("reads a pull request by number, and by URL on its own repository", () => {
552 const { layer, graphqlCalls } = harness({
553 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
554 graphql: () => ({ pullRequest: node(42, "feature") }),
555 });
556 return Effect.gen(function* () {
557 const gh = yield* GitHubSourceControlProvider.make;
558 assert.strictEqual(
559 (yield* gh.getChangeRequest({ cwd: "/repo", reference: "#42" })).number,
560 42,
561 );
562 yield* gh.getChangeRequest({
563 cwd: "/repo",
564 reference: "https://github.com/other/thing/pull/42",
565 });
566 assert.deepStrictEqual(
567 graphqlCalls.flatMap((call) => call.lookups),
568 [
569 { owner: "acme", name: "web", number: 42 },
570 { owner: "other", name: "thing", number: 42 },
571 ],
572 );
573 }).pipe(Effect.provide(layer));
574 });
575 });
576
577 describe("GitHubSourceControlProvider writes", () => {
578 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
579 const requests: Array<GitHubRest.GitHubRestInput> = [];
580 const { layer } = harness({
581 remotes: remotesOutput(
582 ["origin", "git@github.com:me/web.git"],
583 ["upstream", "git@github.com:acme/web.git"],
584 ),
585 api: {
586 rest: (input) =>
587 Effect.sync(() => {
588 requests.push(input);
589 return restResponse({ number: 1 }, 201);
590 }),
591 },
592 });
593 return Effect.gen(function* () {
594 const fs = yield* FileSystem.FileSystem;
595 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
596 yield* fs.writeFileString(bodyFile, "Body");
597 const gh = yield* GitHubSourceControlProvider.make;
598 yield* gh.createChangeRequest({
599 cwd: "/repo",
600 baseRefName: "main",
601 headSelector: "me:feature",
602 title: "Title",
603 bodyFile,
604 });
605 assert.strictEqual(requests[0]!.method, "POST");
606 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
607 assert.strictEqual(requests[0]!.allowReserve, true);
608 assert.deepStrictEqual(requests[0]!.body, {
609 base: "main",
610 head: "me:feature",
611 title: "Title",
612 body: "Body",
613 maintainer_can_modify: true,
614 });
615 yield* gh.createChangeRequest({
616 cwd: "/repo",
617 baseRefName: "main",
618 headSelector: "me:feature",
619 title: "Title",
620 bodyFile,
621 draft: true,
622 });
623 assert.strictEqual((requests[1]!.body as { draft?: unknown }).draft, true);
624 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)));
625 });
626
627 it.effect("creates a repository under an organization the viewer is not", () => {
628 const requests: Array<string> = [];
629 const { layer } = harness({
630 remotes: "",
631 api: {
632 rest: (input) =>
633 Effect.sync(() => {
634 requests.push(`${input.method ?? "GET"} ${input.path}`);
635 return input.path === "user"
636 ? restResponse({ login: "me" })
637 : restResponse({
638 full_name: "acme/new",
639 html_url: "https://github.com/acme/new",
640 ssh_url: "git@github.com:acme/new.git",
641 });
642 }),
643 },
644 });
645 return Effect.gen(function* () {
646 const gh = yield* GitHubSourceControlProvider.make;
647 const urls = yield* gh.createRepository({
648 cwd: "/repo",
649 repository: "acme/new",
650 visibility: "private",
651 });
652 assert.deepStrictEqual(urls, {
653 nameWithOwner: "acme/new",
654 url: "https://github.com/acme/new",
655 sshUrl: "git@github.com:acme/new.git",
656 });
657 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
658 }).pipe(Effect.provide(layer));
659 });
660
661 it.effect("looks up a bare repository name under the signed-in account on that host", () => {
662 const requests: Array<string> = [];
663 return Effect.gen(function* () {
664 const gh = yield* makeProvider({
665 rest: (input) =>
666 Effect.sync(() => {
667 requests.push(`${input.host} ${input.method ?? "GET"} ${input.path}`);
668 return input.path === "user"
669 ? restResponse({ login: "me" })
670 : restResponse({
671 full_name: "me/notes",
672 html_url: `https://${input.host}/me/notes`,
673 ssh_url: `git@${input.host}:me/notes.git`,
674 });
675 }),
676 });
677
678 const urls = yield* gh.getRepositoryCloneUrls({
679 cwd: "/repo",
680 context: githubContext("code.example.test"),
681 repository: " notes.git ",
682 });
683
684 assert.deepStrictEqual(urls, {
685 nameWithOwner: "me/notes",
686 url: "https://code.example.test/me/notes",
687 sshUrl: "git@code.example.test:me/notes.git",
688 });
689 assert.deepStrictEqual(requests, [
690 "code.example.test GET user",
691 "code.example.test GET repos/me/notes",
692 ]);
693 for (const repository of ["me/", "/notes", "a/b/c/d", "", "two words"]) {
694 const error = yield* Effect.flip(gh.getRepositoryCloneUrls({ cwd: "/repo", repository }));
695 assert.include(error.message, "Repositories are named owner/name.");
696 }
697 assert.strictEqual(requests.length, 2);
698 });
699 });
700 });
701
702 describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
703 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
704 const { layer, git } = harness({
705 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
706 localBranches: ["main"],
707 graphql: () => ({ pullRequest: node(6, "main", "someone") }),
708 api: {
709 rest: () =>
710 Effect.fail(
711 new GitHubRequestPolicy.GitHubApiRequestError({
712 host: "github.com",
713 operation: "x",
714 cause: "offline",
715 }),
716 ),
717 },
718 });
719 return Effect.gen(function* () {
720 const gh = yield* GitHubSourceControlProvider.make;
721 yield* Effect.flip(gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true }));
722 assert.deepStrictEqual(git, []);
723 }).pipe(Effect.provide(layer));
724 });
725
726 it.effect("adds a fork remote with the protocol of the URL origin fetches from", () => {
727 // `git remote -v` shows origin's SSH `insteadOf` rewrite; config holds HTTPS, then an SSH push URL.
728 const { layer, git } = harness({
729 remotes: [
730 "origin\tgit@github.com:acme/web.git (fetch)",
731 "origin\tgit@github.com:acme/web.git (push)",
732 "origin\tgit@github.com:acme/web.git (push)",
733 ].join("\n"),
734 originUrls: "https://github.com/acme/web.git\ngit@github.com:acme/web.git\n",
735 graphql: () => ({ pullRequest: node(7, "feature", "someone") }),
736 api: {
737 rest: (input) => {
738 const fullName = input.path.slice("repos/".length);
739 return Effect.succeed(
740 restResponse({
741 full_name: fullName,
742 html_url: `https://github.com/${fullName}`,
743 ssh_url: `git@github.com:${fullName}.git`,
744 default_branch: "main",
745 }),
746 );
747 },
748 },
749 });
750 return Effect.gen(function* () {
751 const gh = yield* GitHubSourceControlProvider.make;
752 yield* gh.checkoutChangeRequest({ cwd: "/repo", reference: "7" });
753 assert.deepStrictEqual(git.find(([name]) => name === "ensureRemote")?.[1], {
754 cwd: "/repo",
755 preferredName: "someone",
756 url: "https://github.com/someone/web",
757 });
758 }).pipe(Effect.provide(layer));
759 });
760
761 it.effect("keeps git's own output out of what a failed checkout reports", () => {
762 const { layer } = harness({
763 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
764 gitFailure: new Error("fatal: /home/me/secret-path: permission denied"),
765 graphql: () => ({ pullRequest: node(5, "feature/x") }),
766 });
767 return Effect.gen(function* () {
768 const gh = yield* GitHubSourceControlProvider.make;
769 const error = yield* gh
770 .checkoutChangeRequest({ cwd: "/repo", reference: "5" })
771 .pipe(Effect.flip);
772 assert.strictEqual(error.detail, "The pull request could not be checked out with git.");
773 assert.notInclude(error.message, "secret-path");
774 }).pipe(Effect.provide(layer));
775 });
776
777 it.effect("records the branch base for gh through the host's config write", () => {
778 const { layer, git } = harness({
779 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
780 });
781 return Effect.gen(function* () {
782 const gh = yield* GitHubSourceControlProvider.make;
783 yield* gh.recordBranchBase!({ cwd: "/repo", branch: "feature", baseBranch: "main" });
784 assert.deepStrictEqual(git, [
785 ["writeConfigValue", { cwd: "/repo", key: "branch.feature.gh-merge-base", value: "main" }],
786 ]);
787 }).pipe(Effect.provide(layer));
788 });
789
790 it("names the local branch the way gh pr checkout does", () => {
791 const name = (headRefName: string, isCrossRepository: boolean) =>
792 GitHubSourceControlProvider.pullRequestCheckoutBranchName({
793 headRefName,
794 headOwner: "someone",
795 isCrossRepository,
796 defaultBranch: "main",
797 });
798 assert.strictEqual(name("main", true), "someone/main");
799 assert.strictEqual(name("feature", true), "feature");
800 assert.strictEqual(name("main", false), "main");
801 });
802 });
803
804 it("accepts active authenticated GitHub accounts when another account fails", () => {
805 const auth = GitHubSourceControlProvider.discovery.parseAuth(
806 processResult(
807 JSON.stringify({
808 hosts: {
809 "github.com": [
810 {
811 state: "success",
812 active: true,
813 host: "github.com",
814 login: "active-user",
815 tokenSource: "keyring",
816 gitProtocol: "ssh",
817 },
818 {
819 state: "error",
820 active: false,
821 host: "github.com",
822 login: "stale-user",
823 tokenSource: "keyring",
824 gitProtocol: "ssh",
825 error: "The token in keyring is invalid.",
826 },
827 ],
828 },
829 }),
830 ),
831 );
832
833 assert.deepStrictEqual(
834 {
835 status: auth.status,
836 account: auth.account,
837 host: auth.host,
838 },
839 {
840 status: "authenticated",
841 account: Option.some("active-user"),
842 host: Option.some("github.com"),
843 },
844 );
845 });
846
847 it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
848 const auth = GitHubSourceControlProvider.discovery.parseAuth(
849 processResult(
850 JSON.stringify({
851 hosts: {
852 "github.com": [
853 {
854 state: "success",
855 active: true,
856 host: "github.com",
857 login: "active-user",
858 tokenSource: "keyring",
859 gitProtocol: "ssh",
860 },
861 ],
862 },
863 }),
864 { stderr: "warning: ignored diagnostic from gh\n" },
865 ),
866 );
867
868 assert.deepStrictEqual(
869 {
870 status: auth.status,
871 account: auth.account,
872 host: auth.host,
873 },
874 {
875 status: "authenticated",
876 account: Option.some("active-user"),
877 host: Option.some("github.com"),
878 },
879 );
880 });
881
882 it("parses GitHub auth status accounts by host and active state", () => {
883 assert.deepStrictEqual(
884 parseGitHubAuthStatus(
885 JSON.stringify({
886 hosts: {
887 "github.com": [
888 {
889 state: "success",
890 active: true,
891 host: "github.com",
892 login: "active-user",
893 tokenSource: "keyring",
894 gitProtocol: "ssh",
895 },
896 {
897 state: "error",
898 active: false,
899 host: "github.com",
900 login: "stale-user",
901 tokenSource: "keyring",
902 gitProtocol: "ssh",
903 },
904 ],
905 "github.example.test": [
906 {
907 state: "success",
908 active: false,
909 host: "github.example.test",
910 login: "enterprise-user",
911 tokenSource: "keyring",
912 gitProtocol: "ssh",
913 },
914 ],
915 },
916 }),
917 ).accounts,
918 [
919 {
920 host: "github.com",
921 account: "active-user",
922 authenticated: true,
923 active: true,
924 error: null,
925 environmentVariable: null,
926 },
927 {
928 host: "github.com",
929 account: "stale-user",
930 authenticated: false,
931 active: false,
932 error: null,
933 environmentVariable: null,
934 },
935 {
936 host: "github.example.test",
937 account: "enterprise-user",
938 authenticated: true,
939 active: false,
940 error: null,
941 environmentVariable: null,
942 },
943 ],
944 );
945 });
946
947 it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
948 const auth = GitHubSourceControlProvider.discovery.parseAuth(
949 processResult(
950 JSON.stringify({
951 hosts: {
952 "github.com": [
953 {
954 state: "error",
955 active: true,
956 host: "github.com",
957 login: "stale-user",
958 tokenSource: "keyring",
959 gitProtocol: "ssh",
960 error: "The token in keyring is invalid.",
961 },
962 ],
963 },
964 }),
965 ),
966 );
967
968 assert.deepStrictEqual(
969 {
970 status: auth.status,
971 host: auth.host,
972 detail: auth.detail,
973 },
974 {
975 status: "unauthenticated",
976 host: Option.some("github.com"),
977 detail: Option.some("The token in keyring is invalid."),
978 },
979 );
980 });
981
982 it("reports an update hint instead of unauthenticated when gh predates --json", () => {
983 const auth = GitHubSourceControlProvider.discovery.parseAuth(
984 processResult("", {
985 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
986 exitCode: ChildProcessSpawner.ExitCode(1),
987 }),
988 );
989
990 assert.strictEqual(auth.status, "unknown");
991 assert.match(
992 Option.getOrElse(auth.detail, () => ""),
993 /2\.81\.0/,
994 );
995 });
996
997 it.effect.each(["pull", "issues"])(
998 "resolves %s subjects on the linked host without using the checkout",
999 (kind) =>
1000 Effect.gen(function* () {
1001 const provider = yield* makeProvider({
1002 rest: (input) => {
1003 assert.strictEqual(input.host, "github.com");
1004 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
1005 return Effect.succeed(
1006 restResponse({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
1007 );
1008 },
1009 });
1010 const lookup = provider.resolveLink?.({
1011 cwd: "/unrelated",
1012 url: new URL(`https://github.com/owner/repo/${kind}/42`),
1013 });
1014 assert.ok(lookup);
1015 assert.deepStrictEqual(yield* lookup, {
1016 title: "Pairing expiry",
1017 body: "Preserve remote access",
1018 });
1019 for (const url of [
1020 "https://github.com/owner/repo",
1021 "https://github.attacker.test/owner/repo/issues/42",
1022 ]) {
1023 assert.strictEqual(
1024 provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
1025 undefined,
1026 );
1027 }
1028 }),
1029 );
1030
1031 it.effect.each(["read", "decode"] as const)(
1032 "retains the %s failure without exposing its raw contents",
1033 (stage) =>
1034 Effect.gen(function* () {
1035 const cause = new GitHubRequestPolicy.GitHubApiResponseError({
1036 host: "github.com",
1037 operation: "resolveLink",
1038 status: 500,
1039 });
1040 const provider = yield* makeProvider({
1041 rest: () =>
1042 stage === "read"
1043 ? Effect.fail(cause)
1044 : Effect.succeed({ ...restResponse(undefined), body: "private response text" }),
1045 });
1046 const lookup = provider.resolveLink?.({
1047 cwd: "/repo",
1048 url: new URL("https://github.com/owner/repo/issues/42"),
1049 });
1050 assert.ok(lookup);
1051 const error = yield* Effect.flip(lookup);
1052 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
1053 assert.strictEqual(error.detail, "The linked subject could not be read.");
1054 assert.notInclude(error.message, "private response text");
1055 if (stage === "read") assert.strictEqual(error.cause, cause);
1056 else assert.propertyVal(error.cause, "_tag", "SchemaError");
1057 }),
1058 );
1059
1060 const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
1061 processResult(
1062 JSON.stringify({
1063 hosts: {
1064 "github.com": [
1065 { state: "success", active: true, host: "github.com", login: "personal" },
1066 { state: "success", active: false, host: "github.com", login: "work" },
1067 ...extra,
1068 ],
1069 "ghe.acme.test": [
1070 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
1071 ],
1072 },
1073 }),
1074 );
1075
1076 it("reports every gh login and leads with the account Settings pin", () => {
1077 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
1078 hosts: { "github.com": { account: "work", enabled: true } },
1079 tokens: {},
1080 signIns: {},
1081 });
1082 assert.deepStrictEqual(auth.account, Option.some("work"));
1083 assert.deepStrictEqual(auth.accounts, [
1084 { host: "github.com", account: "personal", active: true, authenticated: true },
1085 { host: "github.com", account: "work", active: false, authenticated: true },
1086 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
1087 ]);
1088 });
1089
1090 it("reports unauthenticated when Settings turn off every signed-in host", () => {
1091 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
1092 hosts: { "github.com": { enabled: false } },
1093 tokens: {},
1094 signIns: {},
1095 });
1096 assert.strictEqual(auth.status, "unauthenticated");
1097 assert.deepStrictEqual(
1098 auth.detail,
1099 Option.some(
1100 "Every GitHub host gh is signed in to is turned off in Settings → Source control & issues.",
1101 ),
1102 );
1103 });
1104
1105 it("names the environment token that overrides the Settings choice", () => {
1106 const auth = GitHubSourceControlProvider.parseGitHubAuth(
1107 multiAccountStatus([
1108 {
1109 state: "success",
1110 active: false,
1111 host: "github.com",
1112 login: "bot",
1113 tokenSource: "GH_TOKEN",
1114 },
1115 ]),
1116 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {}, signIns: {} },
1117 );
1118 assert.deepStrictEqual(auth.account, Option.some("bot"));
1119 assert.deepStrictEqual(
1120 auth.detail,
1121 Option.some(
1122 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
1123 ),
1124 );
1125 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
1126 });
1127
1128 it.live.each([
1129 "git@code.example.test:team/project.git",
1130 "ssh://git@code.example.test/team/project.git",
1131 "https://code.example.test/team/project.git",
1132 ])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
1133 const rest: GitHubRest.GitHubRestInput[] = [];
1134 const pr = {
1135 ...node(42, "feature", "team"),
1136 url: "https://code.example.test/team/project/pull/42",
1137 isCrossRepository: false,
1138 headRepository: { name: "project", nameWithOwner: "team/project" },
1139 };
1140 const api = {
1141 rest: (input: GitHubRest.GitHubRestInput) =>
1142 Effect.sync(() => {
1143 rest.push(input);
1144 return restResponse({
1145 full_name: "team/project",
1146 html_url: `https://${input.host}/team/project`,
1147 ssh_url: `git@${input.host}:team/project.git`,
1148 default_branch: "main",
1149 });
1150 }),
1151 };
1152 const { layer, git, graphqlCalls } = harness({
1153 remotes: remotesOutput(
1154 ["origin", "git@github.com:team/project.git"],
1155 ["enterprise", remoteUrl],
1156 ),
1157 api,
1158 graphql: (_, call) =>
1159 call.operationName === "PullRequestByNumber"
1160 ? { pullRequest: pr }
1161 : { pullRequests: { nodes: [pr] } },
1162 });
1163 return Effect.gen(function* () {
1164 const provider = yield* GitHubSourceControlProvider.make;
1165 const fs = yield* FileSystem.FileSystem;
1166 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
1167 yield* fs.writeFileString(bodyFile, "Enterprise PR");
1168 const input = {
1169 cwd: "/repo",
1170 context: {
1171 provider: {
1172 kind: SourceControlProviderKind.make("github"),
1173 name: "GitHub Self-Hosted",
1174 baseUrl: "https://code.example.test",
1175 },
1176 remoteName: "enterprise",
1177 remoteUrl,
1178 },
1179 };
1180 for (const state of ["open", "closed"] as const) {
1181 const prs = yield* provider.listChangeRequests({
1182 ...input,
1183 state,
1184 headSelector: "feature",
1185 });
1186 assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
1187 }
1188 yield* provider.getChangeRequest({ ...input, reference: "42" });
1189 yield* provider.getChangeRequest({ ...input, reference: "feature" });
1190 yield* provider.createChangeRequest({
1191 ...input,
1192 baseRefName: "main",
1193 headSelector: "feature",
1194 title: "PR",
1195 bodyFile,
1196 });
1197 assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
1198 yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
1199 yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
1200 yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
1201 const lookups = graphqlCalls.flatMap((call) =>
1202 call.lookups.map(({ owner, name }) => [call.host, owner, name]),
1203 );
1204 assert.deepStrictEqual(
1205 lookups,
1206 Array.from({ length: 5 }, () => ["code.example.test", "team", "project"]),
1207 );
1208 assert.deepStrictEqual(
1209 rest.map(({ host, path }) => [host, path]),
1210 [
1211 ["code.example.test", "repos/team/project/pulls"],
1212 ["code.example.test", "repos/team/project"],
1213 ["code.example.test", "repos/team/other"],
1214 ["github.com", "repos/team/explicit"],
1215 ],
1216 );
1217 assert.deepStrictEqual(git.find(([name]) => name === "createBranch")?.[1], {
1218 cwd: "/repo",
1219 branch: "feature",
1220 startPoint: "refs/remotes/enterprise/feature",
1221 });
1222 assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
1223 cwd: "/repo",
1224 remoteName: "enterprise",
1225 remoteBranch: "feature",
1226 });
1227 }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}));
1228 });
1229
1230 it.effect.each([
1231 { host: "github.com", resolved: "", envRepository: "", expected: "acme/web" },
1232 {
1233 host: "code.example.test",
1234 resolved: "remote.origin.gh-resolved base",
1235 envRepository: "",
1236 expected: "me/web",
1237 },
1238 {
1239 host: "github.com",
1240 resolved: "remote.upstream.gh-resolved acme/other",
1241 envRepository: "",
1242 expected: "acme/other",
1243 },
1244 {
1245 host: "code.example.test",
1246 resolved: "",
1247 envRepository: "chosen/repo",
1248 expected: "chosen/repo",
1249 },
1250 ])(
1251 "preserves repository precedence on $host: $resolved $envRepository",
1252 ({ host, resolved, envRepository, expected }) => {
1253 const targets: string[] = [];
1254 const { layer } = harness({
1255 remotes: remotesOutput(
1256 ["origin", `git@${host}:me/web.git`],
1257 ["upstream", `git@${host}:acme/web.git`],
1258 ),
1259 resolved,
1260 api: {
1261 rest: (input) =>
1262 Effect.sync(() => {
1263 targets.push(`${input.host}/${input.path}`);
1264 return restResponse({
1265 full_name: expected,
1266 html_url: `https://${host}/${expected}`,
1267 ssh_url: `git@${host}:${expected}.git`,
1268 default_branch: "main",
1269 });
1270 }),
1271 },
1272 });
1273 return Effect.gen(function* () {
1274 const provider = yield* GitHubSourceControlProvider.make;
1275 const fs = yield* FileSystem.FileSystem;
1276 const bodyFile = yield* fs.makeTempFileScoped();
1277 yield* fs.writeFileString(bodyFile, "Body");
1278 const input = {
1279 cwd: "/repo",
1280 context: {
1281 provider: {
1282 kind: SourceControlProviderKind.make("github"),
1283 name: "GitHub",
1284 baseUrl: `https://${host}`,
1285 },
1286 remoteName: "origin",
1287 remoteUrl: `git@${host}:me/web.git`,
1288 },
1289 };
1290 yield* provider.getDefaultBranch(input);
1291 yield* provider.createChangeRequest({
1292 ...input,
1293 baseRefName: "main",
1294 headSelector: "me:feature",
1295 title: "PR",
1296 bodyFile,
1297 });
1298 assert.deepStrictEqual(targets, [
1299 `${host}/repos/${expected}`,
1300 `${host}/repos/${expected}/pulls`,
1301 ]);
1302 assert.deepStrictEqual(
1303 yield* provider.createsChangeRequestsIn!({ ...input, repository: "me/web" }),
1304 expected === "me/web",
1305 );
1306 }).pipe(
1307 Effect.provide(layer),
1308 Effect.provideService(HostProcess.Environment, { GH_REPO: envRepository }),
1309 );
1310 },
1311 );
1312
1313 it.effect(
1314 "says a GH_REPO naming an unparseable host falls back to the remotes, as creation does",
1315 () => {
1316 const { layer } = harness({
1317 remotes: remotesOutput(["upstream", "git@github.com:acme/web.git"]),
1318 resolved: "",
1319 api: {},
1320 });
1321 return Effect.gen(function* () {
1322 const provider = yield* GitHubSourceControlProvider.make;
1323 const targets = yield* provider.createsChangeRequestsIn!({
1324 cwd: "/repo",
1325 context: {
1326 provider: {
1327 kind: SourceControlProviderKind.make("github"),
1328 name: "GitHub",
1329 baseUrl: "https://github.com",
1330 },
1331 remoteName: "upstream",
1332 remoteUrl: "git@github.com:acme/web.git",
1333 },
1334 repository: "acme/web",
1335 });
1336 assert.isTrue(targets);
1337 }).pipe(
1338 Effect.provide(layer),
1339 Effect.provideService(HostProcess.Environment, { GH_REPO: "bad host/acme/web" }),
1340 );
1341 },
1342 );