The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,506 lines 90.2 KB
Raw
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Layer from "effect/Layer";
7 import * as Option from "effect/Option";
8 import * as PlatformError from "effect/PlatformError";
9 import * as Schema from "effect/Schema";
10 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11 import * as TestClock from "effect/testing/TestClock";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as HttpClientRequest from "effect/http/HttpClientRequest";
14 import * as HttpClientResponse from "effect/http/HttpClientResponse";
15 import { VcsProcessSpawnError, VcsProcessTimeoutError } from "@t3tools/contracts";
16 import { firstNonEmptyLine } from "@t3tools/source-control-core/server/discovery";
17 import * as HostProcess from "@t3tools/shared/HostProcess";
18 import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
19
20 import * as ForgejoCli from "./ForgejoCli.ts";
21 import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
22 import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
23 import { markRequiredForgejoChecks } from "./forgejoRequiredChecks.ts";
24
25 const processOutput = TestSourceControlHost.processOutput;
26
27 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
28 const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
29
30 const requestJson = (request: HttpClientRequest.HttpClientRequest): unknown => {
31 assert.strictEqual(request.body._tag, "Uint8Array");
32 return request.body._tag === "Uint8Array"
33 ? decodeJson(new TextDecoder().decode(request.body.body))
34 : undefined;
35 };
36 const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
37
38 it.effect("reads clone URLs on the given host rather than the checkout's", () => {
39 const urls: string[] = [];
40 const client = HttpClient.make((request) => {
41 urls.push(request.url);
42 return Effect.succeed(
43 HttpClientResponse.fromWeb(
44 request,
45 new Response(
46 encodeJson({
47 full_name: "maria/project",
48 clone_url: "https://forgejo.test/maria/project.git",
49 ssh_url: "git@forgejo.test:maria/project.git",
50 }),
51 ),
52 ),
53 );
54 });
55 return Effect.gen(function* () {
56 const cli = yield* ForgejoCli.make;
57 const provider = yield* ForgejoSourceControlProvider.make.pipe(
58 Effect.provideService(ForgejoCli.ForgejoCli, cli),
59 );
60 const cloneUrls = yield* provider.getRepositoryCloneUrls({
61 cwd: "/repo",
62 repository: "maria/project",
63 host: "forgejo.test",
64 });
65 assert.strictEqual(cloneUrls.url, "https://forgejo.test/maria/project.git");
66 assert.deepStrictEqual(urls, ["https://forgejo.test/api/v1/repos/maria/project"]);
67 }).pipe(
68 Effect.provideService(HttpClient.HttpClient, client),
69 Effect.provideService(
70 FileSystem.FileSystem,
71 FileSystem.makeNoop({
72 exists: () => Effect.succeed(true),
73 readFileString: () =>
74 Effect.succeed(
75 encodeJson({
76 hosts: {
77 "forgejo.test": { type: "Application", token: "test-token" },
78 "code.example": { type: "Application", token: "other-token" },
79 },
80 }),
81 ),
82 }),
83 ),
84 Effect.provide(
85 TestSourceControlHost.layer({
86 process: {
87 run: (input) => {
88 if (input.command === "git") {
89 assert.deepStrictEqual(input.args, ["remote", "-v"]);
90 // The checkout is on another Forgejo server with a same-named repository.
91 return Effect.succeed(
92 processOutput("origin\thttps://code.example/maria/project.git (fetch)"),
93 );
94 }
95 assert.strictEqual(input.command, "fj");
96 assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
97 return Effect.succeed(processOutput(""));
98 },
99 },
100 }),
101 ),
102 );
103 });
104
105 const requiredChecksPullRequest = {
106 number: 7,
107 title: "Required checks",
108 body: "",
109 html_url: "https://forgejo.test/acme/web/pulls/7",
110 user: { login: "maria" },
111 state: "open",
112 merged: false,
113 head: { ref: "feature", sha: "head", repo: null },
114 base: { ref: "release/1.x", sha: "base", repo: null },
115 created_at: "2026-10-12T00:00:00Z",
116 updated_at: "2026-10-12T00:00:00Z",
117 closed_at: null,
118 merged_at: null,
119 labels: [],
120 };
121 const requiredChecksStatuses = [
122 ["ci/required-build", "success"],
123 ["ci/optional-lint", "failure"],
124 ].map(([context, status]) => ({
125 context,
126 status,
127 description: null,
128 target_url: null,
129 updated_at: "2026-10-12T00:00:00Z",
130 }));
131
132 const requiredChecksInput = {
133 cwd: "/repo",
134 repository: "acme/web",
135 host: "forgejo.test",
136 number: 7,
137 };
138 const requiredChecksLayer = (
139 branch: Effect.Effect<unknown, ForgejoCli.ForgejoCliError>,
140 statuses = requiredChecksStatuses,
141 pull: Readonly<Record<string, unknown>> = requiredChecksPullRequest,
142 ) =>
143 Layer.mock(ForgejoCli.ForgejoCli)({
144 api: (input) => {
145 const [path, query] = input.path.split("?");
146 const respond = (response: unknown) =>
147 encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
148 switch (path) {
149 case "repos/acme/web/pulls/7":
150 return respond(pull);
151 case "repos/acme/web/statuses/head":
152 return respond(new URLSearchParams(query).get("page") === "1" ? statuses : []);
153 case "repos/acme/web/branches/release/1.x":
154 return Effect.flatMap(branch, respond);
155 case "repos/acme/web":
156 return respond({ full_name: "acme/web", permissions: { push: true, admin: false } });
157 case "user":
158 return respond({ login: "maria" });
159 default:
160 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
161 }
162 },
163 });
164
165 it.effect.each([
166 ["ci/required-deploy", true],
167 ["test-*", true],
168 ["ci/[ab]", false],
169 ] as const)("keeps missing required pattern %s pending (supported: %s)", ([missing, supported]) =>
170 Effect.gen(function* () {
171 const provider = yield* ForgejoPullRequestProvider.make;
172 const readChecks = provider.getChangeRequestChecks;
173 if (readChecks === undefined) return yield* Effect.die("checks read missing");
174 const summary = yield* readChecks(requiredChecksInput);
175 const detail = yield* provider.getChangeRequest(requiredChecksInput);
176 for (const checks of [summary.checks, detail.checks]) {
177 assert.deepStrictEqual(
178 checks.map((check) => [check.name, check.status, check.required]),
179 supported
180 ? [
181 ["ci/optional-lint", "failure", undefined],
182 ["ci/required-build", "success", true],
183 [missing, "pending", true],
184 ]
185 : [
186 ["ci/required-build", "success", undefined],
187 ["ci/optional-lint", "success", undefined],
188 [missing, "pending", undefined],
189 ],
190 );
191 if (!supported) {
192 assert.strictEqual(
193 checks.at(-1)?.description,
194 "Required check pattern cannot be evaluated.",
195 );
196 }
197 }
198 }).pipe(
199 Effect.provide(
200 requiredChecksLayer(
201 Effect.succeed({
202 name: "release/1.x",
203 protected: true,
204 enable_status_check: true,
205 status_check_contexts: ["ci/required-*", missing, missing],
206 }),
207 supported
208 ? requiredChecksStatuses
209 : requiredChecksStatuses.map((status) => ({ ...status, status: "success" })),
210 ),
211 ),
212 ),
213 );
214
215 it("matches many-wildcard required patterns against long check names without backtracking", () => {
216 const checks = ["a".repeat(200), `${"a".repeat(199)}b`, "x?y\nz"].map((name) => ({
217 name,
218 status: "success" as const,
219 description: null,
220 url: null,
221 }));
222 const marked = markRequiredForgejoChecks(checks, {
223 enable_status_check: true,
224 status_check_contexts: [`${"*a".repeat(12)}b`, "x*?y?z"],
225 });
226 assert.deepStrictEqual(
227 marked.map((check) => [check.name.slice(-3), check.required]),
228 [
229 ["aaa", undefined],
230 ["aab", true],
231 ["y\nz", true],
232 ],
233 );
234 });
235
236 it("treats a required pattern's `*` as a wildcard even when the check name has one", () => {
237 const checks = ["*build", "ci/*lint"].map((name) => ({
238 name,
239 status: "success" as const,
240 description: null,
241 url: null,
242 }));
243 const marked = markRequiredForgejoChecks(checks, {
244 enable_status_check: true,
245 status_check_contexts: ["*build", "ci/*"],
246 });
247 assert.deepStrictEqual(
248 marked.map((check) => [check.name, check.required]),
249 [
250 ["*build", true],
251 ["ci/*lint", true],
252 ],
253 );
254 });
255
256 const tiedStatuses = [
257 { id: 15, status: "success" },
258 { id: 14, status: "pending" },
259 ].map(({ id, status }) => ({
260 id,
261 context: "ci/required-build",
262 status,
263 description: null,
264 target_url: null,
265 updated_at: "2026-10-12T10:14:29Z",
266 }));
267
268 it.effect.each([
269 ["newest first", tiedStatuses],
270 ["oldest first", tiedStatuses.toReversed()],
271 ] as const)("reads the status created last when two share a second, listed %s", ([, statuses]) =>
272 Effect.gen(function* () {
273 const provider = yield* ForgejoPullRequestProvider.make;
274 const readChecks = provider.getChangeRequestChecks;
275 if (readChecks === undefined) return yield* Effect.die("checks read missing");
276 const summary = yield* readChecks(requiredChecksInput);
277 const detail = yield* provider.getChangeRequest(requiredChecksInput);
278 for (const checks of [summary.checks, detail.checks]) {
279 assert.deepStrictEqual(
280 checks.map((check) => [check.name, check.status]),
281 [["ci/required-build", "success"]],
282 );
283 }
284 }).pipe(Effect.provide(requiredChecksLayer(Effect.succeed({}), statuses))),
285 );
286
287 const forgejoMergeProvider = (repository: Effect.Effect<string, ForgejoCli.ForgejoCliError>) => {
288 const writes: Array<ForgejoCli.ForgejoApiInput> = [];
289 const provider = ForgejoPullRequestProvider.make.pipe(
290 Effect.provide(
291 Layer.mock(ForgejoCli.ForgejoCli)({
292 api: (input) => {
293 if (input.method !== undefined && input.method !== "GET") writes.push(input);
294 return (input.path === "repos/reviewer/project" ? repository : Effect.succeed("")).pipe(
295 Effect.map((stdout) => ({
296 exitCode: ChildProcessSpawner.ExitCode(0),
297 stdout,
298 stderr: "",
299 stdoutTruncated: false,
300 stderrTruncated: false,
301 })),
302 );
303 },
304 }),
305 ),
306 );
307 return { provider, writes };
308 };
309 const forgejoMergeInput = {
310 cwd: "/forgejo",
311 repository: "reviewer/project",
312 host: "forge.example:3000",
313 number: 1,
314 action: "merge",
315 mergeMethod: "squash",
316 } as const;
317
318 it.effect("follows the Forgejo repository's delete-branch-after-merge setting", () =>
319 Effect.gen(function* () {
320 for (const [setting, deleteBranch] of [
321 [{ default_delete_branch_after_merge: true }, true],
322 [{ default_delete_branch_after_merge: false }, false],
323 [{}, false],
324 ] as const) {
325 const { provider, writes } = forgejoMergeProvider(
326 Effect.succeed(JSON.stringify({ full_name: "reviewer/project", ...setting })),
327 );
328 yield* (yield* provider).runAction(forgejoMergeInput);
329 assert.deepStrictEqual(
330 writes.map((write) => [write.path, write.body]),
331 [
332 [
333 "repos/reviewer/project/pulls/1/merge",
334 { Do: "squash", delete_branch_after_merge: deleteBranch },
335 ],
336 ],
337 `repository setting ${JSON.stringify(setting)}`,
338 );
339 }
340 }),
341 );
342
343 it.effect("does not merge on Forgejo when the repository settings cannot be read", () =>
344 Effect.gen(function* () {
345 const { provider, writes } = forgejoMergeProvider(
346 Effect.fail(
347 new ForgejoCli.ForgejoCliError({
348 command: "tea",
349 cwd: "/forgejo",
350 detail: "Forgejo is unavailable.",
351 }),
352 ),
353 );
354 const exit = yield* Effect.exit((yield* provider).runAction(forgejoMergeInput));
355 assert.deepStrictEqual(
356 writes.map((write) => write.path),
357 [],
358 "merged without knowing whether to delete the source branch",
359 );
360 assert.isTrue(Exit.isFailure(exit));
361 }),
362 );
363
364 it.effect.each([
365 [true, false],
366 [false, true],
367 ] as const)(
368 "reports a Forgejo merge whose branch deletion was refused by whether it merged (merged: %s)",
369 ([merged, fails]) => {
370 const refused = new ForgejoCli.ForgejoCliError({
371 command: "fj",
372 cwd: "/repo",
373 detail: "branch is protected",
374 httpStatus: 403,
375 reason: "forbidden",
376 });
377 return Effect.gen(function* () {
378 const provider = yield* ForgejoPullRequestProvider.make;
379 const exit = yield* Effect.exit(
380 provider.runAction({ ...requiredChecksInput, action: "merge", mergeMethod: "merge" }),
381 );
382 assert.strictEqual(exit._tag === "Failure", fails);
383 }).pipe(
384 Effect.provide(
385 Layer.mock(ForgejoCli.ForgejoCli)({
386 api: (input) => {
387 const respond = (response: unknown) =>
388 encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
389 switch (input.path) {
390 case "repos/acme/web":
391 return respond({ full_name: "acme/web", default_delete_branch_after_merge: true });
392 case "repos/acme/web/pulls/7/merge":
393 return Effect.fail(refused);
394 case "repos/acme/web/pulls/7":
395 return respond({ ...requiredChecksPullRequest, merged });
396 default:
397 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
398 }
399 },
400 }),
401 ),
402 );
403 },
404 );
405
406 // regression: #18775 a failed branch-protection read surfaces; only 403/404 are treated as no policy
407 it.effect.each([
408 ["rate limit", { reason: "rate-limit", httpStatus: 429 }, "rate-limited"],
409 ["authentication failure", { reason: "authentication", httpStatus: 401 }, "unauthenticated"],
410 ["network failure", {}, "failed"],
411 ] as const)("propagates branch metadata %s", ([detail, fields, reason]) => {
412 const cause = new ForgejoCli.ForgejoCliError({ command: "fj", cwd: "/repo", detail, ...fields });
413 return Effect.gen(function* () {
414 const provider = yield* ForgejoPullRequestProvider.make;
415 const readChecks = provider.getChangeRequestChecks;
416 if (readChecks === undefined) return yield* Effect.die("checks read missing");
417 for (const read of [readChecks, provider.getChangeRequest]) {
418 const error = yield* read(requiredChecksInput).pipe(Effect.flip);
419 assert.strictEqual(error.reason, reason);
420 assert.strictEqual(error.cause, cause);
421 }
422 }).pipe(Effect.provide(requiredChecksLayer(Effect.fail(cause))));
423 });
424
425 it.effect("reads a merged pull request's merge commit and who merged it", () =>
426 Effect.gen(function* () {
427 const provider = yield* ForgejoPullRequestProvider.make;
428 const detail = yield* provider.getChangeRequest(requiredChecksInput);
429 assert.strictEqual(detail.state, "merged");
430 assert.strictEqual(detail.mergeCommitSha, "394a757942c5c3a9fb3cca31e348849e8c6a6dbe");
431 assert.deepStrictEqual(detail.mergedBy, { login: "gusted", name: null, avatarUrl: null });
432 }).pipe(
433 Effect.provide(
434 requiredChecksLayer(Effect.succeed({ name: "release/1.x" }), [], {
435 ...requiredChecksPullRequest,
436 state: "closed",
437 merged: true,
438 closed_at: "2026-10-27T00:08:58+01:00",
439 merged_at: "2026-10-27T00:08:58+01:00",
440 merge_commit_sha: "394a757942c5c3a9fb3cca31e348849e8c6a6dbe",
441 merged_by: { login: "gusted" },
442 }),
443 ),
444 ),
445 );
446
447 it.effect("reads Forgejo jobs that did not run as finished checks", () =>
448 Effect.gen(function* () {
449 const provider = yield* ForgejoPullRequestProvider.make;
450 const read = provider.getChangeRequestChecks;
451 if (read === undefined) return yield* Effect.die("checks read missing");
452 const result = yield* read({
453 cwd: "/repo",
454 repository: "acme/web",
455 host: "forgejo.test",
456 number: 1,
457 });
458 assert.deepStrictEqual(
459 result.checks.map((check) => [check.name, check.status]),
460 [
461 ["deploy", "skipped"],
462 ["audit", "neutral"],
463 ["docs", "pending"],
464 ],
465 );
466 }).pipe(
467 Effect.provide(
468 Layer.mock(ForgejoCli.ForgejoCli)({
469 api: (input) => {
470 if (input.path.endsWith("branches/main")) {
471 return encodeJsonEffect({}).pipe(Effect.orDie, Effect.map(processOutput));
472 }
473 const status = (context: string, state: string) => ({
474 context,
475 status: state,
476 description: null,
477 target_url: null,
478 updated_at: "2026-10-11T00:00:00Z",
479 });
480 const body = input.path.endsWith("branches/main")
481 ? {}
482 : input.path.endsWith("pulls/1")
483 ? {
484 number: 1,
485 title: "Checks",
486 body: "",
487 html_url: "https://forgejo.test/acme/web/pulls/1",
488 user: null,
489 state: "open",
490 merged: false,
491 head: { ref: "feature", sha: "head", repo: null },
492 base: { ref: "main", sha: "base", repo: null },
493 created_at: "2026-10-11T00:00:00Z",
494 updated_at: "2026-10-11T00:00:00Z",
495 closed_at: null,
496 merged_at: null,
497 labels: [],
498 }
499 : input.path.endsWith("page=1")
500 ? [
501 status("deploy", "skipped"),
502 status("audit", "warning"),
503 status("docs", "future-state"),
504 ]
505 : [];
506 return encodeJsonEffect(body).pipe(Effect.orDie, Effect.map(processOutput));
507 },
508 }),
509 ),
510 ),
511 );
512
513 it.effect("opens Forgejo Actions check links on the pull request's server", () =>
514 Effect.gen(function* () {
515 const provider = yield* ForgejoPullRequestProvider.make;
516 const read = provider.getChangeRequestChecks;
517 if (read === undefined) return yield* Effect.die("checks read missing");
518 const result = yield* read({
519 cwd: "/repo",
520 repository: "acme/web",
521 host: "forgejo.test",
522 number: 1,
523 });
524 assert.deepStrictEqual(
525 result.checks.map((check) => [check.name, check.url]),
526 [
527 ["actions", "https://forgejo.test/git/acme/web/actions/runs/7/jobs/2"],
528 ["external", "https://ci.example/build/9"],
529 ["none", null],
530 ],
531 );
532 }).pipe(
533 Effect.provide(
534 Layer.mock(ForgejoCli.ForgejoCli)({
535 api: (input) => {
536 const status = (context: string, target_url: string | null) => ({
537 context,
538 status: "success",
539 description: null,
540 target_url,
541 updated_at: "2026-10-11T00:00:00Z",
542 });
543 const body = input.path.endsWith("branches/main")
544 ? {}
545 : input.path.endsWith("pulls/1")
546 ? {
547 number: 1,
548 title: "Checks",
549 body: "",
550 html_url: "https://forgejo.test/git/acme/web/pulls/1",
551 user: null,
552 state: "open",
553 merged: false,
554 head: { ref: "feature", sha: "head", repo: null },
555 base: { ref: "main", sha: "base", repo: null },
556 created_at: "2026-10-11T00:00:00Z",
557 updated_at: "2026-10-11T00:00:00Z",
558 closed_at: null,
559 merged_at: null,
560 labels: [],
561 }
562 : input.path.endsWith("page=1")
563 ? [
564 // Forgejo includes any sub-path mount in the relative links it reports.
565 status("actions", "/git/acme/web/actions/runs/7/jobs/2"),
566 status("external", "https://ci.example/build/9"),
567 status("none", null),
568 ]
569 : [];
570 return encodeJsonEffect(body).pipe(Effect.orDie, Effect.map(processOutput));
571 },
572 }),
573 ),
574 ),
575 );
576
577 it.effect.each([
578 ["Ready", false, true, false, "mergeable"],
579 ["Draft", true, false, true, "unknown"],
580 ["WIP: Legacy draft", undefined, false, true, "unknown"],
581 ["WIP: Explicitly ready", false, false, false, "unknown"],
582 ] as const)(
583 "reads Forgejo mergeability for %s (draft=%s, mergeable=%s) across list, summary and detail",
584 ([title, draft, mergeable, isDraft, mergeability]) => {
585 const pr = {
586 number: 42,
587 title,
588 body: "",
589 html_url: "https://forgejo.test/maria/project/pulls/42",
590 user: { login: "maria" },
591 state: "open",
592 merged: false,
593 ...(draft === undefined ? {} : { draft }),
594 ...(mergeable === undefined ? {} : { mergeable }),
595 head: { ref: "feature", sha: "head", repo: null },
596 base: { ref: "main", sha: "base", repo: null },
597 created_at: "2026-09-16T00:00:00Z",
598 updated_at: "2026-09-16T00:00:00Z",
599 closed_at: null,
600 merged_at: null,
601 labels: [
602 { id: 1, name: "bug", color: "ee0701", description: "Something is broken" },
603 { id: 2, name: "triage", color: "c5def5", description: "" },
604 ],
605 };
606 const requests: string[] = [];
607 return Effect.gen(function* () {
608 const provider = yield* ForgejoPullRequestProvider.make;
609 const readSummary = provider.getChangeRequestSummary;
610 if (readSummary === undefined) return yield* Effect.die("summary read missing");
611 const readPreview = provider.getChangeRequestPreview;
612 if (readPreview === undefined) return yield* Effect.die("preview read missing");
613 const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 42 };
614 const preview = yield* readPreview(input);
615 assert.deepStrictEqual(requests, ["repos/maria/project/pulls/42"]);
616 assert.strictEqual(preview.isDraft, isDraft);
617 assert.strictEqual(preview.title, title);
618 assert.strictEqual(preview.state, "open");
619 assert.strictEqual(preview.number, 42);
620 assert.strictEqual(preview.url, pr.html_url);
621 assert.deepStrictEqual(preview.author, { login: "maria", name: null, avatarUrl: null });
622 assert.strictEqual(preview.createdAt, "2026-09-16T00:00:00.000Z");
623 const list = yield* provider.listChangeRequests({
624 ...input,
625 state: "open",
626 involvement: "all",
627 viewer: "maria",
628 limit: 10,
629 });
630 const summary = yield* readSummary(input);
631 const detail = yield* provider.getChangeRequest(input);
632 assert.strictEqual(list.items.length, 1);
633 assert.strictEqual(detail.headSha, "head");
634 assert.deepStrictEqual(detail.labels, [
635 { name: "bug", color: "ee0701", description: "Something is broken" },
636 { name: "triage", color: "c5def5", description: null },
637 ]);
638 for (const result of [list.items[0]!, summary, detail]) {
639 assert.strictEqual(result.mergeability, mergeability);
640 assert.strictEqual(result.isDraft, isDraft);
641 }
642 }).pipe(
643 Effect.provide(
644 Layer.mock(ForgejoCli.ForgejoCli)({
645 api: (input) => {
646 requests.push(input.path);
647 const [path, query] = input.path.split("?");
648 let response: unknown;
649 switch (path) {
650 case "repos/maria/project/pulls":
651 response = new URLSearchParams(query).get("page") === "1" ? [pr] : [];
652 break;
653 case "repos/maria/project/pulls/42":
654 response = pr;
655 break;
656 case "repos/maria/project":
657 response = { full_name: "maria/project", permissions: { push: true, admin: true } };
658 break;
659 case "user":
660 response = pr.user;
661 break;
662 case "repos/maria/project/statuses/head":
663 response = [];
664 break;
665 case "repos/maria/project/branches/main":
666 response = { name: "main", protected: false };
667 break;
668 default:
669 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
670 }
671 return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
672 },
673 }),
674 ),
675 );
676 },
677 );
678
679 it.effect("asks Forgejo for one required label by id and the author by login", () => {
680 const paths: Array<string> = [];
681 return Effect.gen(function* () {
682 const provider = yield* ForgejoPullRequestProvider.make;
683 yield* provider.listChangeRequests({
684 cwd: "/repo",
685 repository: "maria/project",
686 host: "forgejo.test",
687 state: "open",
688 involvement: "all",
689 viewer: "maria",
690 limit: 10,
691 filters: { labels: [["size:S", "size:M"], ["Bug"]], author: "@me" },
692 });
693 const listing = paths.find((path) => path.startsWith("repos/maria/project/pulls?"));
694 const params = new URLSearchParams(listing?.split("?")[1]);
695 assert.deepStrictEqual(params.getAll("labels"), ["7"]);
696 assert.strictEqual(params.get("poster"), "maria");
697 }).pipe(
698 Effect.provide(
699 Layer.mock(ForgejoCli.ForgejoCli)({
700 api: (input) => {
701 paths.push(input.path);
702 const response = input.path.startsWith("repos/maria/project/labels")
703 ? [{ id: 7, name: "bug" }]
704 : [];
705 return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
706 },
707 }),
708 ),
709 );
710 });
711
712 it.effect("lists nothing for an author Forgejo has no account for", () =>
713 Effect.gen(function* () {
714 const provider = yield* ForgejoPullRequestProvider.make;
715 const page = yield* provider.listChangeRequests({
716 cwd: "/repo",
717 repository: "maria/project",
718 host: "forgejo.test",
719 state: "open",
720 involvement: "all",
721 viewer: "maria",
722 limit: 10,
723 filters: { author: "nobody" },
724 });
725 assert.deepStrictEqual(page, { items: [], truncated: false, continues: false });
726 }).pipe(
727 Effect.provide(
728 Layer.mock(ForgejoCli.ForgejoCli)({
729 api: (input) =>
730 Effect.fail(
731 new ForgejoCli.ForgejoCliError({
732 command: "fj",
733 cwd: input.cwd,
734 httpStatus: 400,
735 detail: "Forgejo API request failed (HTTP 400): Poster not found",
736 }),
737 ),
738 }),
739 ),
740 ),
741 );
742
743 it.effect.each([
744 { query: undefined, count: 3 },
745 { query: "", count: 3 },
746 { query: " \t ", count: 3 },
747 { query: "", count: 101 },
748 ])("reads all $count assignees once for author query '$query'", ({ query, count }) => {
749 const paths: string[] = [];
750 const users = Array.from({ length: count }, (_, index) => ({ login: `dev-${index}` }));
751 return Effect.gen(function* () {
752 const provider = yield* ForgejoPullRequestProvider.make;
753 const search = provider.searchRepositoryAuthors;
754 if (search === undefined) return yield* Effect.die("author search missing");
755 const found = yield* search({
756 cwd: "/repo",
757 repository: "maria/project",
758 host: "forgejo.test",
759 ...(query === undefined ? {} : { query }),
760 });
761 assert.strictEqual(paths.length, 1);
762 assert.deepStrictEqual(found, {
763 items: users.map(({ login }) => ({ login, name: null, avatarUrl: null })),
764 truncated: false,
765 });
766 }).pipe(
767 Effect.provide(
768 Layer.mock(ForgejoCli.ForgejoCli)({
769 api: (input) => {
770 paths.push(input.path);
771 assert.strictEqual(input.path.split("?")[0], "repos/maria/project/assignees");
772 // Forgejo ignores paging here: every page is the full list, with no Link header.
773 return encodeJsonEffect(users).pipe(Effect.orDie, Effect.map(processOutput));
774 },
775 }),
776 ),
777 );
778 });
779
780 it.effect("says an author search was cut short by a server that pages below its limit", () =>
781 Effect.gen(function* () {
782 const provider = yield* ForgejoPullRequestProvider.make;
783 const search = provider.searchRepositoryAuthors;
784 if (search === undefined) return yield* Effect.die("author search missing");
785 const found = yield* search({
786 cwd: "/repo",
787 repository: "maria/project",
788 host: "forgejo.test",
789 query: "dev",
790 });
791 assert.strictEqual(found.items.length, 30);
792 assert.isTrue(found.truncated);
793 }).pipe(
794 Effect.provide(
795 Layer.mock(ForgejoCli.ForgejoCli)({
796 api: () =>
797 encodeJsonEffect({
798 ok: true,
799 data: Array.from({ length: 30 }, (_, index) => ({ login: `dev-${index}` })),
800 }).pipe(
801 Effect.orDie,
802 Effect.map((stdout) =>
803 processOutput(stdout, {
804 stderr:
805 'HTTP/1.1 200\nlink: <https://forgejo.test/api/v1/users/search?page=2>; rel="next"\n',
806 }),
807 ),
808 ),
809 }),
810 ),
811 ),
812 );
813
814 it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>
815 Effect.gen(function* () {
816 const provider = yield* ForgejoSourceControlProvider.make;
817 const refine = provider.refineRepositoryIdentity;
818 assert.isDefined(refine);
819 const identity = (remoteUrl: string, provider?: string) => ({
820 canonicalKey: "forge.test/team/repo",
821 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
822 rootPath: "/repo",
823 ...(provider === undefined ? {} : { provider: SourceControlProviderKind.make(provider) }),
824 });
825 const served = (baseUrl: string) => () =>
826 Effect.succeed({
827 provider: {
828 kind: SourceControlProviderKind.make("forgejo"),
829 name: "Forgejo / Gitea",
830 baseUrl,
831 },
832 remoteName: "origin",
833 remoteUrl: "",
834 });
835
836 assert.deepStrictEqual(
837 yield* refine!({
838 identity: identity("http://forge.test:3000/git/team/repo.git"),
839 resolveContext: served("http://forge.test:3000/git/"),
840 }),
841 {
842 ...identity("http://forge.test:3000/git/team/repo.git"),
843 provider: SourceControlProviderKind.make("forgejo"),
844 webUrl: "http://forge.test:3000/git/team/repo",
845 },
846 );
847 assert.strictEqual(
848 (yield* refine!({
849 identity: identity("ssh://git@ssh.forge.test/team/repo.git"),
850 resolveContext: served("http://forge.test:3000/git"),
851 })).webUrl,
852 "http://forge.test:3000/git/team/repo",
853 );
854 const github = identity("https://github.com/team/repo.git", "github");
855 assert.strictEqual(
856 yield* refine!({ identity: github, resolveContext: () => Effect.die("not asked") }),
857 github,
858 );
859 const unserved = identity("http://forge.test:3000/team/repo.git");
860 assert.strictEqual(
861 yield* refine!({ identity: unserved, resolveContext: () => Effect.succeed(null) }),
862 unserved,
863 );
864 }).pipe(
865 Effect.provide(
866 Layer.mergeAll(
867 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
868 TestSourceControlHost.layer(),
869 Layer.mock(ForgejoCli.ForgejoCli)({}),
870 ),
871 ),
872 ),
873 );
874
875 it.effect("names the web server behind an SSH alias from the login that serves it", () =>
876 Effect.gen(function* () {
877 const provider = yield* ForgejoSourceControlProvider.make;
878 const resolveWebHost = provider.resolveRemoteWebHost!;
879 const asked: Array<string | undefined> = [];
880 const context = (remoteUrl: string) => ({
881 provider: {
882 kind: SourceControlProviderKind.make("forgejo"),
883 name: "Forgejo",
884 baseUrl: "https://ssh.forge.test",
885 },
886 remoteName: "origin",
887 remoteUrl,
888 requestedHost: "forge.test:3000",
889 });
890 const served = (input: {
891 readonly context: { readonly requestedHost?: string; readonly provider: { kind: string } };
892 }) =>
893 Effect.sync(() => {
894 asked.push(input.context.requestedHost);
895 assert.strictEqual(input.context.provider.kind, "unknown");
896 return {
897 provider: {
898 kind: SourceControlProviderKind.make("forgejo"),
899 name: "Forgejo / Gitea",
900 baseUrl: "http://forge.test:3000/git",
901 },
902 remoteName: "origin",
903 remoteUrl: "",
904 };
905 });
906
907 assert.strictEqual(
908 yield* resolveWebHost({
909 cwd: "/repo",
910 context: context("git@ssh.forge.test:team/repo.git"),
911 resolveContext: served,
912 }),
913 "forge.test:3000",
914 );
915 assert.deepStrictEqual(asked, ["forge.test:3000"]);
916 assert.strictEqual(
917 yield* resolveWebHost({
918 cwd: "/repo",
919 context: context("https://forge.test:3000/team/repo.git"),
920 resolveContext: () => Effect.die("an HTTP remote names its own web host"),
921 }),
922 null,
923 );
924 assert.strictEqual(
925 yield* resolveWebHost({
926 cwd: "/repo",
927 context: context("git@ssh.forge.test:team/repo.git"),
928 resolveContext: () => Effect.succeed(null),
929 }),
930 null,
931 );
932 }).pipe(
933 Effect.provide(
934 Layer.mergeAll(
935 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
936 TestSourceControlHost.layer(),
937 Layer.mock(ForgejoCli.ForgejoCli)({}),
938 ),
939 ),
940 ),
941 );
942
943 it.effect("loads Forgejo pull request references from files and commits views", () =>
944 Effect.gen(function* () {
945 const provider = yield* ForgejoSourceControlProvider.make;
946 for (const reference of [
947 "42",
948 "#42",
949 "https://forgejo.test/maria/project/pulls/42",
950 "https://forgejo.test/maria/project/pulls/42/",
951 "https://forgejo.test/maria/project/pulls/42/files?w=1#diff-1",
952 "http://forgejo.test:3000/git/maria/project/pulls/42/commits",
953 ]) {
954 const result = yield* provider.getChangeRequest({ cwd: "/repo", reference });
955 assert.strictEqual(result.number, 42);
956 assert.strictEqual(result.title, "Forgejo view reference");
957 assert.strictEqual(result.headSha, "head");
958 }
959 const invalid = yield* provider
960 .getChangeRequest({
961 cwd: "/repo",
962 reference: "https://forgejo.test/maria/project/pulls/42invalid/files",
963 })
964 .pipe(Effect.result);
965 assert.strictEqual(invalid._tag, "Failure");
966 }).pipe(
967 Effect.provide(
968 Layer.mergeAll(
969 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
970 TestSourceControlHost.layer({ process: {} }),
971 Layer.mock(ForgejoCli.ForgejoCli)({
972 resolveRepository: () =>
973 Effect.succeed({
974 login: "work",
975 repository: "maria/project",
976 baseUrl: "https://forgejo.test",
977 }),
978 api: (input) => {
979 assert.strictEqual(input.path, "repos/maria/project/pulls/42");
980 return encodeJsonEffect({
981 number: 42,
982 title: "Forgejo view reference",
983 html_url: "https://forgejo.test/maria/project/pulls/42",
984 state: "open",
985 merged: false,
986 base: { ref: "main", sha: "base", repo: null },
987 head: { ref: "feature", sha: "head", repo: null },
988 }).pipe(Effect.orDie, Effect.map(processOutput));
989 },
990 }),
991 ),
992 ),
993 ),
994 );
995
996 // Gitea ignores `head=` on the pull request list, so each page holds every branch's pull requests.
997 // The second lookup still asks for the front of the list: a pull request may have been opened.
998 it.effect("reads a Gitea pull request list at most once for branches that have none", () => {
999 const listPages: Array<string> = [];
1000 return Effect.gen(function* () {
1001 const provider = yield* ForgejoSourceControlProvider.make;
1002 for (const headSelector of ["first-without-pr", "second-without-pr"]) {
1003 const found = yield* provider.listChangeRequests({
1004 cwd: "/repo",
1005 headSelector,
1006 state: "all",
1007 });
1008 assert.deepStrictEqual(found, []);
1009 }
1010 assert.isAtMost(listPages.length, 5);
1011 }).pipe(
1012 Effect.provide(
1013 Layer.mergeAll(
1014 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
1015 TestSourceControlHost.layer({ process: {} }),
1016 Layer.mock(ForgejoCli.ForgejoCli)({
1017 resolveRepository: () =>
1018 Effect.succeed({
1019 login: "work",
1020 repository: "maria/project",
1021 baseUrl: "https://forgejo.test",
1022 }),
1023 api: (input) => {
1024 if (!input.path.startsWith("repos/maria/project/pulls?"))
1025 return Effect.fail(
1026 new ForgejoCli.ForgejoCliError({
1027 command: "tea",
1028 cwd: input.cwd,
1029 httpStatus: 404,
1030 detail: "Forgejo API request failed (HTTP 404): Not Found",
1031 }),
1032 );
1033 listPages.push(input.path);
1034 const repo = { full_name: "maria/project", owner: { login: "maria" } };
1035 const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
1036 const items =
1037 page > 3
1038 ? []
1039 : Array.from({ length: 50 }, (_, index) => {
1040 const number = 200 - (page - 1) * 50 - index;
1041 return {
1042 number,
1043 title: `PR ${number}`,
1044 html_url: `https://forgejo.test/maria/project/pulls/${number}`,
1045 state: "open",
1046 merged: false,
1047 updated_at: `2026-10-12T00:0${Math.floor(number / 60)}:${String(number % 60).padStart(2, "0")}Z`,
1048 base: { ref: "main", label: "main", sha: "base", repo },
1049 head: {
1050 ref: `feature-${number}`,
1051 label: `feature-${number}`,
1052 sha: "h",
1053 repo,
1054 },
1055 };
1056 });
1057 return encodeJsonEffect(items).pipe(Effect.orDie, Effect.map(processOutput));
1058 },
1059 }),
1060 ),
1061 ),
1062 );
1063 });
1064
1065 it.effect("reads only the changed front of a Gitea pull request list it has read before", () => {
1066 const repo = { full_name: "maria/project", owner: { login: "maria" } };
1067 const fork = { full_name: "alice/renamed", owner: { login: "alice" } };
1068 const pull = (number: number, updatedSecond: number, head: string, state = "open") => ({
1069 number,
1070 title: `PR ${number}`,
1071 html_url: `https://forgejo.test/maria/project/pulls/${number}`,
1072 state,
1073 merged: false,
1074 updated_at: `2026-10-12T00:0${Math.floor(updatedSecond / 60)}:${String(updatedSecond % 60).padStart(2, "0")}Z`,
1075 base: { ref: number === 5 ? "release" : "main", label: "main", sha: "base", repo },
1076 head: { ref: head, label: head, sha: "h", repo: number === 5 ? fork : repo },
1077 });
1078 // Newest update first, as `sort=recentupdate` returns them. PR 5 sits on the last page.
1079 let pulls = Array.from({ length: 120 }, (_, index) =>
1080 pull(120 - index, 120 - index, 120 - index === 5 ? "feature" : `other-${120 - index}`),
1081 );
1082 // List pages read; a match is also read once by number before it is returned.
1083 let requests = 0;
1084 return Effect.gen(function* () {
1085 const provider = yield* ForgejoSourceControlProvider.make;
1086 const find = (headSelector: string) =>
1087 provider
1088 .listChangeRequests({ cwd: "/repo", headSelector, state: "all" })
1089 .pipe(Effect.map((found) => found.map((pr) => [pr.number, pr.state])));
1090
1091 assert.deepStrictEqual(yield* find("alice:feature"), [[5, "open"]]);
1092 assert.strictEqual(requests, 4);
1093
1094 pulls = [pull(121, 202, "later"), pull(5, 201, "feature", "closed"), ...pulls].filter(
1095 (entry, index, all) => all.findIndex((other) => other.number === entry.number) === index,
1096 );
1097 assert.deepStrictEqual(yield* find("later"), [[121, "open"]]);
1098 assert.deepStrictEqual(yield* find("alice:feature"), [[5, "closed"]]);
1099 assert.strictEqual(requests, 6);
1100
1101 // Deleting a pull request moves nothing in the list.
1102 pulls = pulls.filter((entry) => entry.number !== 121);
1103 assert.deepStrictEqual(yield* find("later"), []);
1104 assert.strictEqual(requests, 7);
1105
1106 pulls = pulls.filter((entry) => entry.number !== 120);
1107 yield* TestClock.adjust("1 hour");
1108 assert.deepStrictEqual(yield* find("other-120"), []);
1109 assert.strictEqual(requests, 11);
1110 }).pipe(
1111 Effect.provide(
1112 Layer.mergeAll(
1113 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
1114 TestSourceControlHost.layer({ process: {} }),
1115 Layer.mock(ForgejoCli.ForgejoCli)({
1116 resolveRepository: () =>
1117 Effect.succeed({
1118 login: "work",
1119 repository: "maria/project",
1120 baseUrl: "https://forgejo.test",
1121 }),
1122 api: (input) => {
1123 const single = /\/pulls\/(\d+)$/.exec(input.path)?.[1];
1124 if (single !== undefined) {
1125 const found = pulls.find((entry) => entry.number === Number(single));
1126 return found
1127 ? encodeJsonEffect(found).pipe(Effect.orDie, Effect.map(processOutput))
1128 : Effect.fail(
1129 new ForgejoCli.ForgejoCliError({
1130 command: "tea",
1131 cwd: input.cwd,
1132 httpStatus: 404,
1133 detail: "Forgejo API request failed (HTTP 404): Not Found",
1134 }),
1135 );
1136 }
1137 requests++;
1138 const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
1139 return encodeJsonEffect(pulls.slice((page - 1) * 50, page * 50)).pipe(
1140 Effect.orDie,
1141 Effect.map(processOutput),
1142 );
1143 },
1144 }),
1145 ),
1146 ),
1147 );
1148 });
1149
1150 it.effect(
1151 "finds a branch's pull request on Gitea when a page of the full list exceeds 1 MB",
1152 () => {
1153 const repo = { full_name: "maria/project", owner: { login: "maria" } };
1154 const pull = (number: number, head: string, body: string) => ({
1155 number,
1156 title: `PR ${number}`,
1157 body,
1158 html_url: `http://forgejo.local:3000/maria/project/pulls/${number}`,
1159 state: "closed",
1160 merged: true,
1161 updated_at: `2026-10-12T00:00:0${number}Z`,
1162 base: { ref: "main", label: "main", sha: "base", repo },
1163 head: { ref: head, label: head, sha: "h", repo },
1164 });
1165 const pulls = [pull(2, "renovate", "x".repeat(999_993)), pull(1, "feature", "small")];
1166 return Effect.gen(function* () {
1167 const provider = yield* ForgejoSourceControlProvider.make;
1168 const found = yield* provider.listChangeRequests({
1169 cwd: "/repo",
1170 context: {
1171 provider: {
1172 kind: SourceControlProviderKind.make("forgejo"),
1173 name: "Forgejo",
1174 baseUrl: "http://forgejo.local:3000",
1175 },
1176 remoteName: "origin",
1177 remoteUrl: "http://forgejo.local:3000/maria/project.git",
1178 },
1179 headSelector: "feature",
1180 state: "all",
1181 });
1182 assert.deepStrictEqual(
1183 found.map((item) => item.number),
1184 [1],
1185 );
1186 }).pipe(
1187 Effect.provide(
1188 ForgejoCli.layer.pipe(
1189 Layer.provideMerge(
1190 Layer.mergeAll(
1191 Layer.succeed(
1192 FileSystem.FileSystem,
1193 FileSystem.makeNoop({ exists: () => Effect.succeed(false) }),
1194 ),
1195 Layer.succeed(
1196 HttpClient.HttpClient,
1197 HttpClient.make(() => {
1198 throw new Error("tea must handle its own HTTP request");
1199 }),
1200 ),
1201 TestSourceControlHost.layer({
1202 process: {
1203 run: (input) => {
1204 if (input.args[0] === "login")
1205 return Effect.succeed(
1206 processOutput(
1207 encodeJson([
1208 {
1209 name: "work",
1210 url: "http://forgejo.local:3000",
1211 ssh_host: "forgejo.local",
1212 user: "maria",
1213 default: "true",
1214 },
1215 ]),
1216 ),
1217 );
1218 const url = new URL(input.args.at(-1) ?? "");
1219 const number = /\/pulls\/(\d+)$/.exec(url.pathname)?.[1];
1220 // Gitea ignores `head=`, so every list page holds every pull request.
1221 const stdout = encodeJson(
1222 number
1223 ? pulls.find((item) => item.number === Number(number))
1224 : url.searchParams.get("page") === "1"
1225 ? pulls
1226 : [],
1227 );
1228 // VcsProcess truncates at 1,000,000 bytes unless a caller raises the cap.
1229 const maxBytes = input.maxOutputBytes ?? 1_000_000;
1230 return Effect.succeed({
1231 ...processOutput(stdout.slice(0, maxBytes), { stderr: "HTTP/1.1 200 OK\n" }),
1232 stdoutTruncated: stdout.length > maxBytes,
1233 });
1234 },
1235 },
1236 }),
1237 ),
1238 ),
1239 ),
1240 ),
1241 );
1242 },
1243 );
1244
1245 it.effect("finds a merged Forgejo pull request whose head branch was deleted", () =>
1246 Effect.gen(function* () {
1247 const provider = yield* ForgejoSourceControlProvider.make;
1248 const found = yield* provider.listChangeRequests({
1249 cwd: "/repo",
1250 headSelector: "feature",
1251 state: "merged",
1252 });
1253 assert.deepStrictEqual(
1254 found.map((pr) => [pr.number, pr.headRefName]),
1255 [[7, "feature"]],
1256 );
1257 }).pipe(
1258 Effect.provide(
1259 Layer.mergeAll(
1260 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
1261 TestSourceControlHost.layer({ process: {} }),
1262 Layer.mock(ForgejoCli.ForgejoCli)({
1263 resolveRepository: () =>
1264 Effect.succeed({
1265 login: "work",
1266 repository: "maria/project",
1267 baseUrl: "https://forgejo.test",
1268 }),
1269 api: (input) => {
1270 const repo = { full_name: "maria/project", owner: { login: "maria" } };
1271 const page = new URLSearchParams(input.path.split("?")[1]).get("page");
1272 return encodeJsonEffect(
1273 page === "1"
1274 ? [
1275 {
1276 number: 7,
1277 title: "Merged feature",
1278 html_url: "https://forgejo.test/maria/project/pulls/7",
1279 state: "closed",
1280 merged: true,
1281 merged_at: "2026-10-12T00:00:00Z",
1282 base: { ref: "main", label: "main", sha: "base", repo },
1283 head: { ref: "refs/pull/7/head", label: "feature", sha: "head", repo },
1284 },
1285 {
1286 number: 8,
1287 title: "Merged from a deleted fork",
1288 html_url: "https://forgejo.test/maria/project/pulls/8",
1289 state: "closed",
1290 merged: true,
1291 merged_at: "2026-10-11T00:00:00Z",
1292 base: { ref: "main", label: "main", sha: "base", repo },
1293 head: { ref: "refs/pull/8/head", label: "feature", sha: "fork", repo: null },
1294 },
1295 {
1296 number: 9,
1297 title: "AGit topic",
1298 html_url: "https://forgejo.test/maria/project/pulls/9",
1299 state: "closed",
1300 merged: true,
1301 merged_at: "2026-10-10T00:00:00Z",
1302 flow: 1,
1303 base: { ref: "main", label: "main", sha: "base", repo },
1304 head: { ref: "refs/pull/9/head", label: "feature", sha: "topic", repo },
1305 },
1306 ]
1307 : [],
1308 ).pipe(Effect.orDie, Effect.map(processOutput));
1309 },
1310 }),
1311 ),
1312 ),
1313 ),
1314 );
1315
1316 it.effect(
1317 "loads Forgejo reactions on comments, reviews and inline threads and resolves review mutations",
1318 () => {
1319 const user = { login: "maria" };
1320 const review = {
1321 id: 8,
1322 body: "review body",
1323 user,
1324 state: "COMMENT",
1325 submitted_at: "2026-09-12T00:00:00Z",
1326 html_url: "https://forgejo.test/maria/project/pulls/2#issuecomment-37",
1327 comments_count: 1,
1328 };
1329 const comment = { id: 12, body: "ordinary", user, created_at: review.submitted_at };
1330 const responses: Record<string, unknown> = {
1331 user,
1332 "repos/maria/project/issues/2/comments": [comment],
1333 "repos/maria/project/pulls/2/reviews": [review],
1334 "repos/maria/project/pulls/2/reviews/8": review,
1335 "repos/maria/project/pulls/2/reviews/9": { ...review, id: 9, html_url: "" },
1336 "repos/maria/project/pulls/2/commits": [],
1337 "repos/maria/project/issues/2/reactions": [],
1338 "repos/maria/project/pulls/2/reviews/8/comments": [
1339 {
1340 ...comment,
1341 id: 38,
1342 body: "inline",
1343 path: "file.ts",
1344 position: 1,
1345 original_position: 1,
1346 commit_id: "head",
1347 original_commit_id: "head",
1348 resolver: null,
1349 },
1350 ],
1351 "repos/maria/project/issues/comments/12/reactions": [{ content: "+1", user }],
1352 "repos/maria/project/issues/comments/37/reactions": [{ content: "heart", user }],
1353 "repos/maria/project/issues/comments/38/reactions": [
1354 { content: "rocket", user: { login: "reviewer" } },
1355 ],
1356 };
1357 const writes: ForgejoCli.ForgejoApiInput[] = [];
1358 let reactionReads = 0;
1359 return Effect.gen(function* () {
1360 const provider = yield* ForgejoPullRequestProvider.make;
1361 const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 2 };
1362 const activity = yield* provider.getChangeRequestActivity(input);
1363 assert.deepStrictEqual(
1364 activity.comments.map((entry) => ({
1365 id: entry.id,
1366 kind: entry.kind,
1367 reactions: entry.reactions,
1368 })),
1369 [
1370 {
1371 id: "12",
1372 kind: "issue-comment",
1373 reactions: [{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true }],
1374 },
1375 {
1376 id: "review:8",
1377 kind: "review",
1378 reactions: [{ content: "heart", count: 1, actors: [], viewerHasReacted: true }],
1379 },
1380 {
1381 id: "38",
1382 kind: "review-comment",
1383 reactions: [
1384 { content: "rocket", count: 1, actors: ["reviewer"], viewerHasReacted: false },
1385 ],
1386 },
1387 ],
1388 );
1389 const inlineComment = activity.comments[2];
1390 assert.ok(inlineComment);
1391 assert.deepStrictEqual(activity.reviewThreads[0]?.comments, [inlineComment]);
1392 for (const reacted of [true, false]) {
1393 yield* provider.setReaction({ ...input, subjectId: "review:8", content: "heart", reacted });
1394 yield* provider.setReaction({ ...input, subjectId: "38", content: "rocket", reacted });
1395 }
1396 assert.deepStrictEqual(
1397 writes.map(({ path, method, body }) => ({ path, method, body })),
1398 [
1399 {
1400 path: "repos/maria/project/issues/comments/37/reactions",
1401 method: "POST",
1402 body: { content: "heart" },
1403 },
1404 {
1405 path: "repos/maria/project/issues/comments/38/reactions",
1406 method: "POST",
1407 body: { content: "rocket" },
1408 },
1409 {
1410 path: "repos/maria/project/issues/comments/37/reactions",
1411 method: "DELETE",
1412 body: { content: "heart" },
1413 },
1414 {
1415 path: "repos/maria/project/issues/comments/38/reactions",
1416 method: "DELETE",
1417 body: { content: "rocket" },
1418 },
1419 ],
1420 );
1421 const missing = yield* provider
1422 .setReaction({ ...input, subjectId: "review:9", content: "heart", reacted: true })
1423 .pipe(Effect.result);
1424 assert.strictEqual(missing._tag, "Failure");
1425 if (missing._tag === "Failure") assert.include(missing.failure.detail, "comment ID");
1426 assert.strictEqual(writes.length, 4);
1427 responses["repos/maria/project/pulls/2/reviews/8/comments"] = Array.from(
1428 { length: 501 },
1429 (_, index) => ({
1430 ...comment,
1431 id: 1000 + index,
1432 path: "file.ts",
1433 position: 1,
1434 original_position: 1,
1435 commit_id: "head",
1436 original_commit_id: "head",
1437 resolver: null,
1438 }),
1439 );
1440 for (let index = 0; index < 500; index++) {
1441 responses[`repos/maria/project/issues/comments/${1000 + index}/reactions`] = [];
1442 }
1443 reactionReads = 0;
1444 const bounded = yield* provider.getChangeRequestActivity(input);
1445 assert.strictEqual(bounded.reviewThreads.length, 500);
1446 assert.strictEqual(
1447 bounded.comments.filter((entry) => entry.kind === "review-comment").length,
1448 500,
1449 );
1450 assert.strictEqual(bounded.commentsTruncated, true);
1451 assert.strictEqual(reactionReads, 502);
1452 }).pipe(
1453 Effect.provide(
1454 Layer.mock(ForgejoCli.ForgejoCli)({
1455 api: (input) => {
1456 if (input.method) {
1457 writes.push(input);
1458 return Effect.succeed(processOutput("{}"));
1459 }
1460 const path = input.path.split("?")[0]!;
1461 if (/\/issues\/comments\/\d+\/reactions$/.test(path)) reactionReads++;
1462 assert.ok(Object.hasOwn(responses, path), `Unexpected Forgejo request: ${path}`);
1463 const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
1464 return encodeJsonEffect(page > 1 ? [] : responses[path]).pipe(
1465 Effect.orDie,
1466 Effect.map(processOutput),
1467 );
1468 },
1469 }),
1470 ),
1471 );
1472 },
1473 );
1474
1475 it.effect("lists each Forgejo assignee once as a reviewer candidate", () => {
1476 const paths: string[] = [];
1477 return Effect.gen(function* () {
1478 const provider = yield* ForgejoPullRequestProvider.make;
1479 const result = yield* provider.listReviewerCandidates(requiredChecksInput);
1480 assert.deepStrictEqual(
1481 result.candidates.map((candidate) => [candidate.id, candidate.isRequested]),
1482 [
1483 ["ana", true],
1484 ["noor", false],
1485 ],
1486 );
1487 assert.strictEqual(result.truncated, false);
1488 assert.strictEqual(paths.filter((path) => path.includes("/assignees")).length, 1);
1489 }).pipe(
1490 Effect.provide(
1491 Layer.mock(ForgejoCli.ForgejoCli)({
1492 api: (input) => {
1493 paths.push(input.path);
1494 const respond = (response: unknown) =>
1495 encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
1496 switch (input.path.split("?")[0]) {
1497 case "repos/acme/web/pulls/7":
1498 return respond({
1499 ...requiredChecksPullRequest,
1500 requested_reviewers: [{ login: "ana" }],
1501 });
1502 // Forgejo ignores paging here: every page is the full list, with no Link header.
1503 case "repos/acme/web/assignees":
1504 return respond([{ login: "maria" }, { login: "ana" }, { login: "noor" }]);
1505 default:
1506 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
1507 }
1508 },
1509 }),
1510 ),
1511 );
1512 });
1513
1514 it.effect("discovers Forgejo accounts and retains the server port", () =>
1515 Effect.gen(function* () {
1516 const auth = ForgejoSourceControlProvider.discovery.parseAuth(
1517 processOutput(
1518 yield* encodeJsonEffect([
1519 {
1520 name: "work",
1521 url: "http://forgejo.local:3000",
1522 ssh_host: "git.forgejo.local",
1523 user: "maria",
1524 default: "true",
1525 valid: "true",
1526 },
1527 ]),
1528 ),
1529 );
1530 assert.deepStrictEqual(
1531 firstNonEmptyLine("\u001b[1mtea version 0.16.0\u001b[0m\n"),
1532 Option.some("tea version 0.16.0"),
1533 );
1534 assert.strictEqual(auth.status, "authenticated");
1535 assert.deepStrictEqual(auth.account, Option.some("maria"));
1536 assert.deepStrictEqual(auth.host, Option.some("forgejo.local:3000"));
1537 const revoked = ForgejoSourceControlProvider.discovery.parseAuth(
1538 processOutput(
1539 encodeJson([
1540 {
1541 name: "work",
1542 url: "http://forgejo.local:3000",
1543 user: "maria",
1544 default: "true",
1545 valid: "false",
1546 },
1547 ]),
1548 ),
1549 );
1550 assert.strictEqual(revoked.status, "unauthenticated");
1551 const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
1552 cwd: "/repo",
1553 context: {
1554 provider: {
1555 kind: SourceControlProviderKind.make("unknown"),
1556 name: "git.forgejo.local",
1557 baseUrl: "https://git.forgejo.local",
1558 },
1559 remoteName: "origin",
1560 remoteUrl: "git@git.forgejo.local:maria/project.git",
1561 },
1562 auth: processOutput(
1563 yield* encodeJsonEffect([
1564 {
1565 name: "work",
1566 url: "http://forgejo.local:3000",
1567 ssh_host: "git.forgejo.local",
1568 user: "maria",
1569 default: "true",
1570 },
1571 ]),
1572 ),
1573 });
1574 assert.deepStrictEqual(refined, {
1575 kind: SourceControlProviderKind.make("forgejo"),
1576 name: "Forgejo / Gitea",
1577 baseUrl: "http://forgejo.local:3000",
1578 });
1579 }),
1580 );
1581
1582 it.effect("does not choose a default Forgejo login across ambiguous SSH server ports", () =>
1583 Effect.gen(function* () {
1584 const logins = ForgejoCli.parseForgejoLogins(
1585 yield* encodeJsonEffect([
1586 {
1587 name: "one",
1588 url: "http://forgejo.local:3000",
1589 ssh_host: "forgejo.local",
1590 user: "maria",
1591 default: "true",
1592 },
1593 {
1594 name: "two",
1595 url: "http://forgejo.local:4000",
1596 ssh_host: "forgejo.local",
1597 user: "maria",
1598 default: "false",
1599 },
1600 ]),
1601 );
1602 const remote = ForgejoCli.parseForgejoRemote("git@forgejo.local:maria/project.git");
1603 assert.isNotNull(remote);
1604 assert.deepStrictEqual(
1605 ForgejoCli.parseForgejoRemote("forgejo.local:maria/project.git"),
1606 remote,
1607 );
1608 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!));
1609 assert.strictEqual(
1610 ForgejoCli.matchForgejoLogin(logins, remote!, "forgejo.local:4000")?.name,
1611 "two",
1612 );
1613 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!, "other.local:4000"));
1614 const alias = ForgejoCli.parseForgejoRemote("git@ssh.forgejo.local:maria/project.git");
1615 assert.isNotNull(alias);
1616 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, alias!, "forgejo.local:4000"));
1617 const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
1618 cwd: "/repo",
1619 context: {
1620 provider: {
1621 kind: SourceControlProviderKind.make("unknown"),
1622 name: "Forgejo",
1623 baseUrl: "https://forgejo.local",
1624 },
1625 remoteName: "origin",
1626 remoteUrl: "git@forgejo.local:maria/project.git",
1627 requestedHost: "forgejo.local:4000",
1628 },
1629 auth: processOutput(yield* encodeJsonEffect(logins)),
1630 });
1631 assert.strictEqual(refined?.baseUrl, "http://forgejo.local:4000");
1632 const https = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000/maria/project.git");
1633 assert.isNotNull(https);
1634 assert.strictEqual(ForgejoCli.matchForgejoLogin(logins, https!)?.name, "two");
1635 const hostOnly = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000");
1636 assert.strictEqual(
1637 ForgejoCli.matchForgejoLogin(logins, hostOnly!, undefined, true)?.name,
1638 "two",
1639 );
1640 const mounted = logins.map((login) => ({
1641 ...login,
1642 url: `http://forgejo.local:4000/${login.name}`,
1643 }));
1644 assert.isUndefined(ForgejoCli.matchForgejoLogin(mounted, hostOnly!, undefined, true));
1645 const rootAndMounted = [logins[1]!, { ...logins[0]!, url: "http://forgejo.local:4000/gitea" }];
1646 const underMount = ForgejoCli.parseForgejoRemote(
1647 "http://forgejo.local:4000/gitea/maria/project.git",
1648 );
1649 assert.strictEqual(ForgejoCli.matchForgejoLogin(rootAndMounted, underMount!)?.name, "one");
1650 }),
1651 );
1652
1653 it.effect("rejects HTTP failures even when tea exits successfully", () =>
1654 Effect.gen(function* () {
1655 const cli = yield* ForgejoCli.make;
1656 const result = yield* cli
1657 .api({
1658 cwd: "/repo",
1659 repository: "http://forgejo.local:3000/maria/project",
1660 path: "repos/maria/project/pulls/42",
1661 method: "PATCH",
1662 body: { state: "closed" },
1663 })
1664 .pipe(Effect.result);
1665 assert.strictEqual(result._tag, "Failure");
1666 if (result._tag === "Failure")
1667 assert.strictEqual(
1668 result.failure.detail,
1669 "Forgejo repository or pull request was not found.",
1670 );
1671 }).pipe(
1672 Effect.provideService(
1673 FileSystem.FileSystem,
1674 FileSystem.makeNoop({
1675 exists: () => Effect.succeed(false),
1676 }),
1677 ),
1678 Effect.provideService(
1679 HttpClient.HttpClient,
1680 HttpClient.make(() => {
1681 throw new Error("tea must handle its own HTTP request");
1682 }),
1683 ),
1684 Effect.provide(
1685 TestSourceControlHost.layer({
1686 process: {
1687 run: (input) => {
1688 if (input.args[0] === "api") {
1689 assert.strictEqual(input.stdin, '{"state":"closed"}');
1690 assert.include(input.args, "work");
1691 assert.include(
1692 input.args,
1693 "http://forgejo.local:3000/api/v1/repos/maria/project/pulls/42",
1694 );
1695 }
1696 return Effect.succeed(
1697 input.args[0] === "login"
1698 ? processOutput(
1699 encodeJson([
1700 {
1701 name: "work",
1702 url: "http://forgejo.local:3000",
1703 ssh_host: "forgejo.local",
1704 user: "maria",
1705 default: "true",
1706 },
1707 ]),
1708 )
1709 : processOutput('{"message":"not found"}', { stderr: "HTTP/1.1 404 Not Found\n" }),
1710 );
1711 },
1712 },
1713 }),
1714 ),
1715 ),
1716 );
1717
1718 it.effect("keeps Gitea's failure reason when tea reports an HTTP error", () =>
1719 Effect.gen(function* () {
1720 const cli = yield* ForgejoCli.make;
1721 const result = yield* cli
1722 .api({
1723 cwd: "/repo",
1724 repository: "http://forgejo.local:3000/maria/project",
1725 path: "repos/maria/project/pulls/1/merge",
1726 method: "POST",
1727 body: { Do: "merge", delete_branch_after_merge: true },
1728 })
1729 .pipe(Effect.result);
1730 assert.strictEqual(result._tag, "Failure");
1731 if (result._tag === "Failure") {
1732 assert.include(result.failure.detail, "405");
1733 assert.include(result.failure.detail, "The head branch is behind the base branch");
1734 }
1735 }).pipe(
1736 Effect.provideService(
1737 FileSystem.FileSystem,
1738 FileSystem.makeNoop({
1739 exists: () => Effect.succeed(false),
1740 }),
1741 ),
1742 Effect.provideService(
1743 HttpClient.HttpClient,
1744 HttpClient.make(() => {
1745 throw new Error("tea must handle its own HTTP request");
1746 }),
1747 ),
1748 Effect.provide(
1749 TestSourceControlHost.layer({
1750 process: {
1751 run: (input) =>
1752 Effect.succeed(
1753 input.args[0] === "login"
1754 ? processOutput(
1755 encodeJson([
1756 {
1757 name: "work",
1758 url: "http://forgejo.local:3000",
1759 ssh_host: "forgejo.local",
1760 user: "maria",
1761 default: "true",
1762 },
1763 ]),
1764 )
1765 : processOutput(
1766 '{"message":"The head branch is behind the base branch","url":"http://forgejo.local:3000/api/swagger"}',
1767 {
1768 stderr:
1769 "HTTP/1.1 405 Method Not Allowed\nContent-Type: application/json;charset=utf-8\n",
1770 },
1771 ),
1772 ),
1773 },
1774 }),
1775 ),
1776 ),
1777 );
1778
1779 it.effect("routes mounted Forgejo repositories without repeating the mount in API paths", () =>
1780 Effect.gen(function* () {
1781 const cli = yield* ForgejoCli.make;
1782 const viewer = yield* cli.api({ cwd: "/upstream-only", host: "code.test", path: "user" });
1783 assert.strictEqual(viewer.stdout, "[]");
1784 const mountedRepository = yield* cli.resolveRepository({
1785 cwd: "/upstream-only",
1786 host: "code.test",
1787 repository: "maria/project",
1788 });
1789 assert.strictEqual(mountedRepository.baseUrl, "https://code.test/forgejo");
1790 assert.strictEqual(mountedRepository.repository, "maria/project");
1791 for (const path of [
1792 "repos/forgejo/maria/project/pulls?state=open",
1793 "repos/forgejo/maria/project",
1794 "repos/reviewer/project/contents/file.ts",
1795 ]) {
1796 const result = yield* cli.api({
1797 cwd: "/repo",
1798 repository: "forgejo/maria/project",
1799 context: {
1800 provider: {
1801 kind: SourceControlProviderKind.make("forgejo"),
1802 name: "Forgejo",
1803 baseUrl: "https://code.test/forgejo",
1804 },
1805 remoteName: "origin",
1806 remoteUrl: "https://code.test/forgejo/maria/project.git",
1807 },
1808 path,
1809 });
1810 assert.strictEqual(result.stdout, "[]");
1811 }
1812 const sameOwnerAsMount = yield* cli.resolveRepository({
1813 cwd: "/repo",
1814 repository: "forgejo/project",
1815 context: {
1816 provider: {
1817 kind: SourceControlProviderKind.make("forgejo"),
1818 name: "Forgejo",
1819 baseUrl: "https://code.test/forgejo",
1820 },
1821 remoteName: "origin",
1822 remoteUrl: "ssh://git@code.test/forgejo/project.git",
1823 },
1824 });
1825 assert.strictEqual(sameOwnerAsMount.command, "tea");
1826 assert.strictEqual(sameOwnerAsMount.repository, "forgejo/project");
1827 }).pipe(
1828 Effect.provideService(
1829 FileSystem.FileSystem,
1830 FileSystem.makeNoop({
1831 exists: () => Effect.succeed(true),
1832 readFileString: () =>
1833 Effect.succeed(
1834 encodeJson({
1835 hosts: { "code.test/forgejo": { type: "Application", token: "test-token" } },
1836 }),
1837 ),
1838 }),
1839 ),
1840 Effect.provideService(
1841 HttpClient.HttpClient,
1842 HttpClient.make(() => {
1843 throw new Error("tea must handle its own HTTP request");
1844 }),
1845 ),
1846 Effect.provide(
1847 TestSourceControlHost.layer({
1848 process: {
1849 run: (input) => {
1850 if (input.command === "git")
1851 return Effect.succeed(
1852 processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
1853 );
1854 if (input.args[0] === "login")
1855 return Effect.succeed(
1856 processOutput(
1857 encodeJson([
1858 {
1859 name: "mounted",
1860 url: "https://code.test/forgejo",
1861 ssh_host: "code.test",
1862 user: "maria",
1863 default: "true",
1864 },
1865 ]),
1866 ),
1867 );
1868 const supported = [
1869 "https://code.test/forgejo/api/v1/user",
1870 "https://code.test/forgejo/api/v1/repos/maria/project/pulls?state=open",
1871 "https://code.test/forgejo/api/v1/repos/maria/project",
1872 "https://code.test/forgejo/api/v1/repos/reviewer/project/contents/file.ts",
1873 ];
1874 if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
1875 assert.strictEqual(input.command, "tea");
1876 return Effect.succeed(
1877 supported.includes(input.args.at(-1) ?? "")
1878 ? processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" })
1879 : processOutput("{}", { stderr: "HTTP/1.1 404 Not Found\n" }),
1880 );
1881 },
1882 },
1883 }),
1884 ),
1885 ),
1886 );
1887
1888 it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {
1889 const commands: string[] = [];
1890 const requests: string[] = [];
1891 let repositoryCwd = "";
1892 return Effect.gen(function* () {
1893 const cli = yield* ForgejoCli.make;
1894 for (const remoteUrl of [
1895 "http://forgejo.local:3000/maria/project.git",
1896 "ssh://git@ssh.forgejo.local:2222/maria/project.git",
1897 "ssh://git@forgejo.local:2222/maria/project.git",
1898 ]) {
1899 const result = yield* cli.api({
1900 cwd: "/repo",
1901 repository: "maria/project",
1902 context: {
1903 provider: {
1904 kind: SourceControlProviderKind.make("forgejo"),
1905 name: "Forgejo",
1906 baseUrl: "http://forgejo.local:3000",
1907 },
1908 remoteName: "origin",
1909 remoteUrl,
1910 requestedHost: "forgejo.local:3000",
1911 },
1912 path: "repos/maria/project/issues/42/comments",
1913 method: "POST",
1914 body: { body: "verified through fj" },
1915 });
1916 assert.strictEqual(result.stdout, '{"id":99}');
1917 }
1918 assert.deepStrictEqual(commands, ["fj"]);
1919 assert.deepStrictEqual(requests, [
1920 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
1921 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
1922 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
1923 ]);
1924 const viewer = yield* cli.api({
1925 cwd: "/no-remotes",
1926 host: "forgejo.local:3000",
1927 path: "user",
1928 });
1929 assert.strictEqual(viewer.stdout, '{"login":"maria"}');
1930 assert.strictEqual(requests.at(-1), "https://forgejo.local:3000/api/v1/user");
1931 const upstreamViewer = yield* cli.api({
1932 cwd: "/upstream-only",
1933 host: "forgejo.local:3000",
1934 path: "user",
1935 });
1936 assert.strictEqual(upstreamViewer.stdout, '{"login":"maria"}');
1937 assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
1938 const upstreamRepository = yield* cli.resolveRepository({
1939 cwd: "/upstream-only",
1940 host: "forgejo.local:3000",
1941 repository: "maria/project",
1942 });
1943 assert.strictEqual(upstreamRepository.baseUrl, "http://forgejo.local:3000");
1944 assert.strictEqual(upstreamRepository.repository, "maria/project");
1945 const httpViewer = yield* cli.api({ cwd: "/repo", host: "forgejo.local:3000", path: "user" });
1946 assert.strictEqual(httpViewer.stdout, '{"login":"maria"}');
1947 assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
1948 }).pipe(
1949 Effect.provideService(
1950 FileSystem.FileSystem,
1951 FileSystem.makeNoop({
1952 exists: () => Effect.succeed(true),
1953 readFileString: () =>
1954 Effect.succeed(
1955 encodeJson({
1956 hosts: {
1957 "forgejo.local:3000": { type: "Application", token: "test-token" },
1958 "forgejo.local:4000": { type: "Application", token: "other-token" },
1959 },
1960 aliases: { "ssh.forgejo.local:2222": "forgejo.local:3000" },
1961 }),
1962 ),
1963 }),
1964 ),
1965 Effect.provideService(
1966 HttpClient.HttpClient,
1967 HttpClient.make((request) => {
1968 requests.push(request.url);
1969 if (request.url.endsWith("/user")) {
1970 assert.strictEqual(request.method, "GET");
1971 assert.strictEqual(request.headers.authorization, "token test-token");
1972 return Effect.succeed(
1973 HttpClientResponse.fromWeb(request, new Response('{"login":"maria"}')),
1974 );
1975 }
1976 assert.strictEqual(request.method, "POST");
1977 assert.strictEqual(request.headers.authorization, "token test-token");
1978 assert.deepStrictEqual(requestJson(request), { body: "verified through fj" });
1979 return Effect.succeed(
1980 HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),
1981 );
1982 }),
1983 ),
1984 Effect.provide(
1985 TestSourceControlHost.layer({
1986 process: {
1987 run: (input) => {
1988 commands.push(input.command);
1989 if (input.command === "git") {
1990 repositoryCwd = input.cwd;
1991 return Effect.succeed(
1992 input.cwd === "/no-remotes"
1993 ? processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) })
1994 : processOutput(
1995 input.cwd === "/upstream-only"
1996 ? "upstream\thttp://forgejo.local:3000/maria/project.git (fetch) [blob:none]\nother\thttp://forgejo.local:3000/maria/other.git (fetch) [blob:none]\nunrelated\thttp://other.local:3000/maria/project.git (fetch) [blob:none]"
1997 : "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)",
1998 ),
1999 );
2000 }
2001 assert.strictEqual(input.command, "fj");
2002 assert.deepStrictEqual(input.args, [
2003 "--host",
2004 repositoryCwd === "/no-remotes"
2005 ? "https://forgejo.local:3000"
2006 : "http://forgejo.local:3000",
2007 "whoami",
2008 ]);
2009 return Effect.succeed(processOutput(""));
2010 },
2011 },
2012 }),
2013 ),
2014 );
2015 });
2016
2017 it.effect("loads later fj review pages when the server caps pages below the requested size", () => {
2018 const pages: number[] = [];
2019 let issueCommentRequests = 0;
2020 return Effect.gen(function* () {
2021 const cli = yield* ForgejoCli.make;
2022 const provider = yield* ForgejoPullRequestProvider.make.pipe(
2023 Effect.provideService(ForgejoCli.ForgejoCli, cli),
2024 );
2025 const activity = yield* provider.getChangeRequestActivity({
2026 cwd: "/repo",
2027 repository: "maria/project",
2028 host: "forgejo.test",
2029 number: 42,
2030 });
2031 assert.strictEqual(activity.commentCount, 42);
2032 assert.strictEqual(activity.comments.at(-1)?.id, "review:41");
2033 assert.strictEqual(activity.commentsTruncated, false);
2034 assert.deepStrictEqual(pages, [1, 2, 3]);
2035 assert.strictEqual(issueCommentRequests, 1);
2036 }).pipe(
2037 Effect.provideService(
2038 FileSystem.FileSystem,
2039 FileSystem.makeNoop({
2040 exists: () => Effect.succeed(true),
2041 readFileString: () =>
2042 Effect.succeed(
2043 encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
2044 ),
2045 }),
2046 ),
2047 Effect.provideService(
2048 HttpClient.HttpClient,
2049 HttpClient.make((request) => {
2050 const url = new URL(request.url);
2051 if (url.pathname === "/api/v1/repos/maria/project/issues/42/comments") {
2052 issueCommentRequests++;
2053 return Effect.succeed(
2054 HttpClientResponse.fromWeb(
2055 request,
2056 new Response(
2057 encodeJson([
2058 {
2059 id: 100,
2060 body: "Unpaginated issue comment",
2061 user: { login: "maria" },
2062 created_at: "2026-09-13T00:00:00Z",
2063 },
2064 ]),
2065 ),
2066 ),
2067 );
2068 }
2069 if (url.pathname.endsWith("/reviews")) {
2070 const page = Number(url.searchParams.get("page"));
2071 pages.push(page);
2072 assert.ok(page >= 1 && page <= 3);
2073 const reviews = Array.from({ length: page < 3 ? 20 : 1 }, (_, index) => ({
2074 id: (page - 1) * 20 + index + 1,
2075 body: "Review from a capped page",
2076 user: { login: "maria" },
2077 state: "COMMENT",
2078 submitted_at: "2026-09-13T00:00:00Z",
2079 comments_count: 0,
2080 }));
2081 return Effect.succeed(
2082 HttpClientResponse.fromWeb(
2083 request,
2084 new Response(encodeJson(reviews), {
2085 headers:
2086 page === 2
2087 ? {}
2088 : {
2089 Link:
2090 page === 1
2091 ? `<${url.origin}${url.pathname}?limit=50&page=2>; rel="next"`
2092 : `<${url.origin}${url.pathname}?limit=50&page=1>; rel="prev"`,
2093 },
2094 }),
2095 ),
2096 );
2097 }
2098 return Effect.succeed(
2099 HttpClientResponse.fromWeb(
2100 request,
2101 new Response(encodeJson(url.pathname === "/api/v1/user" ? { login: "maria" } : [])),
2102 ),
2103 );
2104 }),
2105 ),
2106 Effect.provide(
2107 TestSourceControlHost.layer({
2108 process: {
2109 run: (input) => {
2110 if (input.command === "git") {
2111 assert.deepStrictEqual(input.args, ["remote", "-v"]);
2112 return Effect.succeed(
2113 processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
2114 );
2115 }
2116 assert.strictEqual(input.command, "fj");
2117 assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
2118 assert.strictEqual(input.cwd, "/home/maria");
2119 return Effect.succeed(processOutput(""));
2120 },
2121 },
2122 }),
2123 ),
2124 Effect.provideService(HostProcess.HomeDirectory, "/home/maria"),
2125 );
2126 });
2127
2128 it.effect("re-sends an fj write with its method and body to a renamed repository's path", () => {
2129 const requests: string[] = [];
2130 return Effect.gen(function* () {
2131 const cli = yield* ForgejoCli.make;
2132 yield* cli.api({
2133 cwd: "/repo",
2134 repository: "https://forgejo.local/maria/old-name",
2135 path: "repos/maria/old-name/issues/42/comments",
2136 method: "POST",
2137 body: { body: "only once" },
2138 });
2139 assert.deepStrictEqual(requests, [
2140 "https://forgejo.local/api/v1/repos/maria/old-name/issues/42/comments",
2141 "https://forgejo.local/api/v1/repos/maria/new-name/issues/42/comments",
2142 ]);
2143 }).pipe(
2144 Effect.provideService(
2145 FileSystem.FileSystem,
2146 FileSystem.makeNoop({
2147 exists: () => Effect.succeed(true),
2148 readFileString: () =>
2149 Effect.succeed(
2150 encodeJson({
2151 hosts: { "forgejo.local": { type: "Application", token: "test-token" } },
2152 }),
2153 ),
2154 }),
2155 ),
2156 Effect.provideService(
2157 HttpClient.HttpClient,
2158 HttpClient.make((request) => {
2159 requests.push(request.url);
2160 assert.strictEqual(request.method, "POST");
2161 assert.strictEqual(request.headers.authorization, "token test-token");
2162 assert.deepStrictEqual(requestJson(request), { body: "only once" });
2163 return Effect.succeed(
2164 HttpClientResponse.fromWeb(
2165 request,
2166 requests.length === 1
2167 ? new Response(null, {
2168 status: 301,
2169 headers: { location: "/api/v1/repos/maria/new-name/issues/42/comments" },
2170 })
2171 : new Response("{}", { status: 201 }),
2172 ),
2173 );
2174 }),
2175 ),
2176 Effect.provide(
2177 TestSourceControlHost.layer({
2178 process: { run: () => Effect.succeed(processOutput("")) },
2179 }),
2180 ),
2181 );
2182 });
2183
2184 it.effect("handles fj mutation statuses without retrying failures or reading absent bodies", () =>
2185 Effect.gen(function* () {
2186 for (const status of [204, 205, 302, 401, 403, 404, 429, 500]) {
2187 let writes = 0;
2188 yield* Effect.gen(function* () {
2189 const cli = yield* ForgejoCli.make;
2190 const result = yield* cli
2191 .api({
2192 cwd: "/repo",
2193 repository: "https://forgejo.local/maria/project",
2194 path: "repos/maria/project/issues/42/comments",
2195 method: "POST",
2196 body: { body: "only once" },
2197 })
2198 .pipe(Effect.result);
2199 assert.strictEqual(result._tag, status < 300 ? "Success" : "Failure");
2200 if (result._tag === "Success") assert.strictEqual(result.success.stdout, "");
2201 if (result._tag === "Failure") {
2202 assert.strictEqual(result.failure.command, "fj");
2203 assert.strictEqual(result.failure.httpStatus, status);
2204 }
2205 assert.strictEqual(writes, 1);
2206 }).pipe(
2207 Effect.provideService(
2208 FileSystem.FileSystem,
2209 FileSystem.makeNoop({
2210 exists: () => Effect.succeed(true),
2211 readFileString: () =>
2212 Effect.succeed(
2213 encodeJson({
2214 hosts: {
2215 "forgejo.local": { type: "Application", token: "test-token" },
2216 },
2217 }),
2218 ),
2219 }),
2220 ),
2221 Effect.provideService(
2222 HttpClient.HttpClient,
2223 HttpClient.make((request) => {
2224 writes++;
2225 assert.strictEqual(
2226 request.url,
2227 "https://forgejo.local/api/v1/repos/maria/project/issues/42/comments",
2228 );
2229 return Effect.succeed(
2230 HttpClientResponse.fromWeb(
2231 request,
2232 new Response(status < 300 ? null : "", {
2233 status,
2234 headers: { location: "https://other.local/" },
2235 }),
2236 ),
2237 );
2238 }),
2239 ),
2240 Effect.provide(
2241 TestSourceControlHost.layer({
2242 process: {
2243 run: (input) => {
2244 assert.strictEqual(
2245 input.command,
2246 "fj",
2247 "a failed mutation must never switch accounts or CLI",
2248 );
2249 return Effect.succeed(processOutput(""));
2250 },
2251 },
2252 }),
2253 ),
2254 );
2255 }
2256 }),
2257 );
2258
2259 it.effect(
2260 "discovers fj first and retains configured authentication failures instead of switching accounts",
2261 () =>
2262 Effect.gen(function* () {
2263 for (const scenario of ["authenticated", "revoked", "missing", "invalid-storage"] as const) {
2264 const commands: string[] = [];
2265 yield* Effect.gen(function* () {
2266 const spec = yield* ForgejoSourceControlProvider.makeDiscovery;
2267 assert.strictEqual(spec.type, "managed-cli");
2268 if (spec.type !== "managed-cli") return;
2269 const result = yield* spec.probe("/repo");
2270 assert.strictEqual(result.executable, scenario === "missing" ? "tea" : "fj");
2271 assert.strictEqual(
2272 result.auth.status,
2273 scenario === "revoked"
2274 ? "unauthenticated"
2275 : scenario === "invalid-storage"
2276 ? "unknown"
2277 : "authenticated",
2278 );
2279 if (scenario !== "revoked" && scenario !== "invalid-storage")
2280 assert.deepStrictEqual(result.auth.host, Option.some("forgejo.local:3000"));
2281 assert.deepStrictEqual(
2282 result.auth.account,
2283 scenario === "authenticated" || scenario === "missing"
2284 ? Option.some("maria")
2285 : Option.none(),
2286 );
2287 assert.strictEqual(
2288 commands.some((command) => command.startsWith("tea ")),
2289 scenario === "missing",
2290 );
2291 assert.include(commands, "fj version");
2292 }).pipe(
2293 Effect.provide(
2294 Layer.mergeAll(
2295 Layer.mock(ForgejoCli.ForgejoCli)({
2296 getAccount: (input) => {
2297 assert.strictEqual(scenario, "authenticated");
2298 assert.deepStrictEqual(input, {
2299 cwd: "/repo",
2300 baseUrl: "http://forgejo.local:3000",
2301 });
2302 return Effect.succeed("maria");
2303 },
2304 listLogins: (input) => {
2305 assert.strictEqual(
2306 input.remoteUrl,
2307 "http://forgejo.local:3000/maria/project.git",
2308 );
2309 if (scenario === "invalid-storage")
2310 return Effect.fail(
2311 new ForgejoCli.ForgejoCliError({
2312 command: "fj",
2313 cwd: input.cwd,
2314 reason: "authentication",
2315 detail: "fj authentication storage is invalid.",
2316 }),
2317 );
2318 return Effect.succeed([
2319 {
2320 name: "forgejo.local:3000",
2321 url: "http://forgejo.local:3000",
2322 user: "",
2323 default: "false",
2324 },
2325 ]);
2326 },
2327 }),
2328 TestSourceControlHost.layer({
2329 process: {
2330 run: (input) => {
2331 commands.push(`${input.command} ${input.args.join(" ")}`);
2332 if (input.command === "git")
2333 return Effect.succeed(
2334 processOutput("http://forgejo.local:3000/maria/project.git\n"),
2335 );
2336 if (input.command === "fj") {
2337 assert.strictEqual(input.cwd, "/home/maria");
2338 if (scenario === "missing")
2339 return Effect.fail(
2340 new VcsProcessSpawnError({
2341 operation: input.operation,
2342 command: input.command,
2343 cwd: input.cwd,
2344 cause: new Error("fj not found"),
2345 }),
2346 );
2347 if (input.args[0] === "version")
2348 return Effect.succeed(processOutput("fj 0.10.0"));
2349 if (scenario === "invalid-storage") {
2350 assert.deepStrictEqual(input.args, ["auth", "list"]);
2351 return Effect.succeed(processOutput(""));
2352 }
2353 assert.deepStrictEqual(input.args, [
2354 "--host",
2355 "http://forgejo.local:3000",
2356 "whoami",
2357 ]);
2358 return Effect.succeed(
2359 processOutput("", {
2360 exitCode: ChildProcessSpawner.ExitCode(scenario === "revoked" ? 1 : 0),
2361 }),
2362 );
2363 }
2364 assert.strictEqual(input.command, "tea");
2365 return Effect.succeed(
2366 input.args[0] === "--version"
2367 ? processOutput("tea version 0.16.0")
2368 : processOutput(
2369 encodeJson([
2370 {
2371 name: "work",
2372 url: "http://forgejo.local:3000",
2373 user: "maria",
2374 default: "true",
2375 valid: "true",
2376 },
2377 ]),
2378 ),
2379 );
2380 },
2381 },
2382 }),
2383 ),
2384 ),
2385 Effect.provideService(HostProcess.HomeDirectory, "/home/maria"),
2386 );
2387 }
2388 }),
2389 );
2390
2391 it.effect("explains a slow fj instead of advising an install when tea is absent", () =>
2392 Effect.gen(function* () {
2393 const spec = yield* ForgejoSourceControlProvider.makeDiscovery;
2394 assert.strictEqual(spec.type, "managed-cli");
2395 if (spec.type !== "managed-cli") return;
2396 const result = yield* spec.probe("/repo");
2397 assert.strictEqual(result.status, "missing");
2398 assert.strictEqual(result.executable, "fj");
2399 assert.include(result.installHint, "`fj version` timed out");
2400 assert.notInclude(result.installHint, "Install");
2401 }).pipe(
2402 Effect.provide(
2403 Layer.mergeAll(
2404 Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
2405 TestSourceControlHost.layer({
2406 process: {
2407 run: (input) => {
2408 const context = {
2409 operation: input.operation,
2410 command: input.command,
2411 cwd: input.cwd,
2412 };
2413 if (input.command === "git") return Effect.succeed(processOutput(""));
2414 if (input.command === "fj")
2415 return Effect.fail(new VcsProcessTimeoutError({ ...context, timeoutMs: 5_000 }));
2416 return Effect.fail(
2417 new VcsProcessSpawnError({
2418 ...context,
2419 cause: PlatformError.systemError({
2420 _tag: "NotFound",
2421 module: "ChildProcess",
2422 method: "spawn",
2423 pathOrDescriptor: input.command,
2424 }),
2425 }),
2426 );
2427 },
2428 },
2429 }),
2430 ),
2431 ),
2432 ),
2433 );
2434
2435 it.effect("does not call a valid fj login on an HTTP-only server unauthenticated", () =>
2436 Effect.gen(function* () {
2437 const spec = yield* ForgejoSourceControlProvider.makeDiscovery.pipe(
2438 Effect.provide(ForgejoCli.layer),
2439 );
2440 assert.strictEqual(spec.type, "managed-cli");
2441 if (spec.type !== "managed-cli") return;
2442 const result = yield* spec.probe("/repo");
2443 assert.strictEqual(result.executable, "fj");
2444 assert.notStrictEqual(result.auth.status, "unauthenticated");
2445 }).pipe(
2446 Effect.provideService(
2447 FileSystem.FileSystem,
2448 FileSystem.makeNoop({
2449 exists: () => Effect.succeed(true),
2450 // fj stores the host without the scheme the login used.
2451 readFileString: () =>
2452 Effect.succeed(
2453 encodeJson({
2454 hosts: { "forgejo.local:3000": { type: "Application", token: "test-token" } },
2455 }),
2456 ),
2457 }),
2458 ),
2459 Effect.provideService(
2460 HttpClient.HttpClient,
2461 HttpClient.make((request) =>
2462 request.url.startsWith("http://")
2463 ? Effect.succeed(
2464 HttpClientResponse.fromWeb(
2465 request,
2466 new Response(encodeJson({ login: "maria" }), { status: 200 }),
2467 ),
2468 )
2469 : Effect.die(new Error("received corrupt message of type InvalidContentType")),
2470 ),
2471 ),
2472 Effect.provide(
2473 TestSourceControlHost.layer({
2474 process: {
2475 run: (input) => {
2476 // Settings has no project in scope, so there is no origin remote.
2477 if (input.command === "git")
2478 return Effect.succeed(
2479 processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
2480 );
2481 if (input.command !== "fj")
2482 return Effect.fail(
2483 new VcsProcessSpawnError({
2484 operation: input.operation,
2485 command: input.command,
2486 cwd: input.cwd,
2487 cause: new Error("not installed"),
2488 }),
2489 );
2490 if (input.args[0] === "version") return Effect.succeed(processOutput("fj v0.7.0"));
2491 const host = input.args[input.args.indexOf("--host") + 1] ?? "";
2492 return Effect.succeed(
2493 host.startsWith("http://")
2494 ? processOutput("currently signed into maria@forgejo.local:3000")
2495 : processOutput("", {
2496 exitCode: ChildProcessSpawner.ExitCode(1),
2497 stderr: `Error: error sending request for url (${host}/api/v1/user?)\nCaused by:\n 0: client error (Connect)\n 1: received corrupt message of type InvalidContentType`,
2498 }),
2499 );
2500 },
2501 },
2502 }),
2503 ),
2504 Effect.provideService(HostProcess.HomeDirectory, "/home/maria"),
2505 ),
2506 );