feat(source-control): support Forgejo and Gitea with fj and tea #11436
Mergedmaria-rcksmerged 23 commits into
main fromrefs/pull/11436/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/server/src/pullRequest/forgejoPullRequestJson.ts lines 137 to 137OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +117,21 @@117+): PullRequestActor | null {118+ return user?.login119+ ? { login: user.login, name: user.full_name || null, avatarUrl: user.avatar_url || null }120+ : null;121+}122+123+function toIsoUtc(value: string): string {124+ return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso });125+}126+127+export function forgejoChangeRequest(pr: typeof ForgejoPullRequest.Type) {128+ return {129+ number: pr.number,130+ title: pr.title,131+ url: pr.html_url,132+ author: forgejoActor(pr.user),133+ headBranch: pr.head.ref,134+ baseBranch: pr.base.ref,135+ headRepositoryNameWithOwner: pr.head.repo?.full_name ?? null,136+ state: pr.merged ? "merged" : pr.state === "closed" ? "closed" : "open",137+ isDraft: pr.draft ?? false,@@ -43,3 +47,4 @@4347 }44484549 const urlMatch =50+ FORGEJO_PULL_REQUEST_URL_PATTERN.exec(normalizedInput) ??packages/shared/src/changeRequestUrl.ts line 112Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -87,3 +90,5 @@8790 switch (kind) {8891 case "github":8992 return `https://${host}/${repository}/pull/${number}`;93+ case "forgejo":94+ return `https://${host}/${repository}/pulls/${number}`;@@ -0,0 +256,21 @@256+ rebase: repo.allow_rebase ?? true,257+ },258+ } satisfies ProviderChangeRequestDetail;259+ }),260+ getViewerPermissions: getPermissions,261+ getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(262+ function* (input) {263+ const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(264+ [265+ page({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment),266+ page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),267+ page({ ...input, path: `${pullPath(input)}/commits` }, ForgejoCommit),268+ page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),269+ getViewer(input),270+ ],271+ { concurrency: 5 },272+ );273+ const reviewComments = yield* Effect.forEach(274+ reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),275+ (review) =>276+ readArray(
- apps/server/src/sourceControl/ForgejoCli.ts line 686Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +253,21 @@253+ let path = input.path.replace(/^\/+/, "");254+ if (input.repository && input.repository !== repository.repository) {255+ // Repository identities retain the server mount path; API routes do not.256+ const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;257+ if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {258+ path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;259+ }260+ }261+ const result = yield* execute({262+ cwd: input.cwd,263+ args: [264+ "api",265+ "--include",266+ "--login",267+ repository.login,268+ "--repo",269+ repository.repository,270+ "--method",271+ input.method ?? "GET",272+ ...(input.body === undefined ? [] : ["--data", "@-"]),273+ `${repository.baseUrl}/api/v1/${path}`,@@ -1134,3 +1134,8 @@11341134 "GitHub CLI (`gh`) is required to browse change requests on this host. Install it from https://cli.github.com/ and reload.",11351135 unauthenticated: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",11361136 },1137+ forgejo: {1138+ missing:1139+ "Install the official Gitea CLI (`tea` 0.16 or later) from https://gitea.com/gitea/tea to browse Forgejo pull requests.",1140+ unauthenticated:1141+ "Run `tea login add` on the T3 Code server to authenticate your Forgejo server.",packages/shared/src/changeRequestUrl.ts line 56OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -51,3 +51,6 @@5151 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);5252 return claim(host, match);5353 }54+ // Forgejo and Gitea use /pulls/ on arbitrary self-hosted domains.55+ const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);56+ if (forgejo) return claim(host, forgejo);
- packages/shared/src/changeRequestUrl.ts lines 54 to 54OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -51,2 +53,2 @@5153 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);5254 return claim(host, match);
- @@ -49,4 +51,10 @@4951 // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}5052 if (isHostOf(host, "github.com", "github")) {5153 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);52- return claim(host, match);54+ if (match) return claim(host, match);55+ }56+ // Forgejo and Gitea use /pulls/ on arbitrary self-hosted domains.57+ const forgejo = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(url.pathname);58+ if (forgejo) {59+ const link = claim(host, forgejo);60+ return link === null ? null : { ...link, authority: url.host.toLowerCase() };
- apps/web/src/lib/openPullRequestLink.ts line 54Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -30,6 +29,15 @@30- * Returns a click handler that opens a pull request URL in the system browser.31- *32- * Stops event propagation/default so activating the link does not also trigger33- * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a34- * toast when the local API is unavailable or the open fails.35- */29+/** Keep Forgejo servers on different HTTP ports separate when selecting a project. */30+function matchesChangeRequestAuthority(31+ project: EnvironmentProject,32+ link: ChangeRequestLink,33+): boolean {34+ if (link.authority === undefined) return true;35+ try {36+ const remote = new URL(project.repositoryIdentity?.locator.remoteUrl ?? "");37+ if (remote.protocol === "http:" || remote.protocol === "https:") {38+ return remote.host.toLowerCase() === link.authority;39+ }40+ } catch {41+ // SSH remotes do not specify the server's HTTP port; tea resolves the configured login.42+ }43+ return true;@@ -174,4 +197,5 @@174197 target !== null &&175198 linked.host === target.host &&176199 linked.repository === target.repository &&177- linked.number === target.number200+ linked.number === target.number &&201+ (target.authority === undefined || linked.authority === target.authority)
- @@ -89,3 +90,4 @@8990 host,9091 repository,9192 input.number,93+ project?.repositoryIdentity?.locator.remoteUrl,apps/server/src/pullRequest/PullRequestService.ts line 657OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -639,5 +649,9 @@639649 const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);640650 kind = provider === null ? kind : (refinedKinds.get(provider.baseUrl) ?? kind);641651 }642- const host = pullRequestHostOf(identity, kind);643- if (filter.host !== undefined && host !== filter.host.toLowerCase()) continue;652+ let host = pullRequestHostOf(identity, kind);653+ if (filter.host !== undefined && host !== filter.host.toLowerCase()) {654+ if (655+ kind !== "forgejo" ||656+ !isSshRemoteUrl(identity.locator.remoteUrl) ||657+ host !== filter.host.toLowerCase().replace(/:\d+$/u, "")
- apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx line 63Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -56,4 +57,7 @@5657 linking.mode === "multiple" && display !== "menu-item"5758 ? pullRequestEnvironment.linkedThreads({5859 environmentId,59- input: parsed === null ? reference : { ...reference, ...parsed },60+ input:61+ parsed === null62+ ? reference63+ : { ...reference, ...normalizeThreadPullRequestKey(parsed) },packages/shared/src/changeRequestUrl.ts lines 104 to 105Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -83,7 +91,15 @@8391 host: string,8492 repository: string,8593 number: number,94+ remoteUrl?: string,8695 ): string | null {8796 switch (kind) {8897 case "github":8998 return `https://${host}/${repository}/pull/${number}`;99+ case "forgejo": {100+ try {101+ const remote = new URL(remoteUrl ?? "");102+ if (103+ (remote.protocol === "http:" || remote.protocol === "https:") &&104+ (remote.hostname.toLowerCase() === host.toLowerCase() ||105+ remote.host.toLowerCase() === host.toLowerCase())
- apps/server/src/sourceControl/ForgejoSourceControlProvider.ts lines 109 to 109OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +89,21 @@89+ ),90+ );91+ const mapError = (operation: string, cwd: string) =>92+ Effect.mapError(93+ (cause: unknown) =>94+ new SourceControlProviderError({95+ provider: "forgejo",96+ operation,97+ cwd,98+ command: "tea",99+ detail: isForgejoCliError(cause) ? cause.detail : "Forgejo operation failed.",100+ cause,101+ }),102+ );103+ const getPull = Effect.fn("ForgejoSourceControlProvider.getPull")(function* (104+ input: Parameters<105+ SourceControlProvider.SourceControlProvider["Service"]["getChangeRequest"]106+ >[0],107+ ) {108+ const repo = yield* cli.resolveRepository(input);109+ const number = /(?:^#?|\/pulls\/)(\d+)\/?(?:[?#].*)?$/.exec(input.reference)?.[1];
- apps/server/src/pullRequest/ForgejoPullRequestProvider.ts line 244Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +217,21 @@217+ const countBefore = consumed;218+ for (const row of rows.slice(start)) {219+ if (consumed >= input.limit) break;220+ consumed++;221+ if (row) items.push(forgejoChangeRequest(row));222+ }223+ more = result.more || rows.length - start > consumed - countBefore;224+ }225+ return { items, truncated: more, continues: true, cursorAdvance: consumed };226+ },227+ ),228+ getChangeRequestSummary: (input) => getPull(input).pipe(Effect.map(forgejoChangeRequest)),229+ getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {230+ const [pr, repo, viewer] = yield* Effect.all(231+ [getPull(input), getRepo(input), getViewer(input)],232+ { concurrency: 3 },233+ );234+ const statuses = yield* page(235+ {236+ ...input,237+ path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
- @@ -0,0 +451,21 @@451+ remote = {452+ host: input.host.toLowerCase(),453+ hostname: input.host.split(":")[0] ?? input.host,454+ ssh: false,455+ path: remote?.path ?? "",456+ };457+ const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;458+ const fjLogins = yield* listLogins({459+ cwd: input.cwd,460+ command: "fj",461+ ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),462+ });463+ const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>464+ remote465+ ? matchForgejoLogin(logins, remote, remote.ssh ? input.host : undefined)466+ : (logins.find((item) => item.default === "true") ??467+ (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));468+ let login = selectLogin(fjLogins);469+ let command: "fj" | "tea" = "fj";470+ if (471+ !login &&@@ -0,0 +85,21 @@85+ (remote && ForgejoCli.matchForgejoLogin(logins, remote)) ||86+ logins.find((entry) => entry.default === "true") ||87+ logins[0];88+ const fj = yield* probeSourceControlProvider({89+ cwd,90+ process,91+ spec: {92+ ...discovery,93+ executable: "fj",94+ versionArgs: ["version"],95+ authArgs: login ? ["--host", login.url, "whoami"] : ["auth", "list"],96+ parseAuth: (result) =>97+ Result.isFailure(credentials)98+ ? providerAuth({99+ status: "unknown",100+ detail: "Could not read fj authentication storage. Authenticate again with fj.",101+ })102+ : login && result.exitCode === 0103+ ? providerAuth({104+ status: "authenticated",105+ account: login.user,apps/web/src/components/pullRequest/pullRequestDetail.logic.ts lines 114 to 114OutdatedResolvedby maria-rcks@@ -110,3 +110,5 @@110110 return `gh pr checkout ${number}`;111111 case "gitlab":112112 return `glab mr checkout ${number}`;113+ case "forgejo":114+ return `git fetch origin refs/pull/${number}/head && git checkout -b pulls/${number} FETCH_HEAD`;
maria-rcks changed the title
- apps/web/src/components/pullRequest/pullRequestDetail.logic.ts line 114OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -110,3 +110,5 @@110110 return `gh pr checkout ${number}`;111111 case "gitlab":112112 return `glab mr checkout ${number}`;113+ case "forgejo":114+ return `git fetch origin refs/pull/${number}/head && git checkout -B pulls/${number} FETCH_HEAD`;apps/server/src/sourceControl/ForgejoCli.ts line 527OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +507,21 @@507+ if (508+ input.host &&509+ !remote?.ssh &&510+ remote?.host !== input.host.toLowerCase() &&511+ remote?.hostname !== input.host.toLowerCase()512+ )513+ remote = {514+ host: input.host.toLowerCase(),515+ hostname: input.host.split(":")[0] ?? input.host,516+ ssh: false,517+ path: remote?.path ?? "",518+ };519+ const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;520+ const fjLogins = yield* listLogins({521+ cwd: input.cwd,522+ command: "fj",523+ ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),524+ });525+ const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>526+ remote527+ ? matchForgejoLogin(logins, remote, remote.ssh ? input.host : undefined)
- apps/server/src/pullRequest/ForgejoPullRequestProvider.ts lines 127 to 127OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+ read(input, Schema.NullOr(Schema.Array(schema))).pipe(Effect.map((rows) => rows ?? []));108+ const readPage = Effect.fn("ForgejoPullRequestProvider.readPage")(function* <A>(109+ input: ForgejoApiInput,110+ schema: Schema.Codec<A, unknown, never, never>,111+ index: number,112+ ) {113+ const result = yield* request({114+ ...input,115+ path: `${input.path}${input.path.includes("?") ? "&" : "?"}limit=50&page=${index}`,116+ });117+ if (result.stdoutTruncated)118+ return yield* failure(input.path, "Forgejo response exceeded the output limit.");119+ const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);120+ if (Result.isFailure(decoded))121+ return yield* failure(input.path, "Forgejo returned an invalid response.", decoded.failure);122+ const rows = decoded.success ?? [];123+ const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];124+ return {125+ rows,126+ more:127+ rows.length > 0 && (links === undefined ? rows.length === 50 : /rel="?next"?/i.test(links)),
- apps/server/src/pullRequest/ForgejoPullRequestProvider.ts lines 298 to 298OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +278,21 @@278+ items: items.slice(0, 500),279+ truncated: items.length > 500,280+ })),281+ ),282+ page({ ...input, path: `${pullPath(input)}/reviews` }, ForgejoReview),283+ page({ ...input, path: `${pullPath(input)}/commits` }, ForgejoCommit),284+ page({ ...input, path: `${issuePath(input)}/reactions` }, ForgejoReaction),285+ getViewer(input),286+ ],287+ { concurrency: 5 },288+ );289+ const reviewComments = yield* Effect.forEach(290+ reviews.items.filter((review) => review.comments_count > 0 && review.state !== "PENDING"),291+ (review) =>292+ readArray(293+ { ...input, path: `${pullPath(input)}/reviews/${review.id}/comments` },294+ ForgejoReviewComment,295+ ),296+ { concurrency: 4 },297+ );298+ const inline = reviewComments.flat();
- @@ -0,0 +256,21 @@256+ checks: forgejoChecks(statuses.items),257+ baseComparison: !pr.merge_base258+ ? "unknown"259+ : pr.merge_base === pr.base.sha260+ ? "up-to-date"261+ : "behind",262+ viewerPermissions: permissions(repo, pr, viewer),263+ mergeCapabilities: {264+ merge: repo.allow_merge_commits ?? true,265+ squash: repo.allow_squash_merge ?? true,266+ rebase: repo.allow_rebase ?? true,267+ },268+ } satisfies ProviderChangeRequestDetail;269+ }),270+ getViewerPermissions: getPermissions,271+ getChangeRequestActivity: Effect.fn("ForgejoPullRequestProvider.getChangeRequestActivity")(272+ function* (input) {273+ const [comments, reviews, commits, reactions, viewer] = yield* Effect.all(274+ [275+ // Issue comments ignore page/limit; fetch this unpaginated endpoint once.276+ readArray({ ...input, path: `${issuePath(input)}/comments` }, ForgejoComment).pipe(
- apps/server/src/sourceControl/ForgejoCli.ts lines 491 to 491OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +471,21 @@471+ command: "fj",472+ cwd: input.cwd,473+ reason: "invalid-response",474+ detail: "Forgejo returned an invalid account response.",475+ });476+ return user.success.login;477+ });478+479+ const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (480+ input: ForgejoRepositoryInput,481+ hostOnly = false,482+ ) {483+ const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;484+ let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(485+ (value) => value && parseForgejoRemote(value),486+ );487+ let remote =488+ referenceRemote ??489+ (input.repository ? parseForgejoRemote(input.repository) : null) ??490+ (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);491+ if (!remote && (!input.repository || input.host) && !(hostOnly && input.host)) {
- apps/server/src/sourceControl/ForgejoCli.ts lines 538 to 538Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +498,21 @@498+ cwd: input.cwd,499+ allowNonZeroExit: true,500+ })501+ .pipe(502+ Effect.mapError(503+ (cause) =>504+ new ForgejoCliError({505+ command: "tea",506+ cwd: input.cwd,507+ detail: "Could not resolve the Forgejo repository remote.",508+ cause,509+ }),510+ ),511+ );512+ remoteUrl = result.stdout.trim();513+ remote = parseForgejoRemote(remoteUrl);514+ }515+ if (516+ input.host &&517+ !remote?.ssh &&518+ remote?.host !== input.host.toLowerCase() &&
maria-rcks merged this6fd68f5
maria-rcks closed this
Sign in to join this conversation.



















Bugbot is paused — on-demand spend limit reached
Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.
A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.