Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import { ChildProcessSpawner } from "effect/process";
8
9import * as VcsProcess from "../vcs/VcsProcess.ts";
10import * as GitHubApi from "./GitHubApi.ts";
11import * as GitHubCli from "./GitHubCli.ts";
12import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
13import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
14
15const processResult = (
16 stdout: string,
17 options?: {
18 readonly stderr?: string;
19 readonly exitCode?: ChildProcessSpawner.ExitCode;
20 },
21): VcsProcess.VcsProcessOutput => ({
22 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
23 stdout,
24 stderr: options?.stderr ?? "",
25 stdoutTruncated: false,
26 stderrTruncated: false,
27});
28
29function makeProvider(
30 github: Partial<GitHubCli.GitHubCli["Service"]>,
31 api: Partial<GitHubApi.GitHubApi["Service"]> = {},
32) {
33 return GitHubSourceControlProvider.make.pipe(
34 Effect.provide(
35 Layer.merge(Layer.mock(GitHubCli.GitHubCli)(github), Layer.mock(GitHubApi.GitHubApi)(api)),
36 ),
37 );
38}
39
40const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
41
42const restResponse = (body: string): GitHubApi.GitHubRestResponse => ({
43 status: 200,
44 headers: {},
45 body,
46 truncated: false,
47 invalidUtf8: false,
48});
49
50it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
51 Effect.gen(function* () {
52 const provider = yield* makeProvider({
53 getPullRequest: () =>
54 Effect.succeed({
55 number: 42,
56 title: "Add GitHub provider",
57 url: "https://github.com/pingdotgg/t3code/pull/42",
58 baseRefName: "main",
59 headRefName: "feature/source-control",
60 state: "open",
61 isCrossRepository: true,
62 headRepositoryNameWithOwner: "fork/t3code",
63 headRepositoryOwnerLogin: "fork",
64 }),
65 });
66
67 const changeRequest = yield* provider.getChangeRequest({
68 cwd: "/repo",
69 reference: "42",
70 });
71
72 assert.deepStrictEqual(changeRequest, {
73 provider: "github",
74 number: 42,
75 title: "Add GitHub provider",
76 url: "https://github.com/pingdotgg/t3code/pull/42",
77 baseRefName: "main",
78 headRefName: "feature/source-control",
79 state: "open",
80 closedAt: null,
81 mergedAt: null,
82 updatedAt: Option.none(),
83 isCrossRepository: true,
84 headRepositoryNameWithOwner: "fork/t3code",
85 headRepositoryOwnerLogin: "fork",
86 });
87 }),
88);
89
90it.effect("adds safe request context while retaining GitHub CLI causes", () =>
91 Effect.gen(function* () {
92 const cause = new GitHubCli.GitHubPullRequestNotFoundError({
93 command: "gh",
94 cwd: "/repo",
95 cause: new Error("raw upstream detail that should remain in the cause"),
96 });
97 const provider = yield* makeProvider({
98 getPullRequest: () => Effect.fail(cause),
99 });
100
101 const error = yield* provider
102 .getChangeRequest({
103 cwd: "/repo",
104 reference: "https://user:secret@github.com/pingdotgg/t3code/pull/42?token=secret#diff",
105 })
106 .pipe(Effect.flip);
107
108 assert.deepStrictEqual(
109 {
110 provider: error.provider,
111 operation: error.operation,
112 command: error.command,
113 cwd: error.cwd,
114 reference: error.reference,
115 detail: error.detail,
116 },
117 {
118 provider: "github",
119 operation: "getChangeRequest",
120 command: "gh",
121 cwd: "/repo",
122 reference: "https://github.com/pingdotgg/t3code/pull/42",
123 detail: "Pull request not found. Check the PR number or URL and try again.",
124 },
125 );
126 assert.strictEqual(error.cause, cause);
127 assert.equal(error.message.includes("raw upstream detail"), false);
128 }),
129);
130
131it.effect("lists change request history through the batched head lookup", () =>
132 Effect.gen(function* () {
133 let lookup: Parameters<GitHubCli.GitHubCli["Service"]["listPullRequestsByHead"]>[0] | null =
134 null;
135 const provider = yield* makeProvider({
136 listPullRequestsByHead: (input) => {
137 lookup = input;
138 return Effect.succeed([
139 {
140 number: 7,
141 title: "Merged work",
142 url: "https://enterprise.test/acme/web/pull/7",
143 baseRefName: "main",
144 headRefName: "feature/merged",
145 state: "merged",
146 mergedAt: "2026-01-01T00:00:00Z",
147 updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
148 },
149 ]);
150 },
151 });
152
153 const changeRequests = yield* provider.listChangeRequests({
154 cwd: "/repo",
155 context: {
156 provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
157 remoteName: "origin",
158 remoteUrl: "https://enterprise.test/acme/web.git",
159 },
160 headSelector: "feature/merged",
161 state: "all",
162 limit: 10,
163 });
164
165 assert.deepStrictEqual(lookup, {
166 cwd: "/repo",
167 headSelector: "feature/merged",
168 state: "all",
169 limit: 10,
170 rateLimitHost: "enterprise.test",
171 });
172 assert.strictEqual(changeRequests[0]?.provider, "github");
173 assert.strictEqual(changeRequests[0]?.state, "merged");
174 assert.strictEqual(changeRequests[0]?.mergedAt, "2026-01-01T00:00:00Z");
175 assert.deepStrictEqual(
176 changeRequests[0]?.updatedAt,
177 Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
178 );
179 }),
180);
181
182it.effect("creates GitHub PRs through provider-neutral input names", () =>
183 Effect.gen(function* () {
184 let createInput: Parameters<GitHubCli.GitHubCli["Service"]["createPullRequest"]>[0] | null =
185 null;
186 const provider = yield* makeProvider({
187 createPullRequest: (input) => {
188 createInput = input;
189 return Effect.void;
190 },
191 });
192
193 yield* provider.createChangeRequest({
194 cwd: "/repo",
195 baseRefName: "main",
196 headSelector: "owner:feature/provider",
197 title: "Provider PR",
198 bodyFile: "/tmp/body.md",
199 });
200
201 assert.deepStrictEqual(createInput, {
202 cwd: "/repo",
203 baseBranch: "main",
204 headSelector: "owner:feature/provider",
205 title: "Provider PR",
206 bodyFile: "/tmp/body.md",
207 });
208 }),
209);
210
211it("accepts active authenticated GitHub accounts when another account fails", () => {
212 const auth = GitHubSourceControlProvider.discovery.parseAuth(
213 processResult(
214 JSON.stringify({
215 hosts: {
216 "github.com": [
217 {
218 state: "success",
219 active: true,
220 host: "github.com",
221 login: "active-user",
222 tokenSource: "keyring",
223 gitProtocol: "ssh",
224 },
225 {
226 state: "error",
227 active: false,
228 host: "github.com",
229 login: "stale-user",
230 tokenSource: "keyring",
231 gitProtocol: "ssh",
232 error: "The token in keyring is invalid.",
233 },
234 ],
235 },
236 }),
237 ),
238 );
239
240 assert.deepStrictEqual(
241 {
242 status: auth.status,
243 account: auth.account,
244 host: auth.host,
245 },
246 {
247 status: "authenticated",
248 account: Option.some("active-user"),
249 host: Option.some("github.com"),
250 },
251 );
252});
253
254it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
255 const auth = GitHubSourceControlProvider.discovery.parseAuth(
256 processResult(
257 JSON.stringify({
258 hosts: {
259 "github.com": [
260 {
261 state: "success",
262 active: true,
263 host: "github.com",
264 login: "active-user",
265 tokenSource: "keyring",
266 gitProtocol: "ssh",
267 },
268 ],
269 },
270 }),
271 { stderr: "warning: ignored diagnostic from gh\n" },
272 ),
273 );
274
275 assert.deepStrictEqual(
276 {
277 status: auth.status,
278 account: auth.account,
279 host: auth.host,
280 },
281 {
282 status: "authenticated",
283 account: Option.some("active-user"),
284 host: Option.some("github.com"),
285 },
286 );
287});
288
289it("parses GitHub auth status accounts by host and active state", () => {
290 assert.deepStrictEqual(
291 parseGitHubAuthStatus(
292 JSON.stringify({
293 hosts: {
294 "github.com": [
295 {
296 state: "success",
297 active: true,
298 host: "github.com",
299 login: "active-user",
300 tokenSource: "keyring",
301 gitProtocol: "ssh",
302 },
303 {
304 state: "error",
305 active: false,
306 host: "github.com",
307 login: "stale-user",
308 tokenSource: "keyring",
309 gitProtocol: "ssh",
310 },
311 ],
312 "github.example.test": [
313 {
314 state: "success",
315 active: false,
316 host: "github.example.test",
317 login: "enterprise-user",
318 tokenSource: "keyring",
319 gitProtocol: "ssh",
320 },
321 ],
322 },
323 }),
324 ).accounts,
325 [
326 {
327 host: "github.com",
328 account: "active-user",
329 authenticated: true,
330 active: true,
331 error: null,
332 environmentVariable: null,
333 },
334 {
335 host: "github.com",
336 account: "stale-user",
337 authenticated: false,
338 active: false,
339 error: null,
340 environmentVariable: null,
341 },
342 {
343 host: "github.example.test",
344 account: "enterprise-user",
345 authenticated: true,
346 active: false,
347 error: null,
348 environmentVariable: null,
349 },
350 ],
351 );
352});
353
354it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
355 const auth = GitHubSourceControlProvider.discovery.parseAuth(
356 processResult(
357 JSON.stringify({
358 hosts: {
359 "github.com": [
360 {
361 state: "error",
362 active: true,
363 host: "github.com",
364 login: "stale-user",
365 tokenSource: "keyring",
366 gitProtocol: "ssh",
367 error: "The token in keyring is invalid.",
368 },
369 ],
370 },
371 }),
372 ),
373 );
374
375 assert.deepStrictEqual(
376 {
377 status: auth.status,
378 host: auth.host,
379 detail: auth.detail,
380 },
381 {
382 status: "unauthenticated",
383 host: Option.some("github.com"),
384 detail: Option.some("The token in keyring is invalid."),
385 },
386 );
387});
388
389it("reports an update hint instead of unauthenticated when gh predates --json", () => {
390 const auth = GitHubSourceControlProvider.discovery.parseAuth(
391 processResult("", {
392 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
393 exitCode: ChildProcessSpawner.ExitCode(1),
394 }),
395 );
396
397 assert.strictEqual(auth.status, "unknown");
398 assert.match(
399 Option.getOrElse(auth.detail, () => ""),
400 /2\.81\.0/,
401 );
402});
403
404it.effect.each(["pull", "issues"])(
405 "resolves %s subjects on the linked host without using the checkout",
406 (kind) =>
407 Effect.gen(function* () {
408 const provider = yield* makeProvider(
409 {},
410 {
411 rest: (input) => {
412 assert.strictEqual(input.host, "github.com");
413 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
414 return Effect.succeed(
415 restResponse(
416 encodeJson({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
417 ),
418 );
419 },
420 },
421 );
422 const lookup = provider.resolveLink?.({
423 cwd: "/unrelated",
424 url: new URL(`https://github.com/owner/repo/${kind}/42`),
425 });
426 assert.ok(lookup);
427 assert.deepStrictEqual(yield* lookup, {
428 title: "Pairing expiry",
429 body: "Preserve remote access",
430 });
431 assert.strictEqual(
432 provider.resolveLink?.({
433 cwd: "/unrelated",
434 url: new URL("https://github.com/owner/repo"),
435 }),
436 undefined,
437 );
438 }),
439);
440
441it.effect.each(["read", "decode"] as const)(
442 "retains the %s failure without exposing its raw contents",
443 (stage) =>
444 Effect.gen(function* () {
445 const cause = new GitHubApi.GitHubApiResponseError({
446 host: "github.com",
447 operation: "resolveLink",
448 status: 500,
449 });
450 const provider = yield* makeProvider(
451 {},
452 {
453 rest: () =>
454 stage === "read"
455 ? Effect.fail(cause)
456 : Effect.succeed(restResponse("private response text")),
457 },
458 );
459 const lookup = provider.resolveLink?.({
460 cwd: "/repo",
461 url: new URL("https://github.com/owner/repo/issues/42"),
462 });
463 assert.ok(lookup);
464 const error = yield* Effect.flip(lookup);
465 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
466 assert.strictEqual(error.detail, "The linked subject could not be read.");
467 assert.notInclude(error.message, "private response text");
468 if (stage === "read") assert.strictEqual(error.cause, cause);
469 else assert.propertyVal(error.cause, "_tag", "SchemaError");
470 }),
471);
472
473const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
474 processResult(
475 JSON.stringify({
476 hosts: {
477 "github.com": [
478 { state: "success", active: true, host: "github.com", login: "personal" },
479 { state: "success", active: false, host: "github.com", login: "work" },
480 ...extra,
481 ],
482 "ghe.acme.test": [
483 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
484 ],
485 },
486 }),
487 );
488
489it("reports every gh login and leads with the account Settings pin", () => {
490 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
491 hosts: { "github.com": { account: "work", enabled: true } },
492 tokens: {},
493 });
494 assert.deepStrictEqual(auth.account, Option.some("work"));
495 assert.deepStrictEqual(auth.accounts, [
496 { host: "github.com", account: "personal", active: true, authenticated: true },
497 { host: "github.com", account: "work", active: false, authenticated: true },
498 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
499 ]);
500});
501
502it("falls back to gh's active login when the pinned account is gone", () => {
503 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
504 hosts: { "github.com": { account: "former-job", enabled: true } },
505 tokens: {},
506 });
507 assert.deepStrictEqual(auth.account, Option.some("personal"));
508});
509
510it("reports unauthenticated when Settings turn off every signed-in host", () => {
511 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
512 hosts: { "github.com": { enabled: false } },
513 tokens: {},
514 });
515 assert.strictEqual(auth.status, "unauthenticated");
516 assert.deepStrictEqual(
517 auth.detail,
518 Option.some("Every GitHub host gh is signed in to is turned off in Settings → Source Control."),
519 );
520});
521
522it("names the environment token that overrides the Settings choice", () => {
523 const auth = GitHubSourceControlProvider.parseGitHubAuth(
524 multiAccountStatus([
525 {
526 state: "success",
527 active: false,
528 host: "github.com",
529 login: "bot",
530 tokenSource: "GH_TOKEN",
531 },
532 ]),
533 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },
534 );
535 assert.deepStrictEqual(auth.account, Option.some("bot"));
536 assert.deepStrictEqual(
537 auth.detail,
538 Option.some(
539 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
540 ),
541 );
542 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
543});