TypeScript
feat(source-control): support Forgejo and Gitea with fj and tea (#11436)
maria6fd68f5c3e7c
diff --git a/apps/mobile/src/components/SourceControlIcon.tsx b/apps/mobile/src/components/SourceControlIcon.tsxindex 3b371c021ad..873f3729a8a 100644--- a/apps/mobile/src/components/SourceControlIcon.tsx+++ b/apps/mobile/src/components/SourceControlIcon.tsx@@ -1,9 +1,9 @@-import Svg, { Defs, LinearGradient, Path, Stop } from "react-native-svg";+import Svg, { Circle, Defs, G, LinearGradient, Path, Stop } from "react-native-svg";import { withUniwind } from "uniwind";const ThemedSvg = withUniwind(Svg);-export type SourceControlIconKind = "github" | "gitlab" | "bitbucket" | "azure-devops";+export type SourceControlIconKind = "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops";export function SourceControlIcon(props: {readonly kind: SourceControlIconKind;@@ -14,6 +14,19 @@ export function SourceControlIcon(props: {const size = props.size ?? 18;switch (props.kind) {+ case "forgejo":+ // Official two-color mark from https://forgejo.org/favicon.svg.+ return (+ <Svg width={size} height={size} viewBox="0 0 212 212">+ <G transform="translate(6 6)" fill="none">+ <Path d="M58 168 v-98 a50 50 0 0 1 50-50 h20" stroke="#ff6600" strokeWidth={25} />+ <Path d="M58 168 v-30 a50 50 0 0 1 50-50 h20" stroke="#d40000" strokeWidth={25} />+ <Circle cx={142} cy={20} r={18} stroke="#ff6600" strokeWidth={15} />+ <Circle cx={142} cy={88} r={18} stroke="#d40000" strokeWidth={15} />+ <Circle cx={58} cy={180} r={18} stroke="#d40000" strokeWidth={15} />+ </G>+ </Svg>+ );case "github":return (<ThemedSvgdiff --git a/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx b/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsxindex cdf52022a44..17700e6599c 100644--- a/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx+++ b/apps/mobile/src/features/projects/AddProjectRepositoryRoute.tsx@@ -17,6 +17,7 @@ export function AddProjectRepositoryRoute({const title =source === "github" ||source === "gitlab" ||+ source === "forgejo" ||source === "bitbucket" ||source === "azure-devops"? addProjectRemoteSourceLabel(source)diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsxindex cc1e8f4e579..5231228829d 100644--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx@@ -110,6 +110,7 @@ function sourceFromParam(value: string | string[] | undefined): AddProjectRemotesource === "url" ||source === "github" ||source === "gitlab" ||+ source === "forgejo" ||source === "bitbucket" ||source === "azure-devops") {diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.tsindex 999a0c20221..cab5020d742 100644--- a/apps/server/src/git/GitManager.test.ts+++ b/apps/server/src/git/GitManager.test.ts@@ -37,6 +37,10 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as VcsProcess from "../vcs/VcsProcess.ts";import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";import * as GitLabSourceControlProvider from "../sourceControl/GitLabSourceControlProvider.ts";+import {+ ForgejoPullRequestSchema,+ toForgejoChangeRequest,+} from "../sourceControl/forgejoPullRequests.ts";import type { SourceControlProvider } from "../sourceControl/SourceControlProvider.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";import * as ServerConfig from "../config.ts";@@ -46,6 +50,7 @@ import * as ServerSettings from "../serverSettings.ts";import * as GitManager from "./GitManager.ts";const encodeCliJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));+const decodeForgejoPullRequest = Schema.decodeEffect(ForgejoPullRequestSchema);interface FakeGhScenario {prListSequence?: string[];@@ -3851,6 +3856,69 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {20_000,);+ it.effect("matches mounted Forgejo heads without confusing forks sharing a branch", () =>+ Effect.gen(function* () {+ for (const owner of ["maria", "reviewer"]) {+ const mapped = toForgejoChangeRequest(+ yield* decodeForgejoPullRequest({+ number: 42,+ title: "Greeting",+ html_url: "https://forgejo.example/forgejo/maria/project/pulls/42",+ state: "open",+ merged: false,+ base: {+ ref: "main",+ sha: "base",+ repo: { full_name: "maria/project", owner: { login: "maria" } },+ },+ head: {+ ref: "greeting",+ sha: "head",+ repo: { full_name: `${owner}/project`, owner: { login: owner } },+ },+ }),+ );+ const pr = {+ ...mapped,+ isDraft: mapped.isDraft ?? false,+ closedAt: mapped.closedAt ?? null,+ mergedAt: mapped.mergedAt ?? null,+ };+ const repository = GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(+ `https://forgejo.example/forgejo/${owner}/project.git`,+ "forgejo",+ );+ expect(repository).toBe(`${owner}/project`);+ const context = {+ headBranch: "greeting",+ headRepositoryNameWithOwner: repository,+ headRepositoryOwnerLogin: repository?.split("/")[0] ?? null,+ isCrossRepository: owner !== "maria",+ };+ expect(GitManager.matchesBranchHeadContext(pr, context)).toBe(true);+ expect(+ GitManager.matchesBranchHeadContext(pr, {+ ...context,+ headRepositoryNameWithOwner: "other/project",+ headRepositoryOwnerLogin: "other",+ }),+ ).toBe(false);+ }+ expect(+ GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(+ "[email protected]:maria/project.git",+ "forgejo",+ ),+ ).toBe("maria/project");+ expect(+ GitManager.parseRepositoryNameWithOwnerFromRemoteUrl(+ "https://gitlab.example/group/maria/project.git",+ "gitlab",+ ),+ ).toBe("group/maria/project");+ }),+ );+it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () =>Effect.sync(() => {const headContext = {diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.tsindex 1a14fb5be5b..33f041fb6cd 100644--- a/apps/server/src/git/GitManager.ts+++ b/apps/server/src/git/GitManager.ts@@ -277,7 +277,10 @@ function resolvePullRequestWorktreeLocalBranchName(return `t3code/pr-${pullRequest.number}/${suffix}`;}-function parseRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {+export function parseRepositoryNameWithOwnerFromRemoteUrl(+ url: string | null,+ providerKind?: ChangeRequest["provider"],+): string | null {const trimmed = url?.trim() ?? "";if (trimmed.length === 0) {return null;@@ -288,6 +291,12 @@ function parseRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string |trimmed,);const repositoryNameWithOwner = match?.[1]?.trim() ?? "";+ // Forgejo HTTP paths can include an installation mount; its API always names owner/repo.+ if (providerKind === "forgejo" && /^https?:\/\//iu.test(trimmed)) {+ return repositoryNameWithOwner.length > 0+ ? repositoryNameWithOwner.split("/").slice(-2).join("/")+ : null;+ }return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;}@@ -1291,7 +1300,15 @@ export const make = Effect.gen(function* () {(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??(yield* readConfigValueNullable(cwd, "remote.origin.url"));- return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;+ const provider = remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;+ if (!remoteUrl || provider?.kind !== "unknown") return provider;+ const handle = yield* sourceControlProviders+ .resolveHandle({+ cwd,+ context: { provider, remoteName: preferredRemoteName, remoteUrl },+ })+ .pipe(Effect.orElseSucceed(() => null));+ return handle?.context?.provider ?? provider;});const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (@@ -1307,7 +1324,22 @@ export const make = Effect.gen(function* () {}const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);- const repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);+ let repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);+ if (+ remoteUrl !== null &&+ /^https?:\/\//iu.test(remoteUrl) &&+ (repositoryNameWithOwner?.split("/").length ?? 0) > 2+ ) {+ const detected = detectSourceControlProviderFromGitRemoteUrl(remoteUrl);+ const kind =+ detected?.kind === "unknown"+ ? yield* sourceControlProvider(cwd).pipe(+ Effect.map((provider) => provider.kind),+ Effect.orElseSucceed(() => undefined),+ )+ : detected?.kind;+ repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl, kind);+ }return {remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,repositoryNameWithOwner,diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.tsindex 18062a216bb..70da749edea 100644--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts@@ -265,6 +265,40 @@ describe("pull request toolkit handlers", () => {}),);+ it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () =>+ Effect.gen(function* () {+ const harness = yield* makeHarness({+ project: makeProject({+ canonicalKey: "forge.example/git/owner/repo",+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: "http://forge.example:3000/git/owner/repo.git",+ },+ provider: "forgejo",+ displayName: "git/owner/repo",+ }),+ });+ const result = yield* harness.call("link_pull_request", {+ repository: "git/owner/repo",+ number: 42,+ });+ expect(result).toEqual({+ host: "forge.example:3000",+ repository: "git/owner/repo",+ number: 42,+ url: "http://forge.example:3000/git/owner/repo/pulls/42",+ alreadyLinked: false,+ });+ const other = yield* harness.call("link_pull_request", {+ host: "other.example",+ repository: "owner/repo",+ number: 42,+ });+ expect(other.url).toBe("https://other.example/owner/repo/pull/42");+ }),+ );+it.effect("rejects a target that names neither a URL nor repository and number", () =>Effect.gen(function* () {const harness = yield* makeHarness();@@ -334,6 +368,18 @@ describe("pull request toolkit handlers", () => {}),);+ it("reports an older Forgejo link's HTTP port when listing thread links", () => {+ const result = listThreadPullRequests(+ makeThread([+ makeLink(42, {+ host: "forge.example",+ url: "http://forge.example:3000/t3tools/t3code/pulls/42",+ }),+ ]),+ );+ expect(result.pullRequests[0]?.host).toBe("forge.example:3000");+ });+it.effect("fails cleanly when the token's thread no longer exists", () =>Effect.gen(function* () {const harness = yield* makeHarness({ thread: null });diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.tsindex 1106bf43532..80cd49257fb 100644--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts@@ -9,6 +9,7 @@ import {} from "@t3tools/contracts";import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";import {+ normalizeThreadPullRequestKey,resolveThreadPullRequestChains,threadPullRequestKeyOf,visibleThreadPullRequests,@@ -71,7 +72,7 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (if (parsed === null) {return yield* new PullRequestUrlInvalidError({});}- return { ...parsed, url: input.url } satisfies ResolvedTarget;+ return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget;}if (input.repository === undefined || input.number === undefined) {return yield* new PullRequestTargetIncompleteError({});@@ -89,8 +90,12 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* (host,repository,input.number,+ project?.repositoryIdentity?.locator.remoteUrl,) ?? `https://${host}/${repository}/pull/${input.number}`;- return { host, repository, number: input.number, url } satisfies ResolvedTarget;+ return {+ ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }),+ url,+ } satisfies ResolvedTarget;});function entryOf(@@ -108,7 +113,7 @@ function entryOf(}}return {- host: link.host,+ host: normalizeThreadPullRequestKey(link).host,repository: link.repository,number: link.number,url: link.url,diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex a038a566216..21c95142929 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -889,6 +889,39 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-pullassert.deepEqual(yield* readLinks(), []);assert.deepEqual(yield* readThreadUpdatedAt(), [{ updatedAt: "2026-01-01T00:00:05.000Z" }]);+ // Older Forgejo rows stored a portless host; unlink by their URL's authority.+ yield* eventStore.append({+ ...base("2026-01-01T00:00:05.100Z"),+ type: "thread.pull-request-linked",+ payload: {+ threadId,+ link: {+ host: "forge.example",+ repository: "team/repo",+ number: 42,+ url: "http://forge.example:3000/team/repo/pulls/42",+ source: "agent",+ linkedAt: "2026-01-01T00:00:05.100Z",+ snapshot: null,+ stack: null,+ },+ updatedAt: "2026-01-01T00:00:05.100Z",+ },+ });+ yield* eventStore.append({+ ...base("2026-01-01T00:00:05.200Z"),+ type: "thread.pull-request-unlinked",+ payload: {+ threadId,+ host: "forge.example:3000",+ repository: "team/repo",+ number: 42,+ updatedAt: "2026-01-01T00:00:05.200Z",+ },+ });+ yield* projectionPipeline.bootstrap;+ assert.deepEqual(yield* readLinks(), []);+// Deleting the thread clears whatever links it still had.yield* eventStore.append({...base("2026-01-01T00:00:06.000Z"),diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex bbd0aa5ddaa..7e1710a760e 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -880,12 +880,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectiif (Option.isNone(existingRow)) {return;}- yield* projectionThreadPullRequestRepository.delete({+ const links = yield* projectionThreadPullRequestRepository.listByThreadId({threadId: event.payload.threadId,- host: event.payload.host.toLowerCase(),- repository: event.payload.repository.toLowerCase(),- number: event.payload.number,});+ const link = links.find((candidate) =>+ threadPullRequestKeysEqual(candidate, event.payload),+ );+ if (link !== undefined) {+ yield* projectionThreadPullRequestRepository.delete({+ threadId: event.payload.threadId,+ host: link.host,+ repository: link.repository,+ number: link.number,+ });+ }yield* projectionThreadRepository.upsert({...existingRow.value,updatedAt: event.payload.updatedAt,diff --git a/apps/server/src/orchestration/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration/PullRequestSyncReactor.test.tsindex 414f76f3249..4a5b450ea69 100644--- a/apps/server/src/orchestration/PullRequestSyncReactor.test.ts+++ b/apps/server/src/orchestration/PullRequestSyncReactor.test.ts@@ -420,6 +420,31 @@ describe("PullRequestSyncReactor", () => {),);+ it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([+ makeThread("one", {+ pullRequests: [+ makeLink(42, null, {+ host: "forge.example",+ url: "http://forge.example:3000/owner/repository/pulls/42",+ }),+ ],+ }),+ ]),+ summary: (input) => Effect.succeed(makeSummary(input)),+ });+ yield* Effect.gen(function* () {+ yield* startAndSweep(fixture);+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");+ assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );+it.effect("dispatches nothing when the host snapshot is unchanged", () =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/orchestration/PullRequestSyncReactor.ts b/apps/server/src/orchestration/PullRequestSyncReactor.tsindex 0a39fa5d91d..388eab34be4 100644--- a/apps/server/src/orchestration/PullRequestSyncReactor.ts+++ b/apps/server/src/orchestration/PullRequestSyncReactor.ts@@ -11,6 +11,7 @@ import {import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";import {threadPullRequestKeyOf,+ normalizeThreadPullRequestKey,threadPullRequestKeysEqual,visibleThreadPullRequests,} from "@t3tools/shared/threadPullRequests";@@ -191,7 +192,7 @@ export const make = Effect.gen(function* () {type: "thread.pull-request-link.sync",commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),threadId: thread.id,- host: link.host,+ host: normalizeThreadPullRequestKey(link).host,repository: link.repository,number: link.number,snapshot: { ...fields, syncedAt: nowIso },@@ -200,7 +201,11 @@ export const make = Effect.gen(function* () {}if (fetchedStack === null || fetchedStack.stack === null) return;for (const layer of fetchedStack.stack.layers) {- const layerKey = { host: link.host, repository: link.repository, number: layer.number };+ const layerKey = {+ host: normalizeThreadPullRequestKey(link).host,+ repository: link.repository,+ number: layer.number,+ };const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;if (linkedThisSweep.has(dedupeKey)) continue;// Tombstones count as present: a dismissed layer is never re-added.@@ -240,7 +245,7 @@ export const make = Effect.gen(function* () {const first = entries[0]!;const ref = {projectId: first.thread.projectId,- host: first.link.host,+ host: normalizeThreadPullRequestKey(first.link).host,repository: first.link.repository,number: first.link.number,};diff --git a/apps/server/src/orchestration/decider.pullRequests.test.ts b/apps/server/src/orchestration/decider.pullRequests.test.tsindex 49bfd4bea4d..b79ca01a8de 100644--- a/apps/server/src/orchestration/decider.pullRequests.test.ts+++ b/apps/server/src/orchestration/decider.pullRequests.test.ts@@ -115,6 +115,49 @@ const snapshot: ThreadPullRequestSnapshot = {};it.layer(NodeServices.layer)("pull request link decider", (it) => {+ it.effect("links the same Forgejo number on two ports and unlinks an older portless record", () =>+ Effect.gen(function* () {+ const existing = makeLink({+ host: "forge.example",+ url: "http://forge.example:3000/t3tools/t3code/pulls/42",+ });+ let model = makeReadModel([existing]);+ const command = yield* decodeCommand({+ type: "thread.pull-request.link",+ commandId: "link-other-port",+ threadId: THREAD_ID,+ host: "forge.example",+ repository: "t3tools/t3code",+ number: 42,+ url: "http://forge.example:4000/t3tools/t3code/pulls/42",+ source: "manual",+ });+ const linked = expectSingleEvent(+ yield* decideOrchestrationCommand({ readModel: model, command }),+ "thread.pull-request-linked",+ );+ expect(linked.payload.link.host).toBe("forge.example:4000");+ model = yield* projectEvent(model, { ...linked, sequence: 1 });+ expect(model.threads[0]!.pullRequests).toHaveLength(2);+ const unlink = yield* decodeCommand({+ type: "thread.pull-request.unlink",+ commandId: "unlink-old-port",+ threadId: THREAD_ID,+ host: "forge.example:3000",+ repository: "t3tools/t3code",+ number: 42,+ });+ const unlinked = expectSingleEvent(+ yield* decideOrchestrationCommand({ readModel: model, command: unlink }),+ "thread.pull-request-unlinked",+ );+ model = yield* projectEvent(model, { ...unlinked, sequence: 2 });+ expect(model.threads[0]!.pullRequests.map((link) => link.url)).toEqual([+ linked.payload.link.url,+ ]);+ }),+ );+it.effect("legacy unlink cannot remove a newer cross-host link", () =>Effect.gen(function* () {const own = makeLink();diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.tsindex ac1cbfb44d0..d6ddb0b9263 100644--- a/apps/server/src/project/RepositoryIdentityResolver.test.ts+++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts@@ -1,6 +1,7 @@// @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not.import * as NodeFS from "node:fs";import * as NodeServices from "@effect/platform-node/NodeServices";+import { SourceControlProviderError } from "@t3tools/contracts";import { expect, it } from "@effect/vitest";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -41,6 +42,9 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {it.effect("refreshes the Git root only when requested", () => {const calls: Array<ReadonlyArray<string>> = [];let rootPath = "/repo";+ let remoteUrl = "[email protected]:T3Tools/t3code.git";+ let refinements = 0;+ let refinementFails = false;const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {run: (input) =>Effect.sync(() => {@@ -48,7 +52,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {return {stdout: input.args.includes("rev-parse")? `${rootPath}\n`- : "origin\[email protected]:T3Tools/t3code.git (fetch)\n",+ : `origin\t${remoteUrl} (fetch)\n`,stderr: "",code: ChildProcessSpawner.ExitCode(0),timedOut: false,@@ -61,7 +65,29 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {});const resolverLayer = Layer.effect(RepositoryIdentityResolver.RepositoryIdentityResolver,- RepositoryIdentityResolver.make(),+ RepositoryIdentityResolver.make({+ refine: (identity) => {+ refinements++;+ if (refinementFails)+ return Effect.fail(+ new SourceControlProviderError({+ provider: "forgejo",+ operation: "detectProvider",+ cwd: rootPath,+ detail: "account unavailable",+ }),+ );+ return Effect.succeed(+ identity.canonicalKey.startsWith("ssh.forge.test/")+ ? {+ ...identity,+ provider: "forgejo",+ webUrl: "http://forge.test:3000/git/team/repo",+ }+ : identity,+ );+ },+ }),).pipe(Layer.provide(processRunner));return Effect.gen(function* () {@@ -72,6 +98,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {expect(first?.canonicalKey).toBe("github.com/t3tools/t3code");expect(second).toEqual(first);+ expect(refinements).toBe(1);expect(calls).toEqual([["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],["-C", "/repo", "remote", "-v"],@@ -84,6 +111,18 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],["-C", "/repo/packages/web", "remote", "-v"],]);+ remoteUrl = "[email protected]:team/repo.git";+ const forgejo = yield* resolver.resolve(rootPath, { refresh: true });+ expect(forgejo?.webUrl).toBe("http://forge.test:3000/git/team/repo");+ expect(forgejo?.provider).toBe("forgejo");+ expect(forgejo?.canonicalKey).toBe("ssh.forge.test/team/repo");+ expect(forgejo?.locator.remoteUrl).toBe(remoteUrl);+ expect(yield* resolver.resolve(rootPath)).toEqual(forgejo);+ expect(refinements).toBe(3);+ refinementFails = true;+ const unavailable = yield* resolver.resolve(rootPath, { refresh: true });+ expect(unavailable?.webUrl).toBeUndefined();+ expect(unavailable?.canonicalKey).toBe("ssh.forge.test/team/repo");}).pipe(Effect.provide(resolverLayer));});diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.tsindex 755008f6ded..88ecb4186f6 100644--- a/apps/server/src/project/RepositoryIdentityResolver.ts+++ b/apps/server/src/project/RepositoryIdentityResolver.ts@@ -1,4 +1,4 @@-import type { RepositoryIdentity } from "@t3tools/contracts";+import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";import {detectSourceControlProviderFromGitRemoteUrl,normalizeGitRemoteUrl,@@ -20,6 +20,9 @@ export interface RepositoryIdentityResolverOptions {readonly cacheCapacity?: number;readonly positiveCacheTtl?: Duration.Input;readonly negativeCacheTtl?: Duration.Input;+ readonly refine?: (+ identity: RepositoryIdentity,+ ) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;}export class RepositoryIdentityResolver extends Context.Service<@@ -158,6 +161,11 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ((cacheKey) =>resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(Effect.provideService(ProcessRunner.ProcessRunner, processRunner),+ Effect.flatMap((identity) =>+ identity !== null && options.refine+ ? options.refine(identity).pipe(Effect.catch(() => Effect.succeed(identity)))+ : Effect.succeed(identity),+ ),),{capacity: cacheCapacity,diff --git a/apps/server/src/pullRequest/ForgejoPullRequestProvider.ts b/apps/server/src/pullRequest/ForgejoPullRequestProvider.tsnew file mode 100644index 00000000000..526be38f7df--- /dev/null+++ b/apps/server/src/pullRequest/ForgejoPullRequestProvider.ts@@ -0,0 +1,584 @@+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";+import * as Result from "effect/Result";+import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";+import { decodeJsonResult } from "@t3tools/shared/schemaJson";+import { ForgejoCli, type ForgejoApiInput } from "../sourceControl/ForgejoCli.ts";+import {+ PullRequestProviderError,+ type ProviderChangeRequestDetail,+ type ProviderRepositoryRef,+ type PullRequestProviderApi,+} from "./PullRequestProvider.ts";+import {+ ForgejoPullRequest,+ ForgejoRepository,+ ForgejoUser,+ ForgejoComment,+ ForgejoReview,+ ForgejoReviewComment,+ ForgejoCommit,+ ForgejoStatus,+ ForgejoLabel,+ ForgejoReaction,+ FORGEJO_REACTIONS,+ forgejoChangeRequest,+ forgejoActor,+ forgejoComment,+ forgejoReview,+ forgejoReviewThread,+ forgejoCommit,+ forgejoChecks,+ forgejoReactions,+} from "./forgejoPullRequestJson.ts";++const CAPABILITIES: PullRequestCapabilities = {+ diff: true,+ comment: true,+ actions: ["merge", "close", "reopen", "update-branch"],+ mergeMethods: ["merge", "squash", "rebase"],+ updateMethods: ["merge", "rebase"],+ search: false,+ reactions: true,+ labels: true,+ // Forgejo's public API has no thread replies/resolution or draft conversion endpoint.+ review: {+ inlineComment: true,+ reply: false,+ resolve: false,+ verdicts: ["comment", "approve", "request-changes"],+ },+ reviewers: { request: true, listCandidates: true },+ edit: { changeRequest: true, comment: true },+};+const repoPath = (input: ProviderRepositoryRef) =>+ `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;+const pullPath = (input: ProviderRepositoryRef & { readonly number: number }) =>+ `${repoPath(input)}/pulls/${input.number}`;+const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =>+ `${repoPath(input)}/issues/${input.number}`;+// Review IDs differ from the issue-comment IDs used by Forgejo's reactions API.+const reviewCommentId = (review: typeof ForgejoReview.Type) =>+ /#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];++export const make = Effect.gen(function* () {+ const cli = yield* ForgejoCli;+ const failure = (operation: string, detail: string, cause?: unknown) =>+ new PullRequestProviderError({+ provider: "forgejo",+ operation,+ reason: "failed",+ detail,+ ...(cause === undefined ? {} : { cause }),+ });+ const request = (input: ForgejoApiInput) =>+ cli.api(input).pipe(+ Effect.mapError(+ (error) =>+ new PullRequestProviderError({+ provider: "forgejo",+ operation: input.path,+ detail: error.detail,+ cause: error,+ reason:+ error.reason === "missing-cli"+ ? "missing-tool"+ : error.reason === "authentication"+ ? "unauthenticated"+ : error.reason === "rate-limit"+ ? "rate-limited"+ : "failed",+ }),+ ),+ );+ const read = Effect.fn("ForgejoPullRequestProvider.read")(function* <A>(+ input: ForgejoApiInput,+ schema: Schema.Codec<A, unknown, never, never>,+ ) {+ const result = yield* request(input);+ if (result.stdoutTruncated)+ return yield* failure(input.path, "Forgejo response exceeded the output limit.");+ const decoded = decodeJsonResult(schema)(result.stdout);+ return Result.isSuccess(decoded)+ ? decoded.success+ : yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);+ });+ const readArray = <A>(input: ForgejoApiInput, schema: Schema.Codec<A, unknown, never, never>) =>+ read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? []));+ const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>(+ input: ForgejoApiInput,+ schema: Schema.Codec<A, unknown, never, never>,+ index: number,+ ) {+ const result = yield* request({+ ...input,+ path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`,+ });+ if (result.stdoutTruncated)+ return yield* failure(input.path, "Forgejo response exceeded the output limit.");+ const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);+ if (Result.isFailure(decoded))+ return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);+ const rows = decoded.success ?? [];+ const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];+ return {+ rows,+ more: rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links)),+ };+ });+ // Use a stable, small page size that also works with Forgejo's default maximum of 50.+ const page = Effect.fn("ForgejoPullRequestProvider.page")(function* <A>(+ input: ForgejoApiInput,+ schema: Schema.Codec<A, unknown, never, never>,+ limit = 500,+ ) {+ const items: A[] = [];+ for (let index = 1; items.length < limit; index++) {+ const { rows, more } = yield* readPage(input, schema, index);+ items.push(...rows);+ if (!more) return { items, truncated: false };+ }+ return { items, truncated: true };+ });+ const write = (input: ForgejoApiInput) => request(input).pipe(Effect.asVoid);+ const getPull = (input: ProviderRepositoryRef & { readonly number: number }) =>+ read(+ {+ cwd: input.cwd,+ repository: input.repository,+ host: input.host,+ path: pullPath(input),+ },+ ForgejoPullRequest,+ );+ const getRepo = (input: ProviderRepositoryRef) =>+ read({ ...input, path: repoPath(input) }, ForgejoRepository);+ const getViewer = (input: {+ readonly cwd: string;+ readonly repository?: string;+ readonly host?: string;+ }) => read({ ...input, path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));+ const permissions = (+ repo: typeof ForgejoRepository.Type,+ pr: typeof ForgejoPullRequest.Type,+ viewer: string,+ ): PullRequestViewerPermissions => {+ const canWrite = repo.permissions?.push ?? false;+ const canEdit = canWrite || pr.user?.login === viewer;+ const active = !repo.archived;+ return {+ actions: active+ ? CAPABILITIES.actions.filter((action) =>+ action === "merge" || action === "update-branch" ? canWrite : canEdit,+ )+ : [],+ comment: active && (!pr.is_locked || canWrite),+ resolve: false,+ verdicts: active+ ? pr.user?.login === viewer+ ? ["comment"]+ : CAPABILITIES.review.verdicts+ : [],+ requestReviewers: active && canEdit,+ labels: active && canWrite,+ updateMethods:+ active && canWrite ? (repo.allow_rebase_update ? ["merge", "rebase"] : ["merge"]) : [],+ };+ };+ const getPermissions = Effect.fn("ForgejoPullRequestProvider.getPermissions")(function* (+ input: ProviderRepositoryRef & { readonly number: number },+ ) {+ const [repo, pr, viewer] = yield* Effect.all(+ [getRepo(input), getPull(input), getViewer(input)],+ { concurrency: 3 },+ );+ return permissions(repo, pr, viewer);+ });+ const unsupported = (operation: string) =>+ Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));+ const provider: PullRequestProviderApi = {+ kind: "forgejo",+ capabilities: CAPABILITIES,+ getViewer,+ listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(+ function* (input) {+ const offset = input.cursor?.delivered ?? 0;+ const items: ReturnType<typeof forgejoChangeRequest>[] = [];+ const state = input.state === "merged" ? "closed" : input.state;+ const query = {+ ...input,+ path: `${repoPath(input)}/pulls?state=${state}&sort=recentupdate`,+ };+ // Self-hosted servers may cap pages below 50. Establish their actual page size before+ // translating the service's row offset into an API page number.+ const first = yield* readPage(query, Schema.NullOr(ForgejoPullRequest), 1);+ const pageSize = first.rows.length || 50;+ const firstIndex = Math.floor(offset / pageSize) + 1;+ let consumed = 0;+ let more = true;+ for (let index = firstIndex; more && consumed < input.limit; index++) {+ const result =+ index === 1 ? first : yield* readPage(query, Schema.NullOr(ForgejoPullRequest), index);+ const rows = result.rows;+ const start = index === firstIndex ? offset % pageSize : 0;+ const countBefore = consumed;+ for (const row of rows.slice(start)) {+ if (consumed >= input.limit) break;+ consumed++;+ if (row) items.push(forgejoChangeRequest(row));+ }+ more = result.more || rows.length - start > consumed - countBefore;+ }+ return { items, truncated: more, continues: true, cursorAdvance: consumed };+ },+ ),+ getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),+ getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {+ const [pr, repo, viewer] = yield* Effect.all(+ [getPull(input), getRepo(input), getViewer(input)],+ { concurrency: 3 },+ );+ const statuses = yield* page(+ {+ ...input,+ path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,+ },+ ForgejoStatus,+ );+ return {+ ...forgejoChangeRequest(pr),+ body: pr.body ?? "",+ changedFiles: pr.changed_files ?? 0,+ reviewers: (pr.requested_reviewers ?? []).flatMap((user) => {+ const actor = forgejoActor(user);+ return actor ? [actor] : [];+ }),+ checks: forgejoChecks(statuses.items),+ baseComparison: !pr.merge_base+ ? "unknown"+ : pr.merge_base === pr.base.sha+ ? "up-to-date"+ : "behind",+ viewerPermissions: permissions(repo, pr, viewer),+ mergeCapabilities: {+ merge: repo.allow_merge_commits ?? true,+ squash: repo.allow_squash_merge ?? true,+ rebase: repo.allow_rebase ?? true,+ },+ } satisfies ProviderChangeRequestDetail;+ }),+ getViewerPermissions: getPermissions,+ getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(+ function* (input) {+ const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(+ [+ // Issue comments ignore page/limit; fetch this unpaginated endpoint once.+ readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(+ Effect.map((items) => ({+ items: items.slice(0, 500),+ truncated: items.length > 500,+ })),+ ),+ page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),+ page({ ...input, path: `${pullPath(input)}/commits` }, ForgejoCommit),+ page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),+ getViewer(input),+ ],+ { concurrency: 5 },+ );+ const reviewComments = yield* Effect.forEach(+ reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),+ (review) =>+ readArray(+ { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },+ ForgejoReviewComment,+ ),+ { concurrency: 4 },+ );+ const allInline = reviewComments.flat();+ const inline = allInline.slice(0, 500);+ const entries = [+ ...comments.items.map((comment) => ({+ comment: forgejoComment(comment),+ reactionId: String(comment.id),+ })),+ ...reviews.items+ .filter((review) => review.state !== "PENDING" && review.state !== "REQUEST_REVIEW")+ .map((review) => ({+ comment: forgejoReview(review),+ reactionId: reviewCommentId(review),+ })),+ ...inline.map((comment) => ({+ comment: {+ ...forgejoComment(comment),+ kind: "review-comment" as const,+ path: comment.path,+ },+ reactionId: String(comment.id),+ })),+ ];+ const enriched = yield* Effect.forEach(+ entries,+ ({ comment, reactionId }) =>+ (reactionId === undefined+ ? Effect.succeed([])+ : readArray(+ { ...input, path: `${repoPath(input)}/issues/comments/${reactionId}/reactions` },+ ForgejoReaction,+ )+ ).pipe(+ Effect.map((rows) => ({ ...comment, reactions: forgejoReactions(rows, viewer) })),+ ),+ { concurrency: 4 },+ );+ const byId = new Map(enriched.map((comment) => [comment.id, comment]));+ const timeline = enriched.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));+ return {+ comments: timeline,+ commentCount: timeline.length,+ commentsTruncated:+ comments.truncated || reviews.truncated || allInline.length > inline.length,+ reviewThreads: inline.map((comment) => ({+ ...forgejoReviewThread(comment),+ comments: [byId.get(String(comment.id)) ?? forgejoComment(comment)],+ })),+ commits: commits.items.map(forgejoCommit),+ reactions: forgejoReactions(reactions.items, viewer),+ };+ },+ ),+ getDiff: (input) =>+ request({+ ...input,+ path: input.commit+ ? `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}.diff`+ : `${pullPath(input)}.diff`,+ }).pipe(+ Effect.map((result) => ({+ patch: result.stdout,+ truncated: result.stdoutTruncated,+ nextCursor: null,+ })),+ ),+ getDiffFileContents: Effect.fn("ForgejoPullRequestProvider.getDiffFileContents")(+ function* (input) {+ const pr = yield* getPull(input);+ const commit = input.commit+ ? yield* read(+ {+ ...input,+ path: `${repoPath(input)}/git/commits/${encodeURIComponent(input.commit)}`,+ },+ ForgejoCommit,+ )+ : null;+ const oldRef = commit ? commit.parents[0]?.sha : pr.merge_base || pr.base.sha;+ const newRef = input.commit ?? pr.head.sha;+ const content = (repository: string, ref: string, path: string) =>+ read(+ {+ ...input,+ repository,+ path: `${repoPath({ ...input, repository })}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`,+ },+ Schema.Struct({ content: Schema.String, encoding: Schema.Literal("base64") }),+ ).pipe(Effect.map((file) => Buffer.from(file.content, "base64").toString("utf8")));+ const [oldContents, newContents] = yield* Effect.all(+ [+ input.changeType === "new" || !oldRef+ ? Effect.succeed("")+ : content(input.repository, oldRef, input.oldPath),+ input.changeType === "deleted"+ ? Effect.succeed("")+ : content(pr.head.repo?.full_name ?? input.repository, newRef, input.newPath),+ ],+ { concurrency: 2 },+ );+ return { oldContents, newContents };+ },+ ),+ runAction: (input) => {+ switch (input.action) {+ case "merge":+ return write({+ ...input,+ path: `${pullPath(input)}/merge`,+ method: "POST",+ body: { Do: input.mergeMethod ?? "merge" },+ });+ case "close":+ case "reopen":+ return write({+ ...input,+ path: pullPath(input),+ method: "PATCH",+ body: { state: input.action === "close" ? "closed" : "open" },+ });+ case "update-branch":+ return write({+ ...input,+ path: `${pullPath(input)}/update?style=${input.updateMethod ?? "merge"}`,+ method: "POST",+ });+ default:+ return unsupported(input.action);+ }+ },+ updateChangeRequest: (input) =>+ write({+ ...input,+ path: pullPath(input),+ method: "PATCH",+ body: {+ ...(input.title === undefined ? {} : { title: input.title }),+ ...(input.body === undefined ? {} : { body: input.body }),+ },+ }),+ comment: (input) =>+ write({+ ...input,+ path: `${issuePath(input)}/comments`,+ method: "POST",+ body: { body: input.body },+ }),+ updateComment: (input) =>+ write({+ ...input,+ path: `${repoPath(input)}/issues/comments/${encodeURIComponent(input.commentId)}`,+ method: "PATCH",+ body: { body: input.body },+ }),+ submitReview: Effect.fn("ForgejoPullRequestProvider.submitReview")(function* (input) {+ const pr = yield* getPull(input);+ yield* write({+ ...input,+ path: `${pullPath(input)}/reviews`,+ method: "POST",+ body: {+ event:+ input.verdict === "approve"+ ? "APPROVED"+ : input.verdict === "request-changes"+ ? "REQUEST_CHANGES"+ : "COMMENT",+ body: input.body,+ commit_id: pr.head.sha,+ comments: input.comments.map((comment) => {+ const position = comment.position;+ const old =+ position.kind === "deleted" ||+ (position.kind === "context" && position.side === "left");+ return {+ path: old ? (comment.oldPath ?? comment.path) : comment.path,+ body: comment.body,+ old_position: old ? position.oldLine : 0,+ new_position: old ? 0 : position.newLine,+ };+ }),+ },+ });+ }),+ listReviewerCandidates: Effect.fn("ForgejoPullRequestProvider.listReviewerCandidates")(+ function* (input) {+ const [pr, users] = yield* Effect.all(+ [getPull(input), page({ ...input, path: `${repoPath(input)}/assignees` }, ForgejoUser)],+ { concurrency: 2 },+ );+ return {+ candidates: users.items+ .filter((user) => user.login !== pr.user?.login)+ .flatMap((user) => {+ const actor = forgejoActor(user);+ return actor+ ? [+ {+ ...actor,+ id: user.login,+ kind: "user" as const,+ isRequested:+ pr.requested_reviewers?.some((reviewer) => reviewer.login === user.login) ??+ false,+ },+ ]+ : [];+ }),+ truncated: users.truncated,+ };+ },+ ),+ setReviewerRequest: (input) =>+ write({+ ...input,+ path: `${pullPath(input)}/requested_reviewers`,+ method: input.requested ? "POST" : "DELETE",+ body: { reviewers: input.reviewers.map((reviewer) => reviewer.id) },+ }),+ listLabelCandidates: Effect.fn("ForgejoPullRequestProvider.listLabelCandidates")(+ function* (input) {+ const [pr, labels] = yield* Effect.all(+ [getPull(input), page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel)],+ { concurrency: 2 },+ );+ return {+ candidates: labels.items.map((label) => ({+ name: label.name,+ color: label.color ?? null,+ description: label.description ?? null,+ isApplied: pr.labels?.some((applied) => applied.id === label.id) ?? false,+ })),+ truncated: labels.truncated,+ };+ },+ ),+ setLabels: Effect.fn("ForgejoPullRequestProvider.setLabels")(function* (input) {+ const labels = yield* page({ ...input, path: `${repoPath(input)}/labels` }, ForgejoLabel);+ const selected = labels.items.filter((label) => input.labels.includes(label.name));+ if (selected.length !== input.labels.length)+ return yield* failure("setLabels", "One or more requested labels could not be found.");+ if (input.applied)+ yield* write({+ ...input,+ path: `${issuePath(input)}/labels`,+ method: "POST",+ body: { labels: selected.map((label) => label.id) },+ });+ else+ yield* Effect.forEach(+ selected,+ (label) =>+ write({ ...input, path: `${issuePath(input)}/labels/${label.id}`, method: "DELETE" }),+ { concurrency: 1 },+ );+ }),+ setReaction: Effect.fn("ForgejoPullRequestProvider.setReaction")(function* (input) {+ let commentId = input.subjectId;+ if (commentId?.startsWith("review:")) {+ const reviewId = /^review:([1-9]\d*)$/.exec(commentId)?.[1];+ if (!reviewId) return yield* failure("setReaction", "Invalid Forgejo review ID.");+ const review = yield* read(+ { ...input, path: `${pullPath(input)}/reviews/${reviewId}` },+ ForgejoReview,+ );+ commentId = reviewCommentId(review);+ if (!commentId)+ return yield* failure(+ "setReaction",+ "Forgejo did not return a comment ID for this review.",+ );+ }+ if (commentId && !/^[1-9]\d*$/.test(commentId))+ return yield* failure("setReaction", "Invalid Forgejo comment ID.");+ yield* write({+ ...input,+ path: commentId+ ? `${repoPath(input)}/issues/comments/${commentId}/reactions`+ : `${issuePath(input)}/reactions`,+ method: input.reacted ? "POST" : "DELETE",+ body: { content: FORGEJO_REACTIONS[input.content] },+ });+ }),+ replyToThread: () => unsupported("thread replies"),+ setThreadResolution: () => unsupported("thread resolution"),+ };+ return provider;+});diff --git a/apps/server/src/pullRequest/PullRequestProvider.ts b/apps/server/src/pullRequest/PullRequestProvider.tsindex 2309268bba6..ba8d13908b5 100644--- a/apps/server/src/pullRequest/PullRequestProvider.ts+++ b/apps/server/src/pullRequest/PullRequestProvider.ts@@ -282,6 +282,7 @@ export interface PullRequestProviderApi {/** The signed-in account, which is what involvement filtering compares against. */readonly getViewer: (input: {readonly cwd: string;+ readonly host?: string;}) => Effect.Effect<string, PullRequestProviderError>;readonly listChangeRequests: (diff --git a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts b/apps/server/src/pullRequest/PullRequestProviderRegistry.tsindex f5b4251f7d9..9e8727ed7a7 100644--- a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts+++ b/apps/server/src/pullRequest/PullRequestProviderRegistry.ts@@ -8,6 +8,8 @@ import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";import * as GitHubCli from "../sourceControl/GitHubCli.ts";import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";import * as GitLabCli from "../sourceControl/GitLabCli.ts";+import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";+import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";@@ -48,6 +50,7 @@ export const make = Effect.map(Effect.all([GitHubPullRequestProvider.make,GitLabPullRequestProvider.make,+ ForgejoPullRequestProvider.make,BitbucketPullRequestProvider.make,AzureDevOpsPullRequestProvider.make,]),@@ -62,6 +65,7 @@ export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(),),Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.layer))),+ Layer.provide(ForgejoCli.layer),Layer.provide(BitbucketPullRequestApi.layer.pipe(Layer.provide(BitbucketApi.layer))),Layer.provide(AzureDevOpsPullRequestCli.layer.pipe(Layer.provide(AzureDevOpsCli.layer))),);diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 66257a6c3af..da554ffc400 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -1659,6 +1659,118 @@ it.effect("reads a host-native stack through the provider and null where it has}),);+it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after refinement", () =>+ Effect.gen(function* () {+ for (const provider of ["forgejo", "unknown"] as const) {+ const seen: string[] = [];+ const viewers: Array<string | undefined> = [];+ const service = yield* makeService({+ projects: [+ project({+ id: "ssh",+ title: "ssh",+ workspaceRoot: "/ssh",+ repository: "team/repo",+ provider,+ host: "ssh.code.example",+ remoteUrl: "[email protected]:team/repo.git",+ }),+ ],+ providers: [+ fakeProvider("forgejo", {+ getViewer: (input) => {+ viewers.push(input.host);+ assert.strictEqual(input.host, "code.example:3000");+ return Effect.succeed("bilal");+ },+ listChangeRequests: (input) => {+ assert.strictEqual(input.host, "code.example:3000");+ return Effect.succeed({ items: [], truncated: false, continues: true });+ },+ getChangeRequest: (input) => {+ assert.strictEqual(input.host, "code.example:3000");+ return Effect.succeed({ ...hostedChangeRequest("Forgejo detail"), number: 42 });+ },+ getChangeRequestSummary: (input) =>+ Effect.sync(() => {+ seen.push(input.host);+ return changeRequest(42, "2026-07-02T00:00:00Z");+ }),+ }),+ ],+ resolveHandle: ({ context }) => {+ if (context?.requestedHost === undefined) {+ return Effect.succeed({ context: context!, provider: undefined as never });+ }+ assert.strictEqual(context.requestedHost, "code.example:3000");+ return Effect.succeed({+ context: {+ ...context,+ provider: { kind: "forgejo", name: "Forgejo", baseUrl: "http://code.example:3000" },+ },+ provider: undefined as never,+ });+ },+ });+ yield* service.summary(+ {+ projectId: "ssh" as ProjectId,+ host: "code.example:3000",+ repository: "team/repo",+ number: 42,+ },+ { recoverTransientFailure: false },+ );+ assert.deepStrictEqual(seen, ["code.example:3000"]);+ const listed = yield* service.list({+ projectId: "ssh" as ProjectId,+ host: "code.example:3000",+ state: "open",+ });+ assert.strictEqual(listed.viewers["code.example:3000"], "bilal");+ const detail = yield* service.detail({+ projectId: "ssh" as ProjectId,+ host: "code.example:3000",+ repository: "team/repo",+ number: 42,+ });+ assert.strictEqual(detail.body, "Forgejo detail");+ assert.deepStrictEqual(viewers, ["code.example:3000"]);+ }+ }),+);++it.effect("rejects a different Forgejo HTTP port for an HTTP checkout", () =>+ Effect.gen(function* () {+ const service = yield* makeService({+ projects: [+ project({+ id: "http",+ title: "http",+ workspaceRoot: "/http",+ repository: "team/repo",+ provider: "forgejo",+ host: "code.example",+ remoteUrl: "http://code.example:4000/team/repo.git",+ }),+ ],+ providers: [fakeProvider("forgejo")],+ });+ const failure = yield* service+ .summary(+ {+ projectId: "http" as ProjectId,+ host: "code.example:3000",+ repository: "team/repo",+ number: 42,+ },+ { recoverTransientFailure: false },+ )+ .pipe(Effect.flip);+ assert.strictEqual(failure._tag, "PullRequestUnavailableError");+ }),+);+it.effect("routes a hosted reference to another repository through a project on that host", () =>Effect.gen(function* () {const seen: Array<{ cwd: string; repository: string; host: string }> = [];diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 241a9e8b183..005acfa0f5c 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -1,5 +1,6 @@import {canonicalRepositoryKey,+ isSshRemoteUrl,sourceControlRepositorySelector,} from "@t3tools/shared/sourceControl";import * as Cache from "effect/Cache";@@ -553,14 +554,21 @@ export const make = Effect.gen(function* () {if (filter.projectId !== undefined && project.id !== filter.projectId) continue;const identity = project.repositoryIdentity;if (- identity?.provider !== "unknown" ||+ (identity?.provider !== "unknown" &&+ !(identity?.provider === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))) ||sourceControlRepositorySelector(project.repositoryIdentity) === null)continue;const host = pullRequestHostOf(identity, "unknown");// A legacy identity has no canonical host until its provider is refined, so it must reach// the refinement before a host filter can decide whether it belongs in the result.- if (filter.host !== undefined && host !== "unknown" && host !== filter.host.toLowerCase()) {+ if (+ filter.host !== undefined &&+ host !== "unknown" &&+ host !== filter.host.toLowerCase() &&+ pullRequestHostOf(identity, "forgejo") !== filter.host.toLowerCase() &&+ !isSshRemoteUrl(identity.locator.remoteUrl)+ ) {continue;}const { remoteName, remoteUrl } = identity.locator;@@ -581,20 +589,28 @@ export const make = Effect.gen(function* () {Effect.suspend(() =>sourceControlProviders.resolveHandle({cwd: project.workspaceRoot,- context: { provider, remoteName, remoteUrl },+ context: {+ provider:+ provider.kind === "forgejo" ? { ...provider, kind: "unknown" } : provider,+ remoteName,+ remoteUrl,+ ...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)+ ? { requestedHost: filter.host }+ : {}),+ },}),).pipe(Effect.flatMap((handle) => {- const kind = handle.context?.provider.kind;- return kind === undefined || kind === "unknown"+ const refined = handle.context?.provider;+ return refined === undefined || refined.kind === "unknown"? Effect.fail(undefined)- : Effect.succeed(kind);+ : Effect.succeed(refined);}),),),).pipe(- Effect.map((kind) => [baseUrl, kind] as const),- Effect.orElseSucceed(() => [baseUrl, "unknown"] as const),+ Effect.map((provider) => [baseUrl, provider] as const),+ Effect.orElseSucceed(() => [baseUrl, null] as const),),{ concurrency: REPOSITORY_CONCURRENCY },).pipe(Effect.map((resolved) => new Map(resolved)));@@ -617,10 +633,10 @@ export const make = Effect.gen(function* () {),Effect.flatMap((projects) =>refineUnknownProjectKinds(projects, filter).pipe(- Effect.map((refinedKinds) => ({ refinedKinds, projects })),+ Effect.map((refinedProviders) => ({ refinedProviders, projects })),),),- Effect.map(({ refinedKinds, projects }) => {+ Effect.map(({ refinedProviders, projects }) => {const supported: SupportedProject[] = [];const unimplemented = new Map<string,@@ -638,12 +654,22 @@ export const make = Effect.gen(function* () {// Worktrees of one repository are separate projects; reading the remote once keeps// the page from repeating every change request per local checkout. The host is part// of the key, so the same `owner/repo` on two hosts stays two repositories.- if (kind === "unknown") {+ let refinedProvider: SourceControlProviderInfo | null | undefined;+ if (+ kind === "unknown" ||+ (kind === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))+ ) {const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);- kind = provider === null ? kind : (refinedKinds.get(provider.baseUrl) ?? kind);+ refinedProvider = provider === null ? null : refinedProviders.get(provider.baseUrl);+ kind = refinedProvider?.kind ?? kind;+ }+ const host =+ refinedProvider?.kind === "forgejo"+ ? new URL(refinedProvider.baseUrl).host.toLowerCase()+ : pullRequestHostOf(identity, kind);+ if (filter.host !== undefined && host !== filter.host.toLowerCase()) {+ continue;}- const host = pullRequestHostOf(identity, kind);- if (filter.host !== undefined && host !== filter.host.toLowerCase()) continue;const api = registry.get(kind);// Recorded before the de-duplication below, so the viewer lookup keeps the alternates// the listing is about to drop.@@ -816,7 +842,7 @@ export const make = Effect.gen(function* () {return Effect.die(new Error(`Missing pull request provider: ${kind}`));}const api = withRateLimitBackoff(registered, host, rateLimits);- return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd }))).pipe(+ return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd, host }))).pipe(Effect.map((viewer) => ({host,kind,diff --git a/apps/server/src/pullRequest/forgejoPullRequestJson.ts b/apps/server/src/pullRequest/forgejoPullRequestJson.tsnew file mode 100644index 00000000000..1d0b5c1d4cc--- /dev/null+++ b/apps/server/src/pullRequest/forgejoPullRequestJson.ts@@ -0,0 +1,262 @@+import * as Schema from "effect/Schema";+import * as DateTime from "effect/DateTime";+import * as Option from "effect/Option";+import type {+ PullRequestActor,+ PullRequestCheck,+ PullRequestComment,+ PullRequestCommit,+ PullRequestReaction,+ PullRequestReactionContent,+ PullRequestReviewThread,+} from "@t3tools/contracts";+import type { ProviderChangeRequest } from "./PullRequestProvider.ts";+import { dedupeChecks } from "./pullRequestChecks.ts";++export const ForgejoUser = Schema.Struct({+ login: Schema.String,+ full_name: Schema.optional(Schema.NullOr(Schema.String)),+ avatar_url: Schema.optional(Schema.NullOr(Schema.String)),+});+export const ForgejoLabel = Schema.Struct({+ id: Schema.Int,+ name: Schema.String,+ color: Schema.optional(Schema.NullOr(Schema.String)),+ description: Schema.optional(Schema.NullOr(Schema.String)),+});+export const ForgejoRepository = Schema.Struct({+ full_name: Schema.String,+ permissions: Schema.optional(Schema.Struct({ push: Schema.Boolean, admin: Schema.Boolean })),+ archived: Schema.optional(Schema.Boolean),+ allow_merge_commits: Schema.optional(Schema.Boolean),+ allow_squash_merge: Schema.optional(Schema.Boolean),+ allow_rebase: Schema.optional(Schema.Boolean),+ allow_rebase_update: Schema.optional(Schema.Boolean),+});+const Branch = Schema.Struct({+ ref: Schema.String,+ sha: Schema.String,+ repo: Schema.NullOr(ForgejoRepository),+});+export const ForgejoPullRequest = Schema.Struct({+ number: Schema.Int,+ title: Schema.String,+ body: Schema.NullOr(Schema.String),+ html_url: Schema.String,+ user: Schema.NullOr(ForgejoUser),+ state: Schema.String,+ draft: Schema.optional(Schema.Boolean),+ merged: Schema.Boolean,+ mergeable: Schema.optional(Schema.Boolean),+ is_locked: Schema.optional(Schema.Boolean),+ head: Branch,+ base: Branch,+ merge_base: Schema.optional(Schema.String),+ created_at: Schema.String,+ updated_at: Schema.String,+ closed_at: Schema.NullOr(Schema.String),+ merged_at: Schema.NullOr(Schema.String),+ additions: Schema.optional(Schema.NullOr(Schema.Int)),+ deletions: Schema.optional(Schema.NullOr(Schema.Int)),+ changed_files: Schema.optional(Schema.NullOr(Schema.Int)),+ comments: Schema.optional(Schema.Int),+ labels: Schema.NullOr(Schema.Array(ForgejoLabel)),+ requested_reviewers: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),+});+export const ForgejoComment = Schema.Struct({+ id: Schema.Int,+ body: Schema.String,+ user: Schema.NullOr(ForgejoUser),+ created_at: Schema.String,+ html_url: Schema.optional(Schema.String),+});+export const ForgejoReview = Schema.Struct({+ id: Schema.Int,+ body: Schema.String,+ user: Schema.NullOr(ForgejoUser),+ state: Schema.String,+ submitted_at: Schema.String,+ html_url: Schema.optional(Schema.String),+ comments_count: Schema.Int,+});+export const ForgejoReviewComment = Schema.Struct({+ ...ForgejoComment.fields,+ path: Schema.String,+ position: Schema.Int,+ original_position: Schema.Int,+ commit_id: Schema.String,+ original_commit_id: Schema.String,+ resolver: Schema.NullOr(ForgejoUser),+});+export const ForgejoCommit = Schema.Struct({+ sha: Schema.String,+ author: Schema.NullOr(ForgejoUser),+ commit: Schema.Struct({+ message: Schema.String,+ committer: Schema.Struct({ date: Schema.String }),+ }),+ parents: Schema.Array(Schema.Struct({ sha: Schema.String })),+ stats: Schema.optional(+ Schema.NullOr(Schema.Struct({ additions: Schema.Int, deletions: Schema.Int })),+ ),+});+export const ForgejoStatus = Schema.Struct({+ context: Schema.String,+ status: Schema.String,+ description: Schema.NullOr(Schema.String),+ target_url: Schema.NullOr(Schema.String),+ updated_at: Schema.String,+});+export const ForgejoReaction = Schema.Struct({+ content: Schema.String,+ user: Schema.NullOr(ForgejoUser),+});++export function forgejoActor(+ user: typeof ForgejoUser.Type | null | undefined,+): PullRequestActor | null {+ return user?.login+ ? { login: user.login, name: user.full_name || null, avatarUrl: user.avatar_url || null }+ : null;+}++function toIsoUtc(value: string): string {+ return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso });+}++export function forgejoChangeRequest(pr: typeof ForgejoPullRequest.Type) {+ return {+ number: pr.number,+ title: pr.title,+ url: pr.html_url,+ author: forgejoActor(pr.user),+ headBranch: pr.head.ref,+ baseBranch: pr.base.ref,+ headRepositoryNameWithOwner: pr.head.repo?.full_name ?? null,+ state: pr.merged ? "merged" : pr.state === "closed" ? "closed" : "open",+ isDraft: pr.draft ?? /^(?:\[WIP\]|WIP:)/i.test(pr.title),+ mergeability:+ pr.mergeable === undefined ? "unknown" : pr.mergeable ? "mergeable" : "conflicting",+ additions: pr.additions ?? 0,+ deletions: pr.deletions ?? 0,+ createdAt: toIsoUtc(pr.created_at),+ updatedAt: toIsoUtc(pr.updated_at),+ closedAt: pr.closed_at === null ? null : toIsoUtc(pr.closed_at),+ mergedAt: pr.merged_at === null ? null : toIsoUtc(pr.merged_at),+ reviewRequestLogins: (pr.requested_reviewers ?? []).map((user) => user.login),+ labels: (pr.labels ?? []).map((label) => ({ name: label.name, color: label.color ?? null })),+ } satisfies ProviderChangeRequest;+}++export function forgejoComment(comment: typeof ForgejoComment.Type): PullRequestComment {+ return {+ id: String(comment.id),+ kind: "issue-comment",+ author: forgejoActor(comment.user),+ body: comment.body,+ createdAt: toIsoUtc(comment.created_at),+ url: comment.html_url || null,+ path: null,+ reviewState: null,+ };+}++export function forgejoReview(review: typeof ForgejoReview.Type): PullRequestComment {+ return {+ id: `review:${review.id}`,+ kind: "review",+ author: forgejoActor(review.user),+ body: review.body,+ createdAt: toIsoUtc(review.submitted_at),+ url: review.html_url || null,+ path: null,+ reviewState:+ review.state === "REQUEST_CHANGES"+ ? "CHANGES_REQUESTED"+ : review.state === "COMMENT"+ ? "COMMENTED"+ : review.state,+ };+}++export function forgejoReviewThread(+ comment: typeof ForgejoReviewComment.Type,+): PullRequestReviewThread {+ const oldSide = comment.position === 0 && comment.original_position > 0;+ const line = oldSide ? comment.original_position : comment.position;+ return {+ id: String(comment.id),+ path: comment.path,+ line: line > 0 ? line : null,+ side: oldSide ? "left" : "right",+ isResolved: comment.resolver !== null,+ isOutdated: false,+ comments: [forgejoComment(comment)],+ };+}++export function forgejoCommit(commit: typeof ForgejoCommit.Type): PullRequestCommit {+ const author = forgejoActor(commit.author);+ return {+ oid: commit.sha,+ messageHeadline: commit.commit.message.split("\n")[0] ?? "",+ committedDate: toIsoUtc(commit.commit.committer.date),+ authors: author ? [author] : [],+ ...(commit.stats+ ? { additions: commit.stats.additions, deletions: commit.stats.deletions }+ : {}),+ };+}++export function forgejoChecks(+ statuses: ReadonlyArray<typeof ForgejoStatus.Type>,+): ReadonlyArray<PullRequestCheck> {+ return dedupeChecks(+ statuses.map((status) => ({+ workflowName: null,+ at: status.updated_at,+ check: {+ name: status.context || "check",+ description: status.description || null,+ url: status.target_url || null,+ status:+ status.status === "success"+ ? "success"+ : status.status === "failure" || status.status === "error"+ ? "failure"+ : "pending",+ },+ })),+ );+}++export const FORGEJO_REACTIONS: Record<PullRequestReactionContent, string> = {+ "thumbs-up": "+1",+ "thumbs-down": "-1",+ laugh: "laugh",+ hooray: "hooray",+ confused: "confused",+ heart: "heart",+ rocket: "rocket",+ eyes: "eyes",+};+export function forgejoReactions(+ reactions: ReadonlyArray<typeof ForgejoReaction.Type>,+ viewer: string,+): ReadonlyArray<PullRequestReaction> {+ return Object.entries(FORGEJO_REACTIONS).flatMap(([content, emoji]) => {+ const matching = reactions.filter((reaction) => reaction.content === emoji);+ return matching.length === 0+ ? []+ : [+ {+ content: content as PullRequestReactionContent,+ count: matching.length,+ actors: matching.flatMap((reaction) =>+ reaction.user?.login && reaction.user.login !== viewer ? [reaction.user.login] : [],+ ),+ viewerHasReacted: matching.some((reaction) => reaction.user?.login === viewer),+ },+ ];+ });+}diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.tsindex 08237d0e3ef..a87b33c439e 100644--- a/apps/server/src/pullRequest/linkedThreads.test.ts+++ b/apps/server/src/pullRequest/linkedThreads.test.ts@@ -17,6 +17,22 @@ it.effect(VALUES ('project-1', 'Project', '/tmp/project', '[]', ${createdAt}, ${createdAt})`;const fixtures = [+ {+ id: "forgejo-old",+ host: "forge.example",+ repository: "acme/web",+ number: 7,+ source: "manual",+ url: "http://forge.example:3000/acme/web/pulls/7",+ },+ {+ id: "forgejo-other-port",+ host: "forge.example:4000",+ repository: "acme/web",+ number: 7,+ source: "manual",+ url: "http://forge.example:4000/acme/web/pulls/7",+ },{id: "azure",host: "dev.azure.com",@@ -83,10 +99,24 @@ it.effect(yield* sql`INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at)VALUES (${fixture.id}, ${fixture.host}, ${fixture.repository}, ${fixture.number},- 'https://github.com/acme/web/pull/7', ${fixture.source}, ${createdAt})+ ${fixture.url ?? "https://github.com/acme/web/pull/7"}, ${fixture.source}, ${createdAt})`;}+ expect(+ (yield* listLinkedPullRequestThreads({+ host: "forge.example:3000",+ repository: "acme/web",+ number: 7,+ })).threads.map((thread) => thread.id),+ ).toEqual(["forgejo-old"]);+ expect(+ (yield* listLinkedPullRequestThreads({+ host: "forge.example:4000",+ repository: "acme/web",+ number: 7,+ })).threads.map((thread) => thread.id),+ ).toEqual(["forgejo-other-port"]);expect((yield* listLinkedPullRequestThreads({host: "org.visualstudio.com",diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.tsindex 26c751f0b81..7d6efc939dc 100644--- a/apps/server/src/pullRequest/linkedThreads.ts+++ b/apps/server/src/pullRequest/linkedThreads.ts@@ -1,4 +1,7 @@-import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";+import {+ normalizeThreadPullRequestKey,+ threadPullRequestKeysEqual,+} from "@t3tools/shared/threadPullRequests";import {PullRequestLinkedThreadsResult,PullRequestOperationError,@@ -13,19 +16,32 @@ const decodeLinkedThreads = Schema.decodeUnknownEffect(PullRequestLinkedThreadsRexport const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThreads")(function* (input: ThreadPullRequestKey) {const key = normalizeThreadPullRequestKey(input);+ const hostname = key.host.replace(/:\d+$/u, "");const sql = yield* SqlClient.SqlClient;- const threads = yield* sql`+ const rows = yield* sql<{+ id: string;+ projectId: string;+ title: string;+ archivedAt: string | null;+ host: string;+ repository: string;+ number: number;+ url: string;+ }>`SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,- t.archived_at AS "archivedAt"+ t.archived_at AS "archivedAt", link.host, link.repository, link.number, link.urlFROM projection_thread_pull_requests AS linkJOIN projection_threads AS t ON t.thread_id = link.thread_id- WHERE link.host = ${key.host.toLowerCase()}+ WHERE (link.host = ${key.host} OR link.host = ${hostname})AND link.repository = ${key.repository.toLowerCase()}AND link.number = ${key.number}AND link.source != 'stack-dismissed'AND t.deleted_at IS NULLORDER BY t.updated_at DESC, t.thread_id ASC`;+ const threads = rows+ .filter((row) => threadPullRequestKeysEqual(row, key))+ .map(({ id, projectId, title, archivedAt }) => ({ id, projectId, title, archivedAt }));return yield* decodeLinkedThreads({ threads });},Effect.mapError(diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex e3b42a2637a..b8c3ca6096e 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1,4 +1,8 @@-import { EnvironmentHttpApi, ProviderDriverKind } from "@t3tools/contracts";+import {+ EnvironmentHttpApi,+ ProviderDriverKind,+ type RepositoryIdentity,+} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Duration from "effect/Duration";import * as Deferred from "effect/Deferred";@@ -51,6 +55,7 @@ import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";import * as GitHubCli from "./sourceControl/GitHubCli.ts";import * as GitLabCli from "./sourceControl/GitLabCli.ts";+import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";import * as TextGeneration from "./textGeneration/TextGeneration.ts";import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";import * as TerminalManager from "./terminal/Manager.ts";@@ -313,12 +318,54 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(Layer.provide(- Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),+ Layer.mergeAll(+ AzureDevOpsCli.layer,+ BitbucketApi.layer,+ GitHubCli.layer,+ GitLabCli.layer,+ ForgejoCli.layer,+ ),),Layer.provideMerge(GitVcsDriver.layer),Layer.provideMerge(VcsDriverRegistryLayerLive),);+const RepositoryIdentityResolverLayerLive = Layer.effect(+ RepositoryIdentityResolver.RepositoryIdentityResolver,+ Effect.gen(function* () {+ const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;+ return yield* RepositoryIdentityResolver.make({+ refine: Effect.fn(function* (identity: RepositoryIdentity) {+ const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);+ if (+ !remote ||+ !identity.rootPath ||+ (identity.provider !== undefined &&+ identity.provider !== "unknown" &&+ identity.provider !== "forgejo")+ )+ return identity;+ const handle = yield* registry.resolveHandle({+ cwd: identity.rootPath,+ context: {+ provider: { kind: "unknown", name: "Unknown", baseUrl: "" },+ remoteName: identity.locator.remoteName,+ remoteUrl: identity.locator.remoteUrl,+ },+ });+ if (handle.context?.provider.kind !== "forgejo") return identity;+ const baseUrl = handle.context.provider.baseUrl.replace(/\/+$/, "");+ const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");+ const path =+ !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)+ ? remote.path.slice(basePath.length + 1)+ : remote.path;+ return { ...identity, provider: "forgejo", webUrl: `${baseUrl}/${path}` };+ }),+ });+ }),+).pipe(Layer.provide(SourceControlProviderRegistryLayerLive), Layer.provide(ProcessRunner.layer));+const PullRequestServiceLive = PullRequestService.layer.pipe(Layer.provide(PullRequestProviderRegistry.layer),Layer.provide(PullRequestReadCache.layer),@@ -512,7 +559,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),Layer.provideMerge(WorkspaceLayerLive),Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),- Layer.provideMerge(RepositoryIdentityResolver.layer),+ Layer.provideMerge(RepositoryIdentityResolverLayerLive),Layer.provideMerge(ServerEnvironmentLayerLive),Layer.provideMerge(AuthLayerLive),Layer.provideMerge(ServerSecretStore.layer),diff --git a/apps/server/src/sourceControl/ForgejoCli.ts b/apps/server/src/sourceControl/ForgejoCli.tsnew file mode 100644index 00000000000..9fdb4149c8b--- /dev/null+++ b/apps/server/src/sourceControl/ForgejoCli.ts@@ -0,0 +1,720 @@+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Schema from "effect/Schema";+import * as Result from "effect/Result";+import * as Clock from "effect/Clock";+import * as FileSystem from "effect/FileSystem";+import * as Semaphore from "effect/Semaphore";+import * as NodeOS from "node:os";+// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.+import * as NodePath from "node:path";+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";+import { ChildProcessSpawner } from "effect/unstable/process";+import { decodeJsonResult } from "@t3tools/shared/schemaJson";+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";+import * as VcsProcess from "../vcs/VcsProcess.ts";+import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";+import type { SourceControlProviderContext } from "./SourceControlProvider.ts";++const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));++export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {+ command: Schema.Literals(["fj", "tea"]),+ cwd: Schema.String,+ detail: Schema.String,+ reason: Schema.optional(+ Schema.Literals([+ "missing-cli",+ "authentication",+ "forbidden",+ "not-found",+ "rate-limit",+ "invalid-response",+ ]),+ ),+ httpStatus: Schema.optional(Schema.Int),+ cause: Schema.optional(Schema.Defect()),+}) {}++export const ForgejoLoginSchema = Schema.Struct({+ name: Schema.String,+ url: Schema.String,+ ssh_host: Schema.optional(Schema.String),+ valid: Schema.optional(Schema.String),+ user: Schema.String,+ default: Schema.String,+});++export function parseForgejoLogins(raw: string) {+ const decoded = decodeJsonResult(Schema.Array(ForgejoLoginSchema))(raw);+ return Result.isSuccess(decoded) ? decoded.success : [];+}++export const ForgejoKeysSchema = Schema.Struct({+ hosts: Schema.Record(+ Schema.String,+ Schema.Struct({+ type: Schema.Literals(["Application", "OAuth"]),+ token: Schema.String,+ }),+ ),+ aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),+});++const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);++/** Matches fj's directories::ProjectDirs, including its pre-0.6 organization name. */+function forgejoKeysPaths(input: {+ readonly platform: string;+ readonly home: string;+ readonly dataHome?: string;+ readonly appData?: string;+}) {+ if (input.platform === "darwin")+ return ["forgejo-cli", "Cyborus"].map((organization) =>+ NodePath.join(+ input.home,+ "Library",+ "Application Support",+ `${organization}.forgejo-cli`,+ "keys.json",+ ),+ );+ if (input.platform === "win32")+ return ["forgejo-cli", "Cyborus"].map((organization) =>+ NodePath.win32.join(+ input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),+ organization,+ "forgejo-cli",+ "data",+ "keys.json",+ ),+ );+ return [+ NodePath.join(+ input.dataHome && NodePath.isAbsolute(input.dataHome)+ ? input.dataHome+ : NodePath.join(input.home, ".local", "share"),+ "forgejo-cli",+ "keys.json",+ ),+ ];+}++export interface ForgejoRepositoryInput {+ readonly cwd: string;+ readonly context?: SourceControlProviderContext;+ readonly repository?: string;+ readonly reference?: string;+ readonly host?: string;+}++export interface ForgejoRepository {+ readonly command?: "fj" | "tea";+ readonly login: string;+ readonly repository: string;+ readonly baseUrl: string;+}++export interface ForgejoApiInput extends ForgejoRepositoryInput {+ readonly path: string;+ readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";+ readonly body?: unknown;+}++export class ForgejoCli extends Context.Service<+ ForgejoCli,+ {+ readonly execute: (input: {+ readonly command?: "fj" | "tea";+ readonly cwd: string;+ readonly args: ReadonlyArray<string>;+ readonly stdin?: string;+ readonly timeoutMs?: number;+ readonly maxOutputBytes?: number;+ }) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;+ readonly listLogins?: (input: {+ readonly cwd: string;+ readonly command: "fj" | "tea";+ readonly remoteUrl?: string;+ }) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;+ readonly getAccount?: (input: {+ readonly cwd: string;+ readonly baseUrl: string;+ }) => Effect.Effect<string, ForgejoCliError>;+ readonly resolveRepository: (+ input: ForgejoRepositoryInput,+ ) => Effect.Effect<ForgejoRepository, ForgejoCliError>;+ readonly api: (+ input: ForgejoApiInput,+ ) => Effect.Effect<VcsProcess.VcsProcessOutput, ForgejoCliError>;+ }+>()("t3/sourceControl/ForgejoCli") {}++export function parseForgejoRemote(value: string) {+ if (/^(?:https?|ssh):\/\//i.test(value)) {+ try {+ const url = new URL(value);+ return {+ host: url.host.toLowerCase(),+ hostname: url.hostname.toLowerCase(),+ ssh: url.protocol === "ssh:",+ path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),+ };+ } catch {+ return null;+ }+ }+ // SCP remotes may omit the username; URL treats these as a custom scheme.+ const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);+ return ssh?.[1] && ssh[2]+ ? {+ host: ssh[1].toLowerCase(),+ hostname: ssh[1].toLowerCase(),+ ssh: true,+ path: ssh[2].replace(/\.git$/, ""),+ }+ : null;+}++export function matchForgejoLogin(+ logins: ReturnType<typeof parseForgejoLogins>,+ remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,+ requestedHost?: string,+ hostOnly = false,+) {+ const matches = [+ ...new Map(+ logins+ .filter((login) => {+ const url = parseForgejoRemote(login.url);+ if (!url) return false;+ if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;+ return remote.ssh+ ? login.ssh_host?.toLowerCase() === remote.host ||+ login.ssh_host?.toLowerCase() === remote.hostname ||+ url.hostname === remote.hostname+ : url.host === remote.host &&+ ((hostOnly && !remote.path) ||+ !url.path ||+ remote.path === url.path ||+ remote.path.startsWith(`${url.path}/`));+ })+ .map((login) => [login.name, login]),+ ).values(),+ ];+ return matches.length === 1+ ? matches[0]+ : new Set(matches.map((login) => login.url)).size === 1+ ? matches.find((login) => login.default === "true")+ : undefined;+}++export const make = Effect.gen(function* () {+ const process = yield* VcsProcess.VcsProcess;+ const fileSystem = yield* FileSystem.FileSystem;+ const httpClient = yield* HttpClient.HttpClient;+ const authLock = yield* Semaphore.make(1);+ const authenticated = new Map<string, { token: string; time: number }>();+ const execute: ForgejoCli["Service"]["execute"] = (input) =>+ process+ .run({+ ...input,+ operation: "ForgejoCli.execute",+ command: input.command ?? "tea",+ timeoutMs: input.timeoutMs ?? 30_000,+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ForgejoCliError({+ command: input.command ?? "tea",+ cwd: input.cwd,+ ...(input.command === "fj" ? {} : { cause }),+ ...(cause._tag === "VcsProcessSpawnError"+ ? { reason: "missing-cli" as const }+ : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"+ ? { reason: "authentication" as const }+ : {}),+ detail:+ cause._tag === "VcsProcessSpawnError"+ ? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`tea` 0.16 or later) and retry."+ : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"+ ? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `tea login add`."+ : "Forgejo CLI command failed.",+ }),+ ),+ );++ const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {+ for (const path of forgejoKeysPaths({+ platform: yield* HostProcessPlatform,+ home: NodeOS.homedir(),+ ...(globalThis.process.env.XDG_DATA_HOME+ ? { dataHome: globalThis.process.env.XDG_DATA_HOME }+ : {}),+ ...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}),+ })) {+ const exists = yield* fileSystem.exists(path).pipe(+ Effect.mapError(+ () =>+ new ForgejoCliError({+ command: "fj",+ cwd,+ reason: "authentication",+ detail: "Could not read fj authentication storage.",+ }),+ ),+ );+ if (!exists) continue;+ const raw = yield* fileSystem.readFileString(path).pipe(+ Effect.mapError(+ () =>+ new ForgejoCliError({+ command: "fj",+ cwd,+ reason: "authentication",+ detail: "Could not read fj authentication storage.",+ }),+ ),+ );+ const decoded = parseForgejoKeys(raw);+ if (Result.isFailure(decoded))+ return yield* new ForgejoCliError({+ command: "fj",+ cwd,+ reason: "authentication",+ detail: "fj authentication storage is invalid. Authenticate again with fj.",+ });+ return decoded.success;+ }+ const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };+ return empty;+ });++ const publicLogins = (+ keys: typeof ForgejoKeysSchema.Type,+ remoteUrl?: string,+ ): ReturnType<typeof parseForgejoLogins> => {+ const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;+ return Object.keys(keys.hosts).flatMap((host) => {+ const url = parseForgejoRemote(`https://${host}`);+ // fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them.+ if (!url || url.path) return [];+ // fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.+ const scheme =+ remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")+ ? "http"+ : "https";+ const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };+ const aliases = Object.entries(keys.aliases ?? {})+ .filter(([, target]) => target === host)+ .map(([alias]) => ({ ...login, ssh_host: alias }));+ return aliases.length ? aliases : [login];+ });+ };++ const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(+ "ForgejoCli.listLogins",+ )(function* (input) {+ if (input.command === "fj") {+ const keys = yield* readKeys(input.cwd).pipe(Effect.result);+ if (Result.isFailure(keys)) {+ // Stale credentials from an uninstalled fj must not disable an available tea login.+ const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(+ Effect.result,+ );+ if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];+ return yield* keys.failure;+ }+ return publicLogins(keys.success, input.remoteUrl);+ }+ return parseForgejoLogins(+ (yield* execute({ cwd: input.cwd, args: ["login", "list", "--output", "json"] })).stdout,+ );+ });++ const requestFj = Effect.fn("ForgejoCli.requestFj")(+ function* (input: {+ readonly cwd: string;+ readonly baseUrl: string;+ readonly token: string;+ readonly path: string;+ readonly method?: ForgejoApiInput["method"];+ readonly body?: string;+ }) {+ const base = new URL(`${input.baseUrl}/api/v1/`);+ const url = new URL(input.path, base);+ if (+ url.origin !== base.origin ||+ !url.pathname.startsWith(base.pathname) ||+ url.username ||+ url.password+ )+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ detail: "Invalid Forgejo API path.",+ });+ let request = HttpClientRequest.make(input.method ?? "GET")(url.toString()).pipe(+ HttpClientRequest.setHeader("Authorization", `token ${input.token}`),+ );+ if (input.body !== undefined)+ request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));+ const response = yield* httpClient+ .execute(request)+ .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));+ const status = response.status;+ if (status < 200 || status >= 300)+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ httpStatus: status,+ ...(status === 401+ ? { reason: "authentication" as const }+ : status === 403+ ? { reason: "forbidden" as const }+ : status === 404+ ? { reason: "not-found" as const }+ : status === 429+ ? { reason: "rate-limit" as const }+ : {}),+ detail:+ status === 404+ ? "Forgejo repository or pull request was not found."+ : `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`,+ });+ const body =+ status === 204 || status === 205+ ? { text: "", truncated: false, invalidUtf8: false }+ : yield* collectUint8StreamText({+ stream: response.stream,+ maxBytes: 8 * 1024 * 1024,+ });+ if (body.truncated || body.invalidUtf8)+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ reason: "invalid-response",+ detail: "Forgejo returned an oversized or invalid response.",+ });+ return {+ exitCode: ChildProcessSpawner.ExitCode(0),+ stdout: body.text,+ stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}`,+ stdoutTruncated: false,+ stderrTruncated: false,+ };+ },+ (effect, input) =>+ effect.pipe(+ Effect.timeout(30_000),+ Effect.mapError((error) =>+ error._tag === "ForgejoCliError"+ ? error+ : new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ detail: "Forgejo API request failed or timed out.",+ }),+ ),+ ),+ );++ const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (+ cwd: string,+ login: typeof ForgejoLoginSchema.Type,+ ) {+ const keys = yield* readKeys(cwd);+ const token = keys.hosts[login.name]?.token;+ const now = yield* Clock.currentTimeMillis;+ const cached = authenticated.get(login.url);+ if (token && cached?.token === token && now - cached.time < 30_000) return token;+ yield* execute({ command: "fj", cwd, args: ["--host", login.url, "whoami"] });+ // fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.+ const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;+ if (!refreshed)+ return yield* new ForgejoCliError({+ command: "fj",+ cwd,+ reason: "authentication",+ detail: "fj has no credentials for this server. Authenticate again with fj.",+ });+ authenticated.set(login.url, { token: refreshed, time: now });+ return refreshed;+ }, authLock.withPermits(1));++ const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(+ "ForgejoCli.getAccount",+ )(function* (input) {+ const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });+ const login = logins.find(+ (item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),+ );+ if (!login)+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ reason: "authentication",+ detail: "fj has no credentials for this server.",+ });+ const token = yield* authenticateFj(input.cwd, login);+ const currentUser = yield* requestFj({+ cwd: input.cwd,+ baseUrl: login.url.replace(/\/+$/, ""),+ token,+ path: "user",+ });+ const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);+ if (Result.isFailure(user) || !user.success.login.trim())+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ reason: "invalid-response",+ detail: "Forgejo returned an invalid account response.",+ });+ return user.success.login;+ });++ const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (+ input: ForgejoRepositoryInput,+ hostOnly = false,+ ) {+ const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;+ let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(+ (value) => value && parseForgejoRemote(value),+ );+ let remote =+ referenceRemote ??+ (input.repository ? parseForgejoRemote(input.repository) : null) ??+ (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);+ if (!remote && (!input.repository || input.host)) {+ const result = yield* process+ .run({+ operation: "ForgejoCli.remote",+ command: "git",+ args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],+ cwd: input.cwd,+ allowNonZeroExit: true,+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new ForgejoCliError({+ command: "tea",+ cwd: input.cwd,+ detail: "Could not resolve the Forgejo repository remote.",+ cause,+ }),+ ),+ );+ if (input.host) {+ const matchingUrls = [+ ...new Set(+ result.stdout.split("\n").flatMap((line) => {+ const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)$/.exec(line.trim())?.[1];+ return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()+ ? [url]+ : [];+ }),+ ),+ ];+ const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];+ remoteUrl =+ matchingUrls.length === 1+ ? matchingUrls[0]+ : origins.length === 1+ ? origins[0]+ : undefined;+ } else {+ remoteUrl = result.stdout.trim();+ }+ remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;+ }+ if (+ input.host &&+ !remote?.ssh &&+ remote?.host !== input.host.toLowerCase() &&+ remote?.hostname !== input.host.toLowerCase()+ )+ remote = {+ host: input.host.toLowerCase(),+ hostname: input.host.split(":")[0] ?? input.host,+ ssh: false,+ path: remote?.path ?? "",+ };+ const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;+ const fjLogins = yield* listLogins({+ cwd: input.cwd,+ command: "fj",+ ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),+ });+ const requestedHost = input.host ?? input.context?.requestedHost;+ const matchHostOnly = hostOnly || (!!input.host && !remote?.path);+ const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>+ remote+ ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)+ : (logins.find((item) => item.default === "true") ??+ (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));+ let login = selectLogin(fjLogins);+ let command: "fj" | "tea" = "fj";+ if (+ !login &&+ fjLogins.some(+ (item) =>+ !remote ||+ matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),+ )+ ) {+ const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(+ Effect.result,+ );+ if (Result.isSuccess(available))+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ reason: "authentication",+ detail: "Multiple fj logins match this repository. Specify its full server URL.",+ });+ if (available.failure.reason !== "missing-cli") return yield* available.failure;+ }+ if (login) {+ const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);+ if (Result.isFailure(auth)) {+ if (auth.failure.reason === "missing-cli") login = undefined;+ else return yield* auth.failure;+ }+ }+ if (!login) {+ command = "tea";+ login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));+ }+ if (!login)+ return yield* new ForgejoCliError({+ command: "tea",+ cwd: input.cwd,+ reason: "authentication",+ detail:+ "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.",+ });+ if (hostOnly)+ return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };+ const path =+ referenceRemote?.path ??+ (input.repository && !parseForgejoRemote(input.repository)+ ? input.repository+ : remote?.path) ??+ "";+ const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");+ const relativePath =+ basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)+ ? path.slice(basePath.length + 1)+ : path;+ const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");+ if (command === "fj" && !repositoryPath.includes("/")) {+ login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };+ }+ const repository = repositoryPath.includes("/")+ ? repositoryPath+ : `${login.user}/${repositoryPath}`;+ if (!/^[^/\s]+\/[^/\s]+$/.test(repository))+ return yield* new ForgejoCliError({+ command,+ cwd: input.cwd,+ detail: "Specify a Forgejo repository as owner/repository or its full server URL.",+ });+ return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };+ });+ const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);+ const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {+ const repository = yield* resolveTarget(+ input,+ input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),+ );+ const stdin =+ input.body === undefined+ ? undefined+ : yield* encodeApiBody(input.body).pipe(+ Effect.mapError(+ (cause) =>+ new ForgejoCliError({+ command: "tea",+ cwd: input.cwd,+ detail: "Could not encode the Forgejo request body.",+ cause,+ }),+ ),+ );+ let path = input.path.replace(/^\/+/, "");+ if (input.repository && input.repository !== repository.repository) {+ // Repository identities retain the server mount path; API routes do not.+ const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;+ if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {+ path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;+ }+ }+ if (repository.command === "fj") {+ const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;+ if (!token)+ return yield* new ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ reason: "authentication",+ detail: "fj has no credentials for this server.",+ });+ return yield* requestFj({+ cwd: input.cwd,+ baseUrl: repository.baseUrl,+ token,+ path,+ ...(input.method === undefined ? {} : { method: input.method }),+ ...(stdin === undefined ? {} : { body: stdin }),+ });+ }+ const result = yield* execute({+ cwd: input.cwd,+ args: [+ "api",+ "--include",+ "--login",+ repository.login,+ ...(repository.repository ? ["--repo", repository.repository] : []),+ "--method",+ input.method ?? "GET",+ ...(input.body === undefined ? [] : ["--data", "@-"]),+ `${repository.baseUrl}/api/v1/${path}`,+ ],+ ...(stdin === undefined ? {} : { stdin }),+ });+ // tea reports HTTP failures with exit code zero; use its response status.+ const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);+ if (!status || status >= 400)+ return yield* new ForgejoCliError({+ command: "tea",+ cwd: input.cwd,+ ...(status ? { httpStatus: status } : {}),+ ...(status === 401+ ? { reason: "authentication" as const }+ : status === 403+ ? { reason: "forbidden" as const }+ : status === 404+ ? { reason: "not-found" as const }+ : status === 429+ ? { reason: "rate-limit" as const }+ : {}),+ detail:+ status === 401 || status === 403+ ? "Forgejo denied access. Check this server's `tea login` credentials and permissions."+ : status === 404+ ? "Forgejo repository or pull request was not found."+ : status === 429+ ? "Forgejo API rate limit exceeded."+ : `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,+ });+ return result;+ });+ return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });+});++export const layer = Layer.effect(ForgejoCli, make);diff --git a/apps/server/src/sourceControl/ForgejoSourceControlProvider.ts b/apps/server/src/sourceControl/ForgejoSourceControlProvider.tsnew file mode 100644index 00000000000..5a501d96b23--- /dev/null+++ b/apps/server/src/sourceControl/ForgejoSourceControlProvider.ts@@ -0,0 +1,387 @@+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Schema from "effect/Schema";+import * as Result from "effect/Result";+import { SourceControlProviderError } from "@t3tools/contracts";+import * as VcsProcess from "../vcs/VcsProcess.ts";+import * as ForgejoCli from "./ForgejoCli.ts";+import * as SourceControlProvider from "./SourceControlProvider.ts";+import {+ providerAuth,+ probeSourceControlProvider,+ type SourceControlCliDiscoverySpec,+ type SourceControlManagedCliDiscoverySpec,+} from "./SourceControlProviderDiscovery.ts";+import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts";++const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);++export const discovery = {+ type: "cli",+ kind: "forgejo",+ label: "Forgejo / Gitea",+ executable: "tea",+ versionArgs: ["--version"],+ authArgs: ["login", "status", "--output", "json"],+ remoteRefinementArgs: ["login", "list", "--output", "json"],+ parseAuth: (input) => {+ const logins = ForgejoCli.parseForgejoLogins(input.stdout);+ const login = logins.find((entry) => entry.default === "true") ?? logins[0];+ return login+ ? providerAuth({+ status: login.valid === "true" ? "authenticated" : "unauthenticated",+ account: login.user,+ host: ForgejoCli.parseForgejoRemote(login.url)?.host,+ })+ : providerAuth({+ status: "unauthenticated",+ detail: "Run `tea login add` to authenticate a Forgejo or Gitea server.",+ });+ },+ refineUnknownRemote: (input) => {+ const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);+ const login =+ remote &&+ ForgejoCli.matchForgejoLogin(+ ForgejoCli.parseForgejoLogins(input.auth.stdout),+ remote,+ input.context.requestedHost,+ );+ return login ? { kind: "forgejo", name: "Forgejo / Gitea", baseUrl: login.url } : null;+ },+ installHint:+ "Install `fj` 0.6 or later from https://codeberg.org/forgejo-contrib/forgejo-cli and run `fj --host <server-url> auth add-token`, or install `tea` 0.16 or later from https://gitea.com/gitea/tea and run `tea login add` for each Forgejo or Gitea server.",+} satisfies SourceControlCliDiscoverySpec;++export const makeDiscovery = Effect.gen(function* () {+ const cli = yield* ForgejoCli.ForgejoCli;+ const process = yield* VcsProcess.VcsProcess;+ const listLogins = cli.listLogins;+ if (!listLogins) return discovery;+ return {+ type: "managed-cli",+ kind: "forgejo",+ label: discovery.label,+ installHint: discovery.installHint,+ probe: Effect.fn("ForgejoSourceControlProvider.discovery")(function* (cwd: string) {+ const remoteUrl = yield* process+ .run({+ operation: "source-control.discovery.remote",+ command: "git",+ args: ["remote", "get-url", "origin"],+ cwd,+ allowNonZeroExit: true,+ timeoutMs: 5_000,+ maxOutputBytes: 8_000,+ })+ .pipe(+ Effect.map((result) => result.stdout.trim()),+ Effect.orElseSucceed(() => ""),+ );+ const credentials = yield* Effect.result(listLogins({ cwd, command: "fj", remoteUrl }));+ const logins = Result.isSuccess(credentials) ? credentials.success : [];+ const remote = ForgejoCli.parseForgejoRemote(remoteUrl);+ const login =+ (remote && ForgejoCli.matchForgejoLogin(logins, remote)) ||+ logins.find((entry) => entry.default === "true") ||+ logins[0];+ const fj = yield* probeSourceControlProvider({+ cwd,+ process,+ spec: {+ ...discovery,+ executable: "fj",+ versionArgs: ["version"],+ authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],+ parseAuth: (result) =>+ Result.isFailure(credentials)+ ? providerAuth({+ status: "unknown",+ detail: "Could not read fj authentication storage. Authenticate again with fj.",+ })+ : login && result.exitCode === 0+ ? providerAuth({+ status: "authenticated",+ account: login.user,+ host: ForgejoCli.parseForgejoRemote(login.url)?.host,+ })+ : providerAuth({+ status: "unauthenticated",+ detail:+ "Authenticate this server with `fj --host <server-url> auth add-token`.",+ }),+ },+ });+ // A configured fj account owns its requests, including authentication errors.+ if (fj.status === "available" && (login || Result.isFailure(credentials))) {+ if (login && fj.auth.status === "authenticated" && cli.getAccount) {+ const account = yield* cli.getAccount({ cwd, baseUrl: login.url }).pipe(Effect.result);+ return {+ ...fj,+ auth: Result.isSuccess(account)+ ? providerAuth({+ status: "authenticated",+ account: account.success,+ host: ForgejoCli.parseForgejoRemote(login.url)?.host,+ })+ : providerAuth({+ status: "unknown",+ detail: account.failure.detail,+ host: ForgejoCli.parseForgejoRemote(login.url)?.host,+ }),+ };+ }+ return fj;+ }+ const tea = yield* probeSourceControlProvider({ cwd, process, spec: discovery });+ return tea.status === "available" || fj.status === "missing" ? tea : fj;+ }),+ refineUnknownRemote: Effect.fn("ForgejoSourceControlProvider.refineUnknownRemote")(+ function* (input: {+ readonly cwd: string;+ readonly context: SourceControlProvider.SourceControlProviderContext;+ }) {+ const remote = ForgejoCli.parseForgejoRemote(input.context.remoteUrl);+ if (!remote) return null;+ for (const command of ["fj", "tea"] as const) {+ const logins = yield* listLogins({+ cwd: input.cwd,+ command,+ remoteUrl: input.context.remoteUrl,+ }).pipe(Effect.orElseSucceed(() => []));+ const login = ForgejoCli.matchForgejoLogin(logins, remote, input.context.requestedHost);+ if (login) return { kind: "forgejo" as const, name: discovery.label, baseUrl: login.url };+ }+ return null;+ },+ ),+ } satisfies SourceControlManagedCliDiscoverySpec;+});++const RepositorySchema = Schema.Struct({+ full_name: Schema.String,+ clone_url: Schema.String,+ ssh_url: Schema.String,+ default_branch: Schema.optional(Schema.NullOr(Schema.String)),+});+const cloneUrls = (raw: typeof RepositorySchema.Type) => ({+ nameWithOwner: raw.full_name,+ url: raw.clone_url,+ sshUrl: raw.ssh_url,+});+const repositoryPath = (repository: string) =>+ `repos/${repository.split("/").map(encodeURIComponent).join("/")}`;++export const make = Effect.gen(function* () {+ const cli = yield* ForgejoCli.ForgejoCli;+ const fs = yield* FileSystem.FileSystem;+ const process = yield* VcsProcess.VcsProcess;+ const request = <S extends Schema.Codec<unknown, unknown, never, never>>(+ input: ForgejoCli.ForgejoApiInput,+ schema: S,+ ) =>+ cli.api(input).pipe(+ Effect.flatMap((result) =>+ Schema.decodeEffect(Schema.fromJsonString(schema))(result.stdout).pipe(+ Effect.mapError(+ (cause) =>+ new ForgejoCli.ForgejoCliError({+ command: "tea",+ cwd: input.cwd,+ detail: "Forgejo API returned an invalid response.",+ reason: "invalid-response",+ cause,+ }),+ ),+ ),+ ),+ );+ const mapError = (operation: string, cwd: string) =>+ Effect.mapError(+ (cause: unknown) =>+ new SourceControlProviderError({+ provider: "forgejo",+ operation,+ cwd,+ ...(isForgejoCliError(cause) ? { command: cause.command } : {}),+ detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",+ cause,+ }),+ );+ const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (+ input: Parameters<+ SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]+ >[0],+ ) {+ const repo = yield* cli.resolveRepository(input);+ const number = /(?:^#?|\/pulls\/)(\d+)(?:\/[^?#]*)?(?:[?#].*)?$/.exec(input.reference)?.[1];+ if (!number)+ return yield* new ForgejoCli.ForgejoCliError({+ command: "tea",+ cwd: input.cwd,+ detail: "Specify a pull request number or Forgejo pull request URL.",+ });+ return yield* request(+ { ...input, path: `${repositoryPath(repo.repository)}/pulls/${number}` },+ ForgejoPullRequestSchema,+ );+ });+ return SourceControlProvider.SourceControlProvider.of({+ kind: "forgejo",+ listChangeRequests: (input) =>+ Effect.gen(function* () {+ const repo = yield* cli.resolveRepository(input);+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ const branch = SourceControlProvider.sourceBranch(input);+ const results: ReturnType<typeof toForgejoChangeRequest>[] = [];+ const limit = input.limit ?? 20;+ for (let page = 1; results.length < limit; page++) {+ const items = yield* request(+ {+ ...input,+ path: `${repositoryPath(repo.repository)}/pulls?state=${input.state === "merged" ? "closed" : input.state}&sort=recentupdate&limit=50&page=${page}`,+ },+ Schema.Array(ForgejoPullRequestSchema),+ );+ for (const item of items) {+ if (+ item.head.ref !== branch ||+ (source?.repository && item.head.repo?.full_name !== source.repository) ||+ (source?.owner && item.head.repo?.owner.login !== source.owner)+ )+ continue;+ const normalized = toForgejoChangeRequest(item);+ if (input.state === "all" || normalized.state === input.state) results.push(normalized);+ }+ if (items.length === 0) break;+ }+ return results.slice(0, limit);+ }).pipe(mapError("listChangeRequests", input.cwd)),+ getChangeRequest: (input) =>+ getPull(input).pipe(+ Effect.map(toForgejoChangeRequest),+ mapError("getChangeRequest", input.cwd),+ ),+ createChangeRequest: (input) =>+ Effect.gen(function* () {+ const repo = yield* cli.resolveRepository(input);+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ const owner = source?.owner ?? source?.repository?.split("/")[0];+ const head = SourceControlProvider.sourceBranch(input);+ yield* cli.api({+ ...input,+ path: `${repositoryPath(input.target?.repository ?? repo.repository)}/pulls`,+ method: "POST",+ body: {+ base: input.target?.refName ?? input.baseRefName,+ head: owner ? `${owner}:${head}` : head,+ title: input.title,+ body: yield* fs.readFileString(input.bodyFile),+ },+ });+ }).pipe(mapError("createChangeRequest", input.cwd)),+ getRepositoryCloneUrls: (input) =>+ Effect.gen(function* () {+ const repo = yield* cli.resolveRepository(input);+ return cloneUrls(+ yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),+ );+ }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),+ createRepository: (input) =>+ Effect.gen(function* () {+ const repo = yield* cli.resolveRepository(input);+ const user = yield* request(+ { ...input, path: "user" },+ Schema.Struct({ login: Schema.String }),+ );+ const [owner, name] = repo.repository.split("/");+ return cloneUrls(+ yield* request(+ {+ ...input,+ path:+ owner === user.login+ ? "user/repos"+ : `orgs/${encodeURIComponent(owner ?? "")}/repos`,+ method: "POST",+ body: { name, private: input.visibility === "private", auto_init: false },+ },+ RepositorySchema,+ ),+ );+ }).pipe(mapError("createRepository", input.cwd)),+ getDefaultBranch: (input) =>+ Effect.gen(function* () {+ const repo = yield* cli.resolveRepository(input);+ return (+ (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))+ .default_branch ?? null+ );+ }).pipe(mapError("getDefaultBranch", input.cwd)),+ checkoutChangeRequest: (input) =>+ Effect.gen(function* () {+ const repo = yield* cli.resolveRepository(input);+ const pull = yield* getPull(input);+ if (repo.command === "fj") {+ // fj checkout cannot target a repository outside the local remotes.+ const urls = yield* request(+ { ...input, path: repositoryPath(repo.repository) },+ RepositorySchema,+ );+ const remote = input.context?.remoteUrl;+ const useSsh = remote && ForgejoCli.parseForgejoRemote(remote)?.ssh;+ yield* process.run({+ operation: "ForgejoSourceControlProvider.checkoutChangeRequest",+ command: "git",+ cwd: input.cwd,+ args: [+ "fetch",+ "--",+ useSsh ? urls.ssh_url : urls.clone_url,+ `refs/pull/${pull.number}/head`,+ ],+ });+ const branch = `pulls/${pull.number}`;+ const existing = yield* process.run({+ operation: "ForgejoSourceControlProvider.checkoutChangeRequest",+ command: "git",+ cwd: input.cwd,+ args: ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`],+ allowNonZeroExit: true,+ });+ yield* process.run({+ operation: "ForgejoSourceControlProvider.checkoutChangeRequest",+ command: "git",+ cwd: input.cwd,+ args:+ existing.exitCode === 0+ ? ["checkout", branch]+ : ["checkout", "-b", branch, "FETCH_HEAD"],+ });+ } else+ yield* cli.execute({+ cwd: input.cwd,+ args: [+ "pulls",+ "checkout",+ "--login",+ repo.login,+ "--repo",+ repo.repository,+ "--branch",+ String(pull.number),+ ],+ });+ if (input.force) {+ // tea leaves an existing PR branch at its old tip. Keep dirty files safe+ // while bringing the selected branch to the PR revision we fetched.+ yield* process.run({+ operation: "ForgejoSourceControlProvider.checkoutChangeRequest",+ command: "git",+ cwd: input.cwd,+ args: ["reset", "--keep", pull.head.sha],+ });+ }+ }).pipe(mapError("checkoutChangeRequest", input.cwd)),+ });+});diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.tsindex 9e4702af04c..30aa22995b9 100644--- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts+++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts@@ -1,9 +1,14 @@import { assert, it } from "@effect/vitest";import * as NodeServices from "@effect/platform-node/NodeServices";import * as Effect from "effect/Effect";+import type * as Context from "effect/Context";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Schema from "effect/Schema";import { ChildProcessSpawner } from "effect/unstable/process";+import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http";import { VcsProcessSpawnError } from "@t3tools/contracts";import * as ServerConfig from "../config.ts";@@ -13,8 +18,12 @@ import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";import * as BitbucketApi from "./BitbucketApi.ts";import * as GitHubCli from "./GitHubCli.ts";import * as GitLabCli from "./GitLabCli.ts";+import * as ForgejoCli from "./ForgejoCli.ts";+import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";+import * as ForgejoPullRequestProvider from "../pullRequest/ForgejoPullRequestProvider.ts";import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";+import { firstNonEmptyLine } from "./SourceControlProviderDiscovery.ts";const sourceControlProviderRegistryTestLayer = (input: {readonly bitbucket: Partial<BitbucketApi.BitbucketApi["Service"]>;@@ -30,6 +39,7 @@ const sourceControlProviderRegistryTestLayer = (input: {Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),Layer.mock(GitHubCli.GitHubCli)({}),Layer.mock(GitLabCli.GitLabCli)({}),+ Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),Layer.mock(VcsProcess.VcsProcess)(input.process),),@@ -50,6 +60,314 @@ const processOutput = (stderrTruncated: false,});+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));+const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));++it.effect("submits a Forgejo review without sending its summary in the preliminary GET", () => {+ const methods: string[] = [];+ const fetchReview = async (+ ...[input, init]: Parameters<Context.Service.Shape<typeof FetchHttpClient.Fetch>>+ ) => {+ const request = new Request(input instanceof Request ? input.url : String(input), {+ ...(init?.method === undefined ? {} : { method: init.method }),+ ...(init?.headers === undefined ? {} : { headers: init.headers }),+ ...(init?.body === undefined ? {} : { body: init.body }),+ });+ methods.push(request.method);+ if (request.method === "GET") {+ assert.strictEqual(request.url, "https://forgejo.test/api/v1/repos/maria/project/pulls/42");+ return new Response(+ encodeJson({+ number: 42,+ title: "Review target",+ body: "",+ html_url: "https://forgejo.test/maria/project/pulls/42",+ user: { login: "maria" },+ state: "open",+ merged: false,+ head: { ref: "feature", sha: "head", repo: null },+ base: { ref: "main", sha: "base", repo: null },+ created_at: "2026-09-13T00:00:00Z",+ updated_at: "2026-09-13T00:00:00Z",+ closed_at: null,+ merged_at: null,+ labels: [],+ }),+ );+ }+ assert.strictEqual(request.method, "POST");+ assert.strictEqual(+ request.url,+ "https://forgejo.test/api/v1/repos/maria/project/pulls/42/reviews",+ );+ assert.deepStrictEqual(JSON.parse(await request.text()), {+ event: "COMMENT",+ body: "Review summary",+ commit_id: "head",+ comments: [],+ });+ return new Response('{"id":1}', { status: 200 });+ };+ return Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ const provider = yield* ForgejoPullRequestProvider.make.pipe(+ Effect.provideService(ForgejoCli.ForgejoCli, cli),+ );+ yield* provider.submitReview({+ cwd: "/repo",+ repository: "maria/project",+ host: "forgejo.test",+ number: 42,+ verdict: "comment",+ body: "Review summary",+ comments: [],+ });+ assert.deepStrictEqual(methods, ["GET", "POST"]);+ }).pipe(+ Effect.provideService(+ FetchHttpClient.Fetch,+ Object.assign(fetchReview, { preconnect: () => undefined }),+ ),+ Effect.provide(FetchHttpClient.layer),+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(true),+ readFileString: () =>+ Effect.succeed(+ encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),+ ),+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ if (input.command === "git") {+ assert.deepStrictEqual(input.args, ["remote", "-v"]);+ return Effect.succeed(+ processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),+ );+ }+ assert.strictEqual(input.command, "fj");+ assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);+ return Effect.succeed(processOutput(""));+ },+ }),+ ),+ );+});++it.effect("loads Forgejo pull request references from files and commits views", () =>+ Effect.gen(function* () {+ const provider = yield* ForgejoSourceControlProvider.make;+ for (const reference of [+ "42",+ "#42",+ "https://forgejo.test/maria/project/pulls/42",+ "https://forgejo.test/maria/project/pulls/42/",+ "https://forgejo.test/maria/project/pulls/42/files?w=1#diff-1",+ "http://forgejo.test:3000/git/maria/project/pulls/42/commits",+ ]) {+ const result = yield* provider.getChangeRequest({ cwd: "/repo", reference });+ assert.strictEqual(result.number, 42);+ assert.strictEqual(result.title, "Forgejo view reference");+ }+ const invalid = yield* provider+ .getChangeRequest({+ cwd: "/repo",+ reference: "https://forgejo.test/maria/project/pulls/42invalid/files",+ })+ .pipe(Effect.result);+ assert.strictEqual(invalid._tag, "Failure");+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),+ Layer.mock(VcsProcess.VcsProcess)({}),+ Layer.mock(ForgejoCli.ForgejoCli)({+ resolveRepository: () =>+ Effect.succeed({+ login: "work",+ repository: "maria/project",+ baseUrl: "https://forgejo.test",+ }),+ api: (input) => {+ assert.strictEqual(input.path, "repos/maria/project/pulls/42");+ return encodeJsonEffect({+ number: 42,+ title: "Forgejo view reference",+ html_url: "https://forgejo.test/maria/project/pulls/42",+ state: "open",+ merged: false,+ base: { ref: "main", sha: "base", repo: null },+ head: { ref: "feature", sha: "head", repo: null },+ }).pipe(Effect.orDie, Effect.map(processOutput));+ },+ }),+ ),+ ),+ ),+);++it.effect(+ "loads Forgejo reactions on comments, reviews and inline threads and resolves review mutations",+ () => {+ const user = { login: "maria" };+ const review = {+ id: 8,+ body: "review body",+ user,+ state: "COMMENT",+ submitted_at: "2026-09-12T00:00:00Z",+ html_url: "https://forgejo.test/maria/project/pulls/2#issuecomment-37",+ comments_count: 1,+ };+ const comment = { id: 12, body: "ordinary", user, created_at: review.submitted_at };+ const responses: Record<string, unknown> = {+ user,+ "repos/maria/project/issues/2/comments": [comment],+ "repos/maria/project/pulls/2/reviews": [review],+ "repos/maria/project/pulls/2/reviews/8": review,+ "repos/maria/project/pulls/2/reviews/9": { ...review, id: 9, html_url: "" },+ "repos/maria/project/pulls/2/commits": [],+ "repos/maria/project/issues/2/reactions": [],+ "repos/maria/project/pulls/2/reviews/8/comments": [+ {+ ...comment,+ id: 38,+ body: "inline",+ path: "file.ts",+ position: 1,+ original_position: 1,+ commit_id: "head",+ original_commit_id: "head",+ resolver: null,+ },+ ],+ "repos/maria/project/issues/comments/12/reactions": [{ content: "+1", user }],+ "repos/maria/project/issues/comments/37/reactions": [{ content: "heart", user }],+ "repos/maria/project/issues/comments/38/reactions": [+ { content: "rocket", user: { login: "reviewer" } },+ ],+ };+ const writes: ForgejoCli.ForgejoApiInput[] = [];+ let reactionReads = 0;+ return Effect.gen(function* () {+ const provider = yield* ForgejoPullRequestProvider.make;+ const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 2 };+ const activity = yield* provider.getChangeRequestActivity(input);+ assert.deepStrictEqual(+ activity.comments.map((entry) => ({+ id: entry.id,+ kind: entry.kind,+ reactions: entry.reactions,+ })),+ [+ {+ id: "12",+ kind: "issue-comment",+ reactions: [{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true }],+ },+ {+ id: "review:8",+ kind: "review",+ reactions: [{ content: "heart", count: 1, actors: [], viewerHasReacted: true }],+ },+ {+ id: "38",+ kind: "review-comment",+ reactions: [+ { content: "rocket", count: 1, actors: ["reviewer"], viewerHasReacted: false },+ ],+ },+ ],+ );+ const inlineComment = activity.comments[2];+ assert.ok(inlineComment);+ assert.deepStrictEqual(activity.reviewThreads[0]?.comments, [inlineComment]);+ for (const reacted of [true, false]) {+ yield* provider.setReaction({ ...input, subjectId: "review:8", content: "heart", reacted });+ yield* provider.setReaction({ ...input, subjectId: "38", content: "rocket", reacted });+ }+ assert.deepStrictEqual(+ writes.map(({ path, method, body }) => ({ path, method, body })),+ [+ {+ path: "repos/maria/project/issues/comments/37/reactions",+ method: "POST",+ body: { content: "heart" },+ },+ {+ path: "repos/maria/project/issues/comments/38/reactions",+ method: "POST",+ body: { content: "rocket" },+ },+ {+ path: "repos/maria/project/issues/comments/37/reactions",+ method: "DELETE",+ body: { content: "heart" },+ },+ {+ path: "repos/maria/project/issues/comments/38/reactions",+ method: "DELETE",+ body: { content: "rocket" },+ },+ ],+ );+ const missing = yield* provider+ .setReaction({ ...input, subjectId: "review:9", content: "heart", reacted: true })+ .pipe(Effect.result);+ assert.strictEqual(missing._tag, "Failure");+ if (missing._tag === "Failure") assert.include(missing.failure.detail, "comment ID");+ assert.strictEqual(writes.length, 4);+ responses["repos/maria/project/pulls/2/reviews/8/comments"] = Array.from(+ { length: 501 },+ (_, index) => ({+ ...comment,+ id: 1000 + index,+ path: "file.ts",+ position: 1,+ original_position: 1,+ commit_id: "head",+ original_commit_id: "head",+ resolver: null,+ }),+ );+ for (let index = 0; index < 500; index++) {+ responses[`repos/maria/project/issues/comments/${1000 + index}/reactions`] = [];+ }+ reactionReads = 0;+ const bounded = yield* provider.getChangeRequestActivity(input);+ assert.strictEqual(bounded.reviewThreads.length, 500);+ assert.strictEqual(+ bounded.comments.filter((entry) => entry.kind === "review-comment").length,+ 500,+ );+ assert.strictEqual(bounded.commentsTruncated, true);+ assert.strictEqual(reactionReads, 502);+ }).pipe(+ Effect.provide(+ Layer.mock(ForgejoCli.ForgejoCli)({+ api: (input) => {+ if (input.method) {+ writes.push(input);+ return Effect.succeed(processOutput("{}"));+ }+ const path = input.path.split("?")[0]!;+ if (/\/issues\/comments\/\d+\/reactions$/.test(path)) reactionReads++;+ assert.ok(Object.hasOwn(responses, path), `Unexpected Forgejo request: ${path}`);+ const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));+ return encodeJsonEffect(page > 1 ? [] : responses[path]).pipe(+ Effect.orDie,+ Effect.map(processOutput),+ );+ },+ }),+ ),+ );+ },+);+it.effect("reports implemented tools separately from locally available executables", () => {const processMock = {run: (input: VcsProcess.VcsProcessInput) => {@@ -62,7 +380,7 @@ it.effect("reports implemented tools separately from locally available executablif (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") {return Effect.succeed(processOutput(- JSON.stringify({+ encodeJson({hosts: {"github.com": [{@@ -161,6 +479,12 @@ it.effect("reports implemented tools separately from locally available executablauth: "unauthenticated",account: Option.none(),},+ {+ kind: "forgejo",+ status: "missing",+ auth: "unknown",+ account: Option.none(),+ },],);const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");@@ -178,7 +502,7 @@ it.effect("probes provider authentication without exposing token details", () =>if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") {return Effect.succeed(processOutput(- JSON.stringify({+ encodeJson({hosts: {"github.com": [{@@ -202,6 +526,22 @@ Logged in to gitlab.com as gitlab-user`),);}+ if (input.command === "tea" && input.args[0] === "login") {+ return Effect.succeed(+ processOutput(+ encodeJson([+ {+ name: "forgejo",+ url: "https://forgejo.example.com",+ ssh_host: "forgejo.example.com",+ user: "forgejo-user",+ valid: "true",+ default: "true",+ },+ ]),+ ),+ );+ }if (input.command === "az" &&input.args.join(" ") === "account show --query user.name -o tsv"@@ -277,7 +617,1012 @@ Logged in to gitlab.com as gitlab-useraccount: Option.some("bitbucket-user"),detail: Option.none(),},+ {+ kind: "forgejo",+ auth: "authenticated",+ account: Option.some("forgejo-user"),+ detail: Option.none(),+ },],);}).pipe(Effect.provide(testLayer));});++it.effect("discovers Forgejo accounts and retains the server port", () =>+ Effect.gen(function* () {+ const auth = ForgejoSourceControlProvider.discovery.parseAuth(+ processOutput(+ yield* encodeJsonEffect([+ {+ name: "work",+ url: "http://forgejo.local:3000",+ ssh_host: "git.forgejo.local",+ user: "maria",+ default: "true",+ valid: "true",+ },+ ]),+ ),+ );+ assert.deepStrictEqual(+ firstNonEmptyLine("\u001b[1mtea version 0.16.0\u001b[0m\n"),+ Option.some("tea version 0.16.0"),+ );+ assert.strictEqual(auth.status, "authenticated");+ assert.deepStrictEqual(auth.account, Option.some("maria"));+ assert.deepStrictEqual(auth.host, Option.some("forgejo.local:3000"));+ const revoked = ForgejoSourceControlProvider.discovery.parseAuth(+ processOutput(+ encodeJson([+ {+ name: "work",+ url: "http://forgejo.local:3000",+ user: "maria",+ default: "true",+ valid: "false",+ },+ ]),+ ),+ );+ assert.strictEqual(revoked.status, "unauthenticated");+ const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({+ cwd: "/repo",+ context: {+ provider: {+ kind: "unknown",+ name: "git.forgejo.local",+ baseUrl: "https://git.forgejo.local",+ },+ remoteName: "origin",+ remoteUrl: "[email protected]:maria/project.git",+ },+ auth: processOutput(+ yield* encodeJsonEffect([+ {+ name: "work",+ url: "http://forgejo.local:3000",+ ssh_host: "git.forgejo.local",+ user: "maria",+ default: "true",+ },+ ]),+ ),+ });+ assert.deepStrictEqual(refined, {+ kind: "forgejo",+ name: "Forgejo / Gitea",+ baseUrl: "http://forgejo.local:3000",+ });+ }),+);++it.effect("does not choose a default Forgejo login across ambiguous SSH server ports", () =>+ Effect.gen(function* () {+ const logins = ForgejoCli.parseForgejoLogins(+ yield* encodeJsonEffect([+ {+ name: "one",+ url: "http://forgejo.local:3000",+ ssh_host: "forgejo.local",+ user: "maria",+ default: "true",+ },+ {+ name: "two",+ url: "http://forgejo.local:4000",+ ssh_host: "forgejo.local",+ user: "maria",+ default: "false",+ },+ ]),+ );+ const remote = ForgejoCli.parseForgejoRemote("[email protected]:maria/project.git");+ assert.isNotNull(remote);+ assert.deepStrictEqual(+ ForgejoCli.parseForgejoRemote("forgejo.local:maria/project.git"),+ remote,+ );+ assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!));+ assert.strictEqual(+ ForgejoCli.matchForgejoLogin(logins, remote!, "forgejo.local:4000")?.name,+ "two",+ );+ assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!, "other.local:4000"));+ const alias = ForgejoCli.parseForgejoRemote("[email protected]:maria/project.git");+ assert.isNotNull(alias);+ assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, alias!, "forgejo.local:4000"));+ const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({+ cwd: "/repo",+ context: {+ provider: { kind: "unknown", name: "Forgejo", baseUrl: "https://forgejo.local" },+ remoteName: "origin",+ remoteUrl: "[email protected]:maria/project.git",+ requestedHost: "forgejo.local:4000",+ },+ auth: processOutput(yield* encodeJsonEffect(logins)),+ });+ assert.strictEqual(refined?.baseUrl, "http://forgejo.local:4000");+ const https = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000/maria/project.git");+ assert.isNotNull(https);+ assert.strictEqual(ForgejoCli.matchForgejoLogin(logins, https!)?.name, "two");+ const hostOnly = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000");+ assert.strictEqual(+ ForgejoCli.matchForgejoLogin(logins, hostOnly!, undefined, true)?.name,+ "two",+ );+ const mounted = logins.map((login) => ({+ ...login,+ url: `http://forgejo.local:4000/${login.name}`,+ }));+ assert.isUndefined(ForgejoCli.matchForgejoLogin(mounted, hostOnly!, undefined, true));+ }),+);++it.effect("rejects HTTP failures even when tea exits successfully", () =>+ Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ const result = yield* cli+ .api({+ cwd: "/repo",+ repository: "http://forgejo.local:3000/maria/project",+ path: "repos/maria/project/pulls/42",+ method: "PATCH",+ body: { state: "closed" },+ })+ .pipe(Effect.result);+ assert.strictEqual(result._tag, "Failure");+ if (result._tag === "Failure")+ assert.strictEqual(+ result.failure.detail,+ "Forgejo repository or pull request was not found.",+ );+ }).pipe(+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(false),+ }),+ ),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make(() => {+ throw new Error("tea must handle its own HTTP request");+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ if (input.args[0] === "api") {+ assert.strictEqual(input.stdin, '{"state":"closed"}');+ assert.include(input.args, "work");+ assert.include(+ input.args,+ "http://forgejo.local:3000/api/v1/repos/maria/project/pulls/42",+ );+ }+ return Effect.succeed(+ input.args[0] === "login"+ ? processOutput(+ encodeJson([+ {+ name: "work",+ url: "http://forgejo.local:3000",+ ssh_host: "forgejo.local",+ user: "maria",+ default: "true",+ },+ ]),+ )+ : processOutput('{"message":"not found"}', { stderr: "HTTP/1.1 404 Not Found\n" }),+ );+ },+ }),+ ),+ ),+);++it.effect("routes mounted Forgejo repositories without repeating the mount in API paths", () =>+ Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ const viewer = yield* cli.api({ cwd: "/upstream-only", host: "code.test", path: "user" });+ assert.strictEqual(viewer.stdout, "[]");+ const mountedRepository = yield* cli.resolveRepository({+ cwd: "/upstream-only",+ host: "code.test",+ repository: "maria/project",+ });+ assert.strictEqual(mountedRepository.baseUrl, "https://code.test/forgejo");+ assert.strictEqual(mountedRepository.repository, "maria/project");+ for (const path of [+ "repos/forgejo/maria/project/pulls?state=open",+ "repos/forgejo/maria/project",+ "repos/reviewer/project/contents/file.ts",+ ]) {+ const result = yield* cli.api({+ cwd: "/repo",+ repository: "forgejo/maria/project",+ context: {+ provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://code.test/forgejo" },+ remoteName: "origin",+ remoteUrl: "https://code.test/forgejo/maria/project.git",+ },+ path,+ });+ assert.strictEqual(result.stdout, "[]");+ }+ const sameOwnerAsMount = yield* cli.resolveRepository({+ cwd: "/repo",+ repository: "forgejo/project",+ context: {+ provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://code.test/forgejo" },+ remoteName: "origin",+ remoteUrl: "ssh://[email protected]/forgejo/project.git",+ },+ });+ assert.strictEqual(sameOwnerAsMount.command, "tea");+ assert.strictEqual(sameOwnerAsMount.repository, "forgejo/project");+ }).pipe(+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(true),+ readFileString: () =>+ Effect.succeed(+ encodeJson({+ hosts: { "code.test/forgejo": { type: "Application", token: "test-token" } },+ }),+ ),+ }),+ ),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make(() => {+ throw new Error("tea must handle its own HTTP request");+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ if (input.command === "git")+ return Effect.succeed(processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }));+ if (input.args[0] === "login")+ return Effect.succeed(+ processOutput(+ encodeJson([+ {+ name: "mounted",+ url: "https://code.test/forgejo",+ ssh_host: "code.test",+ user: "maria",+ default: "true",+ },+ ]),+ ),+ );+ const supported = [+ "https://code.test/forgejo/api/v1/user",+ "https://code.test/forgejo/api/v1/repos/maria/project/pulls?state=open",+ "https://code.test/forgejo/api/v1/repos/maria/project",+ "https://code.test/forgejo/api/v1/repos/reviewer/project/contents/file.ts",+ ];+ if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");+ assert.strictEqual(input.command, "tea");+ return Effect.succeed(+ supported.includes(input.args.at(-1) ?? "")+ ? processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" })+ : processOutput("{}", { stderr: "HTTP/1.1 404 Not Found\n" }),+ );+ },+ }),+ ),+ ),+);++it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {+ const commands: string[] = [];+ const requests: string[] = [];+ return Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ for (const remoteUrl of [+ "http://forgejo.local:3000/maria/project.git",+ "ssh://[email protected]:2222/maria/project.git",+ "ssh://[email protected]:2222/maria/project.git",+ ]) {+ const result = yield* cli.api({+ cwd: "/repo",+ repository: "maria/project",+ context: {+ provider: {+ kind: "forgejo",+ name: "Forgejo",+ baseUrl: "http://forgejo.local:3000",+ },+ remoteName: "origin",+ remoteUrl,+ requestedHost: "forgejo.local:3000",+ },+ path: "repos/maria/project/issues/42/comments",+ method: "POST",+ body: { body: "verified through fj" },+ });+ assert.strictEqual(result.stdout, '{"id":99}');+ }+ assert.deepStrictEqual(commands, ["fj"]);+ assert.deepStrictEqual(requests, [+ "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",+ "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",+ "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",+ ]);+ const viewer = yield* cli.api({+ cwd: "/no-remotes",+ host: "forgejo.local:3000",+ path: "user",+ });+ assert.strictEqual(viewer.stdout, '{"login":"maria"}');+ assert.strictEqual(requests.at(-1), "https://forgejo.local:3000/api/v1/user");+ const upstreamViewer = yield* cli.api({+ cwd: "/upstream-only",+ host: "forgejo.local:3000",+ path: "user",+ });+ assert.strictEqual(upstreamViewer.stdout, '{"login":"maria"}');+ assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");+ const upstreamRepository = yield* cli.resolveRepository({+ cwd: "/upstream-only",+ host: "forgejo.local:3000",+ repository: "maria/project",+ });+ assert.strictEqual(upstreamRepository.baseUrl, "http://forgejo.local:3000");+ assert.strictEqual(upstreamRepository.repository, "maria/project");+ const httpViewer = yield* cli.api({ cwd: "/repo", host: "forgejo.local:3000", path: "user" });+ assert.strictEqual(httpViewer.stdout, '{"login":"maria"}');+ assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");+ }).pipe(+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(true),+ readFileString: () =>+ Effect.succeed(+ encodeJson({+ hosts: {+ "forgejo.local:3000": { type: "Application", token: "test-token" },+ "forgejo.local:4000": { type: "Application", token: "other-token" },+ },+ aliases: { "ssh.forgejo.local:2222": "forgejo.local:3000" },+ }),+ ),+ }),+ ),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make((request) => {+ requests.push(request.url);+ if (request.url.endsWith("/user")) {+ assert.strictEqual(request.method, "GET");+ assert.strictEqual(request.headers.authorization, "token test-token");+ return Effect.succeed(+ HttpClientResponse.fromWeb(request, new Response('{"login":"maria"}')),+ );+ }+ assert.strictEqual(request.method, "POST");+ assert.strictEqual(request.headers.authorization, "token test-token");+ assert.strictEqual(request.body._tag, "Uint8Array");+ if (request.body._tag === "Uint8Array")+ assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(request.body.body)), {+ body: "verified through fj",+ });+ return Effect.succeed(+ HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),+ );+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ commands.push(input.command);+ if (input.command === "git")+ return Effect.succeed(+ input.cwd === "/no-remotes"+ ? processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) })+ : processOutput(+ `${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)`,+ ),+ );+ assert.strictEqual(input.command, "fj");+ assert.deepStrictEqual(input.args, [+ "--host",+ input.cwd === "/no-remotes"+ ? "https://forgejo.local:3000"+ : "http://forgejo.local:3000",+ "whoami",+ ]);+ return Effect.succeed(processOutput(""));+ },+ }),+ ),+ );+});++it.effect("loads later fj review pages when the server caps pages below the requested size", () => {+ const pages: number[] = [];+ let issueCommentRequests = 0;+ return Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ const provider = yield* ForgejoPullRequestProvider.make.pipe(+ Effect.provideService(ForgejoCli.ForgejoCli, cli),+ );+ const activity = yield* provider.getChangeRequestActivity({+ cwd: "/repo",+ repository: "maria/project",+ host: "forgejo.test",+ number: 42,+ });+ assert.strictEqual(activity.commentCount, 42);+ assert.strictEqual(activity.comments.at(-1)?.id, "review:41");+ assert.strictEqual(activity.commentsTruncated, false);+ assert.deepStrictEqual(pages, [1, 2, 3]);+ assert.strictEqual(issueCommentRequests, 1);+ }).pipe(+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(true),+ readFileString: () =>+ Effect.succeed(+ encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),+ ),+ }),+ ),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make((request) => {+ const url = new URL(request.url);+ if (url.pathname === "/api/v1/repos/maria/project/issues/42/comments") {+ issueCommentRequests++;+ return Effect.succeed(+ HttpClientResponse.fromWeb(+ request,+ new Response(+ encodeJson([+ {+ id: 100,+ body: "Unpaginated issue comment",+ user: { login: "maria" },+ created_at: "2026-09-13T00:00:00Z",+ },+ ]),+ ),+ ),+ );+ }+ if (url.pathname.endsWith("/reviews")) {+ const page = Number(url.searchParams.get("page"));+ pages.push(page);+ assert.ok(page >= 1 && page <= 3);+ const reviews = Array.from({ length: page < 3 ? 20 : 1 }, (_, index) => ({+ id: (page - 1) * 20 + index + 1,+ body: "Review from a capped page",+ user: { login: "maria" },+ state: "COMMENT",+ submitted_at: "2026-09-13T00:00:00Z",+ comments_count: 0,+ }));+ return Effect.succeed(+ HttpClientResponse.fromWeb(+ request,+ new Response(encodeJson(reviews), {+ headers:+ page === 2+ ? {}+ : {+ Link:+ page === 1+ ? `<${url.origin}${url.pathname}?limit=50&page=2>; rel="next"`+ : `<${url.origin}${url.pathname}?limit=50&page=1>; rel="prev"`,+ },+ }),+ ),+ );+ }+ return Effect.succeed(+ HttpClientResponse.fromWeb(+ request,+ new Response(encodeJson(url.pathname === "/api/v1/user" ? { login: "maria" } : [])),+ ),+ );+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ if (input.command === "git") {+ assert.deepStrictEqual(input.args, ["remote", "-v"]);+ return Effect.succeed(+ processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),+ );+ }+ assert.strictEqual(input.command, "fj");+ assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);+ return Effect.succeed(processOutput(""));+ },+ }),+ ),+ );+});++it.effect("falls back to tea when fj is missing or has no account for this server", () =>+ Effect.gen(function* () {+ for (const scenario of ["missing-cli", "missing-account", "stale-invalid-storage"] as const) {+ const commands: string[] = [];+ yield* Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ const result = yield* cli.api({+ cwd: "/repo",+ repository: "https://forgejo.local:3000/maria/project",+ path: "repos/maria/project/pulls",+ });+ assert.strictEqual(result.stdout, "[]");+ assert.deepStrictEqual(+ commands,+ scenario === "missing-account" ? ["tea", "tea"] : ["fj", "tea", "tea"],+ );+ const viewer = yield* cli.api({+ cwd: "/upstream-only",+ host: "forgejo.local:3000",+ path: "user",+ });+ assert.strictEqual(viewer.stdout, "[]");+ }).pipe(+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(true),+ readFileString: () =>+ Effect.succeed(+ scenario === "stale-invalid-storage"+ ? "invalid json"+ : encodeJson({+ hosts: {+ [scenario === "missing-cli" ? "forgejo.local:3000" : "other.local"]: {+ type: "Application",+ token: "test-token",+ },+ },+ }),+ ),+ }),+ ),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make(() => {+ throw new Error("tea must handle its own HTTP request");+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ commands.push(input.command);+ if (input.command === "git")+ return Effect.succeed(+ processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),+ );+ if (input.command === "fj")+ return Effect.fail(+ new VcsProcessSpawnError({+ operation: input.operation,+ command: input.command,+ cwd: input.cwd,+ cause: new Error("fj not found"),+ }),+ );+ assert.strictEqual(input.command, "tea");+ if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");+ return Effect.succeed(+ input.args[0] === "login"+ ? processOutput(+ encodeJson([+ {+ name: "work",+ url: "https://forgejo.local:3000",+ user: "maria",+ default: "true",+ valid: "true",+ },+ ]),+ )+ : processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" }),+ );+ },+ }),+ ),+ );+ }+ }),+);++it.effect("handles fj mutation statuses without retrying failures or reading absent bodies", () =>+ Effect.gen(function* () {+ for (const status of [204, 205, 302, 401, 403, 404, 429, 500]) {+ let writes = 0;+ yield* Effect.gen(function* () {+ const cli = yield* ForgejoCli.make;+ const result = yield* cli+ .api({+ cwd: "/repo",+ repository: "https://forgejo.local/maria/project",+ path: "repos/maria/project/issues/42/comments",+ method: "POST",+ body: { body: "only once" },+ })+ .pipe(Effect.result);+ assert.strictEqual(result._tag, status < 300 ? "Success" : "Failure");+ if (result._tag === "Success") assert.strictEqual(result.success.stdout, "");+ if (result._tag === "Failure") {+ assert.strictEqual(result.failure.command, "fj");+ assert.strictEqual(result.failure.httpStatus, status);+ }+ assert.strictEqual(writes, 1);+ }).pipe(+ Effect.provideService(+ FileSystem.FileSystem,+ FileSystem.makeNoop({+ exists: () => Effect.succeed(true),+ readFileString: () =>+ Effect.succeed(+ encodeJson({+ hosts: {+ "forgejo.local": { type: "Application", token: "test-token" },+ },+ }),+ ),+ }),+ ),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make((request) => {+ writes++;+ assert.strictEqual(+ request.url,+ "https://forgejo.local/api/v1/repos/maria/project/issues/42/comments",+ );+ return Effect.succeed(+ HttpClientResponse.fromWeb(+ request,+ new Response(status < 300 ? null : "", {+ status,+ headers: { location: "https://other.local/" },+ }),+ ),+ );+ }),+ ),+ Effect.provide(+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ assert.strictEqual(+ input.command,+ "fj",+ "a failed mutation must never switch accounts or CLI",+ );+ return Effect.succeed(processOutput(""));+ },+ }),+ ),+ );+ }+ }),+);++it.effect(+ "discovers fj first and retains configured authentication failures instead of switching accounts",+ () =>+ Effect.gen(function* () {+ for (const scenario of ["authenticated", "revoked", "missing", "invalid-storage"] as const) {+ const commands: string[] = [];+ yield* Effect.gen(function* () {+ const spec = yield* ForgejoSourceControlProvider.makeDiscovery;+ assert.strictEqual(spec.type, "managed-cli");+ if (spec.type !== "managed-cli") return;+ const result = yield* spec.probe("/repo");+ assert.strictEqual(result.executable, scenario === "missing" ? "tea" : "fj");+ assert.strictEqual(+ result.auth.status,+ scenario === "revoked"+ ? "unauthenticated"+ : scenario === "invalid-storage"+ ? "unknown"+ : "authenticated",+ );+ if (scenario !== "revoked" && scenario !== "invalid-storage")+ assert.deepStrictEqual(result.auth.host, Option.some("forgejo.local:3000"));+ assert.deepStrictEqual(+ result.auth.account,+ scenario === "authenticated" || scenario === "missing"+ ? Option.some("maria")+ : Option.none(),+ );+ assert.strictEqual(+ commands.some((command) => command.startsWith("tea ")),+ scenario === "missing",+ );+ assert.include(commands, "fj version");+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ Layer.mock(ForgejoCli.ForgejoCli)({+ getAccount: (input) => {+ assert.strictEqual(scenario, "authenticated");+ assert.deepStrictEqual(input, {+ cwd: "/repo",+ baseUrl: "http://forgejo.local:3000",+ });+ return Effect.succeed("maria");+ },+ listLogins: (input) => {+ assert.strictEqual(+ input.remoteUrl,+ "http://forgejo.local:3000/maria/project.git",+ );+ if (scenario === "invalid-storage")+ return Effect.fail(+ new ForgejoCli.ForgejoCliError({+ command: "fj",+ cwd: input.cwd,+ reason: "authentication",+ detail: "fj authentication storage is invalid.",+ }),+ );+ return Effect.succeed([+ {+ name: "forgejo.local:3000",+ url: "http://forgejo.local:3000",+ user: "",+ default: "false",+ },+ ]);+ },+ }),+ Layer.mock(VcsProcess.VcsProcess)({+ run: (input) => {+ commands.push(`${input.command} ${input.args.join(" ")}`);+ if (input.command === "git")+ return Effect.succeed(+ processOutput("http://forgejo.local:3000/maria/project.git\n"),+ );+ if (input.command === "fj") {+ if (scenario === "missing")+ return Effect.fail(+ new VcsProcessSpawnError({+ operation: input.operation,+ command: input.command,+ cwd: input.cwd,+ cause: new Error("fj not found"),+ }),+ );+ if (input.args[0] === "version")+ return Effect.succeed(processOutput("fj 0.10.0"));+ if (scenario === "invalid-storage") {+ assert.deepStrictEqual(input.args, ["auth", "list"]);+ return Effect.succeed(processOutput(""));+ }+ assert.deepStrictEqual(input.args, [+ "--host",+ "http://forgejo.local:3000",+ "whoami",+ ]);+ return Effect.succeed(+ processOutput("", {+ exitCode: ChildProcessSpawner.ExitCode(scenario === "revoked" ? 1 : 0),+ }),+ );+ }+ assert.strictEqual(input.command, "tea");+ return Effect.succeed(+ input.args[0] === "--version"+ ? processOutput("tea version 0.16.0")+ : processOutput(+ encodeJson([+ {+ name: "work",+ url: "http://forgejo.local:3000",+ user: "maria",+ default: "true",+ valid: "true",+ },+ ]),+ ),+ );+ },+ }),+ ),+ ),+ );+ }+ }),+);++it.effect(+ "checks out fj pull refs and preserves existing branches and dirty files until forced",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const git = yield* VcsProcess.VcsProcess;+ const path = yield* Path.Path;+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fj-checkout-" });+ const source = path.join(root, "source");+ const cwd = path.join(root, "checkout");+ yield* fs.makeDirectory(source);+ for (const args of [+ ["init", "-b", "main"],+ ["config", "user.name", "Test"],+ ["config", "user.email", "[email protected]"],+ ])+ yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });+ yield* fs.writeFileString(path.join(source, "base.txt"), "base\n");+ for (const args of [+ ["add", "base.txt"],+ ["commit", "-m", "base"],+ ])+ yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });+ const base = (yield* git.run({+ operation: "test.setup",+ command: "git",+ cwd: source,+ args: ["rev-parse", "HEAD"],+ })).stdout.trim();+ yield* git.run({+ operation: "test.setup",+ command: "git",+ cwd: root,+ args: ["clone", source, cwd],+ });+ yield* fs.writeFileString(path.join(source, "feature.txt"), "pull request change\n");+ for (const args of [+ ["add", "feature.txt"],+ ["commit", "-m", "feature"],+ ["update-ref", "refs/pull/42/head", "HEAD"],+ ])+ yield* git.run({ operation: "test.setup", command: "git", cwd: source, args });+ const head = (yield* git.run({+ operation: "test.setup",+ command: "git",+ cwd: source,+ args: ["rev-parse", "HEAD"],+ })).stdout.trim();+ const fetched: string[] = [];+ const provider = yield* ForgejoSourceControlProvider.make.pipe(+ Effect.provideService(+ VcsProcess.VcsProcess,+ VcsProcess.VcsProcess.of({+ run: (input) => {+ if (input.args[0] !== "fetch") return git.run(input);+ const url = input.args[2];+ assert.isDefined(url);+ fetched.push(url!);+ // Only SSH transport is substituted; both paths fetch the real pull ref.+ return git.run({+ ...input,+ args: input.args.map((arg) =>+ arg === "[email protected]:reviewer/project.git" ? source : arg,+ ),+ });+ },+ }),+ ),+ Effect.provide(+ Layer.mock(ForgejoCli.ForgejoCli)({+ resolveRepository: () =>+ Effect.succeed({+ command: "fj",+ login: "work",+ repository: "reviewer/project",+ baseUrl: "https://forgejo.test",+ }),+ api: (input) => {+ assert.include(+ ["repos/reviewer/project", "repos/reviewer/project/pulls/42"],+ input.path,+ );+ return Effect.succeed(+ processOutput(+ encodeJson(+ input.path.endsWith("/pulls/42")+ ? {+ number: 42,+ title: "Checkout",+ html_url: "https://forgejo.test/reviewer/project/pulls/42",+ state: "open",+ merged: false,+ base: { ref: "main", sha: base, repo: null },+ head: { ref: "feature", sha: head, repo: null },+ }+ : {+ full_name: "reviewer/project",+ clone_url: source,+ ssh_url: "[email protected]:reviewer/project.git",+ default_branch: "main",+ },+ ),+ ),+ );+ },+ }),+ ),+ );+ yield* provider.checkoutChangeRequest({+ cwd,+ reference: "https://forgejo.test/reviewer/project/pulls/42",+ });+ assert.strictEqual(+ (yield* git.run({+ operation: "test.verify",+ command: "git",+ cwd,+ args: ["branch", "--show-current"],+ })).stdout.trim(),+ "pulls/42",+ );+ assert.strictEqual(+ (yield* git.run({+ operation: "test.verify",+ command: "git",+ cwd,+ args: ["rev-parse", "HEAD"],+ })).stdout.trim(),+ head,+ );+ assert.strictEqual(+ yield* fs.readFileString(path.join(cwd, "feature.txt")),+ "pull request change\n",+ );+ for (const args of [+ ["checkout", "main"],+ ["branch", "-f", "pulls/42", "main"],+ ])+ yield* git.run({ operation: "test.setup", command: "git", cwd, args });+ yield* fs.writeFileString(path.join(cwd, "base.txt"), "uncommitted work\n");+ yield* provider.checkoutChangeRequest({ cwd, reference: "42" });+ assert.strictEqual(+ (yield* git.run({+ operation: "test.verify",+ command: "git",+ cwd,+ args: ["rev-parse", "HEAD"],+ })).stdout.trim(),+ base,+ );+ assert.strictEqual(yield* fs.exists(path.join(cwd, "feature.txt")), false);+ yield* provider.checkoutChangeRequest({+ cwd,+ reference: "42",+ force: true,+ context: {+ provider: { kind: "forgejo", name: "Forgejo", baseUrl: "https://forgejo.test" },+ remoteName: "origin",+ remoteUrl: "[email protected]:maria/project.git",+ },+ });+ assert.strictEqual(+ (yield* git.run({+ operation: "test.verify",+ command: "git",+ cwd,+ args: ["rev-parse", "HEAD"],+ })).stdout.trim(),+ head,+ );+ assert.strictEqual(+ yield* fs.readFileString(path.join(cwd, "base.txt")),+ "uncommitted work\n",+ );+ assert.strictEqual(+ yield* fs.readFileString(path.join(cwd, "feature.txt")),+ "pull request change\n",+ );+ assert.deepStrictEqual(fetched, [source, source, "[email protected]:reviewer/project.git"]);+ }).pipe(+ Effect.scoped,+ Effect.provide(VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer))),+ ),+);diff --git a/apps/server/src/sourceControl/SourceControlProvider.ts b/apps/server/src/sourceControl/SourceControlProvider.tsindex 1844e1bfa7c..d295944f97f 100644--- a/apps/server/src/sourceControl/SourceControlProvider.ts+++ b/apps/server/src/sourceControl/SourceControlProvider.ts@@ -14,6 +14,8 @@ export interface SourceControlProviderContext {readonly provider: SourceControlProviderInfo;readonly remoteName: string;readonly remoteUrl: string;+ /** An explicit web authority can disambiguate Forgejo logins sharing an SSH alias. */+ readonly requestedHost?: string;}export interface SourceControlRefSelector {diff --git a/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts b/apps/server/src/sourceControl/SourceControlProviderDiscovery.tsindex 69ac90edbfb..466e6623064 100644--- a/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts+++ b/apps/server/src/sourceControl/SourceControlProviderDiscovery.ts@@ -1,3 +1,4 @@+import * as NodeUtil from "node:util";import type {SourceControlProviderAuth,SourceControlProviderDiscoveryItem,@@ -33,6 +34,7 @@ export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {readonly executable: string;readonly versionArgs: ReadonlyArray<string>;readonly authArgs: ReadonlyArray<string>;+ readonly remoteRefinementArgs?: ReadonlyArray<string>;readonly probeTimeoutMs?: number;readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;readonly refineUnknownRemote?: (@@ -45,8 +47,18 @@ export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;};+export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {+ readonly type: "managed-cli";+ readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;+ readonly refineUnknownRemote: (input: {+ readonly cwd: string;+ readonly context: SourceControlProvider.SourceControlProviderContext;+ }) => Effect.Effect<SourceControlProviderInfo | null>;+};+export type SourceControlProviderDiscoverySpec =| SourceControlCliDiscoverySpec+ | SourceControlManagedCliDiscoverySpec| SourceControlApiDiscoverySpec;type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {@@ -72,7 +84,7 @@ interface DiscoveryProbeResult {}export function firstNonEmptyLine(text: string): Option.Option<string> {- const line = text+ const line = NodeUtil.stripVTControlCharacters(text).split(/\r?\n/).map((entry) => entry.trim()).find((entry) => entry.length > 0);@@ -214,6 +226,7 @@ export function probeSourceControlProvider(input: {readonly process: VcsProcess.VcsProcess["Service"];readonly cwd: string;}): Effect.Effect<SourceControlProviderDiscoveryItem> {+ if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd);if (input.spec.type === "api") {return input.spec.probeAuth.pipe(Effect.map(@@ -288,12 +301,16 @@ export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvide}const context = input.context;- const providers = yield* Effect.forEach(input.specs.filter(isCliRemoteRefinementSpec), (spec) =>- input.process+ const providers = yield* Effect.forEach(input.specs, (spec) => {+ if (spec.type === "managed-cli") {+ return spec.refineUnknownRemote({ cwd: input.cwd, context });+ }+ if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);+ return input.process.run({operation: "source-control.discovery.refine-unknown-remote",command: spec.executable,- args: spec.authArgs,+ args: spec.remoteRefinementArgs ?? spec.authArgs,cwd: input.cwd,allowNonZeroExit: true,timeoutMs: probeTimeoutMs(spec),@@ -309,8 +326,8 @@ export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvide}),),Effect.orElseSucceed(() => null),- ),- );+ );+ });const provider = providers.find((candidate) => candidate !== null);return provider ? { ...context, provider } : context;diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.tsindex 54038502bfd..02e9b03e1f2 100644--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts@@ -15,6 +15,7 @@ import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";import * as BitbucketApi from "./BitbucketApi.ts";import * as GitHubCli from "./GitHubCli.ts";import * as GitLabCli from "./GitLabCli.ts";+import * as ForgejoCli from "./ForgejoCli.ts";import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");@@ -86,12 +87,14 @@ function makeRegistry(input: {return SourceControlProviderRegistry.make.pipe(Effect.provide(Layer.mergeAll(+ NodeServices.layer,registryLayer,processLayer,Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),Layer.mock(BitbucketApi.BitbucketApi)({}),Layer.mock(GitHubCli.GitHubCli)({}),Layer.mock(GitLabCli.GitLabCli)({}),+ Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),ServerConfig.layerTest(process.cwd(), {prefix: "t3-source-control-registry-test-",}).pipe(Layer.provide(NodeServices.layer)),diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.tsindex e9b61c17a4f..57dfc78b667 100644--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts@@ -15,6 +15,7 @@ import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProimport * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";+import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";import * as SourceControlProvider from "./SourceControlProvider.ts";import {probeSourceControlProvider,@@ -296,6 +297,8 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWitexport const make = Effect.gen(function* () {const github = yield* GitHubSourceControlProvider.make;const gitlab = yield* GitLabSourceControlProvider.make;+ const forgejo = yield* ForgejoSourceControlProvider.make;+ const forgejoDiscovery = yield* ForgejoSourceControlProvider.makeDiscovery;const bitbucket = yield* BitbucketSourceControlProvider.make;const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery;const azureDevOps = yield* AzureDevOpsSourceControlProvider.make;@@ -320,6 +323,7 @@ export const make = Effect.gen(function* () {provider: bitbucket,discovery: bitbucketDiscovery,},+ { kind: "forgejo", provider: forgejo, discovery: forgejoDiscovery },]);});diff --git a/apps/server/src/sourceControl/forgejoPullRequests.ts b/apps/server/src/sourceControl/forgejoPullRequests.tsnew file mode 100644index 00000000000..affb9bae74c--- /dev/null+++ b/apps/server/src/sourceControl/forgejoPullRequests.ts@@ -0,0 +1,47 @@+import * as Schema from "effect/Schema";+import * as Option from "effect/Option";+import type { ChangeRequest } from "@t3tools/contracts";++const Repository = Schema.Struct({+ full_name: Schema.String,+ owner: Schema.Struct({ login: Schema.String }),+});+const Branch = Schema.Struct({+ ref: Schema.String,+ sha: Schema.String,+ repo: Schema.NullOr(Repository),+});+export const ForgejoPullRequestSchema = Schema.Struct({+ number: Schema.Int,+ title: Schema.String,+ html_url: Schema.String,+ state: Schema.String,+ merged: Schema.Boolean,+ draft: Schema.optional(Schema.Boolean),+ base: Branch,+ head: Branch,+ closed_at: Schema.optional(Schema.NullOr(Schema.String)),+ merged_at: Schema.optional(Schema.NullOr(Schema.String)),+ updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),+});+export function toForgejoChangeRequest(raw: typeof ForgejoPullRequestSchema.Type): ChangeRequest {+ return {+ provider: "forgejo",+ number: raw.number,+ title: raw.title,+ url: raw.html_url,+ state: raw.merged ? "merged" : raw.state === "closed" ? "closed" : "open",+ isDraft: raw.draft ?? /^(?:\[WIP\]|WIP:)/i.test(raw.title),+ baseRefName: raw.base.ref,+ headRefName: raw.head.ref,+ closedAt: raw.closed_at ?? null,+ mergedAt: raw.merged_at ?? null,+ updatedAt: raw.updated_at ?? Option.none(),+ isCrossRepository:+ raw.head.repo !== null &&+ raw.base.repo !== null &&+ raw.head.repo.full_name !== raw.base.repo.full_name,+ headRepositoryNameWithOwner: raw.head.repo?.full_name ?? null,+ headRepositoryOwnerLogin: raw.head.repo?.owner.login ?? null,+ };+}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex e91fadd3155..10d35e92040 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -155,6 +155,7 @@ import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";import * as GitHubCli from "./sourceControl/GitHubCli.ts";import * as GitLabCli from "./sourceControl/GitLabCli.ts";+import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";@@ -3111,6 +3112,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(BitbucketApi.layer,GitHubCli.layer,GitLabCli.layer,+ ForgejoCli.layer,),),Layer.provideMerge(GitVcsDriver.layer),diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex 72842dd2a1d..8af4419fca3 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -150,7 +150,7 @@ import { orderItemsByPreferredIds, sortLogicalProjectsForSidebar } from "./Sidebimport { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";import { CommandPaletteContent } from "./CommandPaletteContent";import { CommandPaletteResults } from "./CommandPaletteResults";-import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";+import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon, ForgejoIcon } from "./Icons";import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";import { ProjectFavicon } from "./ProjectFavicon";import { ProjectFilePicker } from "./files/ProjectFilePicker";@@ -244,7 +244,7 @@ interface AddProjectEnvironmentOption {type AddProjectRemoteProviderKind = Extract<SourceControlProviderKind,- "github" | "gitlab" | "bitbucket" | "azure-devops"+ "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops">;type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";@@ -267,12 +267,14 @@ const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = ["url","github","gitlab",+ "forgejo","bitbucket","azure-devops",];const REMOTE_PROJECT_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = ["github","gitlab",+ "forgejo","bitbucket","azure-devops",];@@ -281,6 +283,8 @@ function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {switch (source) {case "github":return "GitHub";+ case "forgejo":+ return "Forgejo / Gitea";case "gitlab":return "GitLab";case "bitbucket":@@ -294,6 +298,7 @@ function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {function remoteProjectSourcePathHint(source: AddProjectRemoteSource): string {switch (source) {+ case "forgejo":case "github":return "owner/repo";case "gitlab":@@ -317,6 +322,8 @@ function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: striswitch (source) {case "github":return <GitHubIcon className={className} />;+ case "forgejo":+ return <ForgejoIcon className={className} />;case "gitlab":return <GitLabIcon className={className} />;case "bitbucket":@@ -370,6 +377,7 @@ function buildAddProjectRemoteSourceReadiness(url: { ready: true, hint: null },github: unavailable,gitlab: unavailable,+ forgejo: unavailable,bitbucket: unavailable,"azure-devops": unavailable,};@@ -1759,6 +1767,7 @@ function OpenCommandPaletteDialog(props: {"git","github","gitlab",+ "forgejo","bitbucket","azure","devops",diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsxindex 746a1bbe024..99db055b667 100644--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@ -39,7 +39,13 @@ import {GlobeIcon,} from "lucide-react";import { Radio as RadioPrimitive } from "@base-ui/react/radio";-import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "~/components/Icons";+import {+ AzureDevOpsIcon,+ BitbucketIcon,+ GitHubIcon,+ GitLabIcon,+ ForgejoIcon,+} from "~/components/Icons";import { RadioGroup } from "~/components/ui/radio-group";import { Spinner } from "~/components/ui/spinner";import { toggleVariants } from "~/components/ui/toggle";@@ -123,7 +129,7 @@ interface PendingDefaultBranchAction {type PublishProviderKind = Extract<SourceControlProviderKind,- "github" | "gitlab" | "bitbucket" | "azure-devops"+ "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops">;type GitActionToastId = ReturnType<typeof toastManager.add>;@@ -171,6 +177,14 @@ function requestVcsStatusRefresh(const RUNNING_SOURCE_CONTROL_ACTIONS = ["runStackedAction", "pull", "publishRepository"] as const;const PUBLISH_PROVIDER_OPTIONS = [+ {+ value: "forgejo",+ label: "Forgejo / Gitea",+ description: "Your signed-in server",+ host: "your server",+ pathPlaceholder: "owner/repo",+ Icon: ForgejoIcon,+ },{value: "github",label: "GitHub",@@ -425,6 +439,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {const accounts: Record<PublishProviderKind, string | null> = {github: null,gitlab: null,+ forgejo: null,bitbucket: null,"azure-devops": null,};@@ -476,7 +491,14 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {: "";const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill;const currentPublishProvider = publishProviderOption(publishProvider);- const publishHost = currentPublishProvider.host;+ const publishHost =+ publishProvider === "forgejo"+ ? (Option.getOrNull(+ sourceControlDiscovery.data?.sourceControlProviders.find(+ (provider) => provider.kind === "forgejo",+ )?.auth.host ?? Option.none(),+ ) ?? currentPublishProvider.host)+ : currentPublishProvider.host;const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;const publishProviderLabel = currentPublishProvider.label;const publishWizardSteps = ["Provider", "Repository", "Summary"] as const;diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsxindex 99880a2512a..e4d41d53c3a 100644--- a/apps/web/src/components/Icons.tsx+++ b/apps/web/src/components/Icons.tsx@@ -768,3 +768,16 @@ export const PiAgentIcon: Icon = ({ className, ...props }) => (<path fill="#fff" d="M517.36 400H634.72V634.72H517.36Z" /></svg>);++// Official two-color mark from https://forgejo.org/favicon.svg.+export const ForgejoIcon: Icon = (props) => (+ <svg viewBox="0 0 212 212" aria-hidden="true" {...props}>+ <g transform="translate(6 6)" fill="none">+ <path d="M58 168 v-98 a50 50 0 0 1 50-50 h20" stroke="#ff6600" strokeWidth="25" />+ <path d="M58 168 v-30 a50 50 0 0 1 50-50 h20" stroke="#d40000" strokeWidth="25" />+ <circle cx="142" cy="20" r="18" stroke="#ff6600" strokeWidth="15" />+ <circle cx="142" cy="88" r="18" stroke="#d40000" strokeWidth="15" />+ <circle cx="58" cy="180" r="18" stroke="#d40000" strokeWidth="15" />+ </g>+ </svg>+);diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsxindex 2a69eaeddc9..7201779f13f 100644--- a/apps/web/src/components/ThreadStatusIndicators.tsx+++ b/apps/web/src/components/ThreadStatusIndicators.tsx@@ -102,7 +102,9 @@ export function linkedPullRequestSnapshotStatus(? "azure-devops": link.url.includes("/pull-requests/")? "bitbucket"- : "github";+ : link.url.includes("/pulls/")+ ? "forgejo"+ : "github";return {pr: {number: link.number,diff --git a/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx b/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsxindex aa5dfa78952..88e8144eed0 100644--- a/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx+++ b/apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx@@ -144,7 +144,10 @@ function LinkPullRequestDialog({return {host,repository,- webUrl: (number: number) => changeRequestWebUrl(kind, host, repository, number),+ webUrl: (number: number) =>+ kind === "forgejo" && identity.webUrl+ ? `${identity.webUrl.replace(/\/+$/, "")}/pulls/${number}`+ : changeRequestWebUrl(kind, host, repository, number, identity.locator.remoteUrl),};}, [environmentProjects, projectId]);const linking = usePullRequestLinking(threadRef.environmentId);diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex b0bc3fdb8e2..42bf7ab5102 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -976,6 +976,7 @@ function PullRequestCodeTab({environmentId={environmentId}reference={reference}verdicts={review.verdicts}+ requestChangesSummaryRequired={detail.provider === "forgejo"}onSubmitted={() => {onRefresh();setReviewOpen(false);diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 60188e546d4..3be7b5a1a19 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -727,6 +727,7 @@ export function PullRequestDetailPanel({detail.number,detail.headBranch,detail.headRepositoryNameWithOwner,+ repositoryUrl,): null;const branchRefsQuery = useEnvironmentQuery(@@ -784,11 +785,14 @@ export function PullRequestDetailPanel({if (!coreDetail) return;const next = { key: tabScopeKey, updatedAt: coreDetail.updatedAt };if (shouldRefreshPullRequestActivity(activityRevision.current, next)) {+ // Let an existing read settle before revalidating the new revision. Interrupting a+ // mutation's activity refresh can leave SWR displaying its previous value.+ if (activityQuery.isPending) return;activityQuery.refresh();setRefreshToken((token) => token + 1);}activityRevision.current = next;- }, [activityQuery.refresh, coreDetail, tabScopeKey]);+ }, [activityQuery.isPending, activityQuery.refresh, coreDetail, tabScopeKey]);// Reuse activity and diff until core detail reports a changed revision. Keyed by// the pull request rather than by the panel, because this one panel shows a different pull// request every time it is opened.diff --git a/apps/web/src/components/pullRequest/PullRequestReviewBar.tsx b/apps/web/src/components/pullRequest/PullRequestReviewBar.tsxindex f3235273468..d0b9ab47af5 100644--- a/apps/web/src/components/pullRequest/PullRequestReviewBar.tsx+++ b/apps/web/src/components/pullRequest/PullRequestReviewBar.tsx@@ -50,11 +50,13 @@ export function PullRequestReviewBar({environmentId,reference,verdicts,+ requestChangesSummaryRequired,onSubmitted,}: {environmentId: EnvironmentId;reference: PullRequestRef;verdicts: ReadonlyArray<PullRequestReviewVerdict>;+ requestChangesSummaryRequired: boolean;onSubmitted: () => void;}) {const [pending, setPending] = useState(false);@@ -106,9 +108,11 @@ export function PullRequestReviewBar({onSubmitted();};- // An approval needs no words; anything else does, unless it carries line comments instead.+ // Forgejo requires a summary when requesting changes, even with inline comments.const canSubmit = (verdict: PullRequestReviewVerdict) =>- verdict === "approve" || body.trim().length > 0 || comments.length > 0;+ verdict === "request-changes" && requestChangesSummaryRequired+ ? body.trim().length > 0+ : verdict === "approve" || body.trim().length > 0 || comments.length > 0;return (<div className="px-4 py-3">@@ -128,7 +132,11 @@ export function PullRequestReviewBar({size="sm"className="mt-2"value={body}- placeholder="Summarize your review (optional)"+ placeholder={+ requestChangesSummaryRequired && verdicts.includes("request-changes")+ ? "Summarize your review (required to request changes)"+ : "Summarize your review (optional)"+ }aria-label="Review summary"onChange={(event) => setSummary(reviewKey, event.target.value)}/>diff --git a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsxindex 9d8dcc2424e..57d08218f80 100644--- a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx+++ b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx@@ -7,6 +7,7 @@ import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-rimport { usePullRequestLinking } from "~/hooks/usePullRequestLinking";import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";+import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";import { pullRequestEnvironment } from "~/state/pullRequests";import { useEnvironmentQuery } from "~/state/query";@@ -56,7 +57,10 @@ function EnabledPullRequestThreadLinks({linking.mode === "multiple" && display !== "menu-item"? pullRequestEnvironment.linkedThreads({environmentId,- input: parsed === null ? reference : { ...reference, ...parsed },+ input:+ parsed === null+ ? reference+ : { ...reference, ...normalizeThreadPullRequestKey(parsed) },}): null,);@@ -85,7 +89,10 @@ function EnabledPullRequestThreadLinks({}if (linking.mode === "multiple") {appAtomRegistry.refresh(- pullRequestEnvironment.linkedThreads({ environmentId, input: { ...reference, ...parsed } }),+ pullRequestEnvironment.linkedThreads({+ environmentId,+ input: { ...reference, ...normalizeThreadPullRequestKey(parsed) },+ }),);}onPickerOpenChange?.(false);diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.tsindex 40685aa6ed8..ae5a5067bf1 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts@@ -55,6 +55,7 @@ describe("pull request checkout commands", () => {it.each([["github", "feature", null, "gh pr checkout 42"],["gitlab", "feature", null, "glab mr checkout 42"],+ ["forgejo", "feature", null, null],["azure-devops", "feature", null, "az repos pr checkout --id 42"],["bitbucket",@@ -66,6 +67,32 @@ describe("pull request checkout commands", () => {] as const)("builds the %s command", (provider, branch, repository, expected) => {expect(pullRequestCheckoutCommand(provider, 42, branch, repository)).toBe(expected);});+ it("fetches Forgejo pull refs from the actual repository, including a mounted host and port", () => {+ expect(+ pullRequestCheckoutCommand(+ "forgejo",+ 42,+ "feature",+ null,+ "https://forgejo.local:3000/git/maria/repo",+ ),+ ).toBe(+ "git fetch 'https://forgejo.local:3000/git/maria/repo' refs/pull/42/head && git checkout -B pulls/42 FETCH_HEAD",+ );+ });+ it("quotes shell metacharacters in Forgejo repository URLs", () => {+ expect(+ pullRequestCheckoutCommand(+ "forgejo",+ 42,+ "feature",+ null,+ "https://forgejo.local/maria/repo'$(echo nope)",+ ),+ ).toBe(+ "git fetch 'https://forgejo.local/maria/repo'\\''$(echo nope)' refs/pull/42/head && git checkout -B pulls/42 FETCH_HEAD",+ );+ });});const TIMELINE_SOURCE: Pick<diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.tsindex e4c5cd35f1c..be71c95ddc4 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts@@ -104,12 +104,17 @@ export function pullRequestCheckoutCommand(number: number,headBranch: string,headRepositoryNameWithOwner?: string | null,+ repositoryUrl?: string | null,): string | null {switch (provider) {case "github":return `gh pr checkout ${number}`;case "gitlab":return `glab mr checkout ${number}`;+ case "forgejo":+ return repositoryUrl+ ? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' refs/pull/${number}/head && git checkout -B pulls/${number} FETCH_HEAD`+ : null;case "azure-devops":return `az repos pr checkout --id ${number}`;case "bitbucket": {diff --git a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.tsindex 1ccdb64b73f..16c4fa5d355 100644--- a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts+++ b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts@@ -11,6 +11,7 @@ export type PullRequestLinkContextMenuAction = "copy-link" | "open-external";const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {github: "Open on GitHub",gitlab: "Open on GitLab",+ forgejo: "Open on Forgejo",bitbucket: "Open on Bitbucket","azure-devops": "Open on Azure DevOps",};diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsxindex 2a4858ded4a..733791518d3 100644--- a/apps/web/src/components/settings/SourceControlSettings.tsx+++ b/apps/web/src/components/settings/SourceControlSettings.tsx@@ -52,6 +52,7 @@ import {GitHubIcon,GitIcon,GitLabIcon,+ ForgejoIcon,JujutsuIcon,type Icon,} from "../Icons";@@ -75,6 +76,7 @@ const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {github: GitHubIcon,gitlab: GitLabIcon,+ forgejo: ForgejoIcon,"azure-devops": AzureDevOpsIcon,bitbucket: BitbucketIcon,};diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex bf9103ad477..9a8af52b90f 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -567,7 +567,7 @@ export const SETTINGS_SEARCH_ITEMS = [to: "/settings/source-control",scope: "environment-defaults",searchTerms: [- "version control git github gitlab bitbucket azure devops hosting integrations credentials scan server environment",+ "version control git github gitlab forgejo gitea tea codeberg bitbucket azure devops hosting integrations credentials scan server environment",],},{diff --git a/apps/web/src/lib/openPullRequestLink.test.ts b/apps/web/src/lib/openPullRequestLink.test.tsindex ce9c2193a58..a709b7d8add 100644--- a/apps/web/src/lib/openPullRequestLink.test.ts+++ b/apps/web/src/lib/openPullRequestLink.test.ts@@ -170,6 +170,37 @@ describe("matchesLinkedPullRequestUrl", () => {).toBe(true);});+ it.each([+ ["http://forge.example:3000/git/team/repo/pulls/42/files", true],+ ["http://forge.example:4000/git/team/repo/pulls/42", false],+ ["http://forge.example/git/team/repo/pulls/42", false],+ ])("matches Forgejo links by web authority: %s", (url, expected) => {+ expect(+ matchesLinkedPullRequestUrl(+ { ...linkedPullRequest, url: "http://forge.example:3000/git/team/repo/pulls/42" },+ url,+ ),+ ).toBe(expected);+ });++ it("keeps other providers' existing port normalization", () => {+ expect(+ matchesLinkedPullRequestUrl(+ linkedPullRequest,+ "https://github.com:8443/pingdotgg/t3code/pull/42",+ ),+ ).toBe(true);+ });++ it("keeps Forgejo and GitHub path shapes distinct on a GitHub-named host", () => {+ expect(+ matchesLinkedPullRequestUrl(+ { ...linkedPullRequest, url: "https://github.internal/team/repo/pulls/42" },+ "https://github.internal/team/repo/pull/42",+ ),+ ).toBe(false);+ });+it("rejects a different pull request or host", () => {expect(matchesLinkedPullRequestUrl(linkedPullRequest, "https://github.com/pingdotgg/t3code/pull/43"),@@ -350,6 +381,59 @@ describe("findProjectOnChangeRequestHost", () => {).toBe(backend);});+ it("selects the Forgejo HTTP port for repository and host-level matches", () => {+ const projects = [3000, 4000].map((port) =>+ project(`forgejo-${port}`, {+ canonicalKey: "forge.example/git/team/repo",+ provider: "forgejo",+ displayName: "git/team/repo",+ locator: { remoteUrl: `http://forge.example:${port}/git/team/repo.git` },+ }),+ );+ const reference = parseChangeRequestUrl("http://forge.example:4000/git/team/repo/pulls/42")!;+ expect(findProjectForChangeRequest(projects, reference)).toBe(projects[1]);+ expect(findProjectOnChangeRequestHost(projects, reference)).toBe(projects[1]);+ expect(+ findProjectOnChangeRequestHost(projects, { ...reference, repository: "git/team/other" }),+ ).toBe(projects[1]);+ expect(findProjectForChangeRequest([projects[0]!], reference)).toBeUndefined();+ expect(findProjectOnChangeRequestHost([projects[0]!], reference)).toBeUndefined();+ });++ it("lets tea resolve the web port for Forgejo SSH remotes", () => {+ const checkout = project("forgejo-ssh", {+ canonicalKey: "forge.example/git/team/repo",+ provider: "forgejo",+ displayName: "git/team/repo",+ locator: { remoteUrl: "[email protected]:git/team/repo.git" },+ });+ const reference = parseChangeRequestUrl("http://forge.example:4000/git/team/repo/pulls/42")!;+ expect(findProjectForChangeRequest([checkout], reference)).toBe(checkout);+ const aliased = project("forgejo-alias", {+ canonicalKey: "ssh.forge.example/team/repo",+ provider: "forgejo",+ displayName: "team/repo",+ locator: { remoteUrl: "[email protected]:team/repo.git" },+ webUrl: "http://forge.example:4000/git/team/repo",+ });+ expect(findProjectForChangeRequest([aliased], reference)).toBe(aliased);+ expect(findProjectOnChangeRequestHost([aliased], reference)).toBe(aliased);+ expect(+ findProjectOnChangeRequestHost([aliased], { ...reference, repository: "git/team/other" }),+ ).toBe(aliased);+ for (const url of [+ "http://other.example:4000/git/team/repo/pulls/42",+ "http://forge.example:3000/git/team/repo/pulls/42",+ ]) {+ const other = parseChangeRequestUrl(url)!;+ expect(findProjectForChangeRequest([aliased], other)).toBeUndefined();+ expect(findProjectOnChangeRequestHost([aliased], other)).toBeUndefined();+ }+ const otherMount = parseChangeRequestUrl("http://forge.example:4000/other/team/repo/pulls/42")!;+ expect(findProjectForChangeRequest([aliased], otherMount)).toBeUndefined();+ expect(findProjectOnChangeRequestHost([aliased], otherMount)).toBeUndefined();+ });+it("lends any project on the host to a repository nobody has checked out", () => {expect(findProjectOnChangeRequestHost([frontend], {diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.tsindex 35a9fed4cc5..b691aa58cce 100644--- a/apps/web/src/lib/openPullRequestLink.ts+++ b/apps/web/src/lib/openPullRequestLink.ts@@ -26,13 +26,34 @@ export {changeRequestRepositoryUrl,} from "@t3tools/shared/changeRequestUrl";-/**- * Returns a click handler that opens a pull request URL in the system browser.- *- * Stops event propagation/default so activating the link does not also trigger- * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a- * toast when the local API is unavailable or the open fails.- */+function resolvedForgejoRepository(project: EnvironmentProject): URL | null {+ const identity = project.repositoryIdentity;+ if (identity?.provider !== "forgejo" || !identity.webUrl) return null;+ try {+ const url = new URL(identity.webUrl);+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;+ } catch {+ return null;+ }+}++/** Keep Forgejo servers on different HTTP ports separate when selecting a project. */+function matchesChangeRequestAuthority(+ project: EnvironmentProject,+ link: ChangeRequestLink,+): boolean {+ if (link.authority === undefined) return true;+ try {+ const remote = new URL(project.repositoryIdentity?.locator.remoteUrl ?? "");+ if (remote.protocol === "http:" || remote.protocol === "https:") {+ return remote.host.toLowerCase() === link.authority;+ }+ } catch {+ // SSH remotes do not specify the server's HTTP port; tea resolves the configured login.+ }+ return true;+}+/*** The project a link belongs to, or nothing. Matched the way the server matches: the repository* identity is the full path below the host where one was recorded — which is what nested GitLab@@ -45,9 +66,15 @@ export function findProjectForChangeRequest(): EnvironmentProject | undefined {return projects.find((project) => {const identity = project.repositoryIdentity;- if (!identity) return false;+ if (!identity || !matchesChangeRequestAuthority(project, link)) return false;const kind = identity.provider as SourceControlProviderKind | undefined;if (kind === undefined) return false;+ const web = resolvedForgejoRepository(project);+ if (web)+ return (+ web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&+ web.pathname.replace(/^\/+|\/+$/g, "").toLowerCase() === link.repository.toLowerCase()+ );if (kind === "azure-devops") {return (canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===@@ -60,7 +87,8 @@ export function findProjectForChangeRequest(return (repository !== null &&repository.toLowerCase() === link.repository.toLowerCase() &&- pullRequestHostOf(identity, kind) === link.host.toLowerCase()+ (pullRequestHostOf(identity, kind) === link.host.toLowerCase() ||+ pullRequestHostOf(identity, kind) === link.authority));});}@@ -86,11 +114,25 @@ export function findProjectOnChangeRequestHost(return projects.find((project) => {const identity = project.repositoryIdentity;const kind = identity?.provider as SourceControlProviderKind | undefined;+ const web = resolvedForgejoRepository(project);+ if (web) {+ const mount = web.pathname+ .replace(/^\/+|\/+$/g, "")+ .split("/")+ .slice(0, -2)+ .join("/");+ return (+ web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&+ (!mount || link.repository.toLowerCase().startsWith(`${mount.toLowerCase()}/`))+ );+ }return (identity != null &&kind !== undefined &&kind !== "azure-devops" &&- pullRequestHostOf(identity, kind) === link.host.toLowerCase()+ matchesChangeRequestAuthority(project, link) &&+ (pullRequestHostOf(identity, kind) === link.host.toLowerCase() ||+ pullRequestHostOf(identity, kind) === link.authority));});}@@ -188,7 +230,7 @@ export function useOpenChangeRequestLink(projectId: project.id,...(serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests === true- ? { host: parsed.host }+ ? { host: parsed.authority ?? parsed.host }: {}),repository,url: targetUrl,@@ -203,7 +245,7 @@ export function useOpenChangeRequestLink(state: previous.state ?? "all",repository,number: parsed.number,- selectedHost: parsed.host,+ selectedHost: parsed.authority ?? parsed.host,selectedProjectId: project.id,selectedEnvironmentId: project.environmentId,}),@@ -221,7 +263,7 @@ export function useOpenChangeRequestLink(state: "all",repository,number: parsed.number,- selectedHost: parsed.host,+ selectedHost: parsed.authority ?? parsed.host,selectedProjectId: project.id,// Named so the page opens the right one of two servers holding this project.selectedEnvironmentId: project.environmentId,diff --git a/apps/web/src/pullRequestReference.ts b/apps/web/src/pullRequestReference.tsindex b919e736cc0..421f60f0368 100644--- a/apps/web/src/pullRequestReference.ts+++ b/apps/web/src/pullRequestReference.ts@@ -1,3 +1,6 @@+const FORGEJO_PULL_REQUEST_URL_PATTERN =+ /^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)+[^/\s]+\/pulls\/(\d+)(?:[/?#].*)?$/i;+const FORGEJO_CLI_PR_CHECKOUT_PATTERN = /^tea\s+(?:pr|pulls)\s+checkout\s+(.+)$/i;const GITHUB_PULL_REQUEST_URL_PATTERN =/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;const GITLAB_MERGE_REQUEST_URL_PATTERN =@@ -32,6 +35,7 @@ export function parsePullRequestReference(input: string): string | null {const glabCliCheckoutMatch = GITLAB_CLI_MR_CHECKOUT_PATTERN.exec(trimmed);const azureDevOpsCliCheckoutMatch = AZURE_DEVOPS_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);const normalizedInput =+ FORGEJO_CLI_PR_CHECKOUT_PATTERN.exec(trimmed)?.[1]?.trim() ??ghCliCheckoutMatch?.[1]?.trim() ??glabCliCheckoutMatch?.[1]?.trim() ??(azureDevOpsCliCheckoutMatch?.[1]@@ -43,6 +47,7 @@ export function parsePullRequestReference(input: string): string | null {}const urlMatch =+ FORGEJO_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??GITLAB_MERGE_REQUEST_URL_PATTERN.exec(normalizedInput) ??AZURE_DEVOPS_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);diff --git a/apps/web/src/sourceControlPresentation.ts b/apps/web/src/sourceControlPresentation.tsindex 4e757e6954a..0f627bca5a1 100644--- a/apps/web/src/sourceControlPresentation.ts+++ b/apps/web/src/sourceControlPresentation.ts@@ -13,7 +13,13 @@ import {resolveChangeRequestPresentation,type ChangeRequestTerminology,} from "@t3tools/shared/sourceControl";-import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./components/Icons";+import {+ AzureDevOpsIcon,+ BitbucketIcon,+ GitHubIcon,+ GitLabIcon,+ ForgejoIcon,+} from "./components/Icons";export interface SourceControlPresentation {readonly providerName: string;@@ -32,6 +38,12 @@ export function getSourceControlPresentation(terminology: getChangeRequestTerminology(provider),Icon: GitHubIcon,};+ case "forgejo":+ return {+ providerName: provider?.name || presentation.providerName,+ terminology: getChangeRequestTerminology(provider),+ Icon: ForgejoIcon,+ };case "gitlab":return {providerName: provider?.name || presentation.providerName,diff --git a/apps/web/src/state/sourceControlActions.ts b/apps/web/src/state/sourceControlActions.tsindex 021fb255a4b..efda37c1440 100644--- a/apps/web/src/state/sourceControlActions.ts+++ b/apps/web/src/state/sourceControlActions.ts@@ -269,7 +269,7 @@ export function useSourceControlPublishRepositoryAction(scope: SourceControlActi);const action = useCallback(async (input: {- provider: "github" | "gitlab" | "bitbucket" | "azure-devops";+ provider: "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops";repository: string;visibility: SourceControlRepositoryVisibility;remoteName: string;diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex 48e3eb1992c..b6b4f89af10 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -1,6 +1,6 @@# Source control-T3 Code integrates with GitHub, GitLab, Bitbucket, and Azure DevOps to clone and publish+T3 Code integrates with GitHub, GitLab, Forgejo, Gitea, Bitbucket, and Azure DevOps to clone and publishrepositories, create pull requests, and review changes.## Connect an account@@ -17,6 +17,26 @@ Install [GitHub CLI](https://cli.github.com/) 2.81.0 or newer, then sign in:gh auth login```+### Forgejo and Gitea++Install [Forgejo CLI (`fj`)](https://codeberg.org/forgejo-contrib/forgejo-cli) or+[Gitea CLI (`tea`)](https://gitea.com/gitea/tea) 0.16 or later on your T3 Code server.+Sign in with `fj --host https://your-server auth add-token` or `tea login add`.+Repeat for each server you use, including Codeberg.++T3 Code prefers a matching `fj` login and falls back to `tea` when `fj` is unavailable+or has no login for that server. Once an account is selected, failed actions stay on that+account. Settings shows the detected CLI. Forgejo and Gitea share one integration entry.+Servers hosted under a URL subpath, such as `https://example.com/forgejo`, use `tea` because+fj 0.6 does not preserve the subpath when checking its account.++When cloning or publishing, use a full repository URL to select a specific server.+You can use `owner/repo` when only one fj server is configured, or with your default `tea`+login when fj is unavailable or unconfigured. With multiple fj servers, use the full URL.+If you have multiple `tea` accounts on one server, select one with+`tea login default <login-name>`. Git push and clone also need Git credentials or an SSH key+for that server.+### GitLabInstall [GitLab CLI](https://gitlab.com/gitlab-org/cli), then sign in:diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.tsindex cbbd121959d..4b29e67a217 100644--- a/packages/client-runtime/src/operations/projects.test.ts+++ b/packages/client-runtime/src/operations/projects.test.ts@@ -76,6 +76,13 @@ describe("add project shared logic", () => {sshUrl: "[email protected]:imputnet/helium.git",}),).toBe("https://github.com/imputnet/helium");+ expect(+ getDefaultCloneUrl({+ provider: "forgejo",+ url: "https://forgejo.example.test:8443/owner/repo.git",+ sshUrl: "ssh://[email protected]:2222/owner/repo.git",+ }),+ ).toBe("https://forgejo.example.test:8443/owner/repo.git");});it("preserves existing clone transport behavior for other providers", () => {diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.tsindex 3f5fc3667f3..597b0b5d7b4 100644--- a/packages/client-runtime/src/operations/projects.ts+++ b/packages/client-runtime/src/operations/projects.ts@@ -25,7 +25,7 @@ import type { EnvironmentProject } from "../state/models.ts";export type AddProjectRemoteProviderKind = Extract<SourceControlProviderKind,- "github" | "gitlab" | "bitbucket" | "azure-devops"+ "github" | "gitlab" | "forgejo" | "bitbucket" | "azure-devops">;export type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";@@ -59,6 +59,7 @@ const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray<AddProjectRemoteSource> = ["url","github","gitlab",+ "forgejo","bitbucket","azure-devops",];@@ -66,6 +67,7 @@ const ADD_PROJECT_REMOTE_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [const ADD_PROJECT_REMOTE_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = ["github","gitlab",+ "forgejo","bitbucket","azure-devops",];@@ -74,6 +76,8 @@ export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): strswitch (source) {case "github":return "GitHub";+ case "forgejo":+ return "Forgejo / Gitea";case "gitlab":return "GitLab";case "bitbucket":@@ -87,6 +91,7 @@ export function addProjectRemoteSourceLabel(source: AddProjectRemoteSource): strexport function addProjectRemoteSourcePathHint(source: AddProjectRemoteSource): string {switch (source) {+ case "forgejo":case "github":return "owner/repo";case "gitlab":@@ -117,11 +122,13 @@ export function normalizePastedCloneUrl(input: string): string {return `https://github.com/${repository}`;}-/** GitHub defaults to HTTPS; other providers retain their existing SSH default. */+/** GitHub and Forgejo default to HTTPS; other providers retain their existing SSH default. */export function getDefaultCloneUrl(repository: Pick<SourceControlRepositoryInfo, "provider" | "url" | "sshUrl">,): string {- return repository.provider === "github" ? repository.url : repository.sshUrl;+ return repository.provider === "github" || repository.provider === "forgejo"+ ? repository.url+ : repository.sshUrl;}export function sortAddProjectProviderSources(@@ -153,6 +160,7 @@ export function buildAddProjectRemoteSourceReadiness(url: { ready: true, hint: null },github: unavailable,gitlab: unavailable,+ forgejo: unavailable,bitbucket: unavailable,"azure-devops": unavailable,};diff --git a/packages/client-runtime/src/threadPullRequestCompatibility.test.ts b/packages/client-runtime/src/threadPullRequestCompatibility.test.tsindex 4ce682cca39..a8f444800a1 100644--- a/packages/client-runtime/src/threadPullRequestCompatibility.test.ts+++ b/packages/client-runtime/src/threadPullRequestCompatibility.test.ts@@ -19,6 +19,24 @@ const input = {};describe("thread pull request capability negotiation", () => {+ it.each([true, false])(+ "preserves Forgejo ports in a multi-link mutation: linked=%s",+ (linked) => {+ const mutation = planThreadPullRequestMutation({+ ...input,+ linked,+ capabilities: { threadPullRequests: true },+ reference: {+ host: "forge.example",+ repository: "team/repo",+ number: 7,+ url: "http://forge.example:3000/team/repo/pulls/7",+ },+ });+ expect(mutation).toMatchObject({ input: { host: "forge.example:3000", number: 7 } });+ },+ );+it.each([undefined, {}, { threadPullRequests: false, threadPullRequestLinking: false }])("does not dispatch when linking is unadvertised: %j",(capabilities) => {diff --git a/packages/client-runtime/src/threadPullRequestCompatibility.ts b/packages/client-runtime/src/threadPullRequestCompatibility.tsindex b747e7c7863..4a31f82ec05 100644--- a/packages/client-runtime/src/threadPullRequestCompatibility.ts+++ b/packages/client-runtime/src/threadPullRequestCompatibility.ts@@ -4,6 +4,7 @@ import type {ThreadId,ThreadPullRequestKey,} from "@t3tools/contracts";+import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";type LinkingCapabilities = Pick<ExecutionEnvironmentCapabilities,@@ -36,20 +37,19 @@ export function planThreadPullRequestMutation({legacyRepository?: string | undefined;linked: boolean;}) {+ const key = normalizeThreadPullRequestKey(reference);switch (threadPullRequestLinkMode(capabilities)) {case "multiple":return linked? {type: "thread.pull-request.link" as const,- input: { threadId, ...reference, source: "manual" as const },+ input: { threadId, ...reference, ...key, source: "manual" as const },}: {type: "thread.pull-request.unlink" as const,input: {threadId,- host: reference.host,- repository: reference.repository,- number: reference.number,+ ...key,},};case "single":diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 10e4cda462d..88e2661523a 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -192,6 +192,8 @@ export type RepositoryIdentityLocator = typeof RepositoryIdentityLocator.Type;export const RepositoryIdentity = Schema.Struct({canonicalKey: TrimmedNonEmptyString,locator: RepositoryIdentityLocator,+ /** Repository browser URL resolved from the server's configured hosting account. */+ webUrl: Schema.optionalKey(TrimmedNonEmptyString),rootPath: Schema.optionalKey(TrimmedNonEmptyString),displayName: Schema.optionalKey(TrimmedNonEmptyString),provider: Schema.optionalKey(TrimmedNonEmptyString),diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.tsindex 599006994d0..f268e309ae6 100644--- a/packages/contracts/src/pullRequest.test.ts+++ b/packages/contracts/src/pullRequest.test.ts@@ -7,6 +7,7 @@ import {PullRequestListInput,PullRequestListResult,PullRequestReviewerRequestInput,+ pullRequestHostOf,resolvePullRequestAuthorFilter,} from "./pullRequest.ts";@@ -65,6 +66,20 @@ const LIST_RESULT: PullRequestListResult = {};describe("PullRequestListResult", () => {+ it("separates Forgejo HTTP ports while preserving other provider host identities", () => {+ const identity = {+ canonicalKey: "forge.example/team/repo",+ locator: { remoteUrl: "http://forge.example:3000/team/repo.git" },+ };+ expect(pullRequestHostOf(identity, "forgejo")).toBe("forge.example:3000");+ expect(pullRequestHostOf(identity, "gitlab")).toBe("forge.example");+ expect(+ pullRequestHostOf(+ { ...identity, locator: { remoteUrl: "ssh://[email protected]:2222/team/repo.git" } },+ "forgejo",+ ),+ ).toBe("forge.example");+ });/*** The RPC builds this codec at call time, so a shape it cannot lower — an open-keyed record* with an optional value, for one — fails as an interrupted request rather than as a schemadiff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex 44658bbc6c3..0194521d0d8 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -1134,6 +1134,12 @@ const PROVIDER_REQUIREMENT: Partial<"GitHub CLI (`gh`) is required to browse change requests on this host. Install it from https://cli.github.com/ and reload.",unauthenticated: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",},+ forgejo: {+ missing:+ "Install Forgejo CLI (`fj` 0.6 or later) from https://codeberg.org/forgejo-contrib/forgejo-cli or Gitea CLI (`tea` 0.16 or later) from https://gitea.com/gitea/tea to browse Forgejo pull requests.",+ unauthenticated:+ "Authenticate your Forgejo or Gitea server with `fj --host <server-url> auth add-token` on the T3 Code server. If fj is missing or unconfigured for that server, use `tea login add`. A configured fj account must be repaired with fj.",+ },gitlab: {missing:"GitLab CLI (`glab`) is required to browse change requests on this host. Install it from https://gitlab.com/gitlab-org/cli and reload.",@@ -1161,9 +1167,24 @@ const PROVIDER_REQUIREMENT: Partial<* knows its hosts before the listing answers, and the two must agree on what they are called.*/export function pullRequestHostOf(- identity: { readonly canonicalKey?: string | undefined } | null | undefined,+ identity:+ | {+ readonly canonicalKey?: string | undefined;+ readonly locator?: { readonly remoteUrl: string } | undefined;+ }+ | null+ | undefined,kind: SourceControlProviderKind,): string {+ if (kind === "forgejo") {+ try {+ const remote = new URL(identity?.locator?.remoteUrl ?? "");+ if (remote.protocol === "http:" || remote.protocol === "https:")+ return remote.host.toLowerCase();+ } catch {+ // SSH remotes retain their canonical host; the CLI resolves their web endpoint.+ }+ }const host = identity?.canonicalKey?.split("/")[0]?.trim();return host === undefined || host.length === 0 ? kind : host.toLowerCase();}diff --git a/packages/contracts/src/sourceControl.ts b/packages/contracts/src/sourceControl.tsindex cc98fbc1bbc..b0d2bd4a75b 100644--- a/packages/contracts/src/sourceControl.ts+++ b/packages/contracts/src/sourceControl.ts@@ -5,6 +5,7 @@ import { VcsDriverKind } from "./vcs.ts";export const SourceControlProviderKind = Schema.Literals(["github","gitlab",+ "forgejo","azure-devops","bitbucket","unknown",diff --git a/packages/shared/src/changeRequestUrl.test.ts b/packages/shared/src/changeRequestUrl.test.tsindex 2af718e453f..68211c0faf5 100644--- a/packages/shared/src/changeRequestUrl.test.ts+++ b/packages/shared/src/changeRequestUrl.test.ts@@ -24,6 +24,15 @@ describe("parseChangeRequestUrl", () => {});});+ it("reads Forgejo URLs even when the hostname contains github", () => {+ expect(parseChangeRequestUrl("https://github.internal/team/repo/pulls/7")).toEqual({+ host: "github.internal",+ authority: "github.internal",+ repository: "team/repo",+ number: 7,+ });+ });+it("reads a supported GitHub host with a middle DNS label", () => {expect(parseChangeRequestUrl("https://code.github.example.com/acme/web/pull/42")).toEqual({host: "code.github.example.com",@@ -90,7 +99,23 @@ describe("parseChangeRequestUrl", () => {});describe("siblingPullRequestUrl", () => {+ it("recognizes Forgejo on custom HTTP hosts", () => {+ expect(parseChangeRequestUrl("http://git.example.test:3000/team/repo/pulls/42/files")).toEqual({+ host: "git.example.test",+ authority: "git.example.test:3000",+ repository: "team/repo",+ number: 42,+ });+ });it.each([+ [+ "http://git.example.test:3000/team/repo/pulls/42/files",+ "http://git.example.test:3000/team/repo/pulls/43",+ ],+ [+ "https://git.example.test/forgejo/team/repo/pulls/42/files",+ "https://git.example.test/forgejo/team/repo/pulls/43",+ ],["https://github.com/pull/1/pull/42/files", "https://github.com/pull/1/pull/43"],["https://git.acme.test/team/merge_requests/1/repo/-/merge_requests/42/diffs",@@ -125,6 +150,29 @@ describe("siblingPullRequestUrl", () => {});describe("changeRequestUrlFor", () => {+ it("preserves the origin when the Forgejo host already contains its port", () => {+ expect(+ changeRequestUrlFor(+ "forgejo",+ "forge.example:3000",+ "team/repo",+ 42,+ "http://forge.example:3000/team/repo.git",+ ),+ ).toBe("http://forge.example:3000/team/repo/pulls/42");+ });++ it.each([+ ["http://forge.example:3000/git/owner/repo.git", "http://forge.example:3000"],+ ["https://forge.example:8443/git/owner/repo.git", "https://forge.example:8443"],+ ["[email protected]:git/owner/repo.git", "https://forge.example"],+ ["http://other.example:3000/git/owner/repo.git", "https://forge.example"],+ ])("preserves the matching Forgejo web origin from %s", (remoteUrl, origin) => {+ expect(changeRequestUrlFor("forgejo", "forge.example", "git/owner/repo", 42, remoteUrl)).toBe(+ `${origin}/git/owner/repo/pulls/42`,+ );+ });+it.each([["ssh.dev.azure.com", "v3/org/project/web"],["vs-ssh.visualstudio.com", "v3/org/project/web"],diff --git a/packages/shared/src/changeRequestUrl.ts b/packages/shared/src/changeRequestUrl.tsindex 0687afd38eb..5be8d355a16 100644--- a/packages/shared/src/changeRequestUrl.ts+++ b/packages/shared/src/changeRequestUrl.ts@@ -13,6 +13,8 @@ export interface ChangeRequestLink {readonly host: string;readonly repository: string;readonly number: number;+ /** Forgejo's HTTP host and port, separate from the portless repository identity. */+ readonly authority?: string;}/** The host itself, one of its subdomains, or an install named after the provider. */@@ -49,7 +51,13 @@ export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | nu// GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}if (isHostOf(host, "github.com", "github")) {const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);- return claim(host, match);+ if (match) return claim(host, match);+ }+ // Forgejo and Gitea use /pulls/ on arbitrary self-hosted domains.+ const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);+ if (forgejo) {+ const link = claim(host, forgejo);+ return link === null ? null : { ...link, authority: url.host.toLowerCase() };}// GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`// separator is GitLab's own, so the hostname is not asked about.@@ -83,10 +91,26 @@ export function changeRequestUrlFor(host: string,repository: string,number: number,+ remoteUrl?: string,): string | null {switch (kind) {case "github":return `https://${host}/${repository}/pull/${number}`;+ case "forgejo": {+ try {+ const remote = new URL(remoteUrl ?? "");+ if (+ (remote.protocol === "http:" || remote.protocol === "https:") &&+ (remote.hostname.toLowerCase() === host.toLowerCase() ||+ remote.host.toLowerCase() === host.toLowerCase())+ ) {+ return `${remote.origin}/${repository}/pulls/${number}`;+ }+ } catch {+ // SSH remotes do not specify the server's web origin.+ }+ return `https://${host}/${repository}/pulls/${number}`;+ }case "gitlab":return `https://${host}/${repository}/-/merge_requests/${number}`;case "bitbucket":@@ -174,7 +198,8 @@ export function matchesLinkedPullRequestUrl(target !== null &&linked.host === target.host &&linked.repository === target.repository &&- linked.number === target.number+ linked.number === target.number &&+ linked.authority === target.authority);}@@ -185,7 +210,7 @@ export function changeRequestRepositoryUrl(targetUrl: string): string | null {const url = new URL(targetUrl);const repositoryPath =/^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??- /^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(+ /^(.*?)(?:\/pulls?\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(url.pathname,)?.[1];if (!repositoryPath) return null;@@ -199,7 +224,7 @@ export function siblingPullRequestUrl(url: string, number: number): string | nulconst reference = parseChangeRequestUrl(url);if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;const sibling = new URL(url);- const route = /^\/(-\/merge_requests|pull|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(+ const route = /^\/(-\/merge_requests|pulls?|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(sibling.pathname.slice(reference.repository.length + 1),)?.[1];if (route === undefined) return null;diff --git a/packages/shared/src/sourceControl.test.ts b/packages/shared/src/sourceControl.test.tsindex 6a60d6f9b38..f9c009fac04 100644--- a/packages/shared/src/sourceControl.test.ts+++ b/packages/shared/src/sourceControl.test.ts@@ -59,6 +59,22 @@ describe("detectSourceControlProviderFromRemoteUrl", () => {).toBe("bitbucket");});+ it("detects Forgejo and Gitea hosts while preserving HTTP origins", () => {+ for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) {+ expect(detectSourceControlProviderFromRemoteUrl(`http://${host}:3000/team/repo.git`)).toEqual(+ {+ kind: "forgejo",+ name: "Forgejo",+ baseUrl: `http://${host}:3000`,+ },+ );+ }+ expect(getChangeRequestTerminologyForKind("forgejo")).toEqual({+ shortLabel: "PR",+ singular: "pull request",+ });+ });+it("detects Azure DevOps SSH remotes", () => {// The default Azure DevOps SSH clone URL uses the ssh.dev.azure.com host.expect(diff --git a/packages/shared/src/sourceControl.ts b/packages/shared/src/sourceControl.tsindex 9f1dc384e74..0b2e0e2699c 100644--- a/packages/shared/src/sourceControl.ts+++ b/packages/shared/src/sourceControl.ts@@ -5,7 +5,7 @@ import type {} from "@t3tools/contracts";export interface ChangeRequestPresentation {- readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";+ readonly icon: "github" | "gitlab" | "forgejo" | "azure-devops" | "bitbucket" | "change-request";readonly providerName: string;readonly shortName: string;readonly longName: string;@@ -47,6 +47,17 @@ const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {urlExample: "https://gitlab.com/group/project/-/merge_requests/42",};+const FORGEJO_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {+ icon: "forgejo",+ providerName: "Forgejo",+ shortName: "PR",+ longName: "pull request",+ pluralLongName: "pull requests",+ providerLongName: "Forgejo pull request",+ checkoutCommandExample: "tea pr checkout 123",+ urlExample: "https://codeberg.org/owner/repo/pulls/42",+};+const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {icon: "azure-devops",providerName: "Azure DevOps",@@ -87,6 +98,8 @@ export function resolveChangeRequestPresentation(return GITHUB_CHANGE_REQUEST_PRESENTATION;case "gitlab":return GITLAB_CHANGE_REQUEST_PRESENTATION;+ case "forgejo":+ return FORGEJO_CHANGE_REQUEST_PRESENTATION;case "azure-devops":return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;case "bitbucket":@@ -200,6 +213,20 @@ export function detectSourceControlProviderFromRemoteUrl(}const hostname = parseHostName(host);+ if (+ hostname === "codeberg.org" ||+ hasDnsLabel(hostname, "forgejo") ||+ hasDnsLabel(hostname, "gitea")+ ) {+ return {+ kind: "forgejo",+ name: "Forgejo",+ baseUrl: /^https?:/iu.test(remoteUrl.trim())+ ? new URL(remoteUrl.trim()).origin+ : toBaseUrl(host),+ };+ }+if (isGitHubHost(hostname)) {return {kind: "github",diff --git a/packages/shared/src/threadPullRequests.test.ts b/packages/shared/src/threadPullRequests.test.tsindex 6f231f28989..4844df8f778 100644--- a/packages/shared/src/threadPullRequests.test.ts+++ b/packages/shared/src/threadPullRequests.test.ts@@ -62,6 +62,28 @@ function link(}describe("threadPullRequestKeysEqual", () => {+ it("recovers Forgejo ports from old stored URLs and keeps separate servers distinct", () => {+ const old = link(1, {+ host: "forge.example",+ repository: "team/repo",+ url: "http://forge.example:3000/team/repo/pulls/1",+ });+ expect(threadPullRequestKeysEqual(old, { ...old, host: "forge.example:3000" })).toBe(true);+ expect(+ threadPullRequestKeysEqual(old, {+ host: "forge.example:3000",+ repository: "team/repo",+ number: 1,+ }),+ ).toBe(true);+ expect(+ threadPullRequestKeysEqual(old, {+ ...old,+ url: "http://forge.example:4000/team/repo/pulls/1",+ }),+ ).toBe(false);+ });+it("ignores host and repository case", () => {expect(threadPullRequestKeysEqual(diff --git a/packages/shared/src/threadPullRequests.ts b/packages/shared/src/threadPullRequests.tsindex 55e23027832..e747c151bd1 100644--- a/packages/shared/src/threadPullRequests.ts+++ b/packages/shared/src/threadPullRequests.ts@@ -10,10 +10,23 @@ import { pullRequestHostOf } from "@t3tools/contracts";import { parseChangeRequestUrl } from "./changeRequestUrl.ts";import { canonicalRepositoryKey, sourceControlRepositorySelector } from "./sourceControl.ts";-/** Normalize stored link identity, including Azure's SSH and browser host aliases. */-export function normalizeThreadPullRequestKey(key: ThreadPullRequestKey): ThreadPullRequestKey {+type ThreadPullRequestKeySource = ThreadPullRequestKey & {+ readonly authority?: string;+ readonly url?: string;+};++/** Normalize stored links, recovering Forgejo HTTP ports from old links' URLs. */+export function normalizeThreadPullRequestKey(+ key: ThreadPullRequestKeySource,+): ThreadPullRequestKey {+ const parsed = key.url === undefined ? null : parseChangeRequestUrl(key.url);+ const authority =+ key.authority ??+ (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number+ ? parsed.authority+ : undefined);const canonical = canonicalRepositoryKey(- `${key.host.trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,+ `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,);const separator = canonical.indexOf("/");return {@@ -31,7 +44,7 @@ export function legacyThreadPullRequestKey(const parsed = parseChangeRequestUrl(linked.url);if (parsed !== null && parsed.number === linked.number) {const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);- if (canonical.startsWith("dev.azure.com/")) {+ if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {return normalizeThreadPullRequestKey(parsed);}}@@ -52,13 +65,13 @@ export function legacyThreadPullRequestKey(/** Identity comparison for links: host-level, case-insensitive on host and repository. */export function threadPullRequestKeysEqual(- left: ThreadPullRequestKey,- right: ThreadPullRequestKey,+ left: ThreadPullRequestKeySource,+ right: ThreadPullRequestKeySource,): boolean {return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);}-export function threadPullRequestKeyOf(key: ThreadPullRequestKey): string {+export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {const normalized = normalizeThreadPullRequestKey(key);return `${normalized.host}/${normalized.repository}#${normalized.number}`;}@@ -157,6 +170,20 @@ export function legacyLinkedPullRequestOf(const key = legacyThreadPullRequestKey(link, link.host);return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;}+ const parsed = parseChangeRequestUrl(link.url);+ if (parsed?.authority !== undefined) {+ try {+ const remote = new URL(identity.locator.remoteUrl);+ if (remote.protocol === "http:" || remote.protocol === "https:") {+ return (+ parsed.authority === remote.host && parsed.repository === repository.toLowerCase()+ );+ }+ } catch {+ // SSH web ports are resolved by the provider's configured login.+ }+ return parsed.host === host && parsed.repository === repository.toLowerCase();+ }return (link.host.toLowerCase() === host.toLowerCase() &&link.repository.toLowerCase() === repository.toLowerCase()@@ -193,7 +220,8 @@ export function resolveThreadPullRequestChains(const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();for (const link of visible) {if (link.stack === null) continue;- const stackKey = `${link.host.toLowerCase()}/${link.repository.toLowerCase()}#stack:${link.stack.id}`;+ const key = normalizeThreadPullRequestKey(link);+ const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;const members = nativeStacks.get(stackKey) ?? [];members.push(link);nativeStacks.set(stackKey, members);@@ -206,8 +234,10 @@ export function resolveThreadPullRequestChains(}const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));- const branchKey = (link: ThreadPullRequestLink, branch: string) =>- `${link.host.toLowerCase()}/${link.repository.toLowerCase()}:${branch}`;+ const branchKey = (link: ThreadPullRequestLink, branch: string) => {+ const key = normalizeThreadPullRequestKey(link);+ return `${key.host}/${key.repository}:${branch}`;+ };// Reused head names cannot identify a parent unambiguously.const byHead = new Map<string, ThreadPullRequestLink | null>();for (const link of remaining) {