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

ForgejoSourceControlProvider.test.ts

1,283 lines46.5 KB

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