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

ForgejoSourceControlProvider.test.ts

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