@devries-cameron20 / t3code-1 / commits / f6e45028ef
Fork 0

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

refactor(source-control): Forgejo lives in @t3tools/source-control-forgejo (#17581)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 9, 2026 at 14:50 UTC f6e45028efb69d208a45aee8c2fa514adde44977
31 files changed +1632 -1303
apps/server/package.json
+1
@@ -46,6 +46,7 @@
46 "@t3tools/provider-opencode": "workspace:*",
47 "@t3tools/provider-pi": "workspace:*",
48 "@t3tools/source-control-core": "workspace:*",
49 + "@t3tools/source-control-forgejo": "workspace:*",
50 "diff": "8.0.3",
51 "effect": "catalog:",
52 "jose": "catalog:",
apps/server/scripts/evaluate-thread-titles.ts
+2 -4
@@ -23,10 +23,9 @@ import {
23 } from "@t3tools/provider-core/server/threadTitleContext";
24 import * as ThreadTitleLinks from "../src/textGeneration/ThreadTitleLinks.ts";
25 import * as SourceControlProviderRegistry from "../src/sourceControl/SourceControlProviderRegistry.ts";
26 -import * as ServerSourceControlHost from "../src/sourceControl/ServerSourceControlHost.ts";
26 import * as GitHubApi from "../src/sourceControl/GitHubApi.ts";
27 import * as GitLabCli from "../src/sourceControl/GitLabCli.ts";
29 -import * as ForgejoCli from "../src/sourceControl/ForgejoCli.ts";
28 +import * as SourceControlBuiltInDrivers from "../src/sourceControl/builtInDrivers.ts";
29 import * as AzureDevOpsCli from "../src/sourceControl/AzureDevOpsCli.ts";
30 import * as BitbucketApi from "../src/sourceControl/BitbucketApi.ts";
31 import * as ServerSettings from "../src/serverSettings.ts";
@@ -155,11 +154,10 @@ await Effect.runPromise(
154 Layer.mergeAll(
155 GitHubApi.layerWithDependencies,
156 GitLabCli.layer,
158 - ForgejoCli.layer,
157 + SourceControlBuiltInDrivers.layer,
158 AzureDevOpsCli.layer,
159 // No saved credentials here; Bitbucket falls back to T3CODE_BITBUCKET_* variables.
160 BitbucketApi.layer,
162 - ServerSourceControlHost.layer,
161 ),
162 ),
163 // Default settings: no saved Bitbucket token, gh's own GitHub account choice.
apps/server/src/git/GitManager.test.ts
+1 -1
@@ -57,7 +57,7 @@ import * as GitLabSourceControlProvider from "../sourceControl/GitLabSourceContr
57 import {
58 ForgejoPullRequestSchema,
59 toForgejoChangeRequest,
60 -} from "../sourceControl/forgejoPullRequests.ts";
60 +} from "@t3tools/source-control-forgejo/server/forgejoPullRequests";
61 import type { SourceControlProvider } from "@t3tools/source-control-core/server/SourceControlProvider";
62 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
63 import * as ServerConfig from "../config.ts";
apps/server/src/pullRequest/BitbucketPullRequestApi.ts
+1 -1
@@ -22,7 +22,7 @@ import type {
22 } from "@t3tools/contracts";
23
24 import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
25 -import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";
25 +import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
26 import {
27 buildReviewThreads,
28 decodeCommentsJson,
apps/server/src/pullRequest/PullRequestProviderRegistry.ts
+13 -9
@@ -7,8 +7,6 @@ import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
7 import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
8 import * as GitHubApi from "../sourceControl/GitHubApi.ts";
9 import * as GitLabCli from "../sourceControl/GitLabCli.ts";
10 -import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
11 -import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
10 import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
11 import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
12 import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
@@ -17,6 +15,7 @@ import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
15 import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
16 import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
17 import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
18 +import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
19 import type { PullRequestProviderApi } from "@t3tools/source-control-core/server/PullRequestProvider";
20
21 export class PullRequestProviderRegistry extends Context.Service<
@@ -45,16 +44,21 @@ export function fromProviders(
44 *
45 * @public Service construction is part of the canonical Effect module API.
46 */
48 -export const make = Effect.map(
49 - Effect.all([
47 +export const make = Effect.gen(function* () {
48 + const providers = yield* Effect.all([
49 GitHubPullRequestProvider.make,
50 GitLabPullRequestProvider.make,
52 - ForgejoPullRequestProvider.make,
51 BitbucketPullRequestProvider.make,
52 AzureDevOpsPullRequestProvider.make,
55 - ]),
56 - fromProviders,
57 -);
53 + ]);
54 + const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
55 + driver.make.pipe(Effect.map((instance) => instance.pullRequests)),
56 + );
57 + return fromProviders([
58 + ...providers,
59 + ...drivers.filter((provider): provider is PullRequestProviderApi => provider !== null),
60 + ]);
61 +});
62
63 export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
64 Layer.provide(
@@ -66,7 +70,7 @@ export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
70 ),
71 ),
72 Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.layer))),
69 - Layer.provide(ForgejoCli.layer),
73 + Layer.provide(BuiltInDrivers.layer),
74 Layer.provide(BitbucketPullRequestApi.layer.pipe(Layer.provide(BitbucketApi.layer))),
75 Layer.provide(AzureDevOpsPullRequestCli.layer.pipe(Layer.provide(AzureDevOpsCli.layer))),
76 );
apps/server/src/pullRequest/PullRequestService.test.ts
+2 -2
@@ -30,8 +30,8 @@ import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.t
30 import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
31 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
32 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
33 -import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
34 -import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
33 +import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
34 +import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider";
35 import {
36 PullRequestProviderError,
37 type ProviderChangeRequest,
apps/server/src/server.ts
+3 -4
@@ -56,7 +56,8 @@ import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
56 import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
57 import * as GitHubApi from "./sourceControl/GitHubApi.ts";
58 import * as GitLabCli from "./sourceControl/GitLabCli.ts";
59 -import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";
59 +import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
60 +import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
61 import * as TextGeneration from "./textGeneration/TextGeneration.ts";
62 import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts";
63 import * as TerminalManager from "./terminal/Manager.ts";
@@ -104,7 +105,6 @@ import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
105 import * as GitWorkflowService from "./git/GitWorkflowService.ts";
106 import * as ReviewService from "./review/ReviewService.ts";
107 import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
107 -import * as ServerSourceControlHost from "./sourceControl/ServerSourceControlHost.ts";
108 import * as PullRequestReadCache from "./pullRequest/PullRequestReadCache.ts";
109 import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
110 import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
@@ -305,8 +305,7 @@ const layerSourceControlProviderRegistry = SourceControlProviderRegistry.layer.p
305 BitbucketApi.layer,
306 GitHubApi.layerWithDependencies,
307 GitLabCli.layer,
308 - ForgejoCli.layer,
309 - ServerSourceControlHost.layer,
308 + SourceControlBuiltInDrivers.layer,
309 ),
310 ),
311 Layer.provideMerge(GitVcsDriver.layer),
apps/server/src/sourceControl/SourceControlDiscovery.test.ts
+29 -1261
@@ -20,13 +20,13 @@ import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
20 import * as BitbucketApi from "./BitbucketApi.ts";
21 import * as GitHubApi from "./GitHubApi.ts";
22 import * as GitLabCli from "./GitLabCli.ts";
23 -import * as ForgejoCli from "./ForgejoCli.ts";
24 -import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
25 -import * as ForgejoPullRequestProvider from "../pullRequest/ForgejoPullRequestProvider.ts";
23 +import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
24 +import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
25 +import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider";
26 import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
27 import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
28 import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
29 -import { firstNonEmptyLine } from "@t3tools/source-control-core/server/discovery";
29 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
30
31 const layerSourceControlProviderRegistryTest = (input: {
32 readonly bitbucket: Partial<BitbucketApi.BitbucketApi["Service"]>;
@@ -76,434 +76,6 @@ const processOutput = (
76 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
77 const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
78
79 -it.effect("submits a Forgejo review without sending its summary in the preliminary GET", () => {
80 - const methods: string[] = [];
81 - const fetchReview = async (
82 - ...[input, init]: Parameters<Context.Service.Shape<typeof FetchHttpClient.Fetch>>
83 - ) => {
84 - const request = new Request(input instanceof Request ? input.url : String(input), {
85 - ...(init?.method === undefined ? {} : { method: init.method }),
86 - ...(init?.headers === undefined ? {} : { headers: init.headers }),
87 - ...(init?.body === undefined ? {} : { body: init.body }),
88 - });
89 - methods.push(request.method);
90 - if (request.method === "GET") {
91 - assert.strictEqual(request.url, "https://forgejo.test/api/v1/repos/maria/project/pulls/42");
92 - return new Response(
93 - encodeJson({
94 - number: 42,
95 - title: "Review target",
96 - body: "",
97 - html_url: "https://forgejo.test/maria/project/pulls/42",
98 - user: { login: "maria" },
99 - state: "open",
100 - merged: false,
101 - head: { ref: "feature", sha: "head", repo: null },
102 - base: { ref: "main", sha: "base", repo: null },
103 - created_at: "2026-09-13T00:00:00Z",
104 - updated_at: "2026-09-13T00:00:00Z",
105 - closed_at: null,
106 - merged_at: null,
107 - labels: [],
108 - }),
109 - );
110 - }
111 - assert.strictEqual(request.method, "POST");
112 - assert.strictEqual(
113 - request.url,
114 - "https://forgejo.test/api/v1/repos/maria/project/pulls/42/reviews",
115 - );
116 - assert.deepStrictEqual(JSON.parse(await request.text()), {
117 - event: "COMMENT",
118 - body: "Review summary",
119 - commit_id: "head",
120 - comments: [],
121 - });
122 - return new Response('{"id":1}', { status: 200 });
123 - };
124 - return Effect.gen(function* () {
125 - const cli = yield* ForgejoCli.make;
126 - const provider = yield* ForgejoPullRequestProvider.make.pipe(
127 - Effect.provideService(ForgejoCli.ForgejoCli, cli),
128 - );
129 - yield* provider.submitReview({
130 - cwd: "/repo",
131 - repository: "maria/project",
132 - host: "forgejo.test",
133 - number: 42,
134 - verdict: "comment",
135 - body: "Review summary",
136 - comments: [],
137 - });
138 - assert.deepStrictEqual(methods, ["GET", "POST"]);
139 - }).pipe(
140 - Effect.provideService(
141 - FetchHttpClient.Fetch,
142 - Object.assign(fetchReview, { preconnect: () => undefined }),
143 - ),
144 - Effect.provide(FetchHttpClient.layer),
145 - Effect.provideService(
146 - FileSystem.FileSystem,
147 - FileSystem.makeNoop({
148 - exists: () => Effect.succeed(true),
149 - readFileString: () =>
150 - Effect.succeed(
151 - encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
152 - ),
153 - }),
154 - ),
155 - Effect.provide(
156 - Layer.mock(VcsProcess.VcsProcess)({
157 - run: (input) => {
158 - if (input.command === "git") {
159 - assert.deepStrictEqual(input.args, ["remote", "-v"]);
160 - return Effect.succeed(
161 - processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
162 - );
163 - }
164 - assert.strictEqual(input.command, "fj");
165 - assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
166 - return Effect.succeed(processOutput(""));
167 - },
168 - }),
169 - ),
170 - );
171 -});
172 -
173 -it.effect("reads Forgejo checks without repository or viewer requests", () => {
174 - const paths: string[] = [];
175 - return Effect.gen(function* () {
176 - const provider = yield* ForgejoPullRequestProvider.make;
177 - const read = provider.getChangeRequestChecks;
178 - if (read === undefined) return yield* Effect.die("checks read missing");
179 - const result = yield* read({
180 - cwd: "/repo",
181 - repository: "acme/web",
182 - host: "forgejo.test",
183 - number: 1,
184 - });
185 - assert.strictEqual(result.state, "open");
186 - assert.strictEqual(result.checks[0]?.status, "failure");
187 - assert.deepStrictEqual(paths, [
188 - "repos/acme/web/pulls/1",
189 - "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=1",
190 - "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=2",
191 - ]);
192 - }).pipe(
193 - Effect.provide(
194 - Layer.mock(ForgejoCli.ForgejoCli)({
195 - api: (input) => {
196 - paths.push(input.path);
197 - assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head)/);
198 - return Effect.succeed(
199 - processOutput(
200 - input.path.endsWith("pulls/1")
201 - ? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
202 - "head":{"ref":"feature","sha":"head","repo":null},"base":{"ref":"main","sha":"base","repo":null},
203 - "created_at":"2026-09-16T00:00:00Z","updated_at":"2026-09-16T00:00:00Z","closed_at":null,"merged_at":null,"labels":[]}`
204 - : input.path.endsWith("page=1")
205 - ? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
206 - : "[]",
207 - ),
208 - );
209 - },
210 - }),
211 - ),
212 - );
213 -});
214 -
215 -it.effect.each([
216 - ["Ready", false, true, false, "mergeable"],
217 - ["Draft", true, false, true, "unknown"],
218 - ["Blocked", false, false, false, "unknown"],
219 - ["Unchecked", false, undefined, false, "unknown"],
220 - ["WIP: Legacy draft", undefined, false, true, "unknown"],
221 - ["[WIP] Legacy draft", undefined, false, true, "unknown"],
222 - ["WIP: Explicitly ready", false, false, false, "unknown"],
223 -] as const)(
224 - "reads Forgejo mergeability for %s (draft=%s, mergeable=%s) across list, summary and detail",
225 - ([title, draft, mergeable, isDraft, mergeability]) => {
226 - const pr = {
227 - number: 42,
228 - title,
229 - body: "",
230 - html_url: "https://forgejo.test/maria/project/pulls/42",
231 - user: { login: "maria" },
232 - state: "open",
233 - merged: false,
234 - ...(draft === undefined ? {} : { draft }),
235 - ...(mergeable === undefined ? {} : { mergeable }),
236 - head: { ref: "feature", sha: "head", repo: null },
237 - base: { ref: "main", sha: "base", repo: null },
238 - created_at: "2026-09-16T00:00:00Z",
239 - updated_at: "2026-09-16T00:00:00Z",
240 - closed_at: null,
241 - merged_at: null,
242 - labels: [],
243 - };
244 - return Effect.gen(function* () {
245 - const provider = yield* ForgejoPullRequestProvider.make;
246 - const readSummary = provider.getChangeRequestSummary;
247 - if (readSummary === undefined) return yield* Effect.die("summary read missing");
248 - const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 42 };
249 - const list = yield* provider.listChangeRequests({
250 - ...input,
251 - state: "open",
252 - involvement: "all",
253 - viewer: "maria",
254 - limit: 10,
255 - });
256 - const summary = yield* readSummary(input);
257 - const detail = yield* provider.getChangeRequest(input);
258 - assert.strictEqual(list.items.length, 1);
259 - for (const result of [list.items[0]!, summary, detail]) {
260 - assert.strictEqual(result.mergeability, mergeability);
261 - assert.strictEqual(result.isDraft, isDraft);
262 - }
263 - }).pipe(
264 - Effect.provide(
265 - Layer.mock(ForgejoCli.ForgejoCli)({
266 - api: (input) => {
267 - const [path, query] = input.path.split("?");
268 - let response: unknown;
269 - switch (path) {
270 - case "repos/maria/project/pulls":
271 - response = new URLSearchParams(query).get("page") === "1" ? [pr] : [];
272 - break;
273 - case "repos/maria/project/pulls/42":
274 - response = pr;
275 - break;
276 - case "repos/maria/project":
277 - response = { full_name: "maria/project", permissions: { push: true, admin: true } };
278 - break;
279 - case "user":
280 - response = pr.user;
281 - break;
282 - case "repos/maria/project/statuses/head":
283 - response = [];
284 - break;
285 - default:
286 - return Effect.die(`Unexpected Forgejo request: ${input.path}`);
287 - }
288 - return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
289 - },
290 - }),
291 - ),
292 - );
293 - },
294 -);
295 -
296 -it.effect("loads Forgejo pull request references from files and commits views", () =>
297 - Effect.gen(function* () {
298 - const provider = yield* ForgejoSourceControlProvider.make;
299 - for (const reference of [
300 - "42",
301 - "#42",
302 - "https://forgejo.test/maria/project/pulls/42",
303 - "https://forgejo.test/maria/project/pulls/42/",
304 - "https://forgejo.test/maria/project/pulls/42/files?w=1#diff-1",
305 - "http://forgejo.test:3000/git/maria/project/pulls/42/commits",
306 - ]) {
307 - const result = yield* provider.getChangeRequest({ cwd: "/repo", reference });
308 - assert.strictEqual(result.number, 42);
309 - assert.strictEqual(result.title, "Forgejo view reference");
310 - }
311 - const invalid = yield* provider
312 - .getChangeRequest({
313 - cwd: "/repo",
314 - reference: "https://forgejo.test/maria/project/pulls/42invalid/files",
315 - })
316 - .pipe(Effect.result);
317 - assert.strictEqual(invalid._tag, "Failure");
318 - }).pipe(
319 - Effect.provide(
320 - Layer.mergeAll(
321 - Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
322 - Layer.mock(VcsProcess.VcsProcess)({}),
323 - Layer.mock(ForgejoCli.ForgejoCli)({
324 - resolveRepository: () =>
325 - Effect.succeed({
326 - login: "work",
327 - repository: "maria/project",
328 - baseUrl: "https://forgejo.test",
329 - }),
330 - api: (input) => {
331 - assert.strictEqual(input.path, "repos/maria/project/pulls/42");
332 - return encodeJsonEffect({
333 - number: 42,
334 - title: "Forgejo view reference",
335 - html_url: "https://forgejo.test/maria/project/pulls/42",
336 - state: "open",
337 - merged: false,
338 - base: { ref: "main", sha: "base", repo: null },
339 - head: { ref: "feature", sha: "head", repo: null },
340 - }).pipe(Effect.orDie, Effect.map(processOutput));
341 - },
342 - }),
343 - ),
344 - ),
345 - ),
346 -);
347 -
348 -it.effect(
349 - "loads Forgejo reactions on comments, reviews and inline threads and resolves review mutations",
350 - () => {
351 - const user = { login: "maria" };
352 - const review = {
353 - id: 8,
354 - body: "review body",
355 - user,
356 - state: "COMMENT",
357 - submitted_at: "2026-09-12T00:00:00Z",
358 - html_url: "https://forgejo.test/maria/project/pulls/2#issuecomment-37",
359 - comments_count: 1,
360 - };
361 - const comment = { id: 12, body: "ordinary", user, created_at: review.submitted_at };
362 - const responses: Record<string, unknown> = {
363 - user,
364 - "repos/maria/project/issues/2/comments": [comment],
365 - "repos/maria/project/pulls/2/reviews": [review],
366 - "repos/maria/project/pulls/2/reviews/8": review,
367 - "repos/maria/project/pulls/2/reviews/9": { ...review, id: 9, html_url: "" },
368 - "repos/maria/project/pulls/2/commits": [],
369 - "repos/maria/project/issues/2/reactions": [],
370 - "repos/maria/project/pulls/2/reviews/8/comments": [
371 - {
372 - ...comment,
373 - id: 38,
374 - body: "inline",
375 - path: "file.ts",
376 - position: 1,
377 - original_position: 1,
378 - commit_id: "head",
379 - original_commit_id: "head",
380 - resolver: null,
381 - },
382 - ],
383 - "repos/maria/project/issues/comments/12/reactions": [{ content: "+1", user }],
384 - "repos/maria/project/issues/comments/37/reactions": [{ content: "heart", user }],
385 - "repos/maria/project/issues/comments/38/reactions": [
386 - { content: "rocket", user: { login: "reviewer" } },
387 - ],
388 - };
389 - const writes: ForgejoCli.ForgejoApiInput[] = [];
390 - let reactionReads = 0;
391 - return Effect.gen(function* () {
392 - const provider = yield* ForgejoPullRequestProvider.make;
393 - const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 2 };
394 - const activity = yield* provider.getChangeRequestActivity(input);
395 - assert.deepStrictEqual(
396 - activity.comments.map((entry) => ({
397 - id: entry.id,
398 - kind: entry.kind,
399 - reactions: entry.reactions,
400 - })),
401 - [
402 - {
403 - id: "12",
404 - kind: "issue-comment",
405 - reactions: [{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true }],
406 - },
407 - {
408 - id: "review:8",
409 - kind: "review",
410 - reactions: [{ content: "heart", count: 1, actors: [], viewerHasReacted: true }],
411 - },
412 - {
413 - id: "38",
414 - kind: "review-comment",
415 - reactions: [
416 - { content: "rocket", count: 1, actors: ["reviewer"], viewerHasReacted: false },
417 - ],
418 - },
419 - ],
420 - );
421 - const inlineComment = activity.comments[2];
422 - assert.ok(inlineComment);
423 - assert.deepStrictEqual(activity.reviewThreads[0]?.comments, [inlineComment]);
424 - for (const reacted of [true, false]) {
425 - yield* provider.setReaction({ ...input, subjectId: "review:8", content: "heart", reacted });
426 - yield* provider.setReaction({ ...input, subjectId: "38", content: "rocket", reacted });
427 - }
428 - assert.deepStrictEqual(
429 - writes.map(({ path, method, body }) => ({ path, method, body })),
430 - [
431 - {
432 - path: "repos/maria/project/issues/comments/37/reactions",
433 - method: "POST",
434 - body: { content: "heart" },
435 - },
436 - {
437 - path: "repos/maria/project/issues/comments/38/reactions",
438 - method: "POST",
439 - body: { content: "rocket" },
440 - },
441 - {
442 - path: "repos/maria/project/issues/comments/37/reactions",
443 - method: "DELETE",
444 - body: { content: "heart" },
445 - },
446 - {
447 - path: "repos/maria/project/issues/comments/38/reactions",
448 - method: "DELETE",
449 - body: { content: "rocket" },
450 - },
451 - ],
452 - );
453 - const missing = yield* provider
454 - .setReaction({ ...input, subjectId: "review:9", content: "heart", reacted: true })
455 - .pipe(Effect.result);
456 - assert.strictEqual(missing._tag, "Failure");
457 - if (missing._tag === "Failure") assert.include(missing.failure.detail, "comment ID");
458 - assert.strictEqual(writes.length, 4);
459 - responses["repos/maria/project/pulls/2/reviews/8/comments"] = Array.from(
460 - { length: 501 },
461 - (_, index) => ({
462 - ...comment,
463 - id: 1000 + index,
464 - path: "file.ts",
465 - position: 1,
466 - original_position: 1,
467 - commit_id: "head",
468 - original_commit_id: "head",
469 - resolver: null,
470 - }),
471 - );
472 - for (let index = 0; index < 500; index++) {
473 - responses[`repos/maria/project/issues/comments/${1000 + index}/reactions`] = [];
474 - }
475 - reactionReads = 0;
476 - const bounded = yield* provider.getChangeRequestActivity(input);
477 - assert.strictEqual(bounded.reviewThreads.length, 500);
478 - assert.strictEqual(
479 - bounded.comments.filter((entry) => entry.kind === "review-comment").length,
480 - 500,
481 - );
482 - assert.strictEqual(bounded.commentsTruncated, true);
483 - assert.strictEqual(reactionReads, 502);
484 - }).pipe(
485 - Effect.provide(
486 - Layer.mock(ForgejoCli.ForgejoCli)({
487 - api: (input) => {
488 - if (input.method) {
489 - writes.push(input);
490 - return Effect.succeed(processOutput("{}"));
491 - }
492 - const path = input.path.split("?")[0]!;
493 - if (/\/issues\/comments\/\d+\/reactions$/.test(path)) reactionReads++;
494 - assert.ok(Object.hasOwn(responses, path), `Unexpected Forgejo request: ${path}`);
495 - const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
496 - return encodeJsonEffect(page > 1 ? [] : responses[path]).pipe(
497 - Effect.orDie,
498 - Effect.map(processOutput),
499 - );
500 - },
501 - }),
502 - ),
503 - );
504 - },
505 -);
506 -
79 it.effect("reports implemented tools separately from locally available executables", () => {
80 const processMock = {
81 run: (input: VcsProcess.VcsProcessInput) => {
@@ -764,820 +336,6 @@ Logged in to gitlab.com as gitlab-user
336 }).pipe(Effect.provide(layerTest));
337 });
338
767 -it.effect("discovers Forgejo accounts and retains the server port", () =>
768 - Effect.gen(function* () {
769 - const auth = ForgejoSourceControlProvider.discovery.parseAuth(
770 - processOutput(
771 - yield* encodeJsonEffect([
772 - {
773 - name: "work",
774 - url: "http://forgejo.local:3000",
775 - ssh_host: "git.forgejo.local",
776 - user: "maria",
777 - default: "true",
778 - valid: "true",
779 - },
780 - ]),
781 - ),
782 - );
783 - assert.deepStrictEqual(
784 - firstNonEmptyLine("\u001b[1mtea version 0.16.0\u001b[0m\n"),
785 - Option.some("tea version 0.16.0"),
786 - );
787 - assert.strictEqual(auth.status, "authenticated");
788 - assert.deepStrictEqual(auth.account, Option.some("maria"));
789 - assert.deepStrictEqual(auth.host, Option.some("forgejo.local:3000"));
790 - const revoked = ForgejoSourceControlProvider.discovery.parseAuth(
791 - processOutput(
792 - encodeJson([
793 - {
794 - name: "work",
795 - url: "http://forgejo.local:3000",
796 - user: "maria",
797 - default: "true",
798 - valid: "false",
799 - },
800 - ]),
801 - ),
802 - );
803 - assert.strictEqual(revoked.status, "unauthenticated");
804 - const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
805 - cwd: "/repo",
806 - context: {
807 - provider: {
808 - kind: "unknown",
809 - name: "git.forgejo.local",
810 - baseUrl: "https://git.forgejo.local",
811 - },
812 - remoteName: "origin",
813 - remoteUrl: "git@git.forgejo.local:maria/project.git",
814 - },
815 - auth: processOutput(
816 - yield* encodeJsonEffect([
817 - {
818 - name: "work",
819 - url: "http://forgejo.local:3000",
820 - ssh_host: "git.forgejo.local",
821 - user: "maria",
822 - default: "true",
823 - },
824 - ]),
825 - ),
826 - });
827 - assert.deepStrictEqual(refined, {
828 - kind: "forgejo",
829 - name: "Forgejo / Gitea",
830 - baseUrl: "http://forgejo.local:3000",
831 - });
832 - }),
833 -);
834 -
835 -it.effect("does not choose a default Forgejo login across ambiguous SSH server ports", () =>
836 - Effect.gen(function* () {
837 - const logins = ForgejoCli.parseForgejoLogins(
838 - yield* encodeJsonEffect([
839 - {
840 - name: "one",
841 - url: "http://forgejo.local:3000",
842 - ssh_host: "forgejo.local",
843 - user: "maria",
844 - default: "true",
845 - },
846 - {
847 - name: "two",
848 - url: "http://forgejo.local:4000",
849 - ssh_host: "forgejo.local",
850 - user: "maria",
851 - default: "false",
852 - },
853 - ]),
854 - );
855 - const remote = ForgejoCli.parseForgejoRemote("git@forgejo.local:maria/project.git");
856 - assert.isNotNull(remote);
857 - assert.deepStrictEqual(
858 - ForgejoCli.parseForgejoRemote("forgejo.local:maria/project.git"),
859 - remote,
860 - );
861 - assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!));
862 - assert.strictEqual(
863 - ForgejoCli.matchForgejoLogin(logins, remote!, "forgejo.local:4000")?.name,
864 - "two",
865 - );
866 - assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!, "other.local:4000"));
867 - const alias = ForgejoCli.parseForgejoRemote("git@ssh.forgejo.local:maria/project.git");
868 - assert.isNotNull(alias);
869 - assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, alias!, "forgejo.local:4000"));
870 - const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
871 - cwd: "/repo",
872 - context: {
873 - provider: { kind: "unknown", name: "Forgejo", baseUrl: "https://forgejo.local" },
874 - remoteName: "origin",
875 - remoteUrl: "git@forgejo.local:maria/project.git",
876 - requestedHost: "forgejo.local:4000",
877 - },
878 - auth: processOutput(yield* encodeJsonEffect(logins)),
879 - });
880 - assert.strictEqual(refined?.baseUrl, "http://forgejo.local:4000");
881 - const https = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000/maria/project.git");
882 - assert.isNotNull(https);
883 - assert.strictEqual(ForgejoCli.matchForgejoLogin(logins, https!)?.name, "two");
884 - const hostOnly = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000");
885 - assert.strictEqual(
886 - ForgejoCli.matchForgejoLogin(logins, hostOnly!, undefined, true)?.name,
887 - "two",
888 - );
889 - const mounted = logins.map((login) => ({
890 - ...login,
891 - url: `http://forgejo.local:4000/${login.name}`,
892 - }));
893 - assert.isUndefined(ForgejoCli.matchForgejoLogin(mounted, hostOnly!, undefined, true));
894 - }),
895 -);
896 -
897 -it.effect("rejects HTTP failures even when tea exits successfully", () =>
898 - Effect.gen(function* () {
899 - const cli = yield* ForgejoCli.make;
900 - const result = yield* cli
901 - .api({
902 - cwd: "/repo",
903 - repository: "http://forgejo.local:3000/maria/project",
904 - path: "repos/maria/project/pulls/42",
905 - method: "PATCH",
906 - body: { state: "closed" },
907 - })
908 - .pipe(Effect.result);
909 - assert.strictEqual(result._tag, "Failure");
910 - if (result._tag === "Failure")
911 - assert.strictEqual(
912 - result.failure.detail,
913 - "Forgejo repository or pull request was not found.",
914 - );
915 - }).pipe(
916 - Effect.provideService(
917 - FileSystem.FileSystem,
918 - FileSystem.makeNoop({
919 - exists: () => Effect.succeed(false),
920 - }),
921 - ),
922 - Effect.provideService(
923 - HttpClient.HttpClient,
924 - HttpClient.make(() => {
925 - throw new Error("tea must handle its own HTTP request");
926 - }),
927 - ),
928 - Effect.provide(
929 - Layer.mock(VcsProcess.VcsProcess)({
930 - run: (input) => {
931 - if (input.args[0] === "api") {
932 - assert.strictEqual(input.stdin, '{"state":"closed"}');
933 - assert.include(input.args, "work");
934 - assert.include(
935 - input.args,
936 - "http://forgejo.local:3000/api/v1/repos/maria/project/pulls/42",
937 - );
938 - }
939 - return Effect.succeed(
940 - input.args[0] === "login"
941 - ? processOutput(
942 - encodeJson([
943 - {
944 - name: "work",
945 - url: "http://forgejo.local:3000",
946 - ssh_host: "forgejo.local",
947 - user: "maria",
948 - default: "true",
949 - },
950 - ]),
951 - )
952 - : processOutput('{"message":"not found"}', { stderr: "HTTP/1.1 404 Not Found\n" }),
953 - );
954 - },
955 - }),
956 - ),
957 - ),
958 -);
959 -
960 -it.effect("routes mounted Forgejo repositories without repeating the mount in API paths", () =>
961 - Effect.gen(function* () {
962 - const cli = yield* ForgejoCli.make;
963 - const viewer = yield* cli.api({ cwd: "/upstream-only", host: "code.test", path: "user" });
964 - assert.strictEqual(viewer.stdout, "[]");
965 - const mountedRepository = yield* cli.resolveRepository({
966 - cwd: "/upstream-only",
967 - host: "code.test",
968 - repository: "maria/project",
969 - });
970 - assert.strictEqual(mountedRepository.baseUrl, "https://code.test/forgejo");
971 - assert.strictEqual(mountedRepository.repository, "maria/project");
972 - for (const path of [
973 - "repos/forgejo/maria/project/pulls?state=open",
974 - "repos/forgejo/maria/project",
975 - "repos/reviewer/project/contents/file.ts",
976 - ]) {
977 - const result = yield* cli.api({
978 - cwd: "/repo",
979 - repository: "forgejo/maria/project",
980 - context: {
981 - provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://code.test/forgejo" },
982 - remoteName: "origin",
983 - remoteUrl: "https://code.test/forgejo/maria/project.git",
984 - },
985 - path,
986 - });
987 - assert.strictEqual(result.stdout, "[]");
988 - }
989 - const sameOwnerAsMount = yield* cli.resolveRepository({
990 - cwd: "/repo",
991 - repository: "forgejo/project",
992 - context: {
993 - provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://code.test/forgejo" },
994 - remoteName: "origin",
995 - remoteUrl: "ssh://git@code.test/forgejo/project.git",
996 - },
997 - });
998 - assert.strictEqual(sameOwnerAsMount.command, "tea");
999 - assert.strictEqual(sameOwnerAsMount.repository, "forgejo/project");
1000 - }).pipe(
1001 - Effect.provideService(
1002 - FileSystem.FileSystem,
1003 - FileSystem.makeNoop({
1004 - exists: () => Effect.succeed(true),
1005 - readFileString: () =>
1006 - Effect.succeed(
1007 - encodeJson({
1008 - hosts: { "code.test/forgejo": { type: "Application", token: "test-token" } },
1009 - }),
1010 - ),
1011 - }),
1012 - ),
1013 - Effect.provideService(
1014 - HttpClient.HttpClient,
1015 - HttpClient.make(() => {
1016 - throw new Error("tea must handle its own HTTP request");
1017 - }),
1018 - ),
1019 - Effect.provide(
1020 - Layer.mock(VcsProcess.VcsProcess)({
1021 - run: (input) => {
1022 - if (input.command === "git")
1023 - return Effect.succeed(processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }));
1024 - if (input.args[0] === "login")
1025 - return Effect.succeed(
1026 - processOutput(
1027 - encodeJson([
1028 - {
1029 - name: "mounted",
1030 - url: "https://code.test/forgejo",
1031 - ssh_host: "code.test",
1032 - user: "maria",
1033 - default: "true",
1034 - },
1035 - ]),
1036 - ),
1037 - );
1038 - const supported = [
1039 - "https://code.test/forgejo/api/v1/user",
1040 - "https://code.test/forgejo/api/v1/repos/maria/project/pulls?state=open",
1041 - "https://code.test/forgejo/api/v1/repos/maria/project",
1042 - "https://code.test/forgejo/api/v1/repos/reviewer/project/contents/file.ts",
1043 - ];
1044 - if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
1045 - assert.strictEqual(input.command, "tea");
1046 - return Effect.succeed(
1047 - supported.includes(input.args.at(-1) ?? "")
1048 - ? processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" })
1049 - : processOutput("{}", { stderr: "HTTP/1.1 404 Not Found\n" }),
1050 - );
1051 - },
1052 - }),
1053 - ),
1054 - ),
1055 -);
1056 -
1057 -it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {
1058 - const commands: string[] = [];
1059 - const requests: string[] = [];
1060 - return Effect.gen(function* () {
1061 - const cli = yield* ForgejoCli.make;
1062 - for (const remoteUrl of [
1063 - "http://forgejo.local:3000/maria/project.git",
1064 - "ssh://git@ssh.forgejo.local:2222/maria/project.git",
1065 - "ssh://git@forgejo.local:2222/maria/project.git",
1066 - ]) {
1067 - const result = yield* cli.api({
1068 - cwd: "/repo",
1069 - repository: "maria/project",
1070 - context: {
1071 - provider: {
1072 - kind: "forgejo",
1073 - name: "Forgejo",
1074 - baseUrl: "http://forgejo.local:3000",
1075 - },
1076 - remoteName: "origin",
1077 - remoteUrl,
1078 - requestedHost: "forgejo.local:3000",
1079 - },
1080 - path: "repos/maria/project/issues/42/comments",
1081 - method: "POST",
1082 - body: { body: "verified through fj" },
1083 - });
1084 - assert.strictEqual(result.stdout, '{"id":99}');
1085 - }
1086 - assert.deepStrictEqual(commands, ["fj"]);
1087 - assert.deepStrictEqual(requests, [
1088 - "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
1089 - "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
1090 - "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
1091 - ]);
1092 - const viewer = yield* cli.api({
1093 - cwd: "/no-remotes",
1094 - host: "forgejo.local:3000",
1095 - path: "user",
1096 - });
1097 - assert.strictEqual(viewer.stdout, '{"login":"maria"}');
1098 - assert.strictEqual(requests.at(-1), "https://forgejo.local:3000/api/v1/user");
1099 - const upstreamViewer = yield* cli.api({
1100 - cwd: "/upstream-only",
1101 - host: "forgejo.local:3000",
1102 - path: "user",
1103 - });
1104 - assert.strictEqual(upstreamViewer.stdout, '{"login":"maria"}');
1105 - assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
1106 - const upstreamRepository = yield* cli.resolveRepository({
1107 - cwd: "/upstream-only",
1108 - host: "forgejo.local:3000",
1109 - repository: "maria/project",
1110 - });
1111 - assert.strictEqual(upstreamRepository.baseUrl, "http://forgejo.local:3000");
1112 - assert.strictEqual(upstreamRepository.repository, "maria/project");
1113 - const httpViewer = yield* cli.api({ cwd: "/repo", host: "forgejo.local:3000", path: "user" });
1114 - assert.strictEqual(httpViewer.stdout, '{"login":"maria"}');
1115 - assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
1116 - }).pipe(
1117 - Effect.provideService(
1118 - FileSystem.FileSystem,
1119 - FileSystem.makeNoop({
1120 - exists: () => Effect.succeed(true),
1121 - readFileString: () =>
1122 - Effect.succeed(
1123 - encodeJson({
1124 - hosts: {
1125 - "forgejo.local:3000": { type: "Application", token: "test-token" },
1126 - "forgejo.local:4000": { type: "Application", token: "other-token" },
1127 - },
1128 - aliases: { "ssh.forgejo.local:2222": "forgejo.local:3000" },
1129 - }),
1130 - ),
1131 - }),
1132 - ),
1133 - Effect.provideService(
1134 - HttpClient.HttpClient,
1135 - HttpClient.make((request) => {
1136 - requests.push(request.url);
1137 - if (request.url.endsWith("/user")) {
1138 - assert.strictEqual(request.method, "GET");
1139 - assert.strictEqual(request.headers.authorization, "token test-token");
1140 - return Effect.succeed(
1141 - HttpClientResponse.fromWeb(request, new Response('{"login":"maria"}')),
1142 - );
1143 - }
1144 - assert.strictEqual(request.method, "POST");
1145 - assert.strictEqual(request.headers.authorization, "token test-token");
1146 - assert.strictEqual(request.body._tag, "Uint8Array");
1147 - if (request.body._tag === "Uint8Array")
1148 - assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(request.body.body)), {
1149 - body: "verified through fj",
1150 - });
1151 - return Effect.succeed(
1152 - HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),
1153 - );
1154 - }),
1155 - ),
1156 - Effect.provide(
1157 - Layer.mock(VcsProcess.VcsProcess)({
1158 - run: (input) => {
1159 - commands.push(input.command);
1160 - if (input.command === "git")
1161 - return Effect.succeed(
1162 - input.cwd === "/no-remotes"
1163 - ? processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) })
1164 - : processOutput(
1165 - `${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)`,
1166 - ),
1167 - );
1168 - assert.strictEqual(input.command, "fj");
1169 - assert.deepStrictEqual(input.args, [
1170 - "--host",
1171 - input.cwd === "/no-remotes"
1172 - ? "https://forgejo.local:3000"
1173 - : "http://forgejo.local:3000",
1174 - "whoami",
1175 - ]);
1176 - return Effect.succeed(processOutput(""));
1177 - },
1178 - }),
1179 - ),
1180 - );
1181 -});
1182 -
1183 -it.effect("loads later fj review pages when the server caps pages below the requested size", () => {
1184 - const pages: number[] = [];
1185 - let issueCommentRequests = 0;
1186 - return Effect.gen(function* () {
1187 - const cli = yield* ForgejoCli.make;
1188 - const provider = yield* ForgejoPullRequestProvider.make.pipe(
1189 - Effect.provideService(ForgejoCli.ForgejoCli, cli),
1190 - );
1191 - const activity = yield* provider.getChangeRequestActivity({
1192 - cwd: "/repo",
1193 - repository: "maria/project",
1194 - host: "forgejo.test",
1195 - number: 42,
1196 - });
1197 - assert.strictEqual(activity.commentCount, 42);
1198 - assert.strictEqual(activity.comments.at(-1)?.id, "review:41");
1199 - assert.strictEqual(activity.commentsTruncated, false);
1200 - assert.deepStrictEqual(pages, [1, 2, 3]);
1201 - assert.strictEqual(issueCommentRequests, 1);
1202 - }).pipe(
1203 - Effect.provideService(
1204 - FileSystem.FileSystem,
1205 - FileSystem.makeNoop({
1206 - exists: () => Effect.succeed(true),
1207 - readFileString: () =>
1208 - Effect.succeed(
1209 - encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
1210 - ),
1211 - }),
1212 - ),
1213 - Effect.provideService(
1214 - HttpClient.HttpClient,
1215 - HttpClient.make((request) => {
1216 - const url = new URL(request.url);
1217 - if (url.pathname === "/api/v1/repos/maria/project/issues/42/comments") {
1218 - issueCommentRequests++;
1219 - return Effect.succeed(
1220 - HttpClientResponse.fromWeb(
1221 - request,
1222 - new Response(
1223 - encodeJson([
1224 - {
1225 - id: 100,
1226 - body: "Unpaginated issue comment",
1227 - user: { login: "maria" },
1228 - created_at: "2026-09-13T00:00:00Z",
1229 - },
1230 - ]),
1231 - ),
1232 - ),
1233 - );
1234 - }
1235 - if (url.pathname.endsWith("/reviews")) {
1236 - const page = Number(url.searchParams.get("page"));
1237 - pages.push(page);
1238 - assert.ok(page >= 1 && page <= 3);
1239 - const reviews = Array.from({ length: page < 3 ? 20 : 1 }, (_, index) => ({
1240 - id: (page - 1) * 20 + index + 1,
1241 - body: "Review from a capped page",
1242 - user: { login: "maria" },
1243 - state: "COMMENT",
1244 - submitted_at: "2026-09-13T00:00:00Z",
1245 - comments_count: 0,
1246 - }));
1247 - return Effect.succeed(
1248 - HttpClientResponse.fromWeb(
1249 - request,
1250 - new Response(encodeJson(reviews), {
1251 - headers:
1252 - page === 2
1253 - ? {}
1254 - : {
1255 - Link:
1256 - page === 1
1257 - ? `<${url.origin}${url.pathname}?limit=50&page=2>; rel="next"`
1258 - : `<${url.origin}${url.pathname}?limit=50&page=1>; rel="prev"`,
1259 - },
1260 - }),
1261 - ),
1262 - );
1263 - }
1264 - return Effect.succeed(
1265 - HttpClientResponse.fromWeb(
1266 - request,
1267 - new Response(encodeJson(url.pathname === "/api/v1/user" ? { login: "maria" } : [])),
1268 - ),
1269 - );
1270 - }),
1271 - ),
1272 - Effect.provide(
1273 - Layer.mock(VcsProcess.VcsProcess)({
1274 - run: (input) => {
1275 - if (input.command === "git") {
1276 - assert.deepStrictEqual(input.args, ["remote", "-v"]);
1277 - return Effect.succeed(
1278 - processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
1279 - );
1280 - }
1281 - assert.strictEqual(input.command, "fj");
1282 - assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
1283 - return Effect.succeed(processOutput(""));
1284 - },
1285 - }),
1286 - ),
1287 - );
1288 -});
1289 -
1290 -it.effect("falls back to tea when fj is missing or has no account for this server", () =>
1291 - Effect.gen(function* () {
1292 - for (const scenario of ["missing-cli", "missing-account", "stale-invalid-storage"] as const) {
1293 - const commands: string[] = [];
1294 - yield* Effect.gen(function* () {
1295 - const cli = yield* ForgejoCli.make;
1296 - const result = yield* cli.api({
1297 - cwd: "/repo",
1298 - repository: "https://forgejo.local:3000/maria/project",
1299 - path: "repos/maria/project/pulls",
1300 - });
1301 - assert.strictEqual(result.stdout, "[]");
1302 - assert.deepStrictEqual(
1303 - commands,
1304 - scenario === "missing-account" ? ["tea", "tea"] : ["fj", "tea", "tea"],
1305 - );
1306 - const viewer = yield* cli.api({
1307 - cwd: "/upstream-only",
1308 - host: "forgejo.local:3000",
1309 - path: "user",
1310 - });
1311 - assert.strictEqual(viewer.stdout, "[]");
1312 - }).pipe(
1313 - Effect.provideService(
1314 - FileSystem.FileSystem,
1315 - FileSystem.makeNoop({
1316 - exists: () => Effect.succeed(true),
1317 - readFileString: () =>
1318 - Effect.succeed(
1319 - scenario === "stale-invalid-storage"
1320 - ? "invalid json"
1321 - : encodeJson({
1322 - hosts: {
1323 - [scenario === "missing-cli" ? "forgejo.local:3000" : "other.local"]: {
1324 - type: "Application",
1325 - token: "test-token",
1326 - },
1327 - },
1328 - }),
1329 - ),
1330 - }),
1331 - ),
1332 - Effect.provideService(
1333 - HttpClient.HttpClient,
1334 - HttpClient.make(() => {
1335 - throw new Error("tea must handle its own HTTP request");
1336 - }),
1337 - ),
1338 - Effect.provide(
1339 - Layer.mock(VcsProcess.VcsProcess)({
1340 - run: (input) => {
1341 - commands.push(input.command);
1342 - if (input.command === "git")
1343 - return Effect.succeed(
1344 - processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
1345 - );
1346 - if (input.command === "fj")
1347 - return Effect.fail(
1348 - new VcsProcessSpawnError({
1349 - operation: input.operation,
1350 - command: input.command,
1351 - cwd: input.cwd,
1352 - cause: new Error("fj not found"),
1353 - }),
1354 - );
1355 - assert.strictEqual(input.command, "tea");
1356 - if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
1357 - return Effect.succeed(
1358 - input.args[0] === "login"
1359 - ? processOutput(
1360 - encodeJson([
1361 - {
1362 - name: "work",
1363 - url: "https://forgejo.local:3000",
1364 - user: "maria",
1365 - default: "true",
1366 - valid: "true",
1367 - },
1368 - ]),
1369 - )
1370 - : processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" }),
1371 - );
1372 - },
1373 - }),
1374 - ),
1375 - );
1376 - }
1377 - }),
1378 -);
1379 -
1380 -it.effect("handles fj mutation statuses without retrying failures or reading absent bodies", () =>
1381 - Effect.gen(function* () {
1382 - for (const status of [204, 205, 302, 401, 403, 404, 429, 500]) {
1383 - let writes = 0;
1384 - yield* Effect.gen(function* () {
1385 - const cli = yield* ForgejoCli.make;
1386 - const result = yield* cli
1387 - .api({
1388 - cwd: "/repo",
1389 - repository: "https://forgejo.local/maria/project",
1390 - path: "repos/maria/project/issues/42/comments",
1391 - method: "POST",
1392 - body: { body: "only once" },
1393 - })
1394 - .pipe(Effect.result);
1395 - assert.strictEqual(result._tag, status < 300 ? "Success" : "Failure");
1396 - if (result._tag === "Success") assert.strictEqual(result.success.stdout, "");
1397 - if (result._tag === "Failure") {
1398 - assert.strictEqual(result.failure.command, "fj");
1399 - assert.strictEqual(result.failure.httpStatus, status);
1400 - }
1401 - assert.strictEqual(writes, 1);
1402 - }).pipe(
1403 - Effect.provideService(
1404 - FileSystem.FileSystem,
1405 - FileSystem.makeNoop({
1406 - exists: () => Effect.succeed(true),
1407 - readFileString: () =>
1408 - Effect.succeed(
1409 - encodeJson({
1410 - hosts: {
1411 - "forgejo.local": { type: "Application", token: "test-token" },
1412 - },
1413 - }),
1414 - ),
1415 - }),
1416 - ),
1417 - Effect.provideService(
1418 - HttpClient.HttpClient,
1419 - HttpClient.make((request) => {
1420 - writes++;
1421 - assert.strictEqual(
1422 - request.url,
1423 - "https://forgejo.local/api/v1/repos/maria/project/issues/42/comments",
1424 - );
1425 - return Effect.succeed(
1426 - HttpClientResponse.fromWeb(
1427 - request,
1428 - new Response(status < 300 ? null : "", {
1429 - status,
1430 - headers: { location: "https://other.local/" },
1431 - }),
1432 - ),
1433 - );
1434 - }),
1435 - ),
1436 - Effect.provide(
1437 - Layer.mock(VcsProcess.VcsProcess)({
1438 - run: (input) => {
1439 - assert.strictEqual(
1440 - input.command,
1441 - "fj",
1442 - "a failed mutation must never switch accounts or CLI",
1443 - );
1444 - return Effect.succeed(processOutput(""));
1445 - },
1446 - }),
1447 - ),
1448 - );
1449 - }
1450 - }),
1451 -);
1452 -
1453 -it.effect(
1454 - "discovers fj first and retains configured authentication failures instead of switching accounts",
1455 - () =>
1456 - Effect.gen(function* () {
1457 - for (const scenario of ["authenticated", "revoked", "missing", "invalid-storage"] as const) {
1458 - const commands: string[] = [];
1459 - yield* Effect.gen(function* () {
1460 - const spec = yield* ForgejoSourceControlProvider.makeDiscovery;
1461 - assert.strictEqual(spec.type, "managed-cli");
1462 - if (spec.type !== "managed-cli") return;
1463 - const result = yield* spec.probe("/repo");
1464 - assert.strictEqual(result.executable, scenario === "missing" ? "tea" : "fj");
1465 - assert.strictEqual(
1466 - result.auth.status,
1467 - scenario === "revoked"
1468 - ? "unauthenticated"
1469 - : scenario === "invalid-storage"
1470 - ? "unknown"
1471 - : "authenticated",
1472 - );
1473 - if (scenario !== "revoked" && scenario !== "invalid-storage")
1474 - assert.deepStrictEqual(result.auth.host, Option.some("forgejo.local:3000"));
1475 - assert.deepStrictEqual(
1476 - result.auth.account,
1477 - scenario === "authenticated" || scenario === "missing"
1478 - ? Option.some("maria")
1479 - : Option.none(),
1480 - );
1481 - assert.strictEqual(
1482 - commands.some((command) => command.startsWith("tea ")),
1483 - scenario === "missing",
1484 - );
1485 - assert.include(commands, "fj version");
1486 - }).pipe(
1487 - Effect.provide(
1488 - Layer.mergeAll(
1489 - Layer.mock(ForgejoCli.ForgejoCli)({
1490 - getAccount: (input) => {
1491 - assert.strictEqual(scenario, "authenticated");
1492 - assert.deepStrictEqual(input, {
1493 - cwd: "/repo",
1494 - baseUrl: "http://forgejo.local:3000",
1495 - });
1496 - return Effect.succeed("maria");
1497 - },
1498 - listLogins: (input) => {
1499 - assert.strictEqual(
1500 - input.remoteUrl,
1501 - "http://forgejo.local:3000/maria/project.git",
1502 - );
1503 - if (scenario === "invalid-storage")
1504 - return Effect.fail(
1505 - new ForgejoCli.ForgejoCliError({
1506 - command: "fj",
1507 - cwd: input.cwd,
1508 - reason: "authentication",
1509 - detail: "fj authentication storage is invalid.",
1510 - }),
1511 - );
1512 - return Effect.succeed([
1513 - {
1514 - name: "forgejo.local:3000",
1515 - url: "http://forgejo.local:3000",
1516 - user: "",
1517 - default: "false",
1518 - },
1519 - ]);
1520 - },
1521 - }),
1522 - Layer.mock(VcsProcess.VcsProcess)({
1523 - run: (input) => {
1524 - commands.push(`${input.command} ${input.args.join(" ")}`);
1525 - if (input.command === "git")
1526 - return Effect.succeed(
1527 - processOutput("http://forgejo.local:3000/maria/project.git\n"),
1528 - );
1529 - if (input.command === "fj") {
1530 - if (scenario === "missing")
1531 - return Effect.fail(
1532 - new VcsProcessSpawnError({
1533 - operation: input.operation,
1534 - command: input.command,
1535 - cwd: input.cwd,
1536 - cause: new Error("fj not found"),
1537 - }),
1538 - );
1539 - if (input.args[0] === "version")
1540 - return Effect.succeed(processOutput("fj 0.10.0"));
1541 - if (scenario === "invalid-storage") {
1542 - assert.deepStrictEqual(input.args, ["auth", "list"]);
1543 - return Effect.succeed(processOutput(""));
1544 - }
1545 - assert.deepStrictEqual(input.args, [
1546 - "--host",
1547 - "http://forgejo.local:3000",
1548 - "whoami",
1549 - ]);
1550 - return Effect.succeed(
1551 - processOutput("", {
1552 - exitCode: ChildProcessSpawner.ExitCode(scenario === "revoked" ? 1 : 0),
1553 - }),
1554 - );
1555 - }
1556 - assert.strictEqual(input.command, "tea");
1557 - return Effect.succeed(
1558 - input.args[0] === "--version"
1559 - ? processOutput("tea version 0.16.0")
1560 - : processOutput(
1561 - encodeJson([
1562 - {
1563 - name: "work",
1564 - url: "http://forgejo.local:3000",
1565 - user: "maria",
1566 - default: "true",
1567 - valid: "true",
1568 - },
1569 - ]),
1570 - ),
1571 - );
1572 - },
1573 - }),
1574 - ),
1575 - ),
1576 - );
1577 - }
1578 - }),
1579 -);
1580 -
339 it.effect(
340 "checks out fj pull refs and preserves existing branches and dirty files until forced",
341 () =>
@@ -1627,22 +385,26 @@ it.effect(
385 args: ["rev-parse", "HEAD"],
386 })).stdout.trim();
387 const fetched: string[] = [];
388 + const host = yield* SourceControlHost.SourceControlHost;
389 const provider = yield* ForgejoSourceControlProvider.make.pipe(
390 Effect.provideService(
1632 - VcsProcess.VcsProcess,
1633 - VcsProcess.VcsProcess.of({
1634 - run: (input) => {
1635 - if (input.args[0] !== "fetch") return git.run(input);
1636 - const url = input.args[2];
1637 - assert.isDefined(url);
1638 - fetched.push(url!);
1639 - // Only SSH transport is substituted; both paths fetch the real pull ref.
1640 - return git.run({
1641 - ...input,
1642 - args: input.args.map((arg) =>
1643 - arg === "git@forgejo.test:reviewer/project.git" ? source : arg,
1644 - ),
1645 - });
391 + SourceControlHost.SourceControlHost,
392 + SourceControlHost.SourceControlHost.of({
393 + settings: host.settings,
394 + process: {
395 + run: (input) => {
396 + if (input.args[0] !== "fetch") return git.run(input);
397 + const url = input.args[2];
398 + assert.isDefined(url);
399 + fetched.push(url!);
400 + // Only SSH transport is substituted; both paths fetch the real pull ref.
401 + return git.run({
402 + ...input,
403 + args: input.args.map((arg) =>
404 + arg === "git@forgejo.test:reviewer/project.git" ? source : arg,
405 + ),
406 + });
407 + },
408 },
409 }),
410 ),
@@ -1759,6 +521,12 @@ it.effect(
521 assert.deepStrictEqual(fetched, [source, source, "git@forgejo.test:reviewer/project.git"]);
522 }).pipe(
523 Effect.scoped,
1762 - Effect.provide(VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer))),
524 + Effect.provide(
525 + ServerSourceControlHost.layer.pipe(
526 + Layer.provideMerge(VcsProcess.layer),
527 + Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
528 + Layer.provideMerge(NodeServices.layer),
529 + ),
530 + ),
531 ),
532 );
apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
+1 -1
@@ -19,7 +19,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
19 import * as GitHubApi from "./GitHubApi.ts";
20 import * as GitHubCredentials from "./GitHubCredentials.ts";
21 import * as GitLabCli from "./GitLabCli.ts";
22 -import * as ForgejoCli from "./ForgejoCli.ts";
22 +import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
23 import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
24 import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
25
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+11 -4
@@ -15,7 +15,7 @@ import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlPro
15 import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
16 import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
17 import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
18 -import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
18 +import * as BuiltInDrivers from "./builtInDrivers.ts";
19 import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
20 import {
21 probeSourceControlProvider,
@@ -308,11 +308,18 @@ export const make = Effect.gen(function* () {
308 const github = yield* GitHubSourceControlProvider.make;
309 const githubDiscovery = yield* GitHubSourceControlProvider.makeDiscovery;
310 const gitlab = yield* GitLabSourceControlProvider.make;
311 - const forgejo = yield* ForgejoSourceControlProvider.make;
312 - const forgejoDiscovery = yield* ForgejoSourceControlProvider.makeDiscovery;
311 const bitbucket = yield* BitbucketSourceControlProvider.make;
312 const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery;
313 const azureDevOps = yield* AzureDevOpsSourceControlProvider.make;
314 + const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
315 + driver.make.pipe(
316 + Effect.map((instance): SourceControlProviderRegistration => ({
317 + kind: driver.kind,
318 + provider: instance.sourceControl,
319 + discovery: instance.discovery,
320 + })),
321 + ),
322 + );
323 return yield* makeWithProviders([
324 {
325 kind: "github",
@@ -334,7 +341,7 @@ export const make = Effect.gen(function* () {
341 provider: bitbucket,
342 discovery: bitbucketDiscovery,
343 },
337 - { kind: "forgejo", provider: forgejo, discovery: forgejoDiscovery },
344 + ...drivers,
345 ]);
346 });
347
apps/server/src/sourceControl/builtInDrivers.ts new
+20
@@ -0,0 +1,20 @@
1 +/**
2 + * The source control drivers this build ships with. Both registries, repository operations and
3 + * pull requests, iterate this list; a host with no driver here shows up as unsupported.
4 + *
5 + * Adding a host means writing its `@t3tools/source-control-<host>` package, adding its driver
6 + * here, and providing its services' layers in `layer` below.
7 + *
8 + * @module sourceControl/builtInDrivers
9 + */
10 +import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
11 +import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
12 +import * as Layer from "effect/Layer";
13 +
14 +import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
15 +
16 +/** Ordered as the hosts appear in discovery, after the ones still built in the server. */
17 +export const BUILT_IN_SOURCE_CONTROL_DRIVERS = [ForgejoDriver.driver] as const;
18 +
19 +/** The services the built-in drivers' packages own, plus the host port they all run against. */
20 +export const layer = ForgejoCli.layer.pipe(Layer.provideMerge(ServerSourceControlHost.layer));
apps/server/src/ws.ts
+2 -4
@@ -233,9 +233,8 @@ import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
233 import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
234 import * as GitHubApi from "./sourceControl/GitHubApi.ts";
235 import * as GitLabCli from "./sourceControl/GitLabCli.ts";
236 -import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";
236 +import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
237 import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
238 -import * as ServerSourceControlHost from "./sourceControl/ServerSourceControlHost.ts";
238 import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
239 import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
240 import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
@@ -3209,8 +3208,7 @@ export const layer = Layer.unwrap(
3208 BitbucketApi.layer,
3209 GitHubApi.layerWithDependencies,
3210 GitLabCli.layer,
3212 - ForgejoCli.layer,
3213 - ServerSourceControlHost.layer,
3211 + SourceControlBuiltInDrivers.layer,
3212 ),
3213 ),
3214 Layer.provideMerge(GitVcsDriver.layer),
package.json
+1 -1
@@ -28,7 +28,7 @@
28 "tc": "vp run -r --concurrency-limit 2 typecheck",
29 "lint": "vp lint --report-unused-disable-directives",
30 "knip": "knip --preprocessor ./scripts/knip-schemas.ts",
31 - "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-grok --workspace packages/source-control-core --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",
31 + "knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-grok --workspace packages/source-control-core --workspace packages/source-control-forgejo --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",
32 "knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts",
33 "lint:mobile": "node scripts/mobile-native-static-check.ts",
34 "test": "vp run -r test",
packages/source-control-core/package.json
+9
@@ -3,10 +3,18 @@
3 "private": true,
4 "type": "module",
5 "exports": {
6 + "./server/diffFileRevisions": {
7 + "types": "./src/server/diffFileRevisions.ts",
8 + "import": "./src/server/diffFileRevisions.ts"
9 + },
10 "./server/discovery": {
11 "types": "./src/server/discovery.ts",
12 "import": "./src/server/discovery.ts"
13 },
14 + "./server/driver": {
15 + "types": "./src/server/driver.ts",
16 + "import": "./src/server/driver.ts"
17 + },
18 "./server/mergeMessage": {
19 "types": "./src/server/mergeMessage.ts",
20 "import": "./src/server/mergeMessage.ts"
@@ -38,6 +46,7 @@
46 },
47 "dependencies": {
48 "@t3tools/contracts": "workspace:*",
49 + "@t3tools/shared": "workspace:*",
50 "effect": "catalog:"
51 },
52 "devDependencies": {
packages/source-control-core/src/server/diffFileRevisions.test.ts renamed
+1 -1
@@ -1,6 +1,6 @@
1 import { assert, describe, it } from "@effect/vitest";
2
3 -import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";
3 +import { parseDiffFileRevisions } from "./diffFileRevisions.ts";
4
5 function patchOf(...lines: ReadonlyArray<string>): string {
6 return `${lines.join("\n")}\n`;
packages/source-control-core/src/server/diffFileRevisions.ts renamed
packages/source-control-core/src/server/driver.ts new
+36
@@ -0,0 +1,36 @@
1 +/**
2 + * SourceControlDriver — what a source control provider package hands the server.
3 + *
4 + * One driver per host kind. The server lists its drivers once and both registries (repository
5 + * operations and pull requests) iterate that list, so adding a host means writing its package
6 + * and adding its driver to the list.
7 + *
8 + * `make` yields what it needs from the environment: the `SourceControlHost` port, Effect
9 + * platform services, and the package's own services, which the server provides from the
10 + * package's layers. Its `R` channel is the full list.
11 + *
12 + * @module source-control-core/server/driver
13 + */
14 +import type { SourceControlProviderKind } from "@t3tools/contracts";
15 +import type * as Effect from "effect/Effect";
16 +
17 +import type { SourceControlProviderDiscoverySpec } from "./discovery.ts";
18 +import type { PullRequestProviderApi } from "./PullRequestProvider.ts";
19 +import type * as SourceControlProvider from "./SourceControlProvider.ts";
20 +
21 +export interface SourceControlDriverInstance {
22 + readonly sourceControl: SourceControlProvider.SourceControlProvider["Service"];
23 + readonly discovery: SourceControlProviderDiscoverySpec;
24 + /** Null for a host whose pull requests this build cannot read. */
25 + readonly pullRequests: PullRequestProviderApi | null;
26 +}
27 +
28 +export interface SourceControlDriver<R = never> {
29 + readonly kind: SourceControlProviderKind;
30 + readonly make: Effect.Effect<SourceControlDriverInstance, never, R>;
31 +}
32 +
33 +/** Declares a driver with its `R` inferred from `make`. */
34 +export const defineSourceControlDriver = <R>(
35 + driver: SourceControlDriver<R>,
36 +): SourceControlDriver<R> => driver;
packages/source-control-forgejo/package.json new
+48
@@ -0,0 +1,48 @@
1 +{
2 + "name": "@t3tools/source-control-forgejo",
3 + "private": true,
4 + "type": "module",
5 + "exports": {
6 + "./server/driver": {
7 + "types": "./src/server/driver.ts",
8 + "import": "./src/server/driver.ts"
9 + },
10 + "./server/ForgejoCli": {
11 + "types": "./src/server/ForgejoCli.ts",
12 + "import": "./src/server/ForgejoCli.ts"
13 + },
14 + "./server/forgejoPullRequestJson": {
15 + "types": "./src/server/forgejoPullRequestJson.ts",
16 + "import": "./src/server/forgejoPullRequestJson.ts"
17 + },
18 + "./server/ForgejoPullRequestProvider": {
19 + "types": "./src/server/ForgejoPullRequestProvider.ts",
20 + "import": "./src/server/ForgejoPullRequestProvider.ts"
21 + },
22 + "./server/forgejoPullRequests": {
23 + "types": "./src/server/forgejoPullRequests.ts",
24 + "import": "./src/server/forgejoPullRequests.ts"
25 + },
26 + "./server/ForgejoSourceControlProvider": {
27 + "types": "./src/server/ForgejoSourceControlProvider.ts",
28 + "import": "./src/server/ForgejoSourceControlProvider.ts"
29 + }
30 + },
31 + "scripts": {
32 + "typecheck": "tsc --noEmit",
33 + "test": "vp test run --config ../../vite.config.ts --dir ."
34 + },
35 + "dependencies": {
36 + "@t3tools/contracts": "workspace:*",
37 + "@t3tools/provider-core": "workspace:*",
38 + "@t3tools/shared": "workspace:*",
39 + "@t3tools/source-control-core": "workspace:*",
40 + "effect": "catalog:"
41 + },
42 + "devDependencies": {
43 + "@effect/vitest": "catalog:",
44 + "@t3tools/source-control-testing": "workspace:*",
45 + "@types/node": "catalog:",
46 + "vite-plus": "catalog:"
47 + }
48 +}
packages/source-control-forgejo/src/server/ForgejoCli.ts renamed
+5 -5
@@ -13,7 +13,7 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
13 import { ChildProcessSpawner } from "effect/process";
14 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
15 import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
16 -import * as VcsProcess from "../vcs/VcsProcess.ts";
16 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
17 import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
18 import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
19
@@ -133,7 +133,7 @@ export class ForgejoCli extends Context.Service<
133 readonly stdin?: string;
134 readonly timeoutMs?: number;
135 readonly maxOutputBytes?: number;
136 - }) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
136 + }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
137 readonly listLogins?: (input: {
138 readonly cwd: string;
139 readonly command: "fj" | "tea";
@@ -148,9 +148,9 @@ export class ForgejoCli extends Context.Service<
148 ) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
149 readonly api: (
150 input: ForgejoApiInput,
151 - ) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;
151 + ) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
152 }
153 ->()("t3/sourceControl/ForgejoCli") {}
153 +>()("@t3tools/source-control-forgejo/server/ForgejoCli") {}
154
155 export function parseForgejoRemote(value: string) {
156 if (/^(?:https?|ssh):\/\//i.test(value)) {
@@ -212,7 +212,7 @@ export function matchForgejoLogin(
212 }
213
214 export const make = Effect.gen(function* () {
215 - const process = yield* VcsProcess.VcsProcess;
215 + const { process } = yield* SourceControlHost.SourceControlHost;
216 const fileSystem = yield* FileSystem.FileSystem;
217 const httpClient = yield* HttpClient.HttpClient;
218 const authLock = yield* Semaphore.make(1);
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts renamed
+2 -2
@@ -3,8 +3,8 @@ import * as Schema from "effect/Schema";
3 import * as Result from "effect/Result";
4 import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
5 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
6 -import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
7 -import { parseDiffFileRevisions } from "./bitbucketDiffRevisions.ts";
6 +import * as ForgejoCli from "./ForgejoCli.ts";
7 +import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
8 import {
9 PullRequestProviderError,
10 type ProviderChangeRequestDetail,
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts new
+1283
@@ -0,0 +1,1283 @@
1 +import { assert, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import type * as Context from "effect/Context";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9 +import * as FetchHttpClient from "effect/http/FetchHttpClient";
10 +import * as HttpClient from "effect/http/HttpClient";
11 +import * as HttpClientResponse from "effect/http/HttpClientResponse";
12 +import { VcsProcessSpawnError } from "@t3tools/contracts";
13 +import { firstNonEmptyLine } from "@t3tools/source-control-core/server/discovery";
14 +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
15 +
16 +import * as ForgejoCli from "./ForgejoCli.ts";
17 +import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
18 +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
19 +
20 +const processOutput = TestSourceControlHost.processOutput;
21 +
22 +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
23 +const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
24 +
25 +it.effect("submits a Forgejo review without sending its summary in the preliminary GET", () => {
26 + const methods: string[] = [];
27 + const fetchReview = async (
28 + ...[input, init]: Parameters<Context.Service.Shape<typeof FetchHttpClient.Fetch>>
29 + ) => {
30 + const request = new Request(input instanceof Request ? input.url : String(input), {
31 + ...(init?.method === undefined ? {} : { method: init.method }),
32 + ...(init?.headers === undefined ? {} : { headers: init.headers }),
33 + ...(init?.body === undefined ? {} : { body: init.body }),
34 + });
35 + methods.push(request.method);
36 + if (request.method === "GET") {
37 + assert.strictEqual(request.url, "https://forgejo.test/api/v1/repos/maria/project/pulls/42");
38 + return new Response(
39 + encodeJson({
40 + number: 42,
41 + title: "Review target",
42 + body: "",
43 + html_url: "https://forgejo.test/maria/project/pulls/42",
44 + user: { login: "maria" },
45 + state: "open",
46 + merged: false,
47 + head: { ref: "feature", sha: "head", repo: null },
48 + base: { ref: "main", sha: "base", repo: null },
49 + created_at: "2026-09-13T00:00:00Z",
50 + updated_at: "2026-09-13T00:00:00Z",
51 + closed_at: null,
52 + merged_at: null,
53 + labels: [],
54 + }),
55 + );
56 + }
57 + assert.strictEqual(request.method, "POST");
58 + assert.strictEqual(
59 + request.url,
60 + "https://forgejo.test/api/v1/repos/maria/project/pulls/42/reviews",
61 + );
62 + assert.deepStrictEqual(JSON.parse(await request.text()), {
63 + event: "COMMENT",
64 + body: "Review summary",
65 + commit_id: "head",
66 + comments: [],
67 + });
68 + return new Response('{"id":1}', { status: 200 });
69 + };
70 + return Effect.gen(function* () {
71 + const cli = yield* ForgejoCli.make;
72 + const provider = yield* ForgejoPullRequestProvider.make.pipe(
73 + Effect.provideService(ForgejoCli.ForgejoCli, cli),
74 + );
75 + yield* provider.submitReview({
76 + cwd: "/repo",
77 + repository: "maria/project",
78 + host: "forgejo.test",
79 + number: 42,
80 + verdict: "comment",
81 + body: "Review summary",
82 + comments: [],
83 + });
84 + assert.deepStrictEqual(methods, ["GET", "POST"]);
85 + }).pipe(
86 + Effect.provideService(
87 + FetchHttpClient.Fetch,
88 + Object.assign(fetchReview, { preconnect: () => undefined }),
89 + ),
90 + Effect.provide(FetchHttpClient.layer),
91 + Effect.provideService(
92 + FileSystem.FileSystem,
93 + FileSystem.makeNoop({
94 + exists: () => Effect.succeed(true),
95 + readFileString: () =>
96 + Effect.succeed(
97 + encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
98 + ),
99 + }),
100 + ),
101 + Effect.provide(
102 + TestSourceControlHost.layer({
103 + process: {
104 + run: (input) => {
105 + if (input.command === "git") {
106 + assert.deepStrictEqual(input.args, ["remote", "-v"]);
107 + return Effect.succeed(
108 + processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
109 + );
110 + }
111 + assert.strictEqual(input.command, "fj");
112 + assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
113 + return Effect.succeed(processOutput(""));
114 + },
115 + },
116 + }),
117 + ),
118 + );
119 +});
120 +
121 +it.effect("reads Forgejo checks without repository or viewer requests", () => {
122 + const paths: string[] = [];
123 + return Effect.gen(function* () {
124 + const provider = yield* ForgejoPullRequestProvider.make;
125 + const read = provider.getChangeRequestChecks;
126 + if (read === undefined) return yield* Effect.die("checks read missing");
127 + const result = yield* read({
128 + cwd: "/repo",
129 + repository: "acme/web",
130 + host: "forgejo.test",
131 + number: 1,
132 + });
133 + assert.strictEqual(result.state, "open");
134 + assert.strictEqual(result.checks[0]?.status, "failure");
135 + assert.deepStrictEqual(paths, [
136 + "repos/acme/web/pulls/1",
137 + "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=1",
138 + "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=2",
139 + ]);
140 + }).pipe(
141 + Effect.provide(
142 + Layer.mock(ForgejoCli.ForgejoCli)({
143 + api: (input) => {
144 + paths.push(input.path);
145 + assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head)/);
146 + return Effect.succeed(
147 + processOutput(
148 + input.path.endsWith("pulls/1")
149 + ? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
150 + "head":{"ref":"feature","sha":"head","repo":null},"base":{"ref":"main","sha":"base","repo":null},
151 + "created_at":"2026-09-16T00:00:00Z","updated_at":"2026-09-16T00:00:00Z","closed_at":null,"merged_at":null,"labels":[]}`
152 + : input.path.endsWith("page=1")
153 + ? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
154 + : "[]",
155 + ),
156 + );
157 + },
158 + }),
159 + ),
160 + );
161 +});
162 +
163 +it.effect.each([
164 + ["Ready", false, true, false, "mergeable"],
165 + ["Draft", true, false, true, "unknown"],
166 + ["Blocked", false, false, false, "unknown"],
167 + ["Unchecked", false, undefined, false, "unknown"],
168 + ["WIP: Legacy draft", undefined, false, true, "unknown"],
169 + ["[WIP] Legacy draft", undefined, false, true, "unknown"],
170 + ["WIP: Explicitly ready", false, false, false, "unknown"],
171 +] as const)(
172 + "reads Forgejo mergeability for %s (draft=%s, mergeable=%s) across list, summary and detail",
173 + ([title, draft, mergeable, isDraft, mergeability]) => {
174 + const pr = {
175 + number: 42,
176 + title,
177 + body: "",
178 + html_url: "https://forgejo.test/maria/project/pulls/42",
179 + user: { login: "maria" },
180 + state: "open",
181 + merged: false,
182 + ...(draft === undefined ? {} : { draft }),
183 + ...(mergeable === undefined ? {} : { mergeable }),
184 + head: { ref: "feature", sha: "head", repo: null },
185 + base: { ref: "main", sha: "base", repo: null },
186 + created_at: "2026-09-16T00:00:00Z",
187 + updated_at: "2026-09-16T00:00:00Z",
188 + closed_at: null,
189 + merged_at: null,
190 + labels: [],
191 + };
192 + return Effect.gen(function* () {
193 + const provider = yield* ForgejoPullRequestProvider.make;
194 + const readSummary = provider.getChangeRequestSummary;
195 + if (readSummary === undefined) return yield* Effect.die("summary read missing");
196 + const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 42 };
197 + const list = yield* provider.listChangeRequests({
198 + ...input,
199 + state: "open",
200 + involvement: "all",
201 + viewer: "maria",
202 + limit: 10,
203 + });
204 + const summary = yield* readSummary(input);
205 + const detail = yield* provider.getChangeRequest(input);
206 + assert.strictEqual(list.items.length, 1);
207 + for (const result of [list.items[0]!, summary, detail]) {
208 + assert.strictEqual(result.mergeability, mergeability);
209 + assert.strictEqual(result.isDraft, isDraft);
210 + }
211 + }).pipe(
212 + Effect.provide(
213 + Layer.mock(ForgejoCli.ForgejoCli)({
214 + api: (input) => {
215 + const [path, query] = input.path.split("?");
216 + let response: unknown;
217 + switch (path) {
218 + case "repos/maria/project/pulls":
219 + response = new URLSearchParams(query).get("page") === "1" ? [pr] : [];
220 + break;
221 + case "repos/maria/project/pulls/42":
222 + response = pr;
223 + break;
224 + case "repos/maria/project":
225 + response = { full_name: "maria/project", permissions: { push: true, admin: true } };
226 + break;
227 + case "user":
228 + response = pr.user;
229 + break;
230 + case "repos/maria/project/statuses/head":
231 + response = [];
232 + break;
233 + default:
234 + return Effect.die(`Unexpected Forgejo request: ${input.path}`);
235 + }
236 + return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
237 + },
238 + }),
239 + ),
240 + );
241 + },
242 +);
243 +
244 +it.effect("loads Forgejo pull request references from files and commits views", () =>
245 + Effect.gen(function* () {
246 + const provider = yield* ForgejoSourceControlProvider.make;
247 + for (const reference of [
248 + "42",
249 + "#42",
250 + "https://forgejo.test/maria/project/pulls/42",
251 + "https://forgejo.test/maria/project/pulls/42/",
252 + "https://forgejo.test/maria/project/pulls/42/files?w=1#diff-1",
253 + "http://forgejo.test:3000/git/maria/project/pulls/42/commits",
254 + ]) {
255 + const result = yield* provider.getChangeRequest({ cwd: "/repo", reference });
256 + assert.strictEqual(result.number, 42);
257 + assert.strictEqual(result.title, "Forgejo view reference");
258 + }
259 + const invalid = yield* provider
260 + .getChangeRequest({
261 + cwd: "/repo",
262 + reference: "https://forgejo.test/maria/project/pulls/42invalid/files",
263 + })
264 + .pipe(Effect.result);
265 + assert.strictEqual(invalid._tag, "Failure");
266 + }).pipe(
267 + Effect.provide(
268 + Layer.mergeAll(
269 + Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
270 + TestSourceControlHost.layer({ process: {} }),
271 + Layer.mock(ForgejoCli.ForgejoCli)({
272 + resolveRepository: () =>
273 + Effect.succeed({
274 + login: "work",
275 + repository: "maria/project",
276 + baseUrl: "https://forgejo.test",
277 + }),
278 + api: (input) => {
279 + assert.strictEqual(input.path, "repos/maria/project/pulls/42");
280 + return encodeJsonEffect({
281 + number: 42,
282 + title: "Forgejo view reference",
283 + html_url: "https://forgejo.test/maria/project/pulls/42",
284 + state: "open",
285 + merged: false,
286 + base: { ref: "main", sha: "base", repo: null },
287 + head: { ref: "feature", sha: "head", repo: null },
288 + }).pipe(Effect.orDie, Effect.map(processOutput));
289 + },
290 + }),
291 + ),
292 + ),
293 + ),
294 +);
295 +
296 +it.effect(
297 + "loads Forgejo reactions on comments, reviews and inline threads and resolves review mutations",
298 + () => {
299 + const user = { login: "maria" };
300 + const review = {
301 + id: 8,
302 + body: "review body",
303 + user,
304 + state: "COMMENT",
305 + submitted_at: "2026-09-12T00:00:00Z",
306 + html_url: "https://forgejo.test/maria/project/pulls/2#issuecomment-37",
307 + comments_count: 1,
308 + };
309 + const comment = { id: 12, body: "ordinary", user, created_at: review.submitted_at };
310 + const responses: Record<string, unknown> = {
311 + user,
312 + "repos/maria/project/issues/2/comments": [comment],
313 + "repos/maria/project/pulls/2/reviews": [review],
314 + "repos/maria/project/pulls/2/reviews/8": review,
315 + "repos/maria/project/pulls/2/reviews/9": { ...review, id: 9, html_url: "" },
316 + "repos/maria/project/pulls/2/commits": [],
317 + "repos/maria/project/issues/2/reactions": [],
318 + "repos/maria/project/pulls/2/reviews/8/comments": [
319 + {
320 + ...comment,
321 + id: 38,
322 + body: "inline",
323 + path: "file.ts",
324 + position: 1,
325 + original_position: 1,
326 + commit_id: "head",
327 + original_commit_id: "head",
328 + resolver: null,
329 + },
330 + ],
331 + "repos/maria/project/issues/comments/12/reactions": [{ content: "+1", user }],
332 + "repos/maria/project/issues/comments/37/reactions": [{ content: "heart", user }],
333 + "repos/maria/project/issues/comments/38/reactions": [
334 + { content: "rocket", user: { login: "reviewer" } },
335 + ],
336 + };
337 + const writes: ForgejoCli.ForgejoApiInput[] = [];
338 + let reactionReads = 0;
339 + return Effect.gen(function* () {
340 + const provider = yield* ForgejoPullRequestProvider.make;
341 + const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 2 };
342 + const activity = yield* provider.getChangeRequestActivity(input);
343 + assert.deepStrictEqual(
344 + activity.comments.map((entry) => ({
345 + id: entry.id,
346 + kind: entry.kind,
347 + reactions: entry.reactions,
348 + })),
349 + [
350 + {
351 + id: "12",
352 + kind: "issue-comment",
353 + reactions: [{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true }],
354 + },
355 + {
356 + id: "review:8",
357 + kind: "review",
358 + reactions: [{ content: "heart", count: 1, actors: [], viewerHasReacted: true }],
359 + },
360 + {
361 + id: "38",
362 + kind: "review-comment",
363 + reactions: [
364 + { content: "rocket", count: 1, actors: ["reviewer"], viewerHasReacted: false },
365 + ],
366 + },
367 + ],
368 + );
369 + const inlineComment = activity.comments[2];
370 + assert.ok(inlineComment);
371 + assert.deepStrictEqual(activity.reviewThreads[0]?.comments, [inlineComment]);
372 + for (const reacted of [true, false]) {
373 + yield* provider.setReaction({ ...input, subjectId: "review:8", content: "heart", reacted });
374 + yield* provider.setReaction({ ...input, subjectId: "38", content: "rocket", reacted });
375 + }
376 + assert.deepStrictEqual(
377 + writes.map(({ path, method, body }) => ({ path, method, body })),
378 + [
379 + {
380 + path: "repos/maria/project/issues/comments/37/reactions",
381 + method: "POST",
382 + body: { content: "heart" },
383 + },
384 + {
385 + path: "repos/maria/project/issues/comments/38/reactions",
386 + method: "POST",
387 + body: { content: "rocket" },
388 + },
389 + {
390 + path: "repos/maria/project/issues/comments/37/reactions",
391 + method: "DELETE",
392 + body: { content: "heart" },
393 + },
394 + {
395 + path: "repos/maria/project/issues/comments/38/reactions",
396 + method: "DELETE",
397 + body: { content: "rocket" },
398 + },
399 + ],
400 + );
401 + const missing = yield* provider
402 + .setReaction({ ...input, subjectId: "review:9", content: "heart", reacted: true })
403 + .pipe(Effect.result);
404 + assert.strictEqual(missing._tag, "Failure");
405 + if (missing._tag === "Failure") assert.include(missing.failure.detail, "comment ID");
406 + assert.strictEqual(writes.length, 4);
407 + responses["repos/maria/project/pulls/2/reviews/8/comments"] = Array.from(
408 + { length: 501 },
409 + (_, index) => ({
410 + ...comment,
411 + id: 1000 + index,
412 + path: "file.ts",
413 + position: 1,
414 + original_position: 1,
415 + commit_id: "head",
416 + original_commit_id: "head",
417 + resolver: null,
418 + }),
419 + );
420 + for (let index = 0; index < 500; index++) {
421 + responses[`repos/maria/project/issues/comments/${1000 + index}/reactions`] = [];
422 + }
423 + reactionReads = 0;
424 + const bounded = yield* provider.getChangeRequestActivity(input);
425 + assert.strictEqual(bounded.reviewThreads.length, 500);
426 + assert.strictEqual(
427 + bounded.comments.filter((entry) => entry.kind === "review-comment").length,
428 + 500,
429 + );
430 + assert.strictEqual(bounded.commentsTruncated, true);
431 + assert.strictEqual(reactionReads, 502);
432 + }).pipe(
433 + Effect.provide(
434 + Layer.mock(ForgejoCli.ForgejoCli)({
435 + api: (input) => {
436 + if (input.method) {
437 + writes.push(input);
438 + return Effect.succeed(processOutput("{}"));
439 + }
440 + const path = input.path.split("?")[0]!;
441 + if (/\/issues\/comments\/\d+\/reactions$/.test(path)) reactionReads++;
442 + assert.ok(Object.hasOwn(responses, path), `Unexpected Forgejo request: ${path}`);
443 + const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
444 + return encodeJsonEffect(page > 1 ? [] : responses[path]).pipe(
445 + Effect.orDie,
446 + Effect.map(processOutput),
447 + );
448 + },
449 + }),
450 + ),
451 + );
452 + },
453 +);
454 +
455 +it.effect("discovers Forgejo accounts and retains the server port", () =>
456 + Effect.gen(function* () {
457 + const auth = ForgejoSourceControlProvider.discovery.parseAuth(
458 + processOutput(
459 + yield* encodeJsonEffect([
460 + {
461 + name: "work",
462 + url: "http://forgejo.local:3000",
463 + ssh_host: "git.forgejo.local",
464 + user: "maria",
465 + default: "true",
466 + valid: "true",
467 + },
468 + ]),
469 + ),
470 + );
471 + assert.deepStrictEqual(
472 + firstNonEmptyLine("\u001b[1mtea version 0.16.0\u001b[0m\n"),
473 + Option.some("tea version 0.16.0"),
474 + );
475 + assert.strictEqual(auth.status, "authenticated");
476 + assert.deepStrictEqual(auth.account, Option.some("maria"));
477 + assert.deepStrictEqual(auth.host, Option.some("forgejo.local:3000"));
478 + const revoked = ForgejoSourceControlProvider.discovery.parseAuth(
479 + processOutput(
480 + encodeJson([
481 + {
482 + name: "work",
483 + url: "http://forgejo.local:3000",
484 + user: "maria",
485 + default: "true",
486 + valid: "false",
487 + },
488 + ]),
489 + ),
490 + );
491 + assert.strictEqual(revoked.status, "unauthenticated");
492 + const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
493 + cwd: "/repo",
494 + context: {
495 + provider: {
496 + kind: "unknown",
497 + name: "git.forgejo.local",
498 + baseUrl: "https://git.forgejo.local",
499 + },
500 + remoteName: "origin",
501 + remoteUrl: "git@git.forgejo.local:maria/project.git",
502 + },
503 + auth: processOutput(
504 + yield* encodeJsonEffect([
505 + {
506 + name: "work",
507 + url: "http://forgejo.local:3000",
508 + ssh_host: "git.forgejo.local",
509 + user: "maria",
510 + default: "true",
511 + },
512 + ]),
513 + ),
514 + });
515 + assert.deepStrictEqual(refined, {
516 + kind: "forgejo",
517 + name: "Forgejo / Gitea",
518 + baseUrl: "http://forgejo.local:3000",
519 + });
520 + }),
521 +);
522 +
523 +it.effect("does not choose a default Forgejo login across ambiguous SSH server ports", () =>
524 + Effect.gen(function* () {
525 + const logins = ForgejoCli.parseForgejoLogins(
526 + yield* encodeJsonEffect([
527 + {
528 + name: "one",
529 + url: "http://forgejo.local:3000",
530 + ssh_host: "forgejo.local",
531 + user: "maria",
532 + default: "true",
533 + },
534 + {
535 + name: "two",
536 + url: "http://forgejo.local:4000",
537 + ssh_host: "forgejo.local",
538 + user: "maria",
539 + default: "false",
540 + },
541 + ]),
542 + );
543 + const remote = ForgejoCli.parseForgejoRemote("git@forgejo.local:maria/project.git");
544 + assert.isNotNull(remote);
545 + assert.deepStrictEqual(
546 + ForgejoCli.parseForgejoRemote("forgejo.local:maria/project.git"),
547 + remote,
548 + );
549 + assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!));
550 + assert.strictEqual(
551 + ForgejoCli.matchForgejoLogin(logins, remote!, "forgejo.local:4000")?.name,
552 + "two",
553 + );
554 + assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!, "other.local:4000"));
555 + const alias = ForgejoCli.parseForgejoRemote("git@ssh.forgejo.local:maria/project.git");
556 + assert.isNotNull(alias);
557 + assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, alias!, "forgejo.local:4000"));
558 + const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
559 + cwd: "/repo",
560 + context: {
561 + provider: { kind: "unknown", name: "Forgejo", baseUrl: "https://forgejo.local" },
562 + remoteName: "origin",
563 + remoteUrl: "git@forgejo.local:maria/project.git",
564 + requestedHost: "forgejo.local:4000",
565 + },
566 + auth: processOutput(yield* encodeJsonEffect(logins)),
567 + });
568 + assert.strictEqual(refined?.baseUrl, "http://forgejo.local:4000");
569 + const https = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000/maria/project.git");
570 + assert.isNotNull(https);
571 + assert.strictEqual(ForgejoCli.matchForgejoLogin(logins, https!)?.name, "two");
572 + const hostOnly = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000");
573 + assert.strictEqual(
574 + ForgejoCli.matchForgejoLogin(logins, hostOnly!, undefined, true)?.name,
575 + "two",
576 + );
577 + const mounted = logins.map((login) => ({
578 + ...login,
579 + url: `http://forgejo.local:4000/${login.name}`,
580 + }));
581 + assert.isUndefined(ForgejoCli.matchForgejoLogin(mounted, hostOnly!, undefined, true));
582 + }),
583 +);
584 +
585 +it.effect("rejects HTTP failures even when tea exits successfully", () =>
586 + Effect.gen(function* () {
587 + const cli = yield* ForgejoCli.make;
588 + const result = yield* cli
589 + .api({
590 + cwd: "/repo",
591 + repository: "http://forgejo.local:3000/maria/project",
592 + path: "repos/maria/project/pulls/42",
593 + method: "PATCH",
594 + body: { state: "closed" },
595 + })
596 + .pipe(Effect.result);
597 + assert.strictEqual(result._tag, "Failure");
598 + if (result._tag === "Failure")
599 + assert.strictEqual(
600 + result.failure.detail,
601 + "Forgejo repository or pull request was not found.",
602 + );
603 + }).pipe(
604 + Effect.provideService(
605 + FileSystem.FileSystem,
606 + FileSystem.makeNoop({
607 + exists: () => Effect.succeed(false),
608 + }),
609 + ),
610 + Effect.provideService(
611 + HttpClient.HttpClient,
612 + HttpClient.make(() => {
613 + throw new Error("tea must handle its own HTTP request");
614 + }),
615 + ),
616 + Effect.provide(
617 + TestSourceControlHost.layer({
618 + process: {
619 + run: (input) => {
620 + if (input.args[0] === "api") {
621 + assert.strictEqual(input.stdin, '{"state":"closed"}');
622 + assert.include(input.args, "work");
623 + assert.include(
624 + input.args,
625 + "http://forgejo.local:3000/api/v1/repos/maria/project/pulls/42",
626 + );
627 + }
628 + return Effect.succeed(
629 + input.args[0] === "login"
630 + ? processOutput(
631 + encodeJson([
632 + {
633 + name: "work",
634 + url: "http://forgejo.local:3000",
635 + ssh_host: "forgejo.local",
636 + user: "maria",
637 + default: "true",
638 + },
639 + ]),
640 + )
641 + : processOutput('{"message":"not found"}', { stderr: "HTTP/1.1 404 Not Found\n" }),
642 + );
643 + },
644 + },
645 + }),
646 + ),
647 + ),
648 +);
649 +
650 +it.effect("routes mounted Forgejo repositories without repeating the mount in API paths", () =>
651 + Effect.gen(function* () {
652 + const cli = yield* ForgejoCli.make;
653 + const viewer = yield* cli.api({ cwd: "/upstream-only", host: "code.test", path: "user" });
654 + assert.strictEqual(viewer.stdout, "[]");
655 + const mountedRepository = yield* cli.resolveRepository({
656 + cwd: "/upstream-only",
657 + host: "code.test",
658 + repository: "maria/project",
659 + });
660 + assert.strictEqual(mountedRepository.baseUrl, "https://code.test/forgejo");
661 + assert.strictEqual(mountedRepository.repository, "maria/project");
662 + for (const path of [
663 + "repos/forgejo/maria/project/pulls?state=open",
664 + "repos/forgejo/maria/project",
665 + "repos/reviewer/project/contents/file.ts",
666 + ]) {
667 + const result = yield* cli.api({
668 + cwd: "/repo",
669 + repository: "forgejo/maria/project",
670 + context: {
671 + provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://code.test/forgejo" },
672 + remoteName: "origin",
673 + remoteUrl: "https://code.test/forgejo/maria/project.git",
674 + },
675 + path,
676 + });
677 + assert.strictEqual(result.stdout, "[]");
678 + }
679 + const sameOwnerAsMount = yield* cli.resolveRepository({
680 + cwd: "/repo",
681 + repository: "forgejo/project",
682 + context: {
683 + provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://code.test/forgejo" },
684 + remoteName: "origin",
685 + remoteUrl: "ssh://git@code.test/forgejo/project.git",
686 + },
687 + });
688 + assert.strictEqual(sameOwnerAsMount.command, "tea");
689 + assert.strictEqual(sameOwnerAsMount.repository, "forgejo/project");
690 + }).pipe(
691 + Effect.provideService(
692 + FileSystem.FileSystem,
693 + FileSystem.makeNoop({
694 + exists: () => Effect.succeed(true),
695 + readFileString: () =>
696 + Effect.succeed(
697 + encodeJson({
698 + hosts: { "code.test/forgejo": { type: "Application", token: "test-token" } },
699 + }),
700 + ),
701 + }),
702 + ),
703 + Effect.provideService(
704 + HttpClient.HttpClient,
705 + HttpClient.make(() => {
706 + throw new Error("tea must handle its own HTTP request");
707 + }),
708 + ),
709 + Effect.provide(
710 + TestSourceControlHost.layer({
711 + process: {
712 + run: (input) => {
713 + if (input.command === "git")
714 + return Effect.succeed(
715 + processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
716 + );
717 + if (input.args[0] === "login")
718 + return Effect.succeed(
719 + processOutput(
720 + encodeJson([
721 + {
722 + name: "mounted",
723 + url: "https://code.test/forgejo",
724 + ssh_host: "code.test",
725 + user: "maria",
726 + default: "true",
727 + },
728 + ]),
729 + ),
730 + );
731 + const supported = [
732 + "https://code.test/forgejo/api/v1/user",
733 + "https://code.test/forgejo/api/v1/repos/maria/project/pulls?state=open",
734 + "https://code.test/forgejo/api/v1/repos/maria/project",
735 + "https://code.test/forgejo/api/v1/repos/reviewer/project/contents/file.ts",
736 + ];
737 + if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
738 + assert.strictEqual(input.command, "tea");
739 + return Effect.succeed(
740 + supported.includes(input.args.at(-1) ?? "")
741 + ? processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" })
742 + : processOutput("{}", { stderr: "HTTP/1.1 404 Not Found\n" }),
743 + );
744 + },
745 + },
746 + }),
747 + ),
748 + ),
749 +);
750 +
751 +it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {
752 + const commands: string[] = [];
753 + const requests: string[] = [];
754 + return Effect.gen(function* () {
755 + const cli = yield* ForgejoCli.make;
756 + for (const remoteUrl of [
757 + "http://forgejo.local:3000/maria/project.git",
758 + "ssh://git@ssh.forgejo.local:2222/maria/project.git",
759 + "ssh://git@forgejo.local:2222/maria/project.git",
760 + ]) {
761 + const result = yield* cli.api({
762 + cwd: "/repo",
763 + repository: "maria/project",
764 + context: {
765 + provider: {
766 + kind: "forgejo",
767 + name: "Forgejo",
768 + baseUrl: "http://forgejo.local:3000",
769 + },
770 + remoteName: "origin",
771 + remoteUrl,
772 + requestedHost: "forgejo.local:3000",
773 + },
774 + path: "repos/maria/project/issues/42/comments",
775 + method: "POST",
776 + body: { body: "verified through fj" },
777 + });
778 + assert.strictEqual(result.stdout, '{"id":99}');
779 + }
780 + assert.deepStrictEqual(commands, ["fj"]);
781 + assert.deepStrictEqual(requests, [
782 + "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
783 + "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
784 + "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
785 + ]);
786 + const viewer = yield* cli.api({
787 + cwd: "/no-remotes",
788 + host: "forgejo.local:3000",
789 + path: "user",
790 + });
791 + assert.strictEqual(viewer.stdout, '{"login":"maria"}');
792 + assert.strictEqual(requests.at(-1), "https://forgejo.local:3000/api/v1/user");
793 + const upstreamViewer = yield* cli.api({
794 + cwd: "/upstream-only",
795 + host: "forgejo.local:3000",
796 + path: "user",
797 + });
798 + assert.strictEqual(upstreamViewer.stdout, '{"login":"maria"}');
799 + assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
800 + const upstreamRepository = yield* cli.resolveRepository({
801 + cwd: "/upstream-only",
802 + host: "forgejo.local:3000",
803 + repository: "maria/project",
804 + });
805 + assert.strictEqual(upstreamRepository.baseUrl, "http://forgejo.local:3000");
806 + assert.strictEqual(upstreamRepository.repository, "maria/project");
807 + const httpViewer = yield* cli.api({ cwd: "/repo", host: "forgejo.local:3000", path: "user" });
808 + assert.strictEqual(httpViewer.stdout, '{"login":"maria"}');
809 + assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
810 + }).pipe(
811 + Effect.provideService(
812 + FileSystem.FileSystem,
813 + FileSystem.makeNoop({
814 + exists: () => Effect.succeed(true),
815 + readFileString: () =>
816 + Effect.succeed(
817 + encodeJson({
818 + hosts: {
819 + "forgejo.local:3000": { type: "Application", token: "test-token" },
820 + "forgejo.local:4000": { type: "Application", token: "other-token" },
821 + },
822 + aliases: { "ssh.forgejo.local:2222": "forgejo.local:3000" },
823 + }),
824 + ),
825 + }),
826 + ),
827 + Effect.provideService(
828 + HttpClient.HttpClient,
829 + HttpClient.make((request) => {
830 + requests.push(request.url);
831 + if (request.url.endsWith("/user")) {
832 + assert.strictEqual(request.method, "GET");
833 + assert.strictEqual(request.headers.authorization, "token test-token");
834 + return Effect.succeed(
835 + HttpClientResponse.fromWeb(request, new Response('{"login":"maria"}')),
836 + );
837 + }
838 + assert.strictEqual(request.method, "POST");
839 + assert.strictEqual(request.headers.authorization, "token test-token");
840 + assert.strictEqual(request.body._tag, "Uint8Array");
841 + if (request.body._tag === "Uint8Array")
842 + assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(request.body.body)), {
843 + body: "verified through fj",
844 + });
845 + return Effect.succeed(
846 + HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),
847 + );
848 + }),
849 + ),
850 + Effect.provide(
851 + TestSourceControlHost.layer({
852 + process: {
853 + run: (input) => {
854 + commands.push(input.command);
855 + if (input.command === "git")
856 + return Effect.succeed(
857 + input.cwd === "/no-remotes"
858 + ? processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) })
859 + : processOutput(
860 + `${input.cwd === "/upstream-only" ? "upstream" : "origin"}\thttp://forgejo.local:3000/maria/project.git (fetch)\nother\thttp://forgejo.local:3000/maria/other.git (fetch)\nunrelated\thttp://other.local:3000/maria/project.git (fetch)`,
861 + ),
862 + );
863 + assert.strictEqual(input.command, "fj");
864 + assert.deepStrictEqual(input.args, [
865 + "--host",
866 + input.cwd === "/no-remotes"
867 + ? "https://forgejo.local:3000"
868 + : "http://forgejo.local:3000",
869 + "whoami",
870 + ]);
871 + return Effect.succeed(processOutput(""));
872 + },
873 + },
874 + }),
875 + ),
876 + );
877 +});
878 +
879 +it.effect("loads later fj review pages when the server caps pages below the requested size", () => {
880 + const pages: number[] = [];
881 + let issueCommentRequests = 0;
882 + return Effect.gen(function* () {
883 + const cli = yield* ForgejoCli.make;
884 + const provider = yield* ForgejoPullRequestProvider.make.pipe(
885 + Effect.provideService(ForgejoCli.ForgejoCli, cli),
886 + );
887 + const activity = yield* provider.getChangeRequestActivity({
888 + cwd: "/repo",
889 + repository: "maria/project",
890 + host: "forgejo.test",
891 + number: 42,
892 + });
893 + assert.strictEqual(activity.commentCount, 42);
894 + assert.strictEqual(activity.comments.at(-1)?.id, "review:41");
895 + assert.strictEqual(activity.commentsTruncated, false);
896 + assert.deepStrictEqual(pages, [1, 2, 3]);
897 + assert.strictEqual(issueCommentRequests, 1);
898 + }).pipe(
899 + Effect.provideService(
900 + FileSystem.FileSystem,
901 + FileSystem.makeNoop({
902 + exists: () => Effect.succeed(true),
903 + readFileString: () =>
904 + Effect.succeed(
905 + encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
906 + ),
907 + }),
908 + ),
909 + Effect.provideService(
910 + HttpClient.HttpClient,
911 + HttpClient.make((request) => {
912 + const url = new URL(request.url);
913 + if (url.pathname === "/api/v1/repos/maria/project/issues/42/comments") {
914 + issueCommentRequests++;
915 + return Effect.succeed(
916 + HttpClientResponse.fromWeb(
917 + request,
918 + new Response(
919 + encodeJson([
920 + {
921 + id: 100,
922 + body: "Unpaginated issue comment",
923 + user: { login: "maria" },
924 + created_at: "2026-09-13T00:00:00Z",
925 + },
926 + ]),
927 + ),
928 + ),
929 + );
930 + }
931 + if (url.pathname.endsWith("/reviews")) {
932 + const page = Number(url.searchParams.get("page"));
933 + pages.push(page);
934 + assert.ok(page >= 1 && page <= 3);
935 + const reviews = Array.from({ length: page < 3 ? 20 : 1 }, (_, index) => ({
936 + id: (page - 1) * 20 + index + 1,
937 + body: "Review from a capped page",
938 + user: { login: "maria" },
939 + state: "COMMENT",
940 + submitted_at: "2026-09-13T00:00:00Z",
941 + comments_count: 0,
942 + }));
943 + return Effect.succeed(
944 + HttpClientResponse.fromWeb(
945 + request,
946 + new Response(encodeJson(reviews), {
947 + headers:
948 + page === 2
949 + ? {}
950 + : {
951 + Link:
952 + page === 1
953 + ? `<${url.origin}${url.pathname}?limit=50&page=2>; rel="next"`
954 + : `<${url.origin}${url.pathname}?limit=50&page=1>; rel="prev"`,
955 + },
956 + }),
957 + ),
958 + );
959 + }
960 + return Effect.succeed(
961 + HttpClientResponse.fromWeb(
962 + request,
963 + new Response(encodeJson(url.pathname === "/api/v1/user" ? { login: "maria" } : [])),
964 + ),
965 + );
966 + }),
967 + ),
968 + Effect.provide(
969 + TestSourceControlHost.layer({
970 + process: {
971 + run: (input) => {
972 + if (input.command === "git") {
973 + assert.deepStrictEqual(input.args, ["remote", "-v"]);
974 + return Effect.succeed(
975 + processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
976 + );
977 + }
978 + assert.strictEqual(input.command, "fj");
979 + assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
980 + return Effect.succeed(processOutput(""));
981 + },
982 + },
983 + }),
984 + ),
985 + );
986 +});
987 +
988 +it.effect("falls back to tea when fj is missing or has no account for this server", () =>
989 + Effect.gen(function* () {
990 + for (const scenario of ["missing-cli", "missing-account", "stale-invalid-storage"] as const) {
991 + const commands: string[] = [];
992 + yield* Effect.gen(function* () {
993 + const cli = yield* ForgejoCli.make;
994 + const result = yield* cli.api({
995 + cwd: "/repo",
996 + repository: "https://forgejo.local:3000/maria/project",
997 + path: "repos/maria/project/pulls",
998 + });
999 + assert.strictEqual(result.stdout, "[]");
1000 + assert.deepStrictEqual(
1001 + commands,
1002 + scenario === "missing-account" ? ["tea", "tea"] : ["fj", "tea", "tea"],
1003 + );
1004 + const viewer = yield* cli.api({
1005 + cwd: "/upstream-only",
1006 + host: "forgejo.local:3000",
1007 + path: "user",
1008 + });
1009 + assert.strictEqual(viewer.stdout, "[]");
1010 + }).pipe(
1011 + Effect.provideService(
1012 + FileSystem.FileSystem,
1013 + FileSystem.makeNoop({
1014 + exists: () => Effect.succeed(true),
1015 + readFileString: () =>
1016 + Effect.succeed(
1017 + scenario === "stale-invalid-storage"
1018 + ? "invalid json"
1019 + : encodeJson({
1020 + hosts: {
1021 + [scenario === "missing-cli" ? "forgejo.local:3000" : "other.local"]: {
1022 + type: "Application",
1023 + token: "test-token",
1024 + },
1025 + },
1026 + }),
1027 + ),
1028 + }),
1029 + ),
1030 + Effect.provideService(
1031 + HttpClient.HttpClient,
1032 + HttpClient.make(() => {
1033 + throw new Error("tea must handle its own HTTP request");
1034 + }),
1035 + ),
1036 + Effect.provide(
1037 + TestSourceControlHost.layer({
1038 + process: {
1039 + run: (input) => {
1040 + commands.push(input.command);
1041 + if (input.command === "git")
1042 + return Effect.succeed(
1043 + processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
1044 + );
1045 + if (input.command === "fj")
1046 + return Effect.fail(
1047 + new VcsProcessSpawnError({
1048 + operation: input.operation,
1049 + command: input.command,
1050 + cwd: input.cwd,
1051 + cause: new Error("fj not found"),
1052 + }),
1053 + );
1054 + assert.strictEqual(input.command, "tea");
1055 + if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
1056 + return Effect.succeed(
1057 + input.args[0] === "login"
1058 + ? processOutput(
1059 + encodeJson([
1060 + {
1061 + name: "work",
1062 + url: "https://forgejo.local:3000",
1063 + user: "maria",
1064 + default: "true",
1065 + valid: "true",
1066 + },
1067 + ]),
1068 + )
1069 + : processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" }),
1070 + );
1071 + },
1072 + },
1073 + }),
1074 + ),
1075 + );
1076 + }
1077 + }),
1078 +);
1079 +
1080 +it.effect("handles fj mutation statuses without retrying failures or reading absent bodies", () =>
1081 + Effect.gen(function* () {
1082 + for (const status of [204, 205, 302, 401, 403, 404, 429, 500]) {
1083 + let writes = 0;
1084 + yield* Effect.gen(function* () {
1085 + const cli = yield* ForgejoCli.make;
1086 + const result = yield* cli
1087 + .api({
1088 + cwd: "/repo",
1089 + repository: "https://forgejo.local/maria/project",
1090 + path: "repos/maria/project/issues/42/comments",
1091 + method: "POST",
1092 + body: { body: "only once" },
1093 + })
1094 + .pipe(Effect.result);
1095 + assert.strictEqual(result._tag, status < 300 ? "Success" : "Failure");
1096 + if (result._tag === "Success") assert.strictEqual(result.success.stdout, "");
1097 + if (result._tag === "Failure") {
1098 + assert.strictEqual(result.failure.command, "fj");
1099 + assert.strictEqual(result.failure.httpStatus, status);
1100 + }
1101 + assert.strictEqual(writes, 1);
1102 + }).pipe(
1103 + Effect.provideService(
1104 + FileSystem.FileSystem,
1105 + FileSystem.makeNoop({
1106 + exists: () => Effect.succeed(true),
1107 + readFileString: () =>
1108 + Effect.succeed(
1109 + encodeJson({
1110 + hosts: {
1111 + "forgejo.local": { type: "Application", token: "test-token" },
1112 + },
1113 + }),
1114 + ),
1115 + }),
1116 + ),
1117 + Effect.provideService(
1118 + HttpClient.HttpClient,
1119 + HttpClient.make((request) => {
1120 + writes++;
1121 + assert.strictEqual(
1122 + request.url,
1123 + "https://forgejo.local/api/v1/repos/maria/project/issues/42/comments",
1124 + );
1125 + return Effect.succeed(
1126 + HttpClientResponse.fromWeb(
1127 + request,
1128 + new Response(status < 300 ? null : "", {
1129 + status,
1130 + headers: { location: "https://other.local/" },
1131 + }),
1132 + ),
1133 + );
1134 + }),
1135 + ),
1136 + Effect.provide(
1137 + TestSourceControlHost.layer({
1138 + process: {
1139 + run: (input) => {
1140 + assert.strictEqual(
1141 + input.command,
1142 + "fj",
1143 + "a failed mutation must never switch accounts or CLI",
1144 + );
1145 + return Effect.succeed(processOutput(""));
1146 + },
1147 + },
1148 + }),
1149 + ),
1150 + );
1151 + }
1152 + }),
1153 +);
1154 +
1155 +it.effect(
1156 + "discovers fj first and retains configured authentication failures instead of switching accounts",
1157 + () =>
1158 + Effect.gen(function* () {
1159 + for (const scenario of ["authenticated", "revoked", "missing", "invalid-storage"] as const) {
1160 + const commands: string[] = [];
1161 + yield* Effect.gen(function* () {
1162 + const spec = yield* ForgejoSourceControlProvider.makeDiscovery;
1163 + assert.strictEqual(spec.type, "managed-cli");
1164 + if (spec.type !== "managed-cli") return;
1165 + const result = yield* spec.probe("/repo");
1166 + assert.strictEqual(result.executable, scenario === "missing" ? "tea" : "fj");
1167 + assert.strictEqual(
1168 + result.auth.status,
1169 + scenario === "revoked"
1170 + ? "unauthenticated"
1171 + : scenario === "invalid-storage"
1172 + ? "unknown"
1173 + : "authenticated",
1174 + );
1175 + if (scenario !== "revoked" && scenario !== "invalid-storage")
1176 + assert.deepStrictEqual(result.auth.host, Option.some("forgejo.local:3000"));
1177 + assert.deepStrictEqual(
1178 + result.auth.account,
1179 + scenario === "authenticated" || scenario === "missing"
1180 + ? Option.some("maria")
1181 + : Option.none(),
1182 + );
1183 + assert.strictEqual(
1184 + commands.some((command) => command.startsWith("tea ")),
1185 + scenario === "missing",
1186 + );
1187 + assert.include(commands, "fj version");
1188 + }).pipe(
1189 + Effect.provide(
1190 + Layer.mergeAll(
1191 + Layer.mock(ForgejoCli.ForgejoCli)({
1192 + getAccount: (input) => {
1193 + assert.strictEqual(scenario, "authenticated");
1194 + assert.deepStrictEqual(input, {
1195 + cwd: "/repo",
1196 + baseUrl: "http://forgejo.local:3000",
1197 + });
1198 + return Effect.succeed("maria");
1199 + },
1200 + listLogins: (input) => {
1201 + assert.strictEqual(
1202 + input.remoteUrl,
1203 + "http://forgejo.local:3000/maria/project.git",
1204 + );
1205 + if (scenario === "invalid-storage")
1206 + return Effect.fail(
1207 + new ForgejoCli.ForgejoCliError({
1208 + command: "fj",
1209 + cwd: input.cwd,
1210 + reason: "authentication",
1211 + detail: "fj authentication storage is invalid.",
1212 + }),
1213 + );
1214 + return Effect.succeed([
1215 + {
1216 + name: "forgejo.local:3000",
1217 + url: "http://forgejo.local:3000",
1218 + user: "",
1219 + default: "false",
1220 + },
1221 + ]);
1222 + },
1223 + }),
1224 + TestSourceControlHost.layer({
1225 + process: {
1226 + run: (input) => {
1227 + commands.push(`${input.command} ${input.args.join(" ")}`);
1228 + if (input.command === "git")
1229 + return Effect.succeed(
1230 + processOutput("http://forgejo.local:3000/maria/project.git\n"),
1231 + );
1232 + if (input.command === "fj") {
1233 + if (scenario === "missing")
1234 + return Effect.fail(
1235 + new VcsProcessSpawnError({
1236 + operation: input.operation,
1237 + command: input.command,
1238 + cwd: input.cwd,
1239 + cause: new Error("fj not found"),
1240 + }),
1241 + );
1242 + if (input.args[0] === "version")
1243 + return Effect.succeed(processOutput("fj 0.10.0"));
1244 + if (scenario === "invalid-storage") {
1245 + assert.deepStrictEqual(input.args, ["auth", "list"]);
1246 + return Effect.succeed(processOutput(""));
1247 + }
1248 + assert.deepStrictEqual(input.args, [
1249 + "--host",
1250 + "http://forgejo.local:3000",
1251 + "whoami",
1252 + ]);
1253 + return Effect.succeed(
1254 + processOutput("", {
1255 + exitCode: ChildProcessSpawner.ExitCode(scenario === "revoked" ? 1 : 0),
1256 + }),
1257 + );
1258 + }
1259 + assert.strictEqual(input.command, "tea");
1260 + return Effect.succeed(
1261 + input.args[0] === "--version"
1262 + ? processOutput("tea version 0.16.0")
1263 + : processOutput(
1264 + encodeJson([
1265 + {
1266 + name: "work",
1267 + url: "http://forgejo.local:3000",
1268 + user: "maria",
1269 + default: "true",
1270 + valid: "true",
1271 + },
1272 + ]),
1273 + ),
1274 + );
1275 + },
1276 + },
1277 + }),
1278 + ),
1279 + ),
1280 + );
1281 + }
1282 + }),
1283 +);
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts renamed
+3 -3
@@ -3,7 +3,7 @@ import * as FileSystem from "effect/FileSystem";
3 import * as Schema from "effect/Schema";
4 import * as Result from "effect/Result";
5 import { SourceControlProviderError } from "@t3tools/contracts";
6 -import * as VcsProcess from "../vcs/VcsProcess.ts";
6 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
7 import * as ForgejoCli from "./ForgejoCli.ts";
8 import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
9 import {
@@ -55,7 +55,7 @@ export const discovery = {
55
56 export const makeDiscovery = Effect.gen(function* () {
57 const cli = yield* ForgejoCli.ForgejoCli;
58 - const process = yield* VcsProcess.VcsProcess;
58 + const { process } = yield* SourceControlHost.SourceControlHost;
59 const listLogins = cli.listLogins;
60 if (!listLogins) return discovery;
61 return {
@@ -175,7 +175,7 @@ const repositoryPath = (repository: string) =>
175 export const make = Effect.gen(function* () {
176 const cli = yield* ForgejoCli.ForgejoCli;
177 const fs = yield* FileSystem.FileSystem;
178 - const process = yield* VcsProcess.VcsProcess;
178 + const { process } = yield* SourceControlHost.SourceControlHost;
179 const request = <S extends Schema.Codec<unknown, unknown, never, never>>(
180 input: ForgejoCli.ForgejoApiInput,
181 schema: S,
packages/source-control-forgejo/src/server/driver.ts new
+20
@@ -0,0 +1,20 @@
1 +/**
2 + * The Forgejo / Gitea driver: repository operations, discovery, and pull requests through
3 + * `fj` or `tea`.
4 + *
5 + * @module source-control-forgejo/server/driver
6 + */
7 +import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
8 +import * as Effect from "effect/Effect";
9 +
10 +import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
11 +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
12 +
13 +export const driver = defineSourceControlDriver({
14 + kind: "forgejo",
15 + make: Effect.all({
16 + sourceControl: ForgejoSourceControlProvider.make,
17 + discovery: ForgejoSourceControlProvider.makeDiscovery,
18 + pullRequests: ForgejoPullRequestProvider.make,
19 + }),
20 +});
packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts renamed
packages/source-control-forgejo/src/server/forgejoPullRequests.ts renamed
packages/source-control-forgejo/tsconfig.json new
+7
@@ -0,0 +1,7 @@
1 +{
2 + "extends": "../../tsconfig.base.json",
3 + "compilerOptions": {
4 + "types": ["node"]
5 + },
6 + "include": ["src"]
7 +}
packages/source-control-testing/package.json new
+22
@@ -0,0 +1,22 @@
1 +{
2 + "name": "@t3tools/source-control-testing",
3 + "private": true,
4 + "type": "module",
5 + "exports": {
6 + "./TestSourceControlHost": {
7 + "types": "./src/TestSourceControlHost.ts",
8 + "import": "./src/TestSourceControlHost.ts"
9 + }
10 + },
11 + "scripts": {
12 + "typecheck": "tsc --noEmit"
13 + },
14 + "dependencies": {
15 + "@t3tools/contracts": "workspace:*",
16 + "@t3tools/source-control-core": "workspace:*",
17 + "effect": "catalog:"
18 + },
19 + "devDependencies": {
20 + "@types/node": "catalog:"
21 + }
22 +}
packages/source-control-testing/src/TestSourceControlHost.ts new
+47
@@ -0,0 +1,47 @@
1 +/**
2 + * A `SourceControlHost.SourceControlHost` for provider tests. Settings are fixed unless the test
3 + * supplies its own, and every process run goes to the test's `run`, which fails by default so an
4 + * unexpected CLI call is visible.
5 + *
6 + * @module source-control-testing/TestSourceControlHost
7 + */
8 +import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
9 +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
10 +import * as Effect from "effect/Effect";
11 +import * as Layer from "effect/Layer";
12 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13 +
14 +export interface TestSourceControlHostOptions {
15 + readonly settings?: ServerSettings;
16 + readonly process?: Partial<SourceControlHost.SourceControlHost["Service"]["process"]>;
17 +}
18 +
19 +export const layer = (
20 + options: TestSourceControlHostOptions = {},
21 +): Layer.Layer<SourceControlHost.SourceControlHost> =>
22 + Layer.succeed(
23 + SourceControlHost.SourceControlHost,
24 + SourceControlHost.SourceControlHost.of({
25 + settings: { get: Effect.succeed(options.settings ?? DEFAULT_SERVER_SETTINGS) },
26 + process: {
27 + run:
28 + options.process?.run ??
29 + ((input) => Effect.die(`Unexpected ${input.command} run in ${input.operation}.`)),
30 + },
31 + }),
32 + );
33 +
34 +/** A successful run's output, for tests that script CLI responses. */
35 +export const processOutput = (
36 + stdout: string,
37 + options?: {
38 + readonly stderr?: string;
39 + readonly exitCode?: ChildProcessSpawner.ExitCode;
40 + },
41 +): SourceControlHost.SourceControlProcessOutput => ({
42 + exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
43 + stdout,
44 + stderr: options?.stderr ?? "",
45 + stdoutTruncated: false,
46 + stderrTruncated: false,
47 +});
packages/source-control-testing/tsconfig.json new
+7
@@ -0,0 +1,7 @@
1 +{
2 + "extends": "../../tsconfig.base.json",
3 + "compilerOptions": {
4 + "types": ["node"]
5 + },
6 + "include": ["src"]
7 +}
pnpm-lock.yaml
+53
@@ -651,6 +651,9 @@ importers:
651 '@t3tools/source-control-core':
652 specifier: workspace:*
653 version: link:../../packages/source-control-core
654 + '@t3tools/source-control-forgejo':
655 + specifier: workspace:*
656 + version: link:../../packages/source-control-forgejo
657 diff:
658 specifier: 8.0.3
659 version: 8.0.3
@@ -1518,6 +1521,9 @@ importers:
1521 '@t3tools/contracts':
1522 specifier: workspace:*
1523 version: link:../contracts
1524 + '@t3tools/shared':
1525 + specifier: workspace:*
1526 + version: link:../shared
1527 effect:
1528 specifier: 4.0.2
1529 version: 4.0.2(patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688)
@@ -1532,6 +1538,53 @@ importers:
1538 specifier: 1.0.0
1539 version: 1.0.0(@types/node@24.12.4)(@vitest/ui@5.0.1(vitest@5.0.1))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(msw@2.12.11(@types/node@24.12.4)(typescript@7.0.2))(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
1540
1541 + packages/source-control-forgejo:
1542 + dependencies:
1543 + '@t3tools/contracts':
1544 + specifier: workspace:*
1545 + version: link:../contracts
1546 + '@t3tools/provider-core':
1547 + specifier: workspace:*
1548 + version: link:../provider-core
1549 + '@t3tools/shared':
1550 + specifier: workspace:*
1551 + version: link:../shared
1552 + '@t3tools/source-control-core':
1553 + specifier: workspace:*
1554 + version: link:../source-control-core
1555 + effect:
1556 + specifier: 4.0.2
1557 + version: 4.0.2(patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688)
1558 + devDependencies:
1559 + '@effect/vitest':
1560 + specifier: 4.0.2
1561 + version: 4.0.2(patch_hash=595b7d26fb635caba9c3d39fcb189bb78a000192f8d3b60ead7174b310d1ade9)(@types/node@24.12.4)(@vitest/ui@5.0.1)(bufferutil@4.1.0)(effect@4.0.2(patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(msw@2.12.11(@types/node@24.12.4)(typescript@7.0.2))(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
1562 + '@t3tools/source-control-testing':
1563 + specifier: workspace:*
1564 + version: link:../source-control-testing
1565 + '@types/node':
1566 + specifier: 24.12.4
1567 + version: 24.12.4
1568 + vite-plus:
1569 + specifier: 1.0.0
1570 + version: 1.0.0(@types/node@24.12.4)(@vitest/ui@5.0.1(vitest@5.0.1))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(msw@2.12.11(@types/node@24.12.4)(typescript@7.0.2))(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
1571 +
1572 + packages/source-control-testing:
1573 + dependencies:
1574 + '@t3tools/contracts':
1575 + specifier: workspace:*
1576 + version: link:../contracts
1577 + '@t3tools/source-control-core':
1578 + specifier: workspace:*
1579 + version: link:../source-control-core
1580 + effect:
1581 + specifier: 4.0.2
1582 + version: 4.0.2(patch_hash=ec61ee307eaec3e17f757e0e6a16296ea4b7a8c3188df0c6ec5e66301fd78688)
1583 + devDependencies:
1584 + '@types/node':
1585 + specifier: 24.12.4
1586 + version: 24.12.4
1587 +
1588 packages/ssh:
1589 dependencies:
1590 '@t3tools/contracts':
scripts/release-smoke.ts
+2
@@ -38,6 +38,8 @@ const workspaceFiles = [
38 "packages/provider-muse/package.json",
39 "packages/provider-opencode/package.json",
40 "packages/source-control-core/package.json",
41 + "packages/source-control-forgejo/package.json",
42 + "packages/source-control-testing/package.json",
43 "packages/effect-acp/package.json",
44 "packages/effect-codex-app-server/package.json",
45 "scripts/package.json",