Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(pull-requests): protect provider API budgets (#6466)
Bilal Bakrba46f922a271
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 36f348d63..6b35f0d54 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -56,6 +56,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,+ [WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,[WS_METHODS.pullRequestsUpdate]: AuthOrchestrationOperateScope,diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.tsindex 5607b0cd4..631fee971 100644--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts@@ -4,6 +4,7 @@ import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3timport * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";import {PullRequestProviderError,+ type PullRequestProviderFailure,type ProviderChangeRequest,type ProviderChangeRequestActivity,type ProviderChangeRequestDetail,@@ -64,12 +65,13 @@ export const AZURE_DEVOPS_VIEWER_PERMISSIONS: PullRequestViewerPermissions = {};/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */-function reasonFor(+export function azureDevOpsProviderFailure(error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError,-): PullRequestProviderError["reason"] {- if (error._tag === "AzureDevOpsCliUnavailableError") return "missing-tool";- if (error._tag === "AzureDevOpsCliAuthenticationError") return "unauthenticated";- return "failed";+): PullRequestProviderFailure {+ if (error._tag === "AzureDevOpsCliUnavailableError") return { reason: "missing-tool" };+ if (error._tag === "AzureDevOpsCliAuthenticationError") return { reason: "unauthenticated" };+ if (error._tag === "AzureDevOpsCliRateLimitError") return { reason: "rate-limited" };+ return { reason: "failed" };}function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequest {@@ -103,7 +105,7 @@ export const make = Effect.gen(function* () {new PullRequestProviderError({provider: "azure-devops",operation,- reason: reasonFor(error),+ ...azureDevOpsProviderFailure(error),detail: error.detail,cause: error,});diff --git a/apps/server/src/pullRequest/BitbucketPullRequestProvider.test.ts b/apps/server/src/pullRequest/BitbucketPullRequestProvider.test.tsindex 7e57d6c77..db06a360a 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestProvider.test.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestProvider.test.ts@@ -2,11 +2,11 @@ import { describe, expect, it } from "vite-plus/test";import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";import {- bitbucketErrorReason,+ bitbucketProviderFailure,bitbucketViewerPermissions,} from "./BitbucketPullRequestProvider.ts";-describe("bitbucketErrorReason", () => {+describe("bitbucketProviderFailure", () => {it("treats only an HTTP 401 as unusable credentials", () => {const responseError = (status: number) =>new BitbucketApi.BitbucketResponseError({@@ -15,8 +15,8 @@ describe("bitbucketErrorReason", () => {responseBodyLength: 0,});- expect(bitbucketErrorReason(responseError(401))).toBe("unauthenticated");- expect(bitbucketErrorReason(responseError(403))).toBe("failed");+ expect(bitbucketProviderFailure(responseError(401)).reason).toBe("unauthenticated");+ expect(bitbucketProviderFailure(responseError(403)).reason).toBe("failed");});});diff --git a/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts b/apps/server/src/pullRequest/BitbucketPullRequestProvider.tsindex 00e558588..e7a9a6b6d 100644--- a/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts+++ b/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts@@ -4,6 +4,7 @@ import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3timport * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";import {PullRequestProviderError,+ type PullRequestProviderFailure,type ProviderChangeRequest,type ProviderChangeRequestActivity,type ProviderChangeRequestDetail,@@ -59,15 +60,21 @@ export function bitbucketViewerPermissions(input: {}/** The failures that mean the credentials are the problem, rather than one request. */-export function bitbucketErrorReason(+export function bitbucketProviderFailure(error: BitbucketPullRequestApi.BitbucketPullRequestApiError,-): PullRequestProviderError["reason"] {+): PullRequestProviderFailure {// Bitbucket is read over HTTP with credentials from the environment, so there is no tool to be// missing: unusable always means the credentials are absent or refused.if (error._tag === "BitbucketResponseError" && error.status === 401) {- return "unauthenticated";+ return { reason: "unauthenticated" };}- return "failed";+ if (error._tag === "BitbucketResponseError" && error.status === 429) {+ return {+ reason: "rate-limited",+ ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),+ };+ }+ return { reason: "failed" };}function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {@@ -100,7 +107,7 @@ export const make = Effect.gen(function* () {new PullRequestProviderError({provider: "bitbucket",operation,- reason: bitbucketErrorReason(error),+ ...bitbucketProviderFailure(error),// Every Bitbucket failure states its own fact; this names the operation around it, so// the two do not stack into "failed in x: failed in y: ...".detail: error.detail,diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.tsindex d1af03db9..33d0d120c 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts@@ -1,9 +1,11 @@import { afterEach, assert, expect, it, vi } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as TestClock from "effect/testing/TestClock";import { ChildProcessSpawner } from "effect/unstable/process";import * as GitHubCli from "../sourceControl/GitHubCli.ts";+import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";import { BASE_COMPARISON_GRAPHQL_QUERY } from "./gitHubPullRequestJson.ts";@@ -16,6 +18,7 @@ const layer = it.layer(execute: mockedExecute,}),),+ Layer.provide(GitHubGraphQlBudget.layer),),);@@ -107,9 +110,16 @@ function threadCommentsPage(ids: ReadonlyArray<string>,endCursor: string | null,totalCount: number,+ pullRequestId = "PR_7",): string {return JSON.stringify({- data: { node: { comments: threadComments(ids, endCursor, totalCount) } },+ data: {+ repository: { pullRequest: { id: "PR_7" } },+ node: {+ pullRequest: { id: pullRequestId },+ comments: threadComments(ids, endCursor, totalCount),+ },+ },});}@@ -1601,6 +1611,41 @@ layer("GitHubPullRequestCli.layer", (it) => {}),);+ it.effect("accounts for the avatar lookup in the GraphQL budget", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ data: {+ nodes: [{ login: "octocat", avatarUrl: "https://avatars/octocat" }],+ rateLimit: {+ cost: 1,+ limit: 5_000,+ remaining: 4_999,+ resetAt: "2099-08-13T14:00:00Z",+ },+ },+ }),+ ),+ ),+ );+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ const avatars = yield* cli.listActorAvatars({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ ids: ["MDQ6VXNlcjE="],+ });++ expect(callAt(0).args).toContain("ids[]=MDQ6VXNlcjE=");+ expect(callAt(0).args.at(-1)).toContain("rateLimit { cost limit remaining resetAt }");+ expect(avatars.get("octocat")).toBe("https://avatars/octocat");+ }),+ );+it.effect("fails when the authenticated account has no login", () =>Effect.gen(function* () {mockedExecute.mockReturnValueOnce(Effect.succeed(output(" ")));@@ -2144,7 +2189,7 @@ layer("GitHubPullRequestCli.layer", (it) => {}),);- it.effect("finishes a thread longer than one page from the thread's own node", () =>+ it.effect("leaves a long thread paged until the reader asks for more", () =>Effect.gen(function* () {mockedExecute.mockReturnValueOnce(Effect.succeed(@@ -2156,22 +2201,71 @@ layer("GitHubPullRequestCli.layer", (it) => {),),);+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ const conversation = yield* cli.listReviewThreadComments({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ });++ assert.strictEqual(mockedExecute.mock.calls.length, 1);+ expect(conversation.comments.map((comment) => comment.id)).toEqual(["c1"]);+ expect(conversation.reviewThreads[0]).toMatchObject({+ commentCount: 3,+ nextCommentsCursor: "Y3Vyc29yOjI",+ });+ assert.isTrue(conversation.truncated);+ }),+ );++ it.effect("reads one requested page from a review thread cursor", () =>+ Effect.gen(function* () {mockedExecute.mockReturnValueOnce(Effect.succeed(output(threadCommentsPage(["c2", "c3"], null, 3))),);const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;- const conversation = yield* cli.listReviewThreadComments({+ const page = yield* cli.getReviewThreadComments({cwd: "/w",repository: "acme/web",host: "github.com",number: 7,+ threadId: "PRRT_1",+ cursor: "Y3Vyc29yOjI",});- expect(callAt(1).args).toContain("threadId=PRRT_1");- expect(conversation.comments.map((comment) => comment.id)).toEqual(["c1", "c2", "c3"]);- // GitHub's own count, which is what the page shows however much of it was read.- assert.strictEqual(conversation.commentCount, 3);+ expect(callAt(0).args).toContain("owner=acme");+ expect(callAt(0).args).toContain("name=web");+ expect(callAt(0).args).toContain("number=7");+ expect(callAt(0).args).toContain("threadId=PRRT_1");+ expect(callAt(0).args).toContain("cursor=Y3Vyc29yOjI");+ assert.strictEqual(mockedExecute.mock.calls.length, 1);+ expect(page.comments.map((comment) => comment.id)).toEqual(["c2", "c3"]);+ expect(page.nextCursor).toBeNull();+ }),+ );++ it.effect("refuses a review thread from another pull request", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValueOnce(+ Effect.succeed(output(threadCommentsPage(["foreign"], null, 1, "PR_8"))),+ );+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ const error = yield* Effect.flip(+ cli.getReviewThreadComments({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ threadId: "PRRT_FOREIGN",+ cursor: "Y3Vyc29yOjI",+ }),+ );++ assert.strictEqual(error._tag, "GitHubSubjectScopeError");}),);@@ -2242,7 +2336,7 @@ layer("GitHubPullRequestCli.layer", (it) => {// The tuples are flattened straight into argv, so a variable without its flag is a// positional argument gh refuses outright.const args = callAt(0).args;- expect(args).toEqual([+ expect(args.slice(0, -2)).toEqual(["api","graphql","--hostname",@@ -2255,10 +2349,122 @@ layer("GitHubPullRequestCli.layer", (it) => {"number=7","-f","headRef=fork:feat/page",- "-f",- `query=${BASE_COMPARISON_GRAPHQL_QUERY}`,]);expect(comparison).toEqual({ behindBy: 4, viewerCanUpdate: true });+ expect(args.at(-2)).toBe("-f");+ expect(args.at(-1)).toContain(`query=${BASE_COMPARISON_GRAPHQL_QUERY.slice(0, -2)}`);+ }),+ );++ it.effect("stops GraphQL reads at the protected reserve until reset", () =>+ Effect.gen(function* () {+ mockedExecute.mockReturnValue(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ data: {+ repository: {+ pullRequest: {+ viewerCanUpdateBranch: true,+ baseRef: { compare: { behindBy: 4 } },+ },+ },+ rateLimit: {+ cost: 1,+ limit: 5_000,+ remaining: 500,+ resetAt: "2099-08-13T14:00:00Z",+ },+ },+ }),+ ),+ ),+ );+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;+ const input = {+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ headRef: "fork:feat/page",+ } as const;++ yield* cli.getPullRequestBaseComparison(input);+ expect(callAt(0).args.at(-1)).toContain("rateLimit { cost limit remaining resetAt }");++ const error = yield* Effect.flip(cli.getPullRequestBaseComparison(input));++ assert.strictEqual(error._tag, "SourceControlRateLimitPausedError");+ if (error._tag !== "SourceControlRateLimitPausedError") return;+ assert.strictEqual(error.host, "github.com");+ assert.strictEqual(error.retryAt, Date.parse("2099-08-13T14:00:00Z"));+ assert.strictEqual(mockedExecute.mock.calls.length, 1);+ yield* TestClock.setTime(Date.parse("2100-01-01T00:00:00Z"));+ }),+ );++ it.effect("lets an interactive permission read use the protected reserve", () =>+ Effect.gen(function* () {+ mockedExecute+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ data: {+ repository: {+ pullRequest: {+ viewerCanUpdateBranch: true,+ baseRef: { compare: { behindBy: 4 } },+ },+ },+ rateLimit: {+ cost: 1,+ limit: 5_000,+ remaining: 500,+ resetAt: "2099-08-13T14:00:00Z",+ },+ },+ }),+ ),+ ),+ )+ .mockReturnValueOnce(+ Effect.succeed(+ output(+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ JSON.stringify({+ data: {+ repository: {+ viewerPermission: "READ",+ pullRequest: { viewerCanUpdate: true, viewerDidAuthor: true },+ },+ },+ }),+ ),+ ),+ );+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;++ yield* cli.getPullRequestBaseComparison({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ headRef: "fork:feat/page",+ });+ const access = yield* cli.getViewerAccess({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ allowReserve: true,+ });++ assert.strictEqual(mockedExecute.mock.calls.length, 2);+ expect(access).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });+ yield* TestClock.setTime(Date.parse("2100-01-01T00:00:00Z"));}),);diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.tsindex 27402c211..6272737d4 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts@@ -18,11 +18,13 @@ import {type PullRequestReviewVerdict,type PullRequestReviewerCandidateList,type PullRequestReviewerKind,- type PullRequestThreadComment,+ type PullRequestThreadCommentsResult,type PullRequestUpdateMethod,} from "@t3tools/contracts";import * as GitHubCli from "../sourceControl/GitHubCli.ts";+import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";+import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";import {ACTOR_AVATARS_GRAPHQL_QUERY,ADD_REACTION_GRAPHQL_MUTATION,@@ -247,6 +249,7 @@ export type GitHubPullRequestCliError =| GitHubDiffFileContentsUnavailableError| GitHubRepositorySelectorError| GitHubSubjectScopeError+ | SourceControlRateLimit.SourceControlRateLimitPausedError| GitHubViewerLoginUnavailableError;/** A large pull request can produce a multi-megabyte patch; past this it is truncated. */@@ -268,15 +271,6 @@ const DIFF_FILES_PAGE_SIZE = 100;*/const REVIEW_THREAD_PAGES = 10;-/**- * And pages of one thread's own comments, for the rare thread longer than a single page. A- * thousand replies under one line is already a conversation nobody finishes reading.- */-const REVIEW_THREAD_COMMENT_PAGES = 10;--/** How many over-long threads are finished at once, so a wide conversation is not read serially. */-const REVIEW_THREAD_CONCURRENCY = 4;-export interface GitHubPullRequestListBatch {readonly items: ReadonlyArray<GitHubPullRequestListItem>;readonly truncated: boolean;@@ -385,6 +379,8 @@ export class GitHubPullRequestCli extends Context.Service<readonly number: number;/** Qualified `owner:branch`, which is the only form a fork's head resolves under. */readonly headRef: string;+ /** Manual action checks may use the quota held back from automatic reads. */+ readonly allowReserve?: boolean | undefined;}) => Effect.Effect<GitHubBaseComparison, GitHubPullRequestCliError>;readonly getPullRequestActivity: (input: {@@ -434,6 +430,15 @@ export class GitHubPullRequestCli extends Context.Service<readonly ids: ReadonlyArray<string>;}) => Effect.Effect<ReadonlyMap<string, string>, GitHubPullRequestCliError>;+ readonly getReviewThreadComments: (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly number: number;+ readonly threadId: string;+ readonly cursor: string;+ }) => Effect.Effect<PullRequestThreadCommentsResult, GitHubPullRequestCliError>;+/** One `gh repo view`, which answers what the repository allows and where the viewer stands. */readonly getRepositoryAccess: (input: {readonly cwd: string;@@ -447,6 +452,8 @@ export class GitHubPullRequestCli extends Context.Service<readonly repository: string;readonly host: string;readonly number: number;+ /** Manual action checks may use the quota held back from automatic reads. */+ readonly allowReserve?: boolean | undefined;}) => Effect.Effect<GitHubViewerAccess, GitHubPullRequestCliError>;/** Who this pull request may be sent to, and who it has already been sent to. */@@ -824,6 +831,7 @@ function actionArgs(export const make = Effect.gen(function* () {const github = yield* GitHubCli.GitHubCli;+ const graphQlBudget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;/*** The pull request's own node id, which is what a mutation against the pull request itself is@@ -841,6 +849,7 @@ export const make = Effect.gen(function* () {cwd: input.cwd,host: input.host,operation: input.operation,+ allowReserve: true,variables: [["-f", `owner=${owner}`],["-f", `name=${name}`],@@ -870,6 +879,7 @@ export const make = Effect.gen(function* () {cwd: input.cwd,host: input.host,operation: input.operation,+ allowReserve: true,variables: [["-f", `owner=${owner}`],["-f", `name=${name}`],@@ -916,6 +926,7 @@ export const make = Effect.gen(function* () {readonly cwd: string;readonly host: string;readonly operation: string;+ readonly allowReserve?: boolean | undefined;/** Variables as `-f` flags, for values this module composed itself. */readonly variables?: ReadonlyArray<readonly [string, string]>;/**@@ -926,32 +937,40 @@ export const make = Effect.gen(function* () {readonly privateVariables?: Readonly<Record<string, string>>;readonly query: string;readonly decode: (raw: string) => Result.Result<A, unknown>;- }): Effect.Effect<A, GitHubPullRequestCliError> =>- github- .execute(- input.privateVariables === undefined- ? {- cwd: input.cwd,- args: [- "api",- "graphql",- "--hostname",- input.host,- ...(input.variables ?? []).flat(),- "-f",- `query=${input.query}`,- ],- }- : {- cwd: input.cwd,- args: ["api", "graphql", "--hostname", input.host, "--input", "-"],- stdin: encodeGraphQlRequestJson({- query: input.query,- variables: input.privateVariables,- }),- },+ }): Effect.Effect<A, GitHubPullRequestCliError> => {+ return graphQlBudget+ .query(+ input.host,+ input.query,+ input.allowReserve === true ? { allowReserve: true } : undefined,).pipe(+ Effect.flatMap((query) =>+ github.execute(+ input.privateVariables === undefined+ ? {+ cwd: input.cwd,+ args: [+ "api",+ "graphql",+ "--hostname",+ input.host,+ ...(input.variables ?? []).flat(),+ "-f",+ `query=${query}`,+ ],+ }+ : {+ cwd: input.cwd,+ args: ["api", "graphql", "--hostname", input.host, "--input", "-"],+ stdin: encodeGraphQlRequestJson({+ query,+ variables: input.privateVariables,+ }),+ },+ ),+ ),+ Effect.tap((result) => graphQlBudget.observe(input.host, result.stdout)),Effect.flatMap((result) => {const decoded = input.decode(result.stdout.trim());return Result.isSuccess(decoded)@@ -966,6 +985,7 @@ export const make = Effect.gen(function* () {);}),);+ };/*** One page of the patch, read from the files API. GitHub refuses `pr diff` outright past 300@@ -1341,6 +1361,7 @@ export const make = Effect.gen(function* () {cwd: input.cwd,host: input.host,operation: "getPullRequestBaseComparison",+ ...(input.allowReserve === true ? { allowReserve: true } : {}),variables: [["-f", `owner=${owner}`],["-f", `name=${name}`],@@ -1438,6 +1459,36 @@ export const make = Effect.gen(function* () {getPullRequestDiffFileContents,+ getReviewThreadComments: (input) => {+ const { owner, name } = parseRepositorySelector(input.repository);+ return graphqlRead({+ cwd: input.cwd,+ host: input.host,+ operation: "getReviewThreadComments",+ variables: [+ ["-f", `owner=${owner}`],+ ["-f", `name=${name}`],+ ["-F", `number=${input.number}`],+ ["-f", `threadId=${input.threadId}`],+ cursorVariable(input.cursor),+ ],+ query: REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,+ decode: decodeReviewThreadCommentsJson,+ }).pipe(+ Effect.flatMap(({ belongsToPullRequest, comments, nextCursor }) =>+ belongsToPullRequest+ ? Effect.succeed({ comments, nextCursor })+ : Effect.fail(+ new GitHubSubjectScopeError({+ command: "gh",+ cwd: input.cwd,+ operation: "getReviewThreadComments",+ }),+ ),+ ),+ );+ },+listReviewThreadComments: (input) =>Effect.gen(function* () {const { owner, name } = parseRepositorySelector(input.repository);@@ -1457,25 +1508,6 @@ export const make = Effect.gen(function* () {query: REVIEW_THREADS_GRAPHQL_QUERY,decode: decodeReviewThreadsJson,});- const commentPage = (- threadId: string,- cursor: string,- ): Effect.Effect<- {- readonly comments: ReadonlyArray<PullRequestThreadComment>;- readonly nextCursor: string | null;- },- GitHubPullRequestCliError- > =>- graphqlRead({- cwd: input.cwd,- host: input.host,- operation: "listReviewThreadComments",- variables: [["-f", `threadId=${threadId}`], cursorVariable(cursor)],- query: REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,- decode: decodeReviewThreadCommentsJson,- });-const entries: GitHubReviewThreadEntry[] = [];const avatarsByLogin = new Map<string, string>();const commitStats = new Map<@@ -1540,39 +1572,21 @@ export const make = Effect.gen(function* () {dismissalPage += 1;}- // Only the threads GitHub said were unfinished cost a request; the rest arrived whole- // with the page they were listed on.- const finished = yield* Effect.forEach(- entries,- (entry) =>- Effect.gen(function* () {- const comments = [...entry.thread.comments];- let commentCursor = entry.nextCommentCursor;- let commentPageCount = 0;- while (commentCursor !== null && commentPageCount < REVIEW_THREAD_COMMENT_PAGES) {- const read = yield* commentPage(entry.thread.id, commentCursor);- comments.push(...read.comments);- commentCursor = read.nextCursor;- commentPageCount += 1;- }- return {- thread: { ...entry.thread, comments },- commentCount: entry.commentCount,- truncated: commentCursor !== null,- };- }),- { concurrency: REVIEW_THREAD_CONCURRENCY },- );-- const reviewThreads = finished.map((entry) => entry.thread);+ const reviewThreads = entries.map((entry) => ({+ ...entry.thread,+ commentCount: entry.commentCount,+ ...(entry.nextCommentCursor === null+ ? {}+ : { nextCommentsCursor: entry.nextCommentCursor }),+ }));return {comments: reviewThreadConversation(reviewThreads),dismissalsByReviewId,reviewThreads,// GitHub's own count of each thread, so the number the page shows is the host's even// where a bound kept some of the words on GitHub.- commentCount: finished.reduce((total, entry) => total + entry.commentCount, 0),- truncated: cursor !== null || finished.some((entry) => entry.truncated),+ commentCount: entries.reduce((total, entry) => total + entry.commentCount, 0),+ truncated: cursor !== null || entries.some((entry) => entry.nextCommentCursor !== null),reactions,reactionsById,reviewers,@@ -1587,34 +1601,14 @@ export const make = Effect.gen(function* () {if (input.ids.length === 0) {return Effect.succeed(new Map<string, string>());}- return github- .execute({- cwd: input.cwd,- args: [- "api",- "graphql",- "--hostname",- input.host,- ...input.ids.flatMap((id) => ["-f", `ids[]=${id}`]),- "-f",- `query=${ACTOR_AVATARS_GRAPHQL_QUERY}`,- ],- })- .pipe(- Effect.flatMap((result) => {- const decoded = decodeActorAvatarsJson(result.stdout.trim());- return Result.isSuccess(decoded)- ? Effect.succeed(decoded.success)- : Effect.fail(- new GitHubPullRequestReadError({- command: "gh",- cwd: input.cwd,- operation: "listActorAvatars",- cause: decoded.failure,- }),- );- }),- );+ return graphqlRead({+ cwd: input.cwd,+ host: input.host,+ operation: "listActorAvatars",+ variables: input.ids.map((id) => ["-f", `ids[]=${id}`]),+ query: ACTOR_AVATARS_GRAPHQL_QUERY,+ decode: decodeActorAvatarsJson,+ });},getRepositoryAccess: (input) =>@@ -1651,6 +1645,7 @@ export const make = Effect.gen(function* () {cwd: input.cwd,host: input.host,operation: "getViewerAccess",+ ...(input.allowReserve === true ? { allowReserve: true } : {}),variables: [["-f", `owner=${owner}`],["-f", `name=${name}`],@@ -1667,6 +1662,7 @@ export const make = Effect.gen(function* () {cwd: input.cwd,host: input.host,operation: "listReviewerCandidates",+ allowReserve: true,variables: [["-f", `owner=${owner}`],["-f", `name=${name}`],diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.tsindex 13098ce38..2555c05dc 100644--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts@@ -177,6 +177,39 @@ describe("getViewerPermissions", () => {),);+ it.effect("uses the GraphQL reserve for manual permission checks", () => {+ let viewerAllowReserve: boolean | undefined;+ let comparisonAllowReserve: boolean | undefined;+ return Effect.gen(function* () {+ const provider = yield* make;+ yield* provider.getViewerPermissions({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ });++ expect(viewerAllowReserve).toBe(true);+ expect(comparisonAllowReserve).toBe(true);+ }).pipe(+ Effect.provide(+ Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({+ getPullRequestDetail: () => Effect.succeed(openDetail),+ getPullRequestBaseComparison: (input) =>+ Effect.sync(() => {+ comparisonAllowReserve = input.allowReserve;+ return { behindBy: 3, viewerCanUpdate: true };+ }),+ getViewerAccess: (input) =>+ Effect.sync(() => {+ viewerAllowReserve = input.allowReserve;+ return { canWrite: true, canUpdate: true, didAuthor: false };+ }),+ }),+ ),+ );+ });+it.effect("withholds update-branch when the comparison cannot be read", () =>Effect.gen(function* () {const provider = yield* make;diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.tsindex 57d18e8ab..cc097c30c 100644--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts@@ -9,6 +9,7 @@ import type {import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";import {PullRequestProviderError,+ type PullRequestProviderFailure,type ProviderChangeRequestActivity,type ProviderChangeRequestDetail,type PullRequestProviderApi,@@ -82,12 +83,16 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest}/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */-function reasonFor(+export function gitHubProviderFailure(error: GitHubPullRequestCli.GitHubPullRequestCliError,-): PullRequestProviderError["reason"] {- if (error._tag === "GitHubCliUnavailableError") return "missing-tool";- if (error._tag === "GitHubCliAuthenticationError") return "unauthenticated";- return "failed";+): PullRequestProviderFailure {+ if (error._tag === "GitHubCliUnavailableError") return { reason: "missing-tool" };+ if (error._tag === "GitHubCliAuthenticationError") return { reason: "unauthenticated" };+ if (error._tag === "GitHubCliRateLimitError") return { reason: "rate-limited" };+ if (error._tag === "SourceControlRateLimitPausedError") {+ return { reason: "rate-limited", retryAt: error.retryAt };+ }+ return { reason: "failed" };}/**@@ -128,7 +133,7 @@ export const make = Effect.gen(function* () {new PullRequestProviderError({provider: "github",operation,- reason: reasonFor(error),+ ...gitHubProviderFailure(error),detail: error.detail,cause: error,});@@ -355,10 +360,13 @@ export const make = Effect.gen(function* () {),),+ getReviewThreadComments: (input) =>+ cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),+getViewerPermissions: (input) =>Effect.all([- cli.getViewerAccess(input),+ cli.getViewerAccess({ ...input, allowReserve: true }),// Whether this viewer may update the branch is only on the comparison, and the// comparison only resolves through the head ref the detail carries. A failure here// withholds that one action rather than the whole answer, the way the detail path@@ -371,6 +379,7 @@ export const make = Effect.gen(function* () {.getPullRequestBaseComparison({...input,headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,+ allowReserve: true,}).pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),),diff --git a/apps/server/src/pullRequest/GitLabPullRequestProvider.ts b/apps/server/src/pullRequest/GitLabPullRequestProvider.tsindex 07edf08e5..701ef53b0 100644--- a/apps/server/src/pullRequest/GitLabPullRequestProvider.ts+++ b/apps/server/src/pullRequest/GitLabPullRequestProvider.ts@@ -8,6 +8,7 @@ import type {import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";import {PullRequestProviderError,+ type PullRequestProviderFailure,type ProviderChangeRequestActivity,type ProviderChangeRequestDetail,type PullRequestProviderApi,@@ -90,12 +91,13 @@ export function gitLabViewerPermissions(input: {}/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */-function reasonFor(+export function gitLabProviderFailure(error: GitLabPullRequestCli.GitLabPullRequestCliError,-): PullRequestProviderError["reason"] {- if (error._tag === "GitLabCliUnavailableError") return "missing-tool";- if (error._tag === "GitLabCliAuthenticationError") return "unauthenticated";- return "failed";+): PullRequestProviderFailure {+ if (error._tag === "GitLabCliUnavailableError") return { reason: "missing-tool" };+ if (error._tag === "GitLabCliAuthenticationError") return { reason: "unauthenticated" };+ if (error._tag === "GitLabCliRateLimitError") return { reason: "rate-limited" };+ return { reason: "failed" };}export const make = Effect.gen(function* () {@@ -105,7 +107,7 @@ export const make = Effect.gen(function* () {new PullRequestProviderError({provider: "gitlab",operation,- reason: reasonFor(error),+ ...gitLabProviderFailure(error),detail: error.detail,cause: error,});diff --git a/apps/server/src/pullRequest/PullRequestProvider.ts b/apps/server/src/pullRequest/PullRequestProvider.tsindex 6356d593b..644f3552c 100644--- a/apps/server/src/pullRequest/PullRequestProvider.ts+++ b/apps/server/src/pullRequest/PullRequestProvider.ts@@ -22,6 +22,7 @@ import type {PullRequestReviewCommentDraft,PullRequestReviewDecision,PullRequestReviewThread,+ PullRequestThreadCommentsResult,PullRequestReviewVerdict,PullRequestReviewerCandidateList,PullRequestReviewerKind,@@ -37,15 +38,17 @@ import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t* without knowing which CLI or API produced it.** `reason` is the part the service acts on: a missing or unauthenticated tool disables the- * provider for the whole workspace, while anything else is specific to the request.+ * provider for the whole workspace, a rate limit pauses its host, and anything else is specific+ * to the request.*/export class PullRequestProviderError extends Schema.TaggedErrorClass<PullRequestProviderError>()("PullRequestProviderError",{provider: SourceControlProviderKindSchema,operation: Schema.String,- reason: Schema.Literals(["missing-tool", "unauthenticated", "failed"]),+ reason: Schema.Literals(["missing-tool", "unauthenticated", "rate-limited", "failed"]),detail: Schema.String,+ retryAt: Schema.optional(Schema.Number),cause: Schema.optional(Schema.Defect()),},) {@@ -54,6 +57,11 @@ export class PullRequestProviderError extends Schema.TaggedErrorClass<PullReques}}+export interface PullRequestProviderFailure {+ readonly reason: PullRequestProviderError["reason"];+ readonly retryAt?: number | undefined;+}+/** A change request as the provider sees it, before the service attaches project context. */export interface ProviderChangeRequest {readonly number: number;@@ -297,6 +305,15 @@ export interface PullRequestProviderApi {input: ProviderRepositoryRef & { readonly number: number },) => Effect.Effect<ProviderChangeRequestActivity, PullRequestProviderError>;+ /** One explicit page after a reader asks to continue an unfinished review thread. */+ readonly getReviewThreadComments?: (+ input: ProviderRepositoryRef & {+ readonly number: number;+ readonly threadId: string;+ readonly cursor: string;+ },+ ) => Effect.Effect<PullRequestThreadCommentsResult, PullRequestProviderError>;+/*** The same answer `getChangeRequest` carries, on its own. Asked before anything is written, so* a request that reached the server without going past the page is refused by what the hostdiff --git a/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts b/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.tsnew file mode 100644index 000000000..5f837acc8--- /dev/null+++ b/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts@@ -0,0 +1,69 @@+import { assert, it } from "@effect/vitest";++import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";+import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";+import * as GitHubCli from "../sourceControl/GitHubCli.ts";+import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";+import * as GitLabCli from "../sourceControl/GitLabCli.ts";+import { azureDevOpsProviderFailure } from "./AzureDevOpsPullRequestProvider.ts";+import { bitbucketProviderFailure } from "./BitbucketPullRequestProvider.ts";+import { gitHubProviderFailure } from "./GitHubPullRequestProvider.ts";+import { gitLabProviderFailure } from "./GitLabPullRequestProvider.ts";++const cause = new Error("redacted provider failure");++it("classifies rate limits from every pull-request provider", () => {+ assert.deepStrictEqual(+ gitHubProviderFailure(+ new GitHubCli.GitHubCliRateLimitError({ command: "gh", cwd: "/repo", cause }),+ ),+ { reason: "rate-limited" },+ );+ assert.deepStrictEqual(+ gitLabProviderFailure(+ new GitLabCli.GitLabCliRateLimitError({+ operation: "execute",+ command: "glab",+ cwd: "/repo",+ cause,+ }),+ ),+ { reason: "rate-limited" },+ );+ assert.deepStrictEqual(+ azureDevOpsProviderFailure(+ new AzureDevOpsCli.AzureDevOpsCliRateLimitError({+ operation: "execute",+ command: "az",+ cwd: "/repo",+ argumentCount: 1,+ cause,+ }),+ ),+ { reason: "rate-limited" },+ );+ assert.deepStrictEqual(+ bitbucketProviderFailure(+ new BitbucketApi.BitbucketResponseError({+ operation: "request",+ status: 429,+ responseBodyLength: 0,+ retryAt: 120_000,+ }),+ ),+ { reason: "rate-limited", retryAt: 120_000 },+ );+});++it("keeps GitHub's exact retry time", () => {+ assert.deepStrictEqual(+ gitHubProviderFailure(+ new SourceControlRateLimit.SourceControlRateLimitPausedError({+ provider: "github",+ host: "github.com",+ retryAt: 1_786_802_400_000,+ }),+ ),+ { reason: "rate-limited", retryAt: 1_786_802_400_000 },+ );+});diff --git a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts b/apps/server/src/pullRequest/PullRequestProviderRegistry.tsindex 84a4ebef0..d2caf3ff3 100644--- a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts+++ b/apps/server/src/pullRequest/PullRequestProviderRegistry.ts@@ -6,6 +6,7 @@ import type { SourceControlProviderKind } from "@t3tools/contracts";import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";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 AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";@@ -52,7 +53,12 @@ export const make = Effect.map();export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(- Layer.provide(GitHubPullRequestCli.layer.pipe(Layer.provide(GitHubCli.layer))),+ Layer.provide(+ GitHubPullRequestCli.layer.pipe(+ Layer.provide(GitHubCli.layer),+ Layer.provide(GitHubGraphQlBudget.layer),+ ),+ ),Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.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 456a5023b..84bd57dfa 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -11,6 +11,7 @@ import type {import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";+import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";import {PullRequestProviderError,type ProviderChangeRequest,@@ -169,6 +170,7 @@ function makeService(input: {updatedAt: "2026-07-01T00:00:00Z",}),}),+ SourceControlRateLimit.layer,),),);@@ -1339,6 +1341,97 @@ it.effect("reports repositories on a host that could not be read", () =>}),);+it.effect("stops new reads after a rate limit while leaving manual actions available", () =>+ Effect.gen(function* () {+ let listCalls = 0;+ let actionCalls = 0;+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }),+ ],+ providers: [+ fakeProvider("github", {+ listChangeRequests: () =>+ Effect.sync(() => {+ listCalls += 1;+ }).pipe(+ Effect.andThen(+ Effect.fail(+ new PullRequestProviderError({+ provider: "github",+ operation: "listChangeRequests",+ reason: "rate-limited",+ detail: "GitHub API rate limit exceeded.",+ }),+ ),+ ),+ ),+ runAction: () =>+ Effect.sync(() => {+ actionCalls += 1;+ }),+ }),+ ],+ });++ const first = yield* service.list({ state: "open", involvement: "all" });+ const paused = yield* service.list({ state: "open", involvement: "authored" });+ yield* service.runAction({+ projectId: "p1" as ProjectId,+ repository: "acme/web",+ number: 1,+ action: "close",+ });++ assert.strictEqual(listCalls, 1);+ assert.strictEqual(actionCalls, 1);+ assert.lengthOf(first.errors, 1);+ assert.lengthOf(paused.errors, 1);+ }),+);++it.effect("uses a manual rate limit to pause later reads", () =>+ Effect.gen(function* () {+ let listCalls = 0;+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }),+ ],+ providers: [+ fakeProvider("github", {+ listChangeRequests: () =>+ Effect.sync(() => {+ listCalls += 1;+ return { items: [], truncated: false, continues: true };+ }),+ runAction: () =>+ Effect.fail(+ new PullRequestProviderError({+ provider: "github",+ operation: "runAction",+ reason: "rate-limited",+ detail: "GitHub API rate limit exceeded.",+ }),+ ),+ }),+ ],+ });++ yield* Effect.flip(+ service.runAction({+ projectId: "p1" as ProjectId,+ repository: "acme/web",+ number: 1,+ action: "close",+ }),+ );+ const error = yield* Effect.flip(service.list({ state: "open", involvement: "all" }));++ assert.strictEqual(listCalls, 0);+ assert.strictEqual(error._tag, "PullRequestOperationError");+ }),+);+it.effect("flags a review request for the viewer but not on their own change request", () =>Effect.gen(function* () {const service = yield* makeService({diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex f12f72bda..fc76a6501 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -40,6 +40,8 @@ import {type PullRequestSubmitReviewInput,type PullRequestThreadReplyInput,type PullRequestThreadResolutionInput,+ type PullRequestThreadCommentsInput,+ type PullRequestThreadCommentsResult,type PullRequestUpdateInput,type SourceControlProviderInfo,type SourceControlProviderKind,@@ -48,11 +50,12 @@ import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceimport * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";+import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";import {type ProviderChangeRequest,type ProviderListCursor,type PullRequestProviderApi,- type PullRequestProviderError,+ PullRequestProviderError,} from "./PullRequestProvider.ts";import { PullRequestProviderRegistry } from "./PullRequestProviderRegistry.ts";@@ -132,6 +135,9 @@ export class PullRequestService extends Context.Service<readonly activity: (input: PullRequestRef,) => Effect.Effect<PullRequestActivity, PullRequestError>;+ readonly threadComments: (+ input: PullRequestThreadCommentsInput,+ ) => Effect.Effect<PullRequestThreadCommentsResult, PullRequestError>;readonly diff: (input: PullRequestDiffInput,) => Effect.Effect<PullRequestDiffResult, PullRequestError>;@@ -366,6 +372,103 @@ function toPullRequestError(: new PullRequestOperationError({ operation, detail: error.detail, cause: error });}+function withRateLimitBackoff(+ api: PullRequestProviderApi,+ host: string,+ limits: SourceControlRateLimit.SourceControlRateLimit["Service"],+): PullRequestProviderApi {+ const key = { provider: api.kind, host };+ const protect = <A>(+ operation: string,+ effect: Effect.Effect<A, PullRequestProviderError>,+ allowPaused: boolean,+ ) =>+ limits.check(key, allowPaused ? { allowPaused: true } : undefined).pipe(+ Effect.mapError(+ (error) =>+ new PullRequestProviderError({+ provider: api.kind,+ operation,+ reason: "rate-limited",+ detail: error.detail,+ retryAt: error.retryAt,+ cause: error,+ }),+ ),+ Effect.flatMap((lease) =>+ effect.pipe(+ Effect.tap(() => limits.recordSuccess({ ...key, lease })),+ Effect.tapError((error) =>+ error.reason === "rate-limited"+ ? limits.recordRateLimit({+ ...key,+ lease,+ ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),+ })+ : Effect.void,+ ),+ ),+ ),+ );+ const wrap =+ <Args extends ReadonlyArray<unknown>, A>(+ operation: string,+ call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,+ allowPaused = false,+ ) =>+ (...args: Args) =>+ protect(operation, call(...args), allowPaused);+ const interactive = <Args extends ReadonlyArray<unknown>, A>(+ operation: string,+ call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,+ ) => wrap(operation, call, true);++ return {+ kind: api.kind,+ capabilities: api.capabilities,+ getViewer: wrap("getViewer", api.getViewer),+ listChangeRequests: wrap("listChangeRequests", api.listChangeRequests),+ ...(api.listChangeRequestsAcross === undefined+ ? {}+ : {+ listChangeRequestsAcross: wrap("listChangeRequestsAcross", api.listChangeRequestsAcross),+ }),+ ...(api.listChangeRequestStats === undefined+ ? {}+ : {+ listChangeRequestStats: wrap("listChangeRequestStats", api.listChangeRequestStats),+ }),+ getChangeRequest: wrap("getChangeRequest", api.getChangeRequest),+ getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity),+ ...(api.getReviewThreadComments === undefined+ ? {}+ : {+ getReviewThreadComments: wrap("getReviewThreadComments", api.getReviewThreadComments),+ }),+ getViewerPermissions: interactive("getViewerPermissions", api.getViewerPermissions),+ getDiff: wrap("getDiff", api.getDiff),+ ...(api.getDiffFileContents === undefined+ ? {}+ : { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }),+ runAction: interactive("runAction", api.runAction),+ ...(api.updateChangeRequest === undefined+ ? {}+ : {+ updateChangeRequest: interactive("updateChangeRequest", api.updateChangeRequest),+ }),+ comment: interactive("comment", api.comment),+ ...(api.updateComment === undefined+ ? {}+ : { updateComment: interactive("updateComment", api.updateComment) }),+ submitReview: interactive("submitReview", api.submitReview),+ listReviewerCandidates: interactive("listReviewerCandidates", api.listReviewerCandidates),+ setReviewerRequest: interactive("setReviewerRequest", api.setReviewerRequest),+ replyToThread: interactive("replyToThread", api.replyToThread),+ setReaction: interactive("setReaction", api.setReaction),+ setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),+ };+}+/*** The provider-native repository selector. `displayName` is the full path below the host, which* is what nested GitLab groups need; owner/name is the two-segment fallback for identities@@ -394,6 +497,7 @@ export const make = Effect.gen(function* () {const registry = yield* PullRequestProviderRegistry;const projections = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;+ const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit;const refineUnknownProjectKinds = (projects: ReadonlyArray<OrchestrationProjectShell>,@@ -511,7 +615,12 @@ export const make = Effect.gen(function* () {else counted.projectCount += 1;continue;}- supported.push({ project, api, repository, host });+ supported.push({+ project,+ api: withRateLimitBackoff(api, host, rateLimits),+ repository,+ host,+ });}return { supported, unimplemented, viewerRoots };}),@@ -1116,6 +1225,31 @@ export const make = Effect.gen(function* () {),);+ const threadComments: PullRequestService["Service"]["threadComments"] = (input) =>+ requireProject(input).pipe(+ Effect.flatMap(+ (project): Effect.Effect<PullRequestThreadCommentsResult, PullRequestError> => {+ const read = project.api.getReviewThreadComments;+ if (read === undefined) {+ return Effect.fail(+ new PullRequestOperationError({+ operation: "threadComments",+ detail: "This host does not page review thread comments.",+ }),+ );+ }+ return read({+ cwd: project.project.workspaceRoot,+ repository: project.repository,+ host: project.host,+ number: input.number,+ threadId: input.threadId,+ cursor: input.cursor,+ }).pipe(Effect.mapError(toPullRequestError("threadComments")));+ },+ ),+ );+const diffUncached: PullRequestService["Service"]["diff"] = (input) =>requireProject(input).pipe(Effect.flatMap((project) =>@@ -1993,6 +2127,7 @@ export const make = Effect.gen(function* () {listStats,detail,activity,+ threadComments,diff,diffFileContents,runAction: invalidatedByMutation(runAction),diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.tsindex 946394dcd..f372ac300 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts@@ -604,7 +604,9 @@ describe("review thread decoding", () => {decodeReviewThreadCommentsJson(JSON.stringify({data: {+ repository: { pullRequest: { id: "PR_1" } },node: {+ pullRequest: { id: "PR_1" },comments: {pageInfo: { hasNextPage: false, endCursor: "Y3Vyc29yOjk" },nodes: [{ id: "t9", body: "last", createdAt: "2026-07-01T00:00:00Z" }],@@ -623,7 +625,9 @@ describe("reaction decoding", () => {const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>JSON.stringify({data: {+ repository: { pullRequest: { id: "PR_1" } },node: {+ pullRequest: { id: "PR_1" },comments: {pageInfo: { hasNextPage: false, endCursor: null },nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],@@ -669,7 +673,9 @@ describe("reaction decoding", () => {JSON.stringify({data: {viewer: { login: "Bilal" },+ repository: { pullRequest: { id: "PR_1" } },node: {+ pullRequest: { id: "PR_1" },comments: {pageInfo: { hasNextPage: false, endCursor: null },nodes: [@@ -1009,6 +1015,16 @@ describe("decodePullRequestNodeIdJson", () => {});describe("REVIEW_THREADS_GRAPHQL_QUERY", () => {+ it("caps the initial query after the 104-point rate-limit regression", () => {+ const match = REVIEW_THREADS_GRAPHQL_QUERY.match(+ /reviewThreads\(first: (\d+)[\s\S]*?comments\(first: (\d+)\)/u,+ );++ expect(match).not.toBeNull();+ if (match === null) throw new Error("expected review-thread connections");+ expect(Number(match[1]) * Number(match[2])).toBeLessThanOrEqual(1_000);+ });+it("asks for reactionGroups on the pull request itself, its comments, its reviews and each thread's comments", () => {expect(REVIEW_THREADS_GRAPHQL_QUERY.match(/reactionGroups/g)).toHaveLength(4);// The reviews connection is new: only reactions were ever wanted off it.diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.tsindex 7b9ff9d41..6ec17ea11 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts@@ -661,6 +661,10 @@ export function pullRequestSearchGraphQlQuery(rows: number): string {* null for the first page and the last page's `endCursor` after that, so a pull request with* more threads than one page holds is walked rather than cut off at the first fifty.*+ * Only ten comments ride with each thread. A hundred threads times a hundred comments made+ * GitHub reserve 10,000 nested rows and charge 104 points; unfinished threads are paged from+ * their own cursor below.+ ** Reviewers come from here rather than from `gh pr view --json reviewRequests` for two reasons:* that field holds only requests still outstanding, so anyone who has already reviewed drops off* it, and neither it nor any other `gh` JSON field carries an avatar. A reviewer can be a person@@ -689,7 +693,7 @@ export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: StrinpathlinediffSide- comments(first: ${GRAPHQL_PAGE_SIZE}) {+ comments(first: 10) {totalCountpageInfo { hasNextPage endCursor }nodes { id author { login avatarUrl } body createdAt url ${REACTION_GROUPS_FIELDS} }@@ -740,10 +744,12 @@ export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: Strin* from the inner node itself, so a thread longer than a page is followed on its own — a request* GitHub makes necessary, and one no ordinary pull request ever provokes.*/-export const REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY = `query($threadId: ID!, $cursor: String) {+export const REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $threadId: ID!, $cursor: String) {viewer { login }+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { id } }node(id: $threadId) {... on PullRequestReviewThread {+ pullRequest { id }comments(first: ${GRAPHQL_PAGE_SIZE}, after: $cursor) {pageInfo { hasNextPage endCursor }nodes { id author { login avatarUrl } body createdAt url ${REACTION_GROUPS_FIELDS} }@@ -757,8 +763,16 @@ const RawReviewThreadCommentsSchema = Schema.Struct({viewer: Schema.optional(Schema.NullOr(Schema.Struct({ login: Schema.optional(Schema.NullOr(Schema.String)) })),),+ repository: Schema.NullOr(+ Schema.Struct({ pullRequest: Schema.NullOr(Schema.Struct({ id: Schema.String })) }),+ ),/** Null for an id that names nothing the viewer can read, which is not a thread to page. */- node: Schema.NullOr(Schema.Struct({ comments: Schema.optional(RawThreadCommentsSchema) })),+ node: Schema.NullOr(+ Schema.Struct({+ pullRequest: Schema.optional(Schema.Struct({ id: Schema.String })),+ comments: Schema.optional(RawThreadCommentsSchema),+ }),+ ),}),});@@ -1820,6 +1834,7 @@ export function decodeReviewThreadsJson(/** The rest of one thread's comments, in the shape the first page already delivered them. */export function decodeReviewThreadCommentsJson(raw: string): Result.Result<{+ readonly belongsToPullRequest: boolean;readonly comments: ReadonlyArray<PullRequestThreadComment>;readonly nextCursor: string | null;},@@ -1832,6 +1847,10 @@ export function decodeReviewThreadCommentsJson(raw: string): Result.Result<const viewer = trimmed(decoded.success.data.viewer?.login);const comments = decoded.success.data.node?.comments;return Result.succeed({+ belongsToPullRequest:+ decoded.success.data.repository?.pullRequest?.id !== undefined &&+ decoded.success.data.repository?.pullRequest?.id ===+ decoded.success.data.node?.pullRequest?.id,comments: (comments?.nodes ?? []).map((comment) => ({id: comment.id,author: toActor(comment.author),diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 42fc93624..3e41b4390 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -78,6 +78,7 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";import * as GitWorkflowService from "./git/GitWorkflowService.ts";import * as ReviewService from "./review/ReviewService.ts";import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";+import * as SourceControlRateLimit from "./sourceControl/SourceControlRateLimit.ts";import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";import { ObservabilityLive } from "./observability/Layers/Observability.ts";@@ -439,6 +440,7 @@ const PullRequestServiceLive = PullRequestService.layer.pipe(// One registry entry per supported host; the service only knows the registry.Layer.provide(PullRequestProviderRegistry.layer),Layer.provide(SourceControlProviderRegistryLayerLive),+ Layer.provide(SourceControlRateLimit.layer),Layer.provide(VcsProcess.layer),);diff --git a/apps/server/src/sourceControl/AzureDevOpsCli.test.ts b/apps/server/src/sourceControl/AzureDevOpsCli.test.tsindex 1cd4b3885..a5bb9a9e3 100644--- a/apps/server/src/sourceControl/AzureDevOpsCli.test.ts+++ b/apps/server/src/sourceControl/AzureDevOpsCli.test.ts@@ -405,4 +405,25 @@ describe("AzureDevOpsCli.layer", () => {);}).pipe(Effect.provide(layer)),);++ it.effect("preserves rate-limit failures as a distinct error", () =>+ Effect.gen(function* () {+ const cause = new VcsProcessExitError({+ operation: "AzureDevOpsCli.execute",+ command: "az",+ cwd: "/repo",+ argumentCount: 2,+ exitCode: 1,+ detail: "API rate limit exceeded.",+ failureKind: "rate-limited",+ });+ mockRun.mockReturnValueOnce(Effect.fail(cause));++ const az = yield* AzureDevOpsCli.AzureDevOpsCli;+ const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);++ assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCliRateLimitError);+ assert.strictEqual(error.cause, cause);+ }).pipe(Effect.provide(layer)),+ );});diff --git a/apps/server/src/sourceControl/AzureDevOpsCli.ts b/apps/server/src/sourceControl/AzureDevOpsCli.tsindex 609efe4df..556dc4bf2 100644--- a/apps/server/src/sourceControl/AzureDevOpsCli.ts+++ b/apps/server/src/sourceControl/AzureDevOpsCli.ts@@ -55,6 +55,19 @@ export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<A}}+export class AzureDevOpsCliRateLimitError extends Schema.TaggedErrorClass<AzureDevOpsCliRateLimitError>()(+ "AzureDevOpsCliRateLimitError",+ azureDevOpsCommandErrorFields,+) {+ get detail(): string {+ return "Azure DevOps API rate limit exceeded.";+ }++ override get message(): string {+ return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;+ }+}+export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()("AzureDevOpsPullRequestNotFoundError",azureDevOpsCommandErrorFields,@@ -105,6 +118,9 @@ export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<Azureif (cause.failureKind === "authentication") {return new AzureDevOpsCliAuthenticationError(fields);}+ if (cause.failureKind === "rate-limited") {+ return new AzureDevOpsCliRateLimitError(fields);+ }if (cause.failureKind === "not-found") {return new AzureDevOpsPullRequestNotFoundError(fields);}@@ -178,6 +194,7 @@ export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<Azexport const AzureDevOpsCliError = Schema.Union([AzureDevOpsCliUnavailableError,AzureDevOpsCliAuthenticationError,+ AzureDevOpsCliRateLimitError,AzureDevOpsPullRequestNotFoundError,AzureDevOpsCommandFailedError,AzureDevOpsPullRequestListDecodeError,diff --git a/apps/server/src/sourceControl/BitbucketApi.test.ts b/apps/server/src/sourceControl/BitbucketApi.test.tsindex 4f3433693..856d043a7 100644--- a/apps/server/src/sourceControl/BitbucketApi.test.ts+++ b/apps/server/src/sourceControl/BitbucketApi.test.ts@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";+import * as TestClock from "effect/testing/TestClock";import {HttpClient,HttpClientError,@@ -569,6 +570,24 @@ it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {}).pipe(Effect.provide(layer));});+it.effect("keeps a 429 Retry-After time on the response error", () => {+ const { layer } = makeLayer({+ response: () => new Response("busy", { status: 429, headers: { "Retry-After": "120" } }),+ });++ return Effect.gen(function* () {+ yield* TestClock.setTime(1_000);+ const bitbucket = yield* BitbucketApi.BitbucketApi;+ const error = yield* bitbucket+ .request({ method: "GET", url: "/repositories/acme/web" })+ .pipe(Effect.flip);++ assert.instanceOf(error, BitbucketApi.BitbucketResponseError);+ assert.strictEqual(error.status, 429);+ assert.strictEqual(error.retryAt, 121_000);+ }).pipe(Effect.provide(layer));+});+it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {const cause = new Error("response stream failed");const { layer } = makeLayer({diff --git a/apps/server/src/sourceControl/BitbucketApi.ts b/apps/server/src/sourceControl/BitbucketApi.tsindex 4a825be88..4573f2891 100644--- a/apps/server/src/sourceControl/BitbucketApi.ts+++ b/apps/server/src/sourceControl/BitbucketApi.ts@@ -1,3 +1,4 @@+import * as Clock from "effect/Clock";import * as Config from "effect/Config";import * as Context from "effect/Context";import * as Effect from "effect/Effect";@@ -29,6 +30,7 @@ import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";import * as SourceControlProvider from "./SourceControlProvider.ts";import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";+import { retryAtFromHeader } from "./SourceControlRateLimit.ts";const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";/** A response body past this is cut short, so one huge diff cannot exhaust the server. */@@ -98,6 +100,7 @@ export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResoperation: BitbucketApiOperation,status: Schema.Int,responseBodyLength: NonNegativeInt,+ retryAt: Schema.optional(Schema.Number),},) {get detail(): string {@@ -579,28 +582,28 @@ function responseError(): Effect.Effect<never, BitbucketApiError> {// Bounded like any other body: an error response is no smaller than a successful one, and// only its length is reported anyway.- return collectUint8StreamText({- stream: response.stream,- maxBytes: DEFAULT_MAX_RESPONSE_BYTES,- }).pipe(- Effect.mapError(- (cause) =>- new BitbucketResponseBodyReadError({- operation,- status: response.status,- cause,- }),- ),- Effect.flatMap((collected) =>- Effect.fail(- new BitbucketResponseError({- operation,- status: response.status,- responseBodyLength: collected.text.length,- }),+ return Effect.gen(function* () {+ const now = yield* Clock.currentTimeMillis;+ const collected = yield* collectUint8StreamText({+ stream: response.stream,+ maxBytes: DEFAULT_MAX_RESPONSE_BYTES,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new BitbucketResponseBodyReadError({+ operation,+ status: response.status,+ cause,+ }),),- ),- );+ );+ return yield* new BitbucketResponseError({+ operation,+ status: response.status,+ responseBodyLength: collected.text.length,+ retryAt: retryAtFromHeader(response.headers["retry-after"], now),+ });+ });}export const make = Effect.gen(function* () {diff --git a/apps/server/src/sourceControl/GitLabCli.test.ts b/apps/server/src/sourceControl/GitLabCli.test.tsindex 87621e5c8..eb56b434b 100644--- a/apps/server/src/sourceControl/GitLabCli.test.ts+++ b/apps/server/src/sourceControl/GitLabCli.test.ts@@ -364,4 +364,26 @@ layer("GitLabCli.layer", (it) => {assert.strictEqual(error.cause, cause);}),);++ it.effect("preserves rate-limit failures as a distinct error", () =>+ Effect.gen(function* () {+ const cause = new VcsProcessExitError({+ operation: "GitLabCli.execute",+ command: "glab",+ cwd: "/repo",+ exitCode: 1,+ detail: "API rate limit exceeded.",+ failureKind: "rate-limited",+ });+ mockedRun.mockReturnValueOnce(Effect.fail(cause));++ const glab = yield* GitLabCli.GitLabCli;+ const error = yield* glab+ .execute({ cwd: "/repo", args: ["api", "projects"] })+ .pipe(Effect.flip);++ assert.strictEqual(error._tag, "GitLabCliRateLimitError");+ assert.strictEqual(error.cause, cause);+ }),+ );});diff --git a/apps/server/src/sourceControl/GitLabCli.ts b/apps/server/src/sourceControl/GitLabCli.tsindex ce17b2f5b..9a9fc3360 100644--- a/apps/server/src/sourceControl/GitLabCli.ts+++ b/apps/server/src/sourceControl/GitLabCli.ts@@ -61,6 +61,19 @@ export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLab}}+export class GitLabCliRateLimitError extends Schema.TaggedErrorClass<GitLabCliRateLimitError>()(+ "GitLabCliRateLimitError",+ gitLabCliExecutionErrorContext,+) {+ get detail(): string {+ return "GitLab API rate limit exceeded.";+ }++ override get message(): string {+ return `GitLab CLI failed in ${this.operation}: ${this.detail}`;+ }+}+export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()("GitLabMergeRequestNotFoundError",{@@ -126,8 +139,9 @@ export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommswitch (cause.failureKind) {case "authentication":return new GitLabCliAuthenticationError({ ...context, cause });- case "not-found":case "rate-limited":+ return new GitLabCliRateLimitError({ ...context, cause });+ case "not-found":case "command-failed":case undefined:return new GitLabCliCommandError({ ...context, cause });@@ -214,6 +228,7 @@ export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNaexport const GitLabCliError = Schema.Union([GitLabCliUnavailableError,GitLabCliAuthenticationError,+ GitLabCliRateLimitError,GitLabMergeRequestNotFoundError,GitLabCliCommandError,GitLabMergeRequestListDecodeError,diff --git a/apps/server/src/sourceControl/SourceControlRateLimit.test.ts b/apps/server/src/sourceControl/SourceControlRateLimit.test.tsnew file mode 100644index 000000000..5ee233a36--- /dev/null+++ b/apps/server/src/sourceControl/SourceControlRateLimit.test.ts@@ -0,0 +1,122 @@+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as TestClock from "effect/testing/TestClock";++import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";++const github = { provider: "github" as const, host: "github.com" };++it("parses Retry-After seconds and HTTP dates", () => {+ assert.equal(SourceControlRateLimit.retryAtFromHeader("120", 1_000), 121_000);+ assert.equal(+ SourceControlRateLimit.retryAtFromHeader("Thu, 01 Jan 1970 00:02:01 GMT", 1_000),+ 121_000,+ );+ assert.isUndefined(SourceControlRateLimit.retryAtFromHeader("later", 1_000));+});++it.effect("backs off repeated rate limits until a successful request", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(0);+ const limits = yield* SourceControlRateLimit.SourceControlRateLimit;++ const firstLease = yield* limits.check(github);+ yield* limits.recordRateLimit({ ...github, lease: firstLease });+ const firstPause = yield* Effect.flip(limits.check(github));+ assert.deepInclude(firstPause, {+ _tag: "SourceControlRateLimitPausedError",+ provider: "github",+ host: "github.com",+ retryAt: 30_000,+ });+ assert.equal(+ firstPause.detail,+ "github requests to github.com are paused until the rate limit resets.",+ );+ assert.equal(firstPause.message, firstPause.detail);++ yield* TestClock.adjust("30 seconds");+ const secondLease = yield* limits.check(github);+ yield* limits.recordRateLimit({ ...github, lease: secondLease });+ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 90_000);++ yield* TestClock.adjust("60 seconds");+ const successLease = yield* limits.check(github);+ yield* limits.recordSuccess({ ...github, lease: successLease });+ const resetLease = yield* limits.check(github);+ yield* limits.recordRateLimit({ ...github, lease: resetLease });+ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 120_000);+ }).pipe(Effect.provide(SourceControlRateLimit.layer)),+);++it.effect("honors a provider reset time", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(1_000);+ const limits = yield* SourceControlRateLimit.SourceControlRateLimit;+ const lease = yield* limits.check(github);++ yield* limits.recordRateLimit({ ...github, lease, retryAt: 121_000 });+ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 121_000);++ yield* TestClock.adjust("119999 millis");+ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 121_000);+ yield* TestClock.adjust("1 millis");+ assert.equal(yield* limits.check(github), 1);+ }).pipe(Effect.provide(SourceControlRateLimit.layer)),+);++it.effect("lets an interactive request through without clearing an active pause", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(1_000);+ const limits = yield* SourceControlRateLimit.SourceControlRateLimit;+ const lease = yield* limits.check(github);+ yield* limits.recordRateLimit({ ...github, lease, retryAt: 121_000 });++ const interactiveLease = yield* limits.check(github, { allowPaused: true });+ yield* limits.recordSuccess({ ...github, lease: interactiveLease });++ assert.equal(interactiveLease, 1);+ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 121_000);++ yield* limits.recordRateLimit({ ...github, lease: interactiveLease, retryAt: 61_000 });+ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 121_000);+ }).pipe(Effect.provide(SourceControlRateLimit.layer)),+);++it.effect("keeps providers and hosts isolated", () =>+ Effect.gen(function* () {+ const limits = yield* SourceControlRateLimit.SourceControlRateLimit;+ const lease = yield* limits.check(github);+ yield* limits.recordRateLimit({ ...github, lease });++ assert.equal(yield* limits.check({ provider: "gitlab", host: "github.com" }), 0);+ assert.equal(yield* limits.check({ provider: "github", host: "github.example.com" }), 0);+ }).pipe(Effect.provide(SourceControlRateLimit.layer)),+);++it.effect("does not let an older success clear a concurrent pause", () =>+ Effect.gen(function* () {+ const limits = yield* SourceControlRateLimit.SourceControlRateLimit;+ const firstLease = yield* limits.check(github);+ const concurrentLease = yield* limits.check(github);++ yield* limits.recordRateLimit({ ...github, lease: firstLease });+ yield* limits.recordSuccess({ ...github, lease: concurrentLease });++ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 30_000);+ }).pipe(Effect.provide(SourceControlRateLimit.layer)),+);++it.effect("keeps a fresh provider reset from an older request", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(0);+ const limits = yield* SourceControlRateLimit.SourceControlRateLimit;+ const staleLease = yield* limits.check(github);+ yield* limits.recordRateLimit({ ...github, lease: staleLease });++ yield* TestClock.adjust("31 seconds");+ yield* limits.recordRateLimit({ ...github, lease: staleLease, retryAt: 61_000 });++ assert.equal((yield* Effect.flip(limits.check(github))).retryAt, 61_000);+ }).pipe(Effect.provide(SourceControlRateLimit.layer)),+);diff --git a/apps/server/src/sourceControl/SourceControlRateLimit.ts b/apps/server/src/sourceControl/SourceControlRateLimit.tsnew file mode 100644index 000000000..e8f7218de--- /dev/null+++ b/apps/server/src/sourceControl/SourceControlRateLimit.ts@@ -0,0 +1,162 @@+import * as Clock from "effect/Clock";+import * as Context from "effect/Context";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Ref from "effect/Ref";+import * as Schema from "effect/Schema";+import {+ SourceControlProviderKind as SourceControlProviderKindSchema,+ type SourceControlProviderKind,+} from "@t3tools/contracts";++const FALLBACK_COOLDOWN = Duration.seconds(30);+const MAX_FALLBACK_COOLDOWN = Duration.minutes(15);++interface RateLimitKey {+ readonly provider: SourceControlProviderKind;+ readonly host: string;+}++interface RateLimitLease extends RateLimitKey {+ readonly lease: number;+}++interface RateLimitEntry {+ readonly attempt: number;+ readonly generation: number;+ readonly retryAt: number;+}++export class SourceControlRateLimitPausedError extends Schema.TaggedErrorClass<SourceControlRateLimitPausedError>()(+ "SourceControlRateLimitPausedError",+ {+ provider: SourceControlProviderKindSchema,+ host: Schema.String,+ retryAt: Schema.Number,+ },+) {+ get detail(): string {+ return `${this.provider} requests to ${this.host} are paused until the rate limit resets.`;+ }++ override get message(): string {+ return this.detail;+ }+}++export class SourceControlRateLimit extends Context.Service<+ SourceControlRateLimit,+ {+ readonly check: (+ key: RateLimitKey,+ options?: { readonly allowPaused: boolean },+ ) => Effect.Effect<number, SourceControlRateLimitPausedError>;+ readonly recordRateLimit: (+ input: RateLimitLease & { readonly retryAt?: number | undefined },+ ) => Effect.Effect<void>;+ readonly recordSuccess: (input: RateLimitLease) => Effect.Effect<void>;+ }+>()("t3/sourceControl/SourceControlRateLimit") {}++function normalizedKey(key: RateLimitKey): string {+ return `${key.provider}\0${key.host.trim().toLowerCase()}`;+}++function fallbackCooldownMs(attempt: number): number {+ return Math.min(+ Duration.toMillis(FALLBACK_COOLDOWN) * 2 ** Math.max(0, attempt - 1),+ Duration.toMillis(MAX_FALLBACK_COOLDOWN),+ );+}++export function retryAtFromHeader(value: string | undefined, now: number): number | undefined {+ if (value === undefined) return undefined;+ const normalized = value.trim();+ if (/^\d+$/u.test(normalized)) {+ const seconds = Number(normalized);+ const retryAt = now + seconds * 1_000;+ return Number.isSafeInteger(retryAt) ? retryAt : undefined;+ }+ const retryAt = Date.parse(normalized);+ return Number.isFinite(retryAt) && retryAt > now ? retryAt : undefined;+}++export const make = Effect.gen(function* () {+ const entries = yield* Ref.make<ReadonlyMap<string, RateLimitEntry>>(new Map());++ const check: SourceControlRateLimit["Service"]["check"] = Effect.fn(+ "SourceControlRateLimit.check",+ )(function* (input, options) {+ const now = yield* Clock.currentTimeMillis;+ const entry = (yield* Ref.get(entries)).get(normalizedKey(input));+ if (entry !== undefined && entry.retryAt > now && options?.allowPaused !== true) {+ return yield* new SourceControlRateLimitPausedError({+ provider: input.provider,+ host: input.host.trim().toLowerCase(),+ retryAt: entry.retryAt,+ });+ }+ return entry?.generation ?? 0;+ });++ const recordRateLimit: SourceControlRateLimit["Service"]["recordRateLimit"] = Effect.fn(+ "SourceControlRateLimit.recordRateLimit",+ )(function* (input) {+ const now = yield* Clock.currentTimeMillis;+ yield* Ref.update(entries, (current) => {+ const key = normalizedKey(input);+ const previous = current.get(key);+ if (previous !== undefined && previous.generation > input.lease) {+ if (previous.retryAt <= now && (input.retryAt === undefined || input.retryAt <= now)) {+ return current;+ }+ const retryAt =+ input.retryAt !== undefined && input.retryAt > previous.retryAt+ ? input.retryAt+ : previous.retryAt;+ if (retryAt === previous.retryAt) return current;+ const next = new Map(current);+ next.set(key, { ...previous, retryAt });+ return next;+ }++ const attempt = (previous?.attempt ?? 0) + 1;+ const proposedRetryAt =+ input.retryAt !== undefined && input.retryAt > now+ ? input.retryAt+ : now + fallbackCooldownMs(attempt);+ const retryAt =+ previous !== undefined && previous.retryAt > now+ ? Math.max(previous.retryAt, proposedRetryAt)+ : proposedRetryAt;+ const next = new Map(current);+ next.set(key, {+ attempt,+ generation: Math.max(previous?.generation ?? 0, input.lease) + 1,+ retryAt,+ });+ return next;+ });+ });++ const recordSuccess: SourceControlRateLimit["Service"]["recordSuccess"] = Effect.fn(+ "SourceControlRateLimit.recordSuccess",+ )(function* (input) {+ const now = yield* Clock.currentTimeMillis;+ yield* Ref.update(entries, (current) => {+ const key = normalizedKey(input);+ const previous = current.get(key);+ if (previous === undefined || previous.generation !== input.lease || previous.retryAt > now) {+ return current;+ }+ const next = new Map(current);+ next.set(key, { attempt: 0, generation: previous.generation, retryAt: 0 });+ return next;+ });+ });++ return SourceControlRateLimit.of({ check, recordRateLimit, recordSuccess });+});++export const layer = Layer.effect(SourceControlRateLimit, make);diff --git a/apps/server/src/sourceControl/githubGraphQlBudget.test.ts b/apps/server/src/sourceControl/githubGraphQlBudget.test.tsnew file mode 100644index 000000000..a166bf0db--- /dev/null+++ b/apps/server/src/sourceControl/githubGraphQlBudget.test.ts@@ -0,0 +1,189 @@+import { describe, expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as TestClock from "effect/testing/TestClock";++import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";++const RESET_AT = "2026-08-13T14:00:00.000Z";+const NEXT_RESET_AT = "2026-08-13T15:00:00.000Z";+const BEFORE_RESET = Date.parse("2026-08-13T13:30:00.000Z");+const AFTER_RESET = Date.parse("2026-08-13T14:00:01.000Z");++function rateLimit(remaining: number, limit = 5_000, resetAt = RESET_AT): string {+ return JSON.stringify({+ data: {+ viewer: { login: "bilal" },+ rateLimit: { cost: 14, limit, remaining, resetAt },+ },+ });+}++describe("GitHub GraphQL budget", () => {+ it.effect("adds rate metadata to a read query", () =>+ Effect.gen(function* () {+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;++ const query = yield* budget.query(+ "github.com",+ 'query { repository(owner: "acme", name: "web") { name } }',+ );++ expect(query).toContain("rateLimit { cost limit remaining resetAt }");+ expect(query).toContain('repository(owner: "acme", name: "web") { name }');+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("protects the last ten percent with the shared provider cooldown error", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(500));++ const error = yield* Effect.flip(budget.query("github.com", "query { viewer { login } }"));+ expect(error).toMatchObject({+ _tag: "SourceControlRateLimitPausedError",+ provider: "github",+ host: "github.com",+ retryAt: Date.parse(RESET_AT),+ });+ expect(error.message).toBe(+ "github requests to github.com are paused until the rate limit resets.",+ );++ yield* TestClock.setTime(AFTER_RESET);+ expect(yield* budget.query("github.com", "query { viewer { login } }")).toContain(+ "rateLimit",+ );+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("keeps hosts isolated", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(0));++ const error = yield* Effect.flip(budget.query("github.com", "query { viewer { login } }"));+ expect(error._tag).toBe("SourceControlRateLimitPausedError");+ expect(yield* budget.query("github.example.com", "query { viewer { login } }")).toContain(+ "rateLimit",+ );+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("keeps the lower remaining value from out-of-order responses", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(400));+ yield* budget.observe("github.com", rateLimit(600));++ const error = yield* Effect.flip(budget.query("github.com", "query { viewer { login } }"));+ expect(error).toMatchObject({+ _tag: "SourceControlRateLimitPausedError",+ retryAt: Date.parse(RESET_AT),+ });+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("ignores a response from an older reset window", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(400, 5_000, NEXT_RESET_AT));+ yield* budget.observe("github.com", rateLimit(1_000, 5_000, RESET_AT));++ const error = yield* Effect.flip(budget.query("github.com", "query { viewer { login } }"));+ expect(error).toMatchObject({+ _tag: "SourceControlRateLimitPausedError",+ retryAt: Date.parse(NEXT_RESET_AT),+ });+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("accepts a response from a later reset window", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(1_000));+ yield* budget.observe("github.com", rateLimit(400, 5_000, NEXT_RESET_AT));++ const error = yield* Effect.flip(budget.query("github.com", "query { viewer { login } }"));+ expect(error).toMatchObject({+ _tag: "SourceControlRateLimitPausedError",+ retryAt: Date.parse(NEXT_RESET_AT),+ });+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("allows reads above the reserve", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(515));++ expect(yield* budget.query("github.com", "query { viewer { login } }")).toContain(+ "rateLimit",+ );+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("allows an interactive read to use the reserve", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(500));++ expect(+ yield* budget.query("github.com", "query { viewer { login } }", {+ allowReserve: true,+ }),+ ).toContain("rateLimit");+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("reserves an admitted query cost before its response", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", rateLimit(514));++ expect(yield* budget.query("github.com", "query { viewer { login } }")).toContain(+ "rateLimit",+ );+ const error = yield* Effect.flip(budget.query("github.com", "query { viewer { login } }"));++ expect(error).toMatchObject({+ _tag: "SourceControlRateLimitPausedError",+ retryAt: Date.parse(RESET_AT),+ });+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("ignores malformed or partial rate metadata", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ yield* budget.observe("github.com", "{");+ yield* budget.observe(+ "github.com",+ '{"data":{"rateLimit":{"limit":0,"remaining":-1,"resetAt":"never"}}}',+ );++ expect(yield* budget.query("github.com", "query { viewer { login } }")).toContain(+ "rateLimit",+ );+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );++ it.effect("does not add a read field to a mutation", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(BEFORE_RESET);+ const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;+ const mutation = "mutation { addComment(input: {}) { clientMutationId } }";+ yield* budget.observe("github.com", rateLimit(0));++ expect(yield* budget.query("github.com", mutation)).toBe(mutation);+ }).pipe(Effect.provide(GitHubGraphQlBudget.layer)),+ );+});diff --git a/apps/server/src/sourceControl/githubGraphQlBudget.ts b/apps/server/src/sourceControl/githubGraphQlBudget.tsnew file mode 100644index 000000000..9c43de8e0--- /dev/null+++ b/apps/server/src/sourceControl/githubGraphQlBudget.ts@@ -0,0 +1,141 @@+import * as Clock from "effect/Clock";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Ref from "effect/Ref";+import * as Predicate from "effect/Predicate";++import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";++const GRAPHQL_RESERVE_RATIO = 0.1;+const RATE_LIMIT_SELECTION = "rateLimit { cost limit remaining resetAt }";++interface GraphQlBudgetSnapshot {+ readonly cost: number;+ readonly limit: number;+ readonly remaining: number;+ readonly resetAtMs: number;+}++export class GitHubGraphQlBudget extends Context.Service<+ GitHubGraphQlBudget,+ {+ readonly query: (+ host: string,+ document: string,+ options?: { readonly allowReserve: boolean },+ ) => Effect.Effect<string, SourceControlRateLimit.SourceControlRateLimitPausedError>;+ readonly observe: (host: string, raw: string) => Effect.Effect<void>;+ }+>()("t3/sourceControl/githubGraphQlBudget") {}++function hostKey(host: string): string {+ return host.trim().toLowerCase();+}++function snapshotFrom(raw: string): GraphQlBudgetSnapshot | null {+ try {+ const parsed: unknown = JSON.parse(raw);+ if (+ !Predicate.isObject(parsed) ||+ !Predicate.isObject(parsed.data) ||+ !Predicate.isObject(parsed.data.rateLimit)+ ) {+ return null;+ }+ const { cost, limit, remaining, resetAt } = parsed.data.rateLimit;+ if (+ typeof cost !== "number" ||+ !Number.isFinite(cost) ||+ cost < 0 ||+ typeof limit !== "number" ||+ !Number.isFinite(limit) ||+ limit <= 0 ||+ typeof remaining !== "number" ||+ !Number.isFinite(remaining) ||+ remaining < 0 ||+ typeof resetAt !== "string"+ ) {+ return null;+ }+ const resetAtMs = Date.parse(resetAt);+ return Number.isFinite(resetAtMs) ? { cost, limit, remaining, resetAtMs } : null;+ } catch {+ return null;+ }+}++function isReadOperation(document: string): boolean {+ const operation = document.trimStart();+ return operation.startsWith("query") || operation.startsWith("{");+}++function withRateLimit(document: string): string {+ if (!isReadOperation(document)) return document;+ const end = document.lastIndexOf("}");+ if (end === -1 || document.includes(RATE_LIMIT_SELECTION)) return document;+ return `${document.slice(0, end)}\n ${RATE_LIMIT_SELECTION}\n${document.slice(end)}`;+}++export const make = Effect.gen(function* () {+ const snapshots = yield* Ref.make<ReadonlyMap<string, GraphQlBudgetSnapshot>>(new Map());++ const query: GitHubGraphQlBudget["Service"]["query"] = Effect.fn("GitHubGraphQlBudget.query")(+ function* (host, document, options) {+ if (!isReadOperation(document)) return document;+ const now = yield* Clock.currentTimeMillis;+ const retryAt = yield* Ref.modify(snapshots, (current) => {+ const key = hostKey(host);+ const snapshot = current.get(key);+ if (snapshot === undefined) return [null, current] as const;+ if (snapshot.resetAtMs <= now) {+ const next = new Map(current);+ next.delete(key);+ return [null, next] as const;+ }+ const remaining = Math.max(0, snapshot.remaining - Math.max(1, snapshot.cost));+ if (options?.allowReserve !== true && remaining < snapshot.limit * GRAPHQL_RESERVE_RATIO) {+ return [snapshot.resetAtMs, current] as const;+ }+ const next = new Map(current);+ next.set(key, { ...snapshot, remaining });+ return [null, next] as const;+ });+ if (retryAt !== null) {+ return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({+ provider: "github",+ host: hostKey(host),+ retryAt,+ });+ }+ return withRateLimit(document);+ },+ );++ const observe: GitHubGraphQlBudget["Service"]["observe"] = Effect.fn(+ "GitHubGraphQlBudget.observe",+ )(function* (host, raw) {+ const snapshot = snapshotFrom(raw);+ if (snapshot === null) return;+ yield* Ref.update(snapshots, (current) => {+ const key = hostKey(host);+ const previous = current.get(key);+ // Concurrent reads can finish out of order. Quota only falls within one reset window, and+ // an answer from an older window must not replace the current one.+ if (+ previous !== undefined &&+ (snapshot.resetAtMs < previous.resetAtMs ||+ (snapshot.resetAtMs === previous.resetAtMs && snapshot.remaining >= previous.remaining))+ ) {+ return current;+ }+ const next = new Map(current);+ next.set(key, snapshot);+ return next;+ });+ });++ return GitHubGraphQlBudget.of({ query, observe });+});++export const layer = Layer.effect(GitHubGraphQlBudget, make);diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.tsindex 58596d194..bd3e5b4cd 100644--- a/apps/server/src/vcs/VcsProcess.test.ts+++ b/apps/server/src/vcs/VcsProcess.test.ts@@ -165,6 +165,24 @@ describe("VcsProcess.run", () => {}).pipe(provideLive),);+ it.effect("classifies HTTP 429 responses as rate limits", () =>+ Effect.gen(function* () {+ const providerStderr = "HTTP 429: Too Many Requests. request-id=secret-value";+ const error = yield* run({+ operation: "test.rate-limit",+ command: "node",+ args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],+ cwd: process.cwd(),+ }).pipe(Effect.flip);++ expect(error).toMatchObject({+ detail: "API rate limit exceeded.",+ failureKind: "rate-limited",+ });+ expect(error.message).not.toContain(providerStderr);+ }).pipe(provideLive),+ );+it.effect("retains spawn causes without exposing process arguments in the error message", () =>Effect.gen(function* () {const secretArgument = "--token=super-secret-token";diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.tsindex ee4ed9712..ec245fa13 100644--- a/apps/server/src/vcs/VcsProcess.ts+++ b/apps/server/src/vcs/VcsProcess.ts@@ -72,7 +72,9 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFaiif (normalized.includes("api rate limit") ||normalized.includes("rate limit exceeded") ||- normalized.includes("secondary rate limit")+ normalized.includes("secondary rate limit") ||+ normalized.includes("too many requests") ||+ normalized.includes("http 429")) {return "rate-limited";}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 56ea24a4a..ebcf65e4b 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -1659,6 +1659,14 @@ const makeWsRpcLayer = (observeRpcEffect(WS_METHODS.pullRequestsActivity, pullRequests.activity(input), {"rpc.aggregate": "pull-requests",}),+ [WS_METHODS.pullRequestsThreadComments]: (input) =>+ observeRpcEffect(+ WS_METHODS.pullRequestsThreadComments,+ pullRequests.threadComments(input),+ {+ "rpc.aggregate": "pull-requests",+ },+ ),[WS_METHODS.pullRequestsDiffFileContents]: (input) =>observeRpcEffect(WS_METHODS.pullRequestsDiffFileContents,diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsxindex 7f4b8fa1f..b0e00d57c 100644--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx@@ -8,6 +8,7 @@ import type {PullRequestRef,PullRequestReviewPosition,PullRequestReviewThread,+ PullRequestThreadCommentsResult,} from "@t3tools/contracts";import {ChevronDownIcon,@@ -336,6 +337,9 @@ export function PullRequestCodeTab({const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {reportFailure: false,});+ const loadThreadComments = useAtomCommand(pullRequestEnvironment.threadComments, {+ reportFailure: false,+ });const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);const loadDiffFiles = useMemo(() =>@@ -798,6 +802,20 @@ export function PullRequestCodeTab({fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}fixLabel={fixFindingLabel}{...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}+ onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {+ const result = await loadThreadComments({+ environmentId,+ input: { ...reference, threadId: thread.id, cursor },+ });+ if (result._tag === "Failure") {+ toastManager.add({+ type: "error",+ title: "More comments could not be loaded",+ });+ return null;+ }+ return result.value;+ }}onReply={(body) =>runThreadCommand("Reply could not be posted", () =>replyToThread({@@ -833,6 +851,7 @@ export function PullRequestCodeTab({detail,environmentId,fixFindingLabel,+ loadThreadComments,onRefresh,onFixFinding,pendingFinding,diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex a40150ae6..f783029f1 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -111,6 +111,7 @@ import {readableFailure,resolveBaseFreshness,type PullRequestFinding,+ shouldRefreshPullRequestActivity,} from "./pullRequestDetail.logic";import { canEditPullRequestChangeRequest } from "./pullRequestEditing.logic";import {@@ -511,6 +512,17 @@ export function PullRequestDetailPanel({detailQuery.refresh();activityQuery.refresh();}, [activityQuery.refresh, detailQuery.refresh]);+ const activityRevision = useRef<{ readonly key: string; readonly updatedAt: string } | null>(+ null,+ );+ useEffect(() => {+ if (!coreDetail) return;+ const next = { key: pullRequestKey, updatedAt: coreDetail.updatedAt };+ if (shouldRefreshPullRequestActivity(activityRevision.current, next)) {+ activityQuery.refresh();+ }+ activityRevision.current = next;+ }, [activityQuery.refresh, coreDetail, pullRequestKey]);useEffect(() => {if (!detail) return;onStateChange?.({@@ -521,11 +533,11 @@ export function PullRequestDetailPanel({isDraft: detail.isDraft,});}, [detail, onStateChange]);- // A pull request changes while it is open in front of somebody — a push lands, a check- // finishes, a review arrives — so the panel reads it again on the way back to the window and- // while a reader sits on it. Keyed by the pull request rather than by the panel, because this- // one panel shows a different pull request every time it is opened.- useLiveRefresh(refreshDetail, {+ // Core detail is cheap enough to re-read while this stays open. Activity is heavier, so the+ // revision effect above reads it only after this same pull request reports a change. Keyed by+ // the pull request rather than by the panel, because this one panel shows a different pull+ // request every time it is opened.+ useLiveRefresh(detailQuery.refresh, {key: `pull-request:${reference.projectId}:${reference.repository}#${reference.number}`,});// The button, on the other hand, goes around the server's cache rather than through it: it isdiff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsxindex 47f59240a..c2e95ee41 100644--- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx+++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx@@ -6,6 +6,7 @@ import type {EnvironmentId,PullRequestRef,PullRequestReviewThread,+ PullRequestThreadCommentsResult,PullRequestThreadComment,} from "@t3tools/contracts";import {@@ -24,6 +25,10 @@ import { cn } from "~/lib/utils";import { Button } from "../ui/button";import { Textarea } from "../ui/textarea";import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";+import {+ editPullRequestThreadComment,+ mergePullRequestThreadComments,+} from "./pullRequestDetail.logic";import { PullRequestActorLabel } from "./pullRequestPresentation";import { PullRequestMarkdown } from "./PullRequestMarkdown";import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";@@ -98,6 +103,7 @@ export function ReviewThreadCard({fixLabel = "Fix in a thread",onFix,onReply,+ onLoadMore,canEditComment,onEditComment,onToggleResolved,@@ -118,6 +124,8 @@ export function ReviewThreadCard({onFix?: () => void;/** Resolves to whether the host took it, so a reply that failed keeps the words it was given. */onReply: (body: string) => Promise<boolean>;+ /** Reads one more page only after the reader asks for it. */+ onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;/** Whether this reader wrote this remark, which is what rewriting one takes. */canEditComment: (comment: PullRequestThreadComment) => boolean;/** Resolves to whether the host took it, like `onReply`. */@@ -132,13 +140,32 @@ export function ReviewThreadCard({const [editingId, setEditingId] = useState<string | null>(null);const [savingEdit, setSavingEdit] = useState(false);const sendingRef = useRef(false);+ const [loadedPage, setLoadedPage] = useState<+ (PullRequestThreadCommentsResult & { readonly threadId: string }) | null+ >(null);+ const [loadingMore, setLoadingMore] = useState(false);+ const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;+ const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);+ const nextCommentsCursor =+ currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;+ const commentCount = thread.commentCount ?? comments.length;const saveEdit = async (commentId: string, body: string) => {if (savingEdit) return;setSavingEdit(true);const saved = await onEditComment(commentId, body);setSavingEdit(false);- if (saved) setEditingId(null);+ if (saved) {+ setLoadedPage((previous) =>+ previous?.threadId === thread.id+ ? {+ ...previous,+ comments: editPullRequestThreadComment(previous.comments, commentId, body),+ }+ : previous,+ );+ setEditingId(null);+ }};const send = async () => {@@ -149,6 +176,16 @@ export function ReviewThreadCard({// empty box, and the words have to be written again.try {if (await onReply(trimmed)) {+ // The mutation returns no comment. Keep what the reader loaded and reopen its cursor so+ // the new reply remains reachable without spending requests until they ask to load it.+ setLoadedPage((previous) =>+ previous?.threadId === thread.id+ ? {+ ...previous,+ nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,+ }+ : previous,+ );setReply("");setReplying(false);}@@ -156,6 +193,24 @@ export function ReviewThreadCard({sendingRef.current = false;}};+ const loadMore = async () => {+ if (nextCommentsCursor === null || loadingMore) return;+ setLoadingMore(true);+ try {+ const page = await onLoadMore(nextCommentsCursor);+ if (page === null) return;+ setLoadedPage((previous) => ({+ threadId: thread.id,+ comments: mergePullRequestThreadComments(+ previous?.threadId === thread.id ? previous.comments : [],+ page.comments,+ ),+ nextCursor: page.nextCursor,+ }));+ } finally {+ setLoadingMore(false);+ }+ };return (<div@@ -175,8 +230,8 @@ export function ReviewThreadCard({aria-expanded={expanded}onClick={() => setExpanded((current) => !current)}>- {thread.isResolved ? "Resolved" : "Open"} · {thread.comments.length}{" "}- {thread.comments.length === 1 ? "comment" : "comments"}+ {thread.isResolved ? "Resolved" : "Open"} · {commentCount}{" "}+ {commentCount === 1 ? "comment" : "comments"}</button>{thread.isOutdated ? <span>outdated</span> : null}{onFix ? (@@ -207,7 +262,7 @@ export function ReviewThreadCard({{expanded ? (<><div className="mt-2 space-y-3">- {thread.comments.map((comment) => (+ {comments.map((comment) => (<article key={comment.id} className="group min-w-0"><div className="flex items-center gap-2 text-xs text-muted-foreground"><PullRequestActorLabel actor={comment.author} className="text-foreground" />@@ -255,6 +310,19 @@ export function ReviewThreadCard({</article>))}</div>+ {nextCommentsCursor !== null ? (+ <div className="mt-2">+ <Button+ size="xs"+ variant="ghost"+ className="px-1"+ disabled={loadingMore}+ onClick={() => void loadMore()}+ >+ {loadingMore ? "Loading..." : "Load more comments"}+ </Button>+ </div>+ ) : null}{canReply ? (replying ? (diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.tsindex f9d4ce457..044593971 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts@@ -17,6 +17,7 @@ import {handoffPrompt,handoffReviewComments,isThreadOwnPullRequest,+ mergePullRequestThreadComments,orderPullRequestComments,pullRequestActionMenuHasGroup,pullRequestActionNeedsHostRefresh,@@ -24,9 +25,11 @@ import {pullRequestFindingKey,pullRequestHandoffLabels,readableFailure,+ shouldRefreshPullRequestActivity,resolveBaseFreshness,buildPullRequestTimeline,describePullRequestState,+ editPullRequestThreadComment,} from "./pullRequestDetail.logic";import type { ReviewCommentContext } from "~/reviewCommentContext";@@ -55,6 +58,65 @@ const TIMELINE_SOURCE: Pick<closedAt: null,};+describe("pull request activity refresh", () => {+ const first = {+ key: "project:acme/web#7",+ updatedAt: "2026-08-13T13:00:00Z",+ };++ it("refreshes activity only after the same pull request changes", () => {+ expect(+ shouldRefreshPullRequestActivity(first, {+ ...first,+ updatedAt: "2026-08-13T13:01:00Z",+ }),+ ).toBe(true);+ });++ it("does not duplicate the first activity read or carry a revision across pull requests", () => {+ expect(shouldRefreshPullRequestActivity(null, first)).toBe(false);+ expect(shouldRefreshPullRequestActivity(first, first)).toBe(false);+ expect(+ shouldRefreshPullRequestActivity(first, {+ key: "project:acme/web#8",+ updatedAt: "2026-08-13T13:01:00Z",+ }),+ ).toBe(false);+ });+});+describe("review thread comment pages", () => {+ it("appends new comments once and keeps refreshed base comments", () => {+ expect(+ mergePullRequestThreadComments(+ [+ { id: "c1", body: "refreshed" },+ { id: "c2", body: "already in base" },+ ],+ [+ { id: "c2", body: "stale page copy" },+ { id: "c3", body: "next page" },+ ],+ ),+ ).toEqual([+ { id: "c1", body: "refreshed" },+ { id: "c2", body: "already in base" },+ { id: "c3", body: "next page" },+ ]);+ });++ it("keeps a loaded comment after its body is edited", () => {+ const loaded = [+ { id: "c2", body: "old body" },+ { id: "c3", body: "another loaded comment" },+ ];++ expect(editPullRequestThreadComment(loaded, "c2", "saved body")).toEqual([+ { id: "c2", body: "saved body" },+ { id: "c3", body: "another loaded comment" },+ ]);+ });+});+describe("pull request action menu", () => {it("keeps the group divider when auto-merge is the only action", () => {expect(pullRequestActionMenuHasGroup(false, true, false)).toBe(true);diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.tsindex 8c72b944c..27e71236e 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts@@ -14,6 +14,35 @@ import type {import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";+/** Activity changes only when the same host resource reports a newer revision. */+export function shouldRefreshPullRequestActivity(+ previous: { readonly key: string; readonly updatedAt: string } | null,+ next: { readonly key: string; readonly updatedAt: string },+): boolean {+ return previous !== null && previous.key === next.key && previous.updatedAt !== next.updatedAt;+}+/** Appends fetched pages without replacing fresher comments already in the activity response. */+export function mergePullRequestThreadComments<T extends { readonly id: string }>(+ base: ReadonlyArray<T>,+ loaded: ReadonlyArray<T>,+): ReadonlyArray<T> {+ const seen = new Set(base.map((comment) => comment.id));+ return [+ ...base,+ ...loaded.filter((comment) => {+ if (seen.has(comment.id)) return false;+ seen.add(comment.id);+ return true;+ }),+ ];+}++export function editPullRequestThreadComment<+ T extends { readonly id: string; readonly body: string },+>(comments: ReadonlyArray<T>, commentId: string, body: string): ReadonlyArray<T> {+ return comments.map((comment) => (comment.id === commentId ? { ...comment, body } : comment));+}+/*** Whether the pull request on a right-panel surface is the thread's own one. Repository and* number are not enough: one environment can hold two checkouts of the same repository underdiff --git a/apps/web/src/hooks/useLiveRefresh.test.ts b/apps/web/src/hooks/useLiveRefresh.test.tsindex 632dd0d45..75bfbe6df 100644--- a/apps/web/src/hooks/useLiveRefresh.test.ts+++ b/apps/web/src/hooks/useLiveRefresh.test.ts@@ -9,6 +9,12 @@ import {shouldRefreshOnInterval,} from "./useLiveRefresh";+describe("live refresh cadence", () => {+ it("waits five minutes between automatic host reads", () => {+ expect(LIVE_REFRESH_INTERVAL_MS).toBe(5 * 60_000);+ });+});+describe("shouldLiveRefresh", () => {const at = (now: number, lastRefreshedAt: number, visible = true) =>shouldLiveRefresh({ visible, now, lastRefreshedAt });@@ -79,12 +85,16 @@ describe("shouldRefreshOnInterval", () => {expect(tick(LIVE_REFRESH_INTERVAL_MS, LIVE_REFRESH_INTERVAL_MS - 1_000)).toBe(true);});+ it("reads on the first interval after an untouched mount", () => {+ expect(tick(LIVE_REFRESH_INTERVAL_MS + 1_000, 0)).toBe(true);+ });+it("stops reading for a window left showing on a desk nobody is at", () => {expect(tick(LIVE_REFRESH_IDLE_AFTER_MS + 60_000, 0)).toBe(false);});it("starts reading again once the reader touches the window", () => {const away = LIVE_REFRESH_IDLE_AFTER_MS + 60_000;- expect(tick(away + LIVE_REFRESH_INTERVAL_MS, away)).toBe(true);+ expect(tick(away + LIVE_REFRESH_MIN_INTERVAL_MS, away)).toBe(true);});});diff --git a/apps/web/src/hooks/useLiveRefresh.ts b/apps/web/src/hooks/useLiveRefresh.tsindex 9d9b11295..5c3fc3c81 100644--- a/apps/web/src/hooks/useLiveRefresh.ts+++ b/apps/web/src/hooks/useLiveRefresh.ts@@ -18,16 +18,17 @@ import { useEffect, useId, useRef } from "react";/** Long enough that alt-tabbing through windows does not become a request per tab stop. */export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;-/** Slow enough to be cheap on the host, quick enough that a reader is not reading last minute. */-export const LIVE_REFRESH_INTERVAL_MS = 60_000;+/** Slow enough to preserve host quota while still updating a view left open. */+export const LIVE_REFRESH_INTERVAL_MS = 5 * 60_000;/**- * How long a showing window goes untouched before it stops reading. A window left open on a+ * How long a showing window goes untouched before it stops reading. This leaves one minute after+ * the five-minute interval for the first timer tick to run. A window left open on a* monitor nobody is sitting at is showing in every sense the browser knows about, and polling it* until morning spends a night of somebody's rate limit on an answer nobody read. Their next* click, key or scroll starts the interval up again.*/-export const LIVE_REFRESH_IDLE_AFTER_MS = 5 * 60_000;+export const LIVE_REFRESH_IDLE_AFTER_MS = 6 * 60_000;/*** Whether a view should read again now. Separate from the hook because the rule is the whole ofdiff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsxindex af1b970f3..2ee7eb93f 100644--- a/apps/web/src/routes/_chat.pull-requests.tsx+++ b/apps/web/src/routes/_chat.pull-requests.tsx@@ -972,7 +972,6 @@ function PullRequestsRouteView() {useLiveRefresh(() => {refreshList();- baselineQuery.refresh();authoredQuery.refresh();reviewingQuery.refresh();},diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 7e84f4cb6..d4830fa19 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -61,6 +61,16 @@ export function createPullRequestEnvironmentAtoms<R, E>(tag: WS_METHODS.pullRequestsActivity,staleTimeMs: 15_000,}),+ threadComments: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:pull-requests:thread-comments",+ tag: WS_METHODS.pullRequestsThreadComments,+ scheduler: commandScheduler,+ concurrency: {+ mode: "singleFlight",+ key: ({ environmentId, input }) =>+ JSON.stringify([environmentId, input.threadId, input.cursor]),+ },+ }),diff: createEnvironmentQueryAtomFamily(runtime, {label: "environment-data:pull-requests:diff",staleTimeMs: 60_000,diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex dea49ea8f..a49868937 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -241,6 +241,10 @@ export const PullRequestReviewThread = Schema.Struct({*/isOutdated: Schema.Boolean,comments: Schema.Array(PullRequestThreadComment),+ /** Host-reported total, when this thread was read in pages. */+ commentCount: Schema.optional(NonNegativeInt),+ /** Opaque cursor for the next comment page. Absent once this thread is whole. */+ nextCommentsCursor: Schema.optional(TrimmedNonEmptyString),});export type PullRequestReviewThread = typeof PullRequestReviewThread.Type;@@ -904,6 +908,19 @@ export const PullRequestSubmitReviewInput = Schema.Struct({});export type PullRequestSubmitReviewInput = typeof PullRequestSubmitReviewInput.Type;+export const PullRequestThreadCommentsInput = Schema.Struct({+ ...PullRequestRef.fields,+ threadId: TrimmedNonEmptyString,+ cursor: TrimmedNonEmptyString,+});+export type PullRequestThreadCommentsInput = typeof PullRequestThreadCommentsInput.Type;++export const PullRequestThreadCommentsResult = Schema.Struct({+ comments: Schema.Array(PullRequestThreadComment),+ nextCursor: Schema.NullOr(TrimmedNonEmptyString),+});+export type PullRequestThreadCommentsResult = typeof PullRequestThreadCommentsResult.Type;+export const PullRequestThreadReplyInput = Schema.Struct({...PullRequestRef.fields,threadId: TrimmedNonEmptyString,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 115fc8a13..51c65f50e 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -86,6 +86,8 @@ import {PullRequestReviewerCandidateList,PullRequestReviewerRequestInput,PullRequestSubmitReviewInput,+ PullRequestThreadCommentsInput,+ PullRequestThreadCommentsResult,PullRequestThreadReplyInput,PullRequestThreadResolutionInput,PullRequestUnavailableError,@@ -281,6 +283,7 @@ export const WS_METHODS = {pullRequestsListStats: "pullRequests.listStats",pullRequestsDetail: "pullRequests.detail",pullRequestsActivity: "pullRequests.activity",+ pullRequestsThreadComments: "pullRequests.threadComments",pullRequestsDiffFileContents: "pullRequests.diffFileContents",pullRequestsRunAction: "pullRequests.runAction",pullRequestsUpdate: "pullRequests.update",@@ -502,6 +505,12 @@ export const WsPullRequestsActivityRpc = Rpc.make(WS_METHODS.pullRequestsActiviterror: PullRequestRpcError,});+export const WsPullRequestsThreadCommentsRpc = Rpc.make(WS_METHODS.pullRequestsThreadComments, {+ payload: PullRequestThreadCommentsInput,+ success: PullRequestThreadCommentsResult,+ error: PullRequestRpcError,+});+export const WsPullRequestsDiffFileContentsRpc = Rpc.make(WS_METHODS.pullRequestsDiffFileContents, {payload: PullRequestDiffFileContentsInput,success: PullRequestDiffFileContentsResult,@@ -1001,6 +1010,7 @@ export const WsRpcGroup = RpcGroup.make(WsPullRequestsListStatsRpc,WsPullRequestsDetailRpc,WsPullRequestsActivityRpc,+ WsPullRequestsThreadCommentsRpc,WsPullRequestsDiffFileContentsRpc,WsPullRequestsRunActionRpc,WsPullRequestsUpdateRpc,