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

ForgejoSourceControlProvider.test.ts

1,343 lines48.6 KB

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