Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ForgejoSourceControlProvider.test.ts

1,357 lines48.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9import * as HttpClient from "effect/http/HttpClient";
10import * as HttpClientRequest from "effect/http/HttpClientRequest";
11import * as HttpClientResponse from "effect/http/HttpClientResponse";
12import { VcsProcessSpawnError } from "@t3tools/contracts";
13import { firstNonEmptyLine } from "@t3tools/source-control-core/server/discovery";
14import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
15​
16import * as ForgejoCli from "./ForgejoCli.ts";
17import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
18import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
19​
20const processOutput = TestSourceControlHost.processOutput;
21​
22const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
23const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
24​
25const requestJson = (request: HttpClientRequest.HttpClientRequest): unknown => {
26 assert.strictEqual(request.body._tag, "Uint8Array");
27 return request.body._tag === "Uint8Array"
28 ? decodeJson(new TextDecoder().decode(request.body.body))
29 : undefined;
30};
31const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
32​
33it.effect("submits a Forgejo review without sending its summary in the preliminary GET", () => {
34 const methods: string[] = [];
35 const reviewClient = HttpClient.make((request) => {
36 methods.push(request.method);
37 if (request.method === "GET") {
38 assert.strictEqual(request.url, "https://forgejo.test/api/v1/repos/maria/project/pulls/42");
39 return Effect.succeed(
40 HttpClientResponse.fromWeb(
41 request,
42 new Response(
43 encodeJson({
44 number: 42,
45 title: "Review target",
46 body: "",
47 html_url: "https://forgejo.test/maria/project/pulls/42",
48 user: { login: "maria" },
49 state: "open",
50 merged: false,
51 head: { ref: "feature", sha: "head", repo: null },
52 base: { ref: "main", sha: "base", repo: null },
53 created_at: "2026-09-13T00:00:00Z",
54 updated_at: "2026-09-13T00:00:00Z",
55 closed_at: null,
56 merged_at: null,
57 labels: [],
58 }),
59 ),
60 ),
61 );
62 }
63 assert.strictEqual(request.method, "POST");
64 assert.strictEqual(
65 request.url,
66 "https://forgejo.test/api/v1/repos/maria/project/pulls/42/reviews",
67 );
68 assert.deepStrictEqual(requestJson(request), {
69 event: "COMMENT",
70 body: "Review summary",
71 commit_id: "head",
72 comments: [],
73 });
74 return Effect.succeed(
75 HttpClientResponse.fromWeb(request, new Response('{"id":1}', { status: 200 })),
76 );
77 });
78 return Effect.gen(function* () {
79 const cli = yield* ForgejoCli.make;
80 const provider = yield* ForgejoPullRequestProvider.make.pipe(
81 Effect.provideService(ForgejoCli.ForgejoCli, cli),
82 );
83 yield* provider.submitReview({
84 cwd: "/repo",
85 repository: "maria/project",
86 host: "forgejo.test",
87 number: 42,
88 verdict: "comment",
89 body: "Review summary",
90 comments: [],
91 });
92 assert.deepStrictEqual(methods, ["GET", "POST"]);
93 }).pipe(
94 Effect.provideService(HttpClient.HttpClient, reviewClient),
95 Effect.provideService(
96 FileSystem.FileSystem,
97 FileSystem.makeNoop({
98 exists: () => Effect.succeed(true),
99 readFileString: () =>
100 Effect.succeed(
101 encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
102 ),
103 }),
104 ),
105 Effect.provide(
106 TestSourceControlHost.layer({
107 process: {
108 run: (input) => {
109 if (input.command === "git") {
110 assert.deepStrictEqual(input.args, ["remote", "-v"]);
111 return Effect.succeed(
112 processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
113 );
114 }
115 assert.strictEqual(input.command, "fj");
116 assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
117 return Effect.succeed(processOutput(""));
118 },
119 },
120 }),
121 ),
122 );
123});
124​
125it.effect("reads Forgejo checks without repository or viewer requests", () => {
126 const paths: string[] = [];
127 return Effect.gen(function* () {
128 const provider = yield* ForgejoPullRequestProvider.make;
129 const read = provider.getChangeRequestChecks;
130 if (read === undefined) return yield* Effect.die("checks read missing");
131 const result = yield* read({
132 cwd: "/repo",
133 repository: "acme/web",
134 host: "forgejo.test",
135 number: 1,
136 });
137 assert.strictEqual(result.state, "open");
138 assert.strictEqual(result.checks[0]?.status, "failure");
139 assert.deepStrictEqual(paths, [
140 "repos/acme/web/pulls/1",
141 "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=1",
142 "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=2",
143 ]);
144 }).pipe(
145 Effect.provide(
146 Layer.mock(ForgejoCli.ForgejoCli)({
147 api: (input) => {
148 paths.push(input.path);
149 assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head)/);
150 return Effect.succeed(
151 processOutput(
152 input.path.endsWith("pulls/1")
153 ? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
154 "head":{"ref":"feature","sha":"head","repo":null},"base":{"ref":"main","sha":"base","repo":null},
155 "created_at":"2026-09-16T00:00:00Z","updated_at":"2026-09-16T00:00:00Z","closed_at":null,"merged_at":null,"labels":[]}`
156 : input.path.endsWith("page=1")
157 ? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
158 : "[]",
159 ),
160 );
161 },
162 }),
163 ),
164 );
165});
166​
167it.effect.each([
168 ["Ready", false, true, false, "mergeable"],
169 ["Draft", true, false, true, "unknown"],
170 ["Blocked", false, false, false, "unknown"],
171 ["Unchecked", false, undefined, false, "unknown"],
172 ["WIP: Legacy draft", undefined, false, true, "unknown"],
173 ["[WIP] Legacy draft", undefined, false, true, "unknown"],
174 ["WIP: Explicitly ready", false, false, false, "unknown"],
175] as const)(
176 "reads Forgejo mergeability for %s (draft=%s, mergeable=%s) across list, summary and detail",
177 ([title, draft, mergeable, isDraft, mergeability]) => {
178 const pr = {
179 number: 42,
180 title,
181 body: "",
182 html_url: "https://forgejo.test/maria/project/pulls/42",
183 user: { login: "maria" },
184 state: "open",
185 merged: false,
186 ...(draft === undefined ? {} : { draft }),
187 ...(mergeable === undefined ? {} : { mergeable }),
188 head: { ref: "feature", sha: "head", repo: null },
189 base: { ref: "main", sha: "base", repo: null },
190 created_at: "2026-09-16T00:00:00Z",
191 updated_at: "2026-09-16T00:00:00Z",
192 closed_at: null,
193 merged_at: null,
194 labels: [],
195 };
196 return Effect.gen(function* () {
197 const provider = yield* ForgejoPullRequestProvider.make;
198 const readSummary = provider.getChangeRequestSummary;
199 if (readSummary === undefined) return yield* Effect.die("summary read missing");
200 const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 42 };
201 const list = yield* provider.listChangeRequests({
202 ...input,
203 state: "open",
204 involvement: "all",
205 viewer: "maria",
206 limit: 10,
207 });
208 const summary = yield* readSummary(input);
209 const detail = yield* provider.getChangeRequest(input);
210 assert.strictEqual(list.items.length, 1);
211 assert.strictEqual(detail.headSha, "head");
212 for (const result of [list.items[0]!, summary, detail]) {
213 assert.strictEqual(result.mergeability, mergeability);
214 assert.strictEqual(result.isDraft, isDraft);
215 }
216 }).pipe(
217 Effect.provide(
218 Layer.mock(ForgejoCli.ForgejoCli)({
219 api: (input) => {
220 const [path, query] = input.path.split("?");
221 let response: unknown;
222 switch (path) {
223 case "repos/maria/project/pulls":
224 response = new URLSearchParams(query).get("page") === "1" ? [pr] : [];
225 break;
226 case "repos/maria/project/pulls/42":
227 response = pr;
228 break;
229 case "repos/maria/project":
230 response = { full_name: "maria/project", permissions: { push: true, admin: true } };
231 break;
232 case "user":
233 response = pr.user;
234 break;
235 case "repos/maria/project/statuses/head":
236 response = [];
237 break;
238 default:
239 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
240 }
241 return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
242 },
243 }),
244 ),
245 );
246 },
247);
248​
249it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>
250 Effect.gen(function* () {
251 const provider = yield* ForgejoSourceControlProvider.make;
252 const refine = provider.refineRepositoryIdentity;
253 assert.isDefined(refine);
254 const identity = (remoteUrl: string, provider?: string) => ({
255 canonicalKey: "forge.test/team/repo",
256 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
257 rootPath: "/repo",
258 ...(provider === undefined ? {} : { provider }),
259 });
260 const served = (baseUrl: string) => () =>
261 Effect.succeed({
262 provider: {
263 kind: SourceControlProviderKind.make("forgejo"),
264 name: "Forgejo / Gitea",
265 baseUrl,
266 },
267 remoteName: "origin",
268 remoteUrl: "",
269 });
270​
271 assert.deepStrictEqual(
272 yield* refine!({
273 identity: identity("http://forge.test:3000/git/team/repo.git"),
274 resolveContext: served("http://forge.test:3000/git/"),
275 }),
276 {
277 ...identity("http://forge.test:3000/git/team/repo.git"),
278 provider: SourceControlProviderKind.make("forgejo"),
279 webUrl: "http://forge.test:3000/git/team/repo",
280 },
281 );
282 assert.strictEqual(
283 (yield* refine!({
284 identity: identity("ssh://git@ssh.forge.test/team/repo.git"),
285 resolveContext: served("http://forge.test:3000/git"),
286 })).webUrl,
287 "http://forge.test:3000/git/team/repo",
288 );
289 const github = identity("https://github.com/team/repo.git", "github");
290 assert.strictEqual(
291 yield* refine!({ identity: github, resolveContext: () => Effect.die("not asked") }),
292 github,
293 );
294 const unserved = identity("http://forge.test:3000/team/repo.git");
295 assert.strictEqual(
296 yield* refine!({ identity: unserved, resolveContext: () => Effect.succeed(null) }),
297 unserved,
298 );
299 }).pipe(
300 Effect.provide(
301 Layer.mergeAll(
302 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
303 TestSourceControlHost.layer(),
304 Layer.mock(ForgejoCli.ForgejoCli)({}),
305 ),
306 ),
307 ),
308);
309​
310it.effect("loads Forgejo pull request references from files and commits views", () =>
311 Effect.gen(function* () {
312 const provider = yield* ForgejoSourceControlProvider.make;
313 for (const reference of [
314 "42",
315 "#42",
316 "https://forgejo.test/maria/project/pulls/42",
317 "https://forgejo.test/maria/project/pulls/42/",
318 "https://forgejo.test/maria/project/pulls/42/files?w=1#diff-1",
319 "http://forgejo.test:3000/git/maria/project/pulls/42/commits",
320 ]) {
321 const result = yield* provider.getChangeRequest({ cwd: "/repo", reference });
322 assert.strictEqual(result.number, 42);
323 assert.strictEqual(result.title, "Forgejo view reference");
324 }
325 const invalid = yield* provider
326 .getChangeRequest({
327 cwd: "/repo",
328 reference: "https://forgejo.test/maria/project/pulls/42invalid/files",
329 })
330 .pipe(Effect.result);
331 assert.strictEqual(invalid._tag, "Failure");
332 }).pipe(
333 Effect.provide(
334 Layer.mergeAll(
335 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
336 TestSourceControlHost.layer({ process: {} }),
337 Layer.mock(ForgejoCli.ForgejoCli)({
338 resolveRepository: () =>
339 Effect.succeed({
340 login: "work",
341 repository: "maria/project",
342 baseUrl: "https://forgejo.test",
343 }),
344 api: (input) => {
345 assert.strictEqual(input.path, "repos/maria/project/pulls/42");
346 return encodeJsonEffect({
347 number: 42,
348 title: "Forgejo view reference",
349 html_url: "https://forgejo.test/maria/project/pulls/42",
350 state: "open",
351 merged: false,
352 base: { ref: "main", sha: "base", repo: null },
353 head: { ref: "feature", sha: "head", repo: null },
354 }).pipe(Effect.orDie, Effect.map(processOutput));
355 },
356 }),
357 ),
358 ),
359 ),
360);
361​
362it.effect(
363 "loads Forgejo reactions on comments, reviews and inline threads and resolves review mutations",
364 () => {
365 const user = { login: "maria" };
366 const review = {
367 id: 8,
368 body: "review body",
369 user,
370 state: "COMMENT",
371 submitted_at: "2026-09-12T00:00:00Z",
372 html_url: "https://forgejo.test/maria/project/pulls/2#issuecomment-37",
373 comments_count: 1,
374 };
375 const comment = { id: 12, body: "ordinary", user, created_at: review.submitted_at };
376 const responses: Record<string, unknown> = {
377 user,
378 "repos/maria/project/issues/2/comments": [comment],
379 "repos/maria/project/pulls/2/reviews": [review],
380 "repos/maria/project/pulls/2/reviews/8": review,
381 "repos/maria/project/pulls/2/reviews/9": { ...review, id: 9, html_url: "" },
382 "repos/maria/project/pulls/2/commits": [],
383 "repos/maria/project/issues/2/reactions": [],
384 "repos/maria/project/pulls/2/reviews/8/comments": [
385 {
386 ...comment,
387 id: 38,
388 body: "inline",
389 path: "file.ts",
390 position: 1,
391 original_position: 1,
392 commit_id: "head",
393 original_commit_id: "head",
394 resolver: null,
395 },
396 ],
397 "repos/maria/project/issues/comments/12/reactions": [{ content: "+1", user }],
398 "repos/maria/project/issues/comments/37/reactions": [{ content: "heart", user }],
399 "repos/maria/project/issues/comments/38/reactions": [
400 { content: "rocket", user: { login: "reviewer" } },
401 ],
402 };
403 const writes: ForgejoCli.ForgejoApiInput[] = [];
404 let reactionReads = 0;
405 return Effect.gen(function* () {
406 const provider = yield* ForgejoPullRequestProvider.make;
407 const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 2 };
408 const activity = yield* provider.getChangeRequestActivity(input);
409 assert.deepStrictEqual(
410 activity.comments.map((entry) => ({
411 id: entry.id,
412 kind: entry.kind,
413 reactions: entry.reactions,
414 })),
415 [
416 {
417 id: "12",
418 kind: "issue-comment",
419 reactions: [{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true }],
420 },
421 {
422 id: "review:8",
423 kind: "review",
424 reactions: [{ content: "heart", count: 1, actors: [], viewerHasReacted: true }],
425 },
426 {
427 id: "38",
428 kind: "review-comment",
429 reactions: [
430 { content: "rocket", count: 1, actors: ["reviewer"], viewerHasReacted: false },
431 ],
432 },
433 ],
434 );
435 const inlineComment = activity.comments[2];
436 assert.ok(inlineComment);
437 assert.deepStrictEqual(activity.reviewThreads[0]?.comments, [inlineComment]);
438 for (const reacted of [true, false]) {
439 yield* provider.setReaction({ ...input, subjectId: "review:8", content: "heart", reacted });
440 yield* provider.setReaction({ ...input, subjectId: "38", content: "rocket", reacted });
441 }
442 assert.deepStrictEqual(
443 writes.map(({ path, method, body }) => ({ path, method, body })),
444 [
445 {
446 path: "repos/maria/project/issues/comments/37/reactions",
447 method: "POST",
448 body: { content: "heart" },
449 },
450 {
451 path: "repos/maria/project/issues/comments/38/reactions",
452 method: "POST",
453 body: { content: "rocket" },
454 },
455 {
456 path: "repos/maria/project/issues/comments/37/reactions",
457 method: "DELETE",
458 body: { content: "heart" },
459 },
460 {
461 path: "repos/maria/project/issues/comments/38/reactions",
462 method: "DELETE",
463 body: { content: "rocket" },
464 },
465 ],
466 );
467 const missing = yield* provider
468 .setReaction({ ...input, subjectId: "review:9", content: "heart", reacted: true })
469 .pipe(Effect.result);
470 assert.strictEqual(missing._tag, "Failure");
471 if (missing._tag === "Failure") assert.include(missing.failure.detail, "comment ID");
472 assert.strictEqual(writes.length, 4);
473 responses["repos/maria/project/pulls/2/reviews/8/comments"] = Array.from(
474 { length: 501 },
475 (_, index) => ({
476 ...comment,
477 id: 1000 + index,
478 path: "file.ts",
479 position: 1,
480 original_position: 1,
481 commit_id: "head",
482 original_commit_id: "head",
483 resolver: null,
484 }),
485 );
486 for (let index = 0; index < 500; index++) {
487 responses[`repos/maria/project/issues/comments/${1000 + index}/reactions`] = [];
488 }
489 reactionReads = 0;
490 const bounded = yield* provider.getChangeRequestActivity(input);
491 assert.strictEqual(bounded.reviewThreads.length, 500);
492 assert.strictEqual(
493 bounded.comments.filter((entry) => entry.kind === "review-comment").length,
494 500,
495 );
496 assert.strictEqual(bounded.commentsTruncated, true);
497 assert.strictEqual(reactionReads, 502);
498 }).pipe(
499 Effect.provide(
500 Layer.mock(ForgejoCli.ForgejoCli)({
501 api: (input) => {
502 if (input.method) {
503 writes.push(input);
504 return Effect.succeed(processOutput("{}"));
505 }
506 const path = input.path.split("?")[0]!;
507 if (/\/issues\/comments\/\d+\/reactions$/.test(path)) reactionReads++;
508 assert.ok(Object.hasOwn(responses, path), `Unexpected Forgejo request: ${path}`);
509 const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
510 return encodeJsonEffect(page > 1 ? [] : responses[path]).pipe(
511 Effect.orDie,
512 Effect.map(processOutput),
513 );
514 },
515 }),
516 ),
517 );
518 },
519);
520​
521it.effect("discovers Forgejo accounts and retains the server port", () =>
522 Effect.gen(function* () {
523 const auth = ForgejoSourceControlProvider.discovery.parseAuth(
524 processOutput(
525 yield* encodeJsonEffect([
526 {
527 name: "work",
528 url: "http://forgejo.local:3000",
529 ssh_host: "git.forgejo.local",
530 user: "maria",
531 default: "true",
532 valid: "true",
533 },
534 ]),
535 ),
536 );
537 assert.deepStrictEqual(
538 firstNonEmptyLine("\u001b[1mtea version 0.16.0\u001b[0m\n"),
539 Option.some("tea version 0.16.0"),
540 );
541 assert.strictEqual(auth.status, "authenticated");
542 assert.deepStrictEqual(auth.account, Option.some("maria"));
543 assert.deepStrictEqual(auth.host, Option.some("forgejo.local:3000"));
544 const revoked = ForgejoSourceControlProvider.discovery.parseAuth(
545 processOutput(
546 encodeJson([
547 {
548 name: "work",
549 url: "http://forgejo.local:3000",
550 user: "maria",
551 default: "true",
552 valid: "false",
553 },
554 ]),
555 ),
556 );
557 assert.strictEqual(revoked.status, "unauthenticated");
558 const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
559 cwd: "/repo",
560 context: {
561 provider: {
562 kind: SourceControlProviderKind.make("unknown"),
563 name: "git.forgejo.local",
564 baseUrl: "https://git.forgejo.local",
565 },
566 remoteName: "origin",
567 remoteUrl: "git@git.forgejo.local:maria/project.git",
568 },
569 auth: processOutput(
570 yield* encodeJsonEffect([
571 {
572 name: "work",
573 url: "http://forgejo.local:3000",
574 ssh_host: "git.forgejo.local",
575 user: "maria",
576 default: "true",
577 },
578 ]),
579 ),
580 });
581 assert.deepStrictEqual(refined, {
582 kind: SourceControlProviderKind.make("forgejo"),
583 name: "Forgejo / Gitea",
584 baseUrl: "http://forgejo.local:3000",
585 });
586 }),
587);
588​
589it.effect("does not choose a default Forgejo login across ambiguous SSH server ports", () =>
590 Effect.gen(function* () {
591 const logins = ForgejoCli.parseForgejoLogins(
592 yield* encodeJsonEffect([
593 {
594 name: "one",
595 url: "http://forgejo.local:3000",
596 ssh_host: "forgejo.local",
597 user: "maria",
598 default: "true",
599 },
600 {
601 name: "two",
602 url: "http://forgejo.local:4000",
603 ssh_host: "forgejo.local",
604 user: "maria",
605 default: "false",
606 },
607 ]),
608 );
609 const remote = ForgejoCli.parseForgejoRemote("git@forgejo.local:maria/project.git");
610 assert.isNotNull(remote);
611 assert.deepStrictEqual(
612 ForgejoCli.parseForgejoRemote("forgejo.local:maria/project.git"),
613 remote,
614 );
615 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!));
616 assert.strictEqual(
617 ForgejoCli.matchForgejoLogin(logins, remote!, "forgejo.local:4000")?.name,
618 "two",
619 );
620 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!, "other.local:4000"));
621 const alias = ForgejoCli.parseForgejoRemote("git@ssh.forgejo.local:maria/project.git");
622 assert.isNotNull(alias);
623 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, alias!, "forgejo.local:4000"));
624 const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
625 cwd: "/repo",
626 context: {
627 provider: {
628 kind: SourceControlProviderKind.make("unknown"),
629 name: "Forgejo",
630 baseUrl: "https://forgejo.local",
631 },
632 remoteName: "origin",
633 remoteUrl: "git@forgejo.local:maria/project.git",
634 requestedHost: "forgejo.local:4000",
635 },
636 auth: processOutput(yield* encodeJsonEffect(logins)),
637 });
638 assert.strictEqual(refined?.baseUrl, "http://forgejo.local:4000");
639 const https = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000/maria/project.git");
640 assert.isNotNull(https);
641 assert.strictEqual(ForgejoCli.matchForgejoLogin(logins, https!)?.name, "two");
642 const hostOnly = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000");
643 assert.strictEqual(
644 ForgejoCli.matchForgejoLogin(logins, hostOnly!, undefined, true)?.name,
645 "two",
646 );
647 const mounted = logins.map((login) => ({
648 ...login,
649 url: `http://forgejo.local:4000/${login.name}`,
650 }));
651 assert.isUndefined(ForgejoCli.matchForgejoLogin(mounted, hostOnly!, undefined, true));
652 }),
653);
654​
655it.effect("rejects HTTP failures even when tea exits successfully", () =>
656 Effect.gen(function* () {
657 const cli = yield* ForgejoCli.make;
658 const result = yield* cli
659 .api({
660 cwd: "/repo",
661 repository: "http://forgejo.local:3000/maria/project",
662 path: "repos/maria/project/pulls/42",
663 method: "PATCH",
664 body: { state: "closed" },
665 })
666 .pipe(Effect.result);
667 assert.strictEqual(result._tag, "Failure");
668 if (result._tag === "Failure")
669 assert.strictEqual(
670 result.failure.detail,
671 "Forgejo repository or pull request was not found.",
672 );
673 }).pipe(
674 Effect.provideService(
675 FileSystem.FileSystem,
676 FileSystem.makeNoop({
677 exists: () => Effect.succeed(false),
678 }),
679 ),
680 Effect.provideService(
681 HttpClient.HttpClient,
682 HttpClient.make(() => {
683 throw new Error("tea must handle its own HTTP request");
684 }),
685 ),
686 Effect.provide(
687 TestSourceControlHost.layer({
688 process: {
689 run: (input) => {
690 if (input.args[0] === "api") {
691 assert.strictEqual(input.stdin, '{"state":"closed"}');
692 assert.include(input.args, "work");
693 assert.include(
694 input.args,
695 "http://forgejo.local:3000/api/v1/repos/maria/project/pulls/42",
696 );
697 }
698 return Effect.succeed(
699 input.args[0] === "login"
700 ? processOutput(
701 encodeJson([
702 {
703 name: "work",
704 url: "http://forgejo.local:3000",
705 ssh_host: "forgejo.local",
706 user: "maria",
707 default: "true",
708 },
709 ]),
710 )
711 : processOutput('{"message":"not found"}', { stderr: "HTTP/1.1 404 Not Found\n" }),
712 );
713 },
714 },
715 }),
716 ),
717 ),
718);
719​
720it.effect("routes mounted Forgejo repositories without repeating the mount in API paths", () =>
721 Effect.gen(function* () {
722 const cli = yield* ForgejoCli.make;
723 const viewer = yield* cli.api({ cwd: "/upstream-only", host: "code.test", path: "user" });
724 assert.strictEqual(viewer.stdout, "[]");
725 const mountedRepository = yield* cli.resolveRepository({
726 cwd: "/upstream-only",
727 host: "code.test",
728 repository: "maria/project",
729 });
730 assert.strictEqual(mountedRepository.baseUrl, "https://code.test/forgejo");
731 assert.strictEqual(mountedRepository.repository, "maria/project");
732 for (const path of [
733 "repos/forgejo/maria/project/pulls?state=open",
734 "repos/forgejo/maria/project",
735 "repos/reviewer/project/contents/file.ts",
736 ]) {
737 const result = yield* cli.api({
738 cwd: "/repo",
739 repository: "forgejo/maria/project",
740 context: {
741 provider: {
742 kind: SourceControlProviderKind.make("forgejo"),
743 name: "Forgejo",
744 baseUrl: "https://code.test/forgejo",
745 },
746 remoteName: "origin",
747 remoteUrl: "https://code.test/forgejo/maria/project.git",
748 },
749 path,
750 });
751 assert.strictEqual(result.stdout, "[]");
752 }
753 const sameOwnerAsMount = yield* cli.resolveRepository({
754 cwd: "/repo",
755 repository: "forgejo/project",
756 context: {
757 provider: {
758 kind: SourceControlProviderKind.make("forgejo"),
759 name: "Forgejo",
760 baseUrl: "https://code.test/forgejo",
761 },
762 remoteName: "origin",
763 remoteUrl: "ssh://git@code.test/forgejo/project.git",
764 },
765 });
766 assert.strictEqual(sameOwnerAsMount.command, "tea");
767 assert.strictEqual(sameOwnerAsMount.repository, "forgejo/project");
768 }).pipe(
769 Effect.provideService(
770 FileSystem.FileSystem,
771 FileSystem.makeNoop({
772 exists: () => Effect.succeed(true),
773 readFileString: () =>
774 Effect.succeed(
775 encodeJson({
776 hosts: { "code.test/forgejo": { type: "Application", token: "test-token" } },
777 }),
778 ),
779 }),
780 ),
781 Effect.provideService(
782 HttpClient.HttpClient,
783 HttpClient.make(() => {
784 throw new Error("tea must handle its own HTTP request");
785 }),
786 ),
787 Effect.provide(
788 TestSourceControlHost.layer({
789 process: {
790 run: (input) => {
791 if (input.command === "git")
792 return Effect.succeed(
793 processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
794 );
795 if (input.args[0] === "login")
796 return Effect.succeed(
797 processOutput(
798 encodeJson([
799 {
800 name: "mounted",
801 url: "https://code.test/forgejo",
802 ssh_host: "code.test",
803 user: "maria",
804 default: "true",
805 },
806 ]),
807 ),
808 );
809 const supported = [
810 "https://code.test/forgejo/api/v1/user",
811 "https://code.test/forgejo/api/v1/repos/maria/project/pulls?state=open",
812 "https://code.test/forgejo/api/v1/repos/maria/project",
813 "https://code.test/forgejo/api/v1/repos/reviewer/project/contents/file.ts",
814 ];
815 if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
816 assert.strictEqual(input.command, "tea");
817 return Effect.succeed(
818 supported.includes(input.args.at(-1) ?? "")
819 ? processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" })
820 : processOutput("{}", { stderr: "HTTP/1.1 404 Not Found\n" }),
821 );
822 },
823 },
824 }),
825 ),
826 ),
827);
828​
829it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {
830 const commands: string[] = [];
831 const requests: string[] = [];
832 return Effect.gen(function* () {
833 const cli = yield* ForgejoCli.make;
834 for (const remoteUrl of [
835 "http://forgejo.local:3000/maria/project.git",
836 "ssh://git@ssh.forgejo.local:2222/maria/project.git",
837 "ssh://git@forgejo.local:2222/maria/project.git",
838 ]) {
839 const result = yield* cli.api({
840 cwd: "/repo",
841 repository: "maria/project",
842 context: {
843 provider: {
844 kind: SourceControlProviderKind.make("forgejo"),
845 name: "Forgejo",
846 baseUrl: "http://forgejo.local:3000",
847 },
848 remoteName: "origin",
849 remoteUrl,
850 requestedHost: "forgejo.local:3000",
851 },
852 path: "repos/maria/project/issues/42/comments",
853 method: "POST",
854 body: { body: "verified through fj" },
855 });
856 assert.strictEqual(result.stdout, '{"id":99}');
857 }
858 assert.deepStrictEqual(commands, ["fj"]);
859 assert.deepStrictEqual(requests, [
860 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
861 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
862 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
863 ]);
864 const viewer = yield* cli.api({
865 cwd: "/no-remotes",
866 host: "forgejo.local:3000",
867 path: "user",
868 });
869 assert.strictEqual(viewer.stdout, '{"login":"maria"}');
870 assert.strictEqual(requests.at(-1), "https://forgejo.local:3000/api/v1/user");
871 const upstreamViewer = yield* cli.api({
872 cwd: "/upstream-only",
873 host: "forgejo.local:3000",
874 path: "user",
875 });
876 assert.strictEqual(upstreamViewer.stdout, '{"login":"maria"}');
877 assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
878 const upstreamRepository = yield* cli.resolveRepository({
879 cwd: "/upstream-only",
880 host: "forgejo.local:3000",
881 repository: "maria/project",
882 });
883 assert.strictEqual(upstreamRepository.baseUrl, "http://forgejo.local:3000");
884 assert.strictEqual(upstreamRepository.repository, "maria/project");
885 const httpViewer = yield* cli.api({ cwd: "/repo", host: "forgejo.local:3000", path: "user" });
886 assert.strictEqual(httpViewer.stdout, '{"login":"maria"}');
887 assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
888 }).pipe(
889 Effect.provideService(
890 FileSystem.FileSystem,
891 FileSystem.makeNoop({
892 exists: () => Effect.succeed(true),
893 readFileString: () =>
894 Effect.succeed(
895 encodeJson({
896 hosts: {
897 "forgejo.local:3000": { type: "Application", token: "test-token" },
898 "forgejo.local:4000": { type: "Application", token: "other-token" },
899 },
900 aliases: { "ssh.forgejo.local:2222": "forgejo.local:3000" },
901 }),
902 ),
903 }),
904 ),
905 Effect.provideService(
906 HttpClient.HttpClient,
907 HttpClient.make((request) => {
908 requests.push(request.url);
909 if (request.url.endsWith("/user")) {
910 assert.strictEqual(request.method, "GET");
911 assert.strictEqual(request.headers.authorization, "token test-token");
912 return Effect.succeed(
913 HttpClientResponse.fromWeb(request, new Response('{"login":"maria"}')),
914 );
915 }
916 assert.strictEqual(request.method, "POST");
917 assert.strictEqual(request.headers.authorization, "token test-token");
918 assert.deepStrictEqual(requestJson(request), { body: "verified through fj" });
919 return Effect.succeed(
920 HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),
921 );
922 }),
923 ),
924 Effect.provide(
925 TestSourceControlHost.layer({
926 process: {
927 run: (input) => {
928 commands.push(input.command);
929 if (input.command === "git")
930 return Effect.succeed(
931 input.cwd === "/no-remotes"
932 ? processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) })
933 : processOutput(
934 `${input.cwd === "/upstream-only" ? "upstream" : "origin"}\thttp://forgejo.local:3000/maria/project.git (fetch)\nother\thttp://forgejo.local:3000/maria/other.git (fetch)\nunrelated\thttp://other.local:3000/maria/project.git (fetch)`,
935 ),
936 );
937 assert.strictEqual(input.command, "fj");
938 assert.deepStrictEqual(input.args, [
939 "--host",
940 input.cwd === "/no-remotes"
941 ? "https://forgejo.local:3000"
942 : "http://forgejo.local:3000",
943 "whoami",
944 ]);
945 return Effect.succeed(processOutput(""));
946 },
947 },
948 }),
949 ),
950 );
951});
952​
953it.effect("loads later fj review pages when the server caps pages below the requested size", () => {
954 const pages: number[] = [];
955 let issueCommentRequests = 0;
956 return Effect.gen(function* () {
957 const cli = yield* ForgejoCli.make;
958 const provider = yield* ForgejoPullRequestProvider.make.pipe(
959 Effect.provideService(ForgejoCli.ForgejoCli, cli),
960 );
961 const activity = yield* provider.getChangeRequestActivity({
962 cwd: "/repo",
963 repository: "maria/project",
964 host: "forgejo.test",
965 number: 42,
966 });
967 assert.strictEqual(activity.commentCount, 42);
968 assert.strictEqual(activity.comments.at(-1)?.id, "review:41");
969 assert.strictEqual(activity.commentsTruncated, false);
970 assert.deepStrictEqual(pages, [1, 2, 3]);
971 assert.strictEqual(issueCommentRequests, 1);
972 }).pipe(
973 Effect.provideService(
974 FileSystem.FileSystem,
975 FileSystem.makeNoop({
976 exists: () => Effect.succeed(true),
977 readFileString: () =>
978 Effect.succeed(
979 encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
980 ),
981 }),
982 ),
983 Effect.provideService(
984 HttpClient.HttpClient,
985 HttpClient.make((request) => {
986 const url = new URL(request.url);
987 if (url.pathname === "/api/v1/repos/maria/project/issues/42/comments") {
988 issueCommentRequests++;
989 return Effect.succeed(
990 HttpClientResponse.fromWeb(
991 request,
992 new Response(
993 encodeJson([
994 {
995 id: 100,
996 body: "Unpaginated issue comment",
997 user: { login: "maria" },
998 created_at: "2026-09-13T00:00:00Z",
999 },
1000 ]),
1001 ),
1002 ),
1003 );
1005 if (url.pathname.endsWith("/reviews")) {
1006 const page = Number(url.searchParams.get("page"));
1007 pages.push(page);
1008 assert.ok(page >= 1 && page <= 3);
1009 const reviews = Array.from({ length: page < 3 ? 20 : 1 }, (_, index) => ({
1010 id: (page - 1) * 20 + index + 1,
1011 body: "Review from a capped page",
1012 user: { login: "maria" },
1013 state: "COMMENT",
1014 submitted_at: "2026-09-13T00:00:00Z",
1015 comments_count: 0,
1016 }));
1017 return Effect.succeed(
1018 HttpClientResponse.fromWeb(
1019 request,
1020 new Response(encodeJson(reviews), {
1021 headers:
1022 page === 2
1023 ? {}
1024 : {
1025 Link:
1026 page === 1
1027 ? `<${url.origin}${url.pathname}?limit=50&page=2>; rel="next"`
1028 : `<${url.origin}${url.pathname}?limit=50&page=1>; rel="prev"`,
1029 },
1030 }),
1031 ),
1032 );
1034 return Effect.succeed(
1035 HttpClientResponse.fromWeb(
1036 request,
1037 new Response(encodeJson(url.pathname === "/api/v1/user" ? { login: "maria" } : [])),
1038 ),
1039 );
1040 }),
1041 ),
1042 Effect.provide(
1043 TestSourceControlHost.layer({
1044 process: {
1045 run: (input) => {
1046 if (input.command === "git") {
1047 assert.deepStrictEqual(input.args, ["remote", "-v"]);
1048 return Effect.succeed(
1049 processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
1050 );
1052 assert.strictEqual(input.command, "fj");
1053 assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
1054 return Effect.succeed(processOutput(""));
1055 },
1056 },
1057 }),
1058 ),
1059 );
1060});
1061​
1062it.effect("falls back to tea when fj is missing or has no account for this server", () =>
1063 Effect.gen(function* () {
1064 for (const scenario of ["missing-cli", "missing-account", "stale-invalid-storage"] as const) {
1065 const commands: string[] = [];
1066 yield* Effect.gen(function* () {
1067 const cli = yield* ForgejoCli.make;
1068 const result = yield* cli.api({
1069 cwd: "/repo",
1070 repository: "https://forgejo.local:3000/maria/project",
1071 path: "repos/maria/project/pulls",
1072 });
1073 assert.strictEqual(result.stdout, "[]");
1074 assert.deepStrictEqual(
1075 commands,
1076 scenario === "missing-account" ? ["tea", "tea"] : ["fj", "tea", "tea"],
1077 );
1078 const viewer = yield* cli.api({
1079 cwd: "/upstream-only",
1080 host: "forgejo.local:3000",
1081 path: "user",
1082 });
1083 assert.strictEqual(viewer.stdout, "[]");
1084 }).pipe(
1085 Effect.provideService(
1086 FileSystem.FileSystem,
1087 FileSystem.makeNoop({
1088 exists: () => Effect.succeed(true),
1089 readFileString: () =>
1090 Effect.succeed(
1091 scenario === "stale-invalid-storage"
1092 ? "invalid json"
1093 : encodeJson({
1094 hosts: {
1095 [scenario === "missing-cli" ? "forgejo.local:3000" : "other.local"]: {
1096 type: "Application",
1097 token: "test-token",
1098 },
1099 },
1100 }),
1101 ),
1102 }),
1103 ),
1104 Effect.provideService(
1105 HttpClient.HttpClient,
1106 HttpClient.make(() => {
1107 throw new Error("tea must handle its own HTTP request");
1108 }),
1109 ),
1110 Effect.provide(
1111 TestSourceControlHost.layer({
1112 process: {
1113 run: (input) => {
1114 commands.push(input.command);
1115 if (input.command === "git")
1116 return Effect.succeed(
1117 processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
1118 );
1119 if (input.command === "fj")
1120 return Effect.fail(
1121 new VcsProcessSpawnError({
1122 operation: input.operation,
1123 command: input.command,
1124 cwd: input.cwd,
1125 cause: new Error("fj not found"),
1126 }),
1127 );
1128 assert.strictEqual(input.command, "tea");
1129 if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
1130 return Effect.succeed(
1131 input.args[0] === "login"
1132 ? processOutput(
1133 encodeJson([
1135 name: "work",
1136 url: "https://forgejo.local:3000",
1137 user: "maria",
1138 default: "true",
1139 valid: "true",
1140 },
1141 ]),
1143 : processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" }),
1144 );
1145 },
1146 },
1147 }),
1148 ),
1149 );
1151 }),
1153​
1154it.effect("handles fj mutation statuses without retrying failures or reading absent bodies", () =>
1155 Effect.gen(function* () {
1156 for (const status of [204, 205, 302, 401, 403, 404, 429, 500]) {
1157 let writes = 0;
1158 yield* Effect.gen(function* () {
1159 const cli = yield* ForgejoCli.make;
1160 const result = yield* cli
1161 .api({
1162 cwd: "/repo",
1163 repository: "https://forgejo.local/maria/project",
1164 path: "repos/maria/project/issues/42/comments",
1165 method: "POST",
1166 body: { body: "only once" },
1167 })
1168 .pipe(Effect.result);
1169 assert.strictEqual(result._tag, status < 300 ? "Success" : "Failure");
1170 if (result._tag === "Success") assert.strictEqual(result.success.stdout, "");
1171 if (result._tag === "Failure") {
1172 assert.strictEqual(result.failure.command, "fj");
1173 assert.strictEqual(result.failure.httpStatus, status);
1175 assert.strictEqual(writes, 1);
1176 }).pipe(
1177 Effect.provideService(
1178 FileSystem.FileSystem,
1179 FileSystem.makeNoop({
1180 exists: () => Effect.succeed(true),
1181 readFileString: () =>
1182 Effect.succeed(
1183 encodeJson({
1184 hosts: {
1185 "forgejo.local": { type: "Application", token: "test-token" },
1186 },
1187 }),
1188 ),
1189 }),
1190 ),
1191 Effect.provideService(
1192 HttpClient.HttpClient,
1193 HttpClient.make((request) => {
1194 writes++;
1195 assert.strictEqual(
1196 request.url,
1197 "https://forgejo.local/api/v1/repos/maria/project/issues/42/comments",
1198 );
1199 return Effect.succeed(
1200 HttpClientResponse.fromWeb(
1201 request,
1202 new Response(status < 300 ? null : "", {
1203 status,
1204 headers: { location: "https://other.local/" },
1205 }),
1206 ),
1207 );
1208 }),
1209 ),
1210 Effect.provide(
1211 TestSourceControlHost.layer({
1212 process: {
1213 run: (input) => {
1214 assert.strictEqual(
1215 input.command,
1216 "fj",
1217 "a failed mutation must never switch accounts or CLI",
1218 );
1219 return Effect.succeed(processOutput(""));
1220 },
1221 },
1222 }),
1223 ),
1224 );
1226 }),
1228​
1229it.effect(
1230 "discovers fj first and retains configured authentication failures instead of switching accounts",
1231 () =>
1232 Effect.gen(function* () {
1233 for (const scenario of ["authenticated", "revoked", "missing", "invalid-storage"] as const) {
1234 const commands: string[] = [];
1235 yield* Effect.gen(function* () {
1236 const spec = yield* ForgejoSourceControlProvider.makeDiscovery;
1237 assert.strictEqual(spec.type, "managed-cli");
1238 if (spec.type !== "managed-cli") return;
1239 const result = yield* spec.probe("/repo");
1240 assert.strictEqual(result.executable, scenario === "missing" ? "tea" : "fj");
1241 assert.strictEqual(
1242 result.auth.status,
1243 scenario === "revoked"
1244 ? "unauthenticated"
1245 : scenario === "invalid-storage"
1246 ? "unknown"
1247 : "authenticated",
1248 );
1249 if (scenario !== "revoked" && scenario !== "invalid-storage")
1250 assert.deepStrictEqual(result.auth.host, Option.some("forgejo.local:3000"));
1251 assert.deepStrictEqual(
1252 result.auth.account,
1253 scenario === "authenticated" || scenario === "missing"
1254 ? Option.some("maria")
1255 : Option.none(),
1256 );
1257 assert.strictEqual(
1258 commands.some((command) => command.startsWith("tea ")),
1259 scenario === "missing",
1260 );
1261 assert.include(commands, "fj version");
1262 }).pipe(
1263 Effect.provide(
1264 Layer.mergeAll(
1265 Layer.mock(ForgejoCli.ForgejoCli)({
1266 getAccount: (input) => {
1267 assert.strictEqual(scenario, "authenticated");
1268 assert.deepStrictEqual(input, {
1269 cwd: "/repo",
1270 baseUrl: "http://forgejo.local:3000",
1271 });
1272 return Effect.succeed("maria");
1273 },
1274 listLogins: (input) => {
1275 assert.strictEqual(
1276 input.remoteUrl,
1277 "http://forgejo.local:3000/maria/project.git",
1278 );
1279 if (scenario === "invalid-storage")
1280 return Effect.fail(
1281 new ForgejoCli.ForgejoCliError({
1282 command: "fj",
1283 cwd: input.cwd,
1284 reason: "authentication",
1285 detail: "fj authentication storage is invalid.",
1286 }),
1287 );
1288 return Effect.succeed([
1290 name: "forgejo.local:3000",
1291 url: "http://forgejo.local:3000",
1292 user: "",
1293 default: "false",
1294 },
1295 ]);
1296 },
1297 }),
1298 TestSourceControlHost.layer({
1299 process: {
1300 run: (input) => {
1301 commands.push(`${input.command} ${input.args.join(" ")}`);
1302 if (input.command === "git")
1303 return Effect.succeed(
1304 processOutput("http://forgejo.local:3000/maria/project.git\n"),
1305 );
1306 if (input.command === "fj") {
1307 if (scenario === "missing")
1308 return Effect.fail(
1309 new VcsProcessSpawnError({
1310 operation: input.operation,
1311 command: input.command,
1312 cwd: input.cwd,
1313 cause: new Error("fj not found"),
1314 }),
1315 );
1316 if (input.args[0] === "version")
1317 return Effect.succeed(processOutput("fj 0.10.0"));
1318 if (scenario === "invalid-storage") {
1319 assert.deepStrictEqual(input.args, ["auth", "list"]);
1320 return Effect.succeed(processOutput(""));
1322 assert.deepStrictEqual(input.args, [
1323 "--host",
1324 "http://forgejo.local:3000",
1325 "whoami",
1326 ]);
1327 return Effect.succeed(
1328 processOutput("", {
1329 exitCode: ChildProcessSpawner.ExitCode(scenario === "revoked" ? 1 : 0),
1330 }),
1331 );
1333 assert.strictEqual(input.command, "tea");
1334 return Effect.succeed(
1335 input.args[0] === "--version"
1336 ? processOutput("tea version 0.16.0")
1337 : processOutput(
1338 encodeJson([
1340 name: "work",
1341 url: "http://forgejo.local:3000",
1342 user: "maria",
1343 default: "true",
1344 valid: "true",
1345 },
1346 ]),
1347 ),
1348 );
1349 },
1350 },
1351 }),
1352 ),
1353 ),
1354 );
1356 }),