fix(server): settle threads server-side #8600
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 13 commits into
main fromrefs/pull/8600/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration/Services/ThreadSettlementReactor.ts lines 5 to 13OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +1,13 @@1+import * as Context from "effect/Context";2+import type * as Effect from "effect/Effect";3+import type * as Scope from "effect/Scope";4+5+export interface ThreadSettlementReactorShape {6+ readonly start: () => Effect.Effect<void, never, Scope.Scope>;7+ readonly drain: Effect.Effect<void>;8+}9+10+export class ThreadSettlementReactor extends Context.Service<11+ ThreadSettlementReactor,12+ ThreadSettlementReactorShape13+>()("t3/orchestration/Services/ThreadSettlementReactor") {}
- apps/server/src/git/GitManager.ts line 2050Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1842,0 +1894,21 @@1894+ const defaultBranch = yield* gitCore.resolvePrimaryRemoteName(cacheCwd).pipe(1895+ Effect.flatMap((primaryRemote) => gitCore.resolveDefaultBranchName(cacheCwd, primaryRemote)),1896+ Effect.orElseSucceed(() => null),1897+ );1898+ const { latest } = yield* Cache.get(1899+ prLookupCache,1900+ prLookupCacheKey(cacheCwd, {1901+ branch,1902+ upstreamRef,1903+ defaultBranch,1904+ localBranchExists,1905+ }),1906+ );1907+ if (latest === null) return null;1908+ if (1909+ (branch === defaultBranch ||1910+ (defaultBranch === null && (branch === "main" || branch === "master"))) &&1911+ latest.state !== "open"1912+ ) {1913+ return null;1914+ }
- apps/server/src/orchestration/ThreadSettlementReactor.test.ts line 1Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +1 @@1+import {
- apps/web/src/components/settings/SettingsPanels.tsx lines 1963 to 1964Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1955,19 +1959,2 @@1955- description="Settle a thread when its pull request merges. Closed pull requests still settle automatically."1956- resetAction={1957- settings.sidebarAutoSettleOnMerge !==1958- DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? (1959- <SettingResetButton1960- label="auto-settle on merge"1961- onClick={() =>1962- updateSettings({1963- sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,1964- })1965- }1966- />1967- ) : null1968- }1969- control={1970- <Switch1971- checked={settings.sidebarAutoSettleOnMerge}1972- onCheckedChange={(checked) =>1973- updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) })1959+ {supportsAutoSettlement ? (1960+ <>
- apps/server/src/git/GitManager.ts line 1911OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1871,0 +1891,21 @@1891+ const cacheCwd = yield* normalizeStatusCacheKey(cwd);1892+ const remotes = yield* gitCore.execute({1893+ operation: "GitManager.branchPullRequest.remotes",1894+ cwd: cacheCwd,1895+ args: ["remote"],1896+ });1897+ if (remotes.stdout.trim().length === 0) return null;1898+ const branchRef = yield* gitCore.execute({1899+ operation: "GitManager.branchPullRequest.branchRef",1900+ cwd: cacheCwd,1901+ args: ["for-each-ref", "--format=%(refname)%00%(upstream:short)", `refs/heads/${branch}`],1902+ });1903+ const expectedRefName = `refs/heads/${branch}`;1904+ const exactBranch = branchRef.stdout1905+ .split("\n")1906+ .find((line) => line.split("\u0000", 1)[0] === expectedRefName);1907+ const [refName = "", savedUpstream = ""] = exactBranch?.split("\u0000") ?? [];1908+ const localBranchExists = refName.length > 0;1909+ let upstreamRef: string | null = null;1910+ if (savedUpstream.length > 0) {1911+ const remoteName = yield* gitCore.readConfigValue(cacheCwd, `branch.${branch}.remote`);apps/server/src/git/GitManager.ts line 1927OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1871,0 +1907,21 @@1907+ const [refName = "", savedUpstream = ""] = exactBranch?.split("\u0000") ?? [];1908+ const localBranchExists = refName.length > 0;1909+ let upstreamRef: string | null = null;1910+ if (savedUpstream.length > 0) {1911+ const remoteName = yield* gitCore.readConfigValue(cacheCwd, `branch.${branch}.remote`);1912+ const mergeRef = yield* gitCore.readConfigValue(cacheCwd, `branch.${branch}.merge`);1913+ if (remoteName === null || mergeRef === null) {1914+ return yield* new GitManagerError({1915+ operation: "branchPullRequest",1916+ cwd: cacheCwd,1917+ detail: `Saved upstream for ${branch} is incomplete.`,1918+ });1919+ }1920+ const upstreamBranch = mergeRef.replace(/^refs\/heads\//, "");1921+ upstreamRef = `${remoteName}/${upstreamBranch}`;1922+ }1923+ const defaultBranch = yield* gitCore.resolvePrimaryRemoteName(cacheCwd).pipe(1924+ Effect.flatMap((primaryRemote) => gitCore.resolveDefaultBranchName(cacheCwd, primaryRemote)),1925+ Effect.orElseSucceed(() => null),1926+ );1927+ const { latest } = yield* Cache.get(
- apps/server/src/orchestration/ThreadSettlementPolicy.ts lines 49 to 49OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +29,21 @@29+ if (thread.latestUserMessageAt === null || thread.session?.status === "error") return false;30+ const messageAt = Date.parse(thread.latestUserMessageAt);31+ const age = Date.parse(now) - messageAt;32+ if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;33+ if (thread.latestTurn === null) return true;34+ return [35+ thread.latestTurn.requestedAt,36+ thread.latestTurn.startedAt,37+ thread.latestTurn.completedAt,38+ ].every((value) => value == null || Date.parse(value) < messageAt);39+}40+41+function pullRequestSettles(42+ thread: Pick<OrchestrationThreadShell, "createdAt" | "latestUserMessageAt" | "latestTurn">,43+ pullRequest: SettlementPullRequest,44+ autoSettleOnMerge: boolean,45+): boolean {46+ if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {47+ return false;48+ }49+ if (pullRequest.updatedAt === null) return true;apps/server/src/orchestration/decider.ts line 466OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -450,13 +454,13 @@450454 };451455 }452456453- case "thread.settle": {457+ case "thread.settle":458+ case "thread.auto-settle": {454459 const thread = yield* requireThreadNotArchived({455460 readModel,456461 command,457462 threadId: command.threadId,458463 });459- // Server-side twin of the client's canSettle session check: a stale460- // or raced client must not settle a thread whose session is coming461- // alive or working.462- if (thread.session?.status === "starting" || thread.session?.status === "running") {464+ if (465+ command.type === "thread.auto-settle" &&466+ (thread.updatedAt !== command.expectedUpdatedAt || thread.settledOverride !== null)
- apps/server/src/orchestration/ThreadSettlementReactor.ts line 71Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+ const now = DateTime.formatIso(yield* DateTime.now);44+ const projects = new Map(snapshot.projects.map((project) => [project.id, project]));45+ const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));46+ const lookupByKey = new Map<47+ string,48+ Effect.Effect<49+ SettlementPullRequest | null,50+ GitManagerServiceError | PullRequestService.PullRequestError51+ >52+ >();53+54+ const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (55+ thread: (typeof candidates)[number],56+ ) {57+ const project = projects.get(thread.projectId);58+ if (project === undefined) return null;59+ if (thread.linkedPullRequest != null) {60+ const linkedProject = projects.get(thread.linkedPullRequest.projectId);61+ if (linkedProject === undefined) {62+ return yield* Effect.die(new Error("linked pull request project not found"));63+ }
- apps/server/src/git/GitManager.ts lines 1992 to 1994Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1871,0 +1972,21 @@1972+ .map((remoteRef) => remoteRef.trim())1973+ .filter((remoteRef) => remoteRef.length > 0),1974+ );1975+ const matchingRemoteNames = remoteNames.filter((candidate) =>1976+ refNames.has(`refs/remotes/${candidate}/${branch}`),1977+ );1978+ if (matchingRemoteNames.length > 1) {1979+ return yield* new GitManagerError({1980+ operation: "branchPullRequest",1981+ cwd: cacheCwd,1982+ detail: `Multiple remotes track ${branch}. Its pull request is ambiguous.`,1983+ });1984+ }1985+ remoteName = matchingRemoteNames[0] ?? null;1986+ if (remoteName !== null) {1987+ upstreamRef = `${remoteName}/${branch}`;1988+ }1989+ }1990+ const defaultBranch = yield* gitCore1991+ .resolveDefaultBranchName(cacheCwd, "origin")1992+ .pipe(Effect.orElseSucceed(() => null));
- apps/server/src/orchestration/ThreadSettlementReactor.ts line 115Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +95,21 @@95+ Effect.gen(function* () {96+ const settings = yield* settingsService.getSettings;97+ const decisionNow = DateTime.formatIso(yield* DateTime.now);98+ if (99+ !shouldAutoSettleThread({100+ thread,101+ pullRequest,102+ now: decisionNow,103+ autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,104+ autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,105+ })106+ ) {107+ return;108+ }109+ const uuid = yield* crypto.randomUUIDv4;110+ yield* engine.dispatch({111+ type: "thread.auto-settle",112+ commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),113+ threadId: thread.id,114+ snapshotSequence: snapshot.snapshotSequence,115+ });
t3dotgg(GitHub profile, opens in a new tab) changed the title
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.




Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
9ee8608e-a3e2-4f90-8b94-d8020cf3611aYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.