From 3e757bd28bee2f7156003cd00897ab4a1204b6e2 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 24 Jul 2026 05:36:14 -0700 Subject: [PATCH] Background sweep, launch modal, PR investigation, and merge queue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four features from real-data testing feedback: - The sidebar button now opens a launch modal (scope + model + cost summary) instead of navigating. Starting closes the modal and shows a "running in background" toast; completion raises a toast with an actionable-count summary and a "View results" link. The sweep was already navigation-proof; now the UX matches. - Reviews investigate deeper: when a thread's branch has a PR, the server fetches state, review decision, CI rollup, mergeability, and the last five comments via `gh pr view`, feeds them into the review prompt, and returns a prStatus with a computed mergeReady flag (open + clean merge + CI not failing + not blocked on review). Lookups degrade to "no PR context" on any failure. - New "Merge ready" bucket at the top of the results grid with per-card "Merge & settle" and a section-level "Merge all (N)". - Merging runs through a SEQUENTIAL queue: each PR is re-validated against live GitHub state before merging (an earlier queue entry may have just changed the base), merged PRs settle their thread immediately, and a conflict marks the card and hands the rebase to the thread's own agent via a turn message — the queue continues past it. review.mergePullRequest returns conflict/already-closed/not-ready as outcomes rather than errors so the queue can branch on them. Co-Authored-By: Claude Fable 5 --- apps/server/src/review/ReviewService.test.ts | 204 ++++++++++++++ apps/server/src/review/ReviewService.ts | 254 ++++++++++++++++++ apps/server/src/server.test.ts | 6 + apps/server/src/server.ts | 1 + .../textGeneration/ClaudeTextGeneration.ts | 1 + .../src/textGeneration/CodexTextGeneration.ts | 1 + .../textGeneration/CursorTextGeneration.ts | 1 + .../src/textGeneration/GrokTextGeneration.ts | 1 + .../textGeneration/OpenCodeTextGeneration.ts | 1 + .../src/textGeneration/TextGeneration.ts | 11 + .../textGeneration/TextGenerationPrompts.ts | 41 +++ apps/server/src/ws.ts | 5 + apps/web/src/components/SidebarV2.tsx | 14 +- .../reviewSweep/ReviewSweepLaunchDialog.tsx | 62 +++++ .../reviewSweep/ReviewSweepView.tsx | 112 +++++++- apps/web/src/reviewSweepStore.ts | 222 ++++++++++++++- packages/client-runtime/src/state/review.ts | 4 + packages/contracts/src/review.ts | 59 ++++ packages/contracts/src/rpc.ts | 15 ++ 19 files changed, 1000 insertions(+), 15 deletions(-) create mode 100644 apps/web/src/components/reviewSweep/ReviewSweepLaunchDialog.tsx diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index fdc8663831..6d64c383dd 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -5,6 +5,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; +import * as Schema from "effect/Schema"; import { ThreadId, @@ -15,11 +16,35 @@ import { import { ServerConfig } from "../config.ts"; import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as GitHubCli from "../sourceControl/GitHubCli.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as ReviewService from "./ReviewService.ts"; +const GhPrViewFixture = Schema.Struct({ + number: Schema.Int, + url: Schema.String, + state: Schema.String, + reviewDecision: Schema.optionalKey(Schema.NullOr(Schema.String)), + mergeable: Schema.optionalKey(Schema.NullOr(Schema.String)), + statusCheckRollup: Schema.optionalKey(Schema.Array(Schema.Struct({ conclusion: Schema.String }))), + comments: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + author: Schema.Struct({ login: Schema.String }), + body: Schema.String, + createdAt: Schema.String, + }), + ), + ), +}); +const encodeGhPrViewFixture = Schema.encodeUnknownSync(Schema.fromJsonString(GhPrViewFixture)); + +function ghPrViewJson(fixture: typeof GhPrViewFixture.Type): string { + return encodeGhPrViewFixture(fixture); +} + function makeShellFromThread( thread: OrchestrationThread, overrides: Partial = {}, @@ -56,6 +81,7 @@ function makeLayer(input: { readonly shellOverrides?: Partial; readonly generateThreadReview?: TextGeneration.TextGeneration["Service"]["generateThreadReview"]; readonly reviewCalls?: Array; + readonly ghExecute?: GitHubCli.GitHubCli["Service"]["execute"]; }) { return ReviewService.layer.pipe( Layer.provide( @@ -104,6 +130,13 @@ function makeLayer(input: { }, }), ), + Layer.provide( + Layer.mock(GitHubCli.GitHubCli)({ + // Threads in these tests have no PR; investigation must degrade to + // "no context" without touching gh. + execute: input.ghExecute ?? (() => Effect.die("gh not stubbed in this test")), + }), + ), Layer.provide(ServerSettings.layerTest()), Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)), Layer.provideMerge(NodeServices.layer), @@ -398,6 +431,177 @@ describe("ReviewService", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("summarizeThread attaches PR status and prompt context when gh finds a PR", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); + const reviewCalls: Array = []; + const thread = makeThread({ branch: "feat/settle-default" }); + const ghPayload = ghPrViewJson({ + number: 4415, + url: "https://github.com/pingdotgg/t3code/pull/4415", + state: "OPEN", + reviewDecision: "APPROVED", + mergeable: "MERGEABLE", + statusCheckRollup: [{ conclusion: "SUCCESS" }, { conclusion: "SKIPPED" }], + comments: [ + { author: { login: "reviewer" }, body: "LGTM", createdAt: "2026-07-24T00:00:00Z" }, + ], + }); + + const result = yield* Effect.gen(function* () { + const review = yield* ReviewService.ReviewService; + return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true }); + }).pipe( + Effect.provide( + makeLayer({ + workspaceRoot, + baseDir, + thread, + reviewCalls, + ghExecute: () => + Effect.succeed({ + exitCode: 0, + stdout: ghPayload, + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + } as never), + }), + ), + ); + + assert.strictEqual(result.prStatus?.number, 4415); + assert.strictEqual(result.prStatus?.state, "open"); + assert.strictEqual(result.prStatus?.mergeReady, true); + assert.strictEqual(result.prStatus?.checksPassing, true); + assert.strictEqual(reviewCalls[0]?.pullRequest?.number, 4415); + assert.strictEqual(reviewCalls[0]?.pullRequest?.recentComments[0]?.body, "LGTM"); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("summarizeThread degrades to no PR context when gh fails", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); + const reviewCalls: Array = []; + const thread = makeThread({ branch: "feat/no-pr" }); + + const result = yield* Effect.gen(function* () { + const review = yield* ReviewService.ReviewService; + return yield* review.summarizeThread({ threadId: thread.id, canSettleNow: true }); + }).pipe( + Effect.provide( + makeLayer({ + workspaceRoot, + baseDir, + thread, + reviewCalls, + ghExecute: (ghInput) => + Effect.fail( + new GitHubCli.GitHubCliUnavailableError({ + command: "gh", + cwd: ghInput.cwd, + cause: "gh missing in test", + }) as never, + ), + }), + ), + ); + + assert.strictEqual(result.prStatus, undefined); + assert.strictEqual(reviewCalls[0]?.pullRequest, undefined); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("mergePullRequest reports conflict when the branch no longer merges cleanly", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); + const thread = makeThread({ branch: "feat/conflicting" }); + const ghPayload = ghPrViewJson({ + number: 77, + url: "https://github.com/x/y/pull/77", + state: "OPEN", + reviewDecision: "APPROVED", + mergeable: "CONFLICTING", + statusCheckRollup: [{ conclusion: "SUCCESS" }], + comments: [], + }); + + const result = yield* Effect.gen(function* () { + const review = yield* ReviewService.ReviewService; + return yield* review.mergePullRequest({ threadId: thread.id, pullRequestNumber: 77 }); + }).pipe( + Effect.provide( + makeLayer({ + workspaceRoot, + baseDir, + thread, + ghExecute: () => + Effect.succeed({ + exitCode: 0, + stdout: ghPayload, + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + } as never), + }), + ), + ); + + assert.strictEqual(result.outcome, "conflict"); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("mergePullRequest merges and reports merged for a ready PR", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); + const thread = makeThread({ branch: "feat/ready" }); + const ghCalls: string[] = []; + const ghPayload = ghPrViewJson({ + number: 88, + url: "https://github.com/x/y/pull/88", + state: "OPEN", + reviewDecision: "APPROVED", + mergeable: "MERGEABLE", + statusCheckRollup: [{ conclusion: "SUCCESS" }], + comments: [], + }); + + const result = yield* Effect.gen(function* () { + const review = yield* ReviewService.ReviewService; + return yield* review.mergePullRequest({ threadId: thread.id, pullRequestNumber: 88 }); + }).pipe( + Effect.provide( + makeLayer({ + workspaceRoot, + baseDir, + thread, + ghExecute: (ghInput) => { + ghCalls.push(ghInput.args.join(" ")); + return Effect.succeed({ + exitCode: 0, + stdout: ghInput.args[1] === "view" ? ghPayload : "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + } as never); + }, + }), + ), + ); + + assert.strictEqual(result.outcome, "merged"); + assert.ok(ghCalls.some((call) => call.startsWith("pr merge 88"))); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("summarizeThread treats a queued turn start as active", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts index e7bd8859a1..c6d951f612 100644 --- a/apps/server/src/review/ReviewService.ts +++ b/apps/server/src/review/ReviewService.ts @@ -6,7 +6,10 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + import { + ReviewMergeError, ReviewThreadNotFoundError, TextGenerationError, VcsRepositoryDetectionError, @@ -14,6 +17,10 @@ import { type ReviewDiffPreviewError, type ReviewDiffPreviewInput, type ReviewDiffPreviewResult, + type ReviewMergePullRequestError, + type ReviewMergePullRequestInput, + type ReviewMergePullRequestResult, + type ReviewThreadPrStatus, type ReviewThreadSummaryError, type ReviewThreadSummaryInput, type ReviewThreadSummaryResult, @@ -23,6 +30,7 @@ import { resolveThreadWorkspaceCwd } from "../checkpointing/Utils.ts"; import * as ServerConfig from "../config.ts"; import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as GitHubCli from "../sourceControl/GitHubCli.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -36,9 +44,109 @@ export class ReviewService extends Context.Service< readonly summarizeThread: ( input: ReviewThreadSummaryInput, ) => Effect.Effect; + readonly mergePullRequest: ( + input: ReviewMergePullRequestInput, + ) => Effect.Effect; } >()("t3/review/ReviewService") {} +// --------------------------------------------------------------------------- +// PR investigation +// --------------------------------------------------------------------------- + +/** Shape of `gh pr view --json ` we rely on. Decoded leniently: + a schema miss degrades to "no PR context", never a failed review. */ +const GhPrView = Schema.Struct({ + number: Schema.Int, + url: Schema.String, + state: Schema.String, + reviewDecision: Schema.optionalKey(Schema.NullOr(Schema.String)), + mergeable: Schema.optionalKey(Schema.NullOr(Schema.String)), + statusCheckRollup: Schema.optionalKey( + Schema.NullOr( + Schema.Array(Schema.Struct({ conclusion: Schema.optionalKey(Schema.NullOr(Schema.String)) })), + ), + ), + comments: Schema.optionalKey( + Schema.NullOr( + Schema.Array( + Schema.Struct({ + author: Schema.optionalKey(Schema.NullOr(Schema.Struct({ login: Schema.String }))), + body: Schema.String, + createdAt: Schema.String, + }), + ), + ), + ), +}); +const decodeGhPrView = Schema.decodeUnknownEffect(Schema.fromJsonString(GhPrView)); + +const GH_PR_VIEW_FIELDS = "number,url,state,reviewDecision,mergeable,statusCheckRollup,comments"; +const PR_COMMENT_CONTEXT_COUNT = 5; +const PR_COMMENT_CHAR_LIMIT = 500; + +export interface ThreadPrContext { + readonly status: ReviewThreadPrStatus; + /** Pre-rendered recent-comments block for the review prompt. */ + readonly recentComments: ReadonlyArray<{ + readonly author: string; + readonly createdAt: string; + readonly body: string; + }>; +} + +function ghStateToPrState(state: string): "open" | "closed" | "merged" | null { + const normalized = state.trim().toUpperCase(); + if (normalized === "OPEN") return "open"; + if (normalized === "CLOSED") return "closed"; + if (normalized === "MERGED") return "merged"; + return null; +} + +function rollupToChecksPassing( + rollup: ReadonlyArray<{ conclusion?: string | null }> | null | undefined, +): boolean | null { + if (!rollup || rollup.length === 0) return null; + // Neutral/skipped conclusions don't block; pending (null conclusion on some + // check types) and failures do. + const blocking = rollup.some((check) => { + const conclusion = check.conclusion?.trim().toUpperCase() ?? ""; + return !["SUCCESS", "NEUTRAL", "SKIPPED"].includes(conclusion); + }); + return !blocking; +} + +function toPrStatus(view: typeof GhPrView.Type): ReviewThreadPrStatus | null { + const state = ghStateToPrState(view.state); + if (state === null) return null; + const reviewDecision = view.reviewDecision?.trim() || null; + const checksPassing = rollupToChecksPassing(view.statusCheckRollup ?? null); + const mergeable = + view.mergeable == null + ? null + : view.mergeable.trim().toUpperCase() === "MERGEABLE" + ? true + : view.mergeable.trim().toUpperCase() === "CONFLICTING" + ? false + : null; + const mergeReady = + state === "open" && + mergeable === true && + checksPassing !== false && + reviewDecision !== "CHANGES_REQUESTED" && + reviewDecision !== "REVIEW_REQUIRED"; + return { + number: view.number, + url: view.url, + state, + reviewDecision, + checksPassing, + mergeable, + mergeReady, + recentCommentCount: view.comments?.length ?? 0, + }; +} + // Mirrors QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts and // the decider's thread.settle guard. const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000; @@ -83,6 +191,42 @@ export const make = Effect.gen(function* () { const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; const textGeneration = yield* TextGeneration.TextGeneration; const serverSettings = yield* ServerSettings.ServerSettingsService; + const gitHubCli = yield* GitHubCli.GitHubCli; + + /** Look up the thread branch's PR with one `gh pr view`. Every failure — + no PR, gh unauthenticated, schema drift — degrades to null: PR context + enriches a review but must never fail it. */ + const investigateThreadPr = Effect.fn("ReviewService.investigateThreadPr")(function* ( + cwd: string, + branch: string, + ): Effect.fn.Return { + const context = yield* gitHubCli + .execute({ + cwd, + args: ["pr", "view", branch, "--json", GH_PR_VIEW_FIELDS], + timeoutMs: 20_000, + }) + .pipe( + Effect.flatMap((output) => decodeGhPrView(output.stdout)), + Effect.map((view): ThreadPrContext | null => { + const status = toPrStatus(view); + if (status === null) return null; + const recentComments = (view.comments ?? []) + .slice(-PR_COMMENT_CONTEXT_COUNT) + .map((comment) => ({ + author: comment.author?.login ?? "unknown", + createdAt: comment.createdAt, + body: + comment.body.length > PR_COMMENT_CHAR_LIMIT + ? `${comment.body.slice(0, PR_COMMENT_CHAR_LIMIT)}…` + : comment.body, + })); + return { status, recentComments }; + }), + Effect.catch(() => Effect.succeed(null)), + ); + return context; + }); const canonicalizePath = (value: string) => { const resolvedPath = path.resolve(value); @@ -235,6 +379,11 @@ export const make = Effect.gen(function* () { ), ); + // Deeper investigation: live PR state + recent comments, when the + // thread has a branch. Failures degrade to "no PR context". + const prContext = + thread.branch !== null ? yield* investigateThreadPr(cwd, thread.branch) : null; + const generated = yield* textGeneration.generateThreadReview({ cwd, title: thread.title, @@ -242,6 +391,18 @@ export const make = Effect.gen(function* () { firstUserMessage, recentMessages, modelSelection, + ...(prContext !== null + ? { + pullRequest: { + number: prContext.status.number, + state: prContext.status.state, + reviewDecision: prContext.status.reviewDecision, + checksPassing: prContext.status.checksPassing, + mergeable: prContext.status.mergeable, + recentComments: prContext.recentComments, + }, + } + : {}), }); // Belt and braces on top of prompt rules + normalizeThreadReview: an @@ -269,12 +430,105 @@ export const make = Effect.gen(function* () { recommendSettle, settleReason: recommendSettle ? generated.settleReason : null, ...(diffStats !== undefined ? { diffStats } : {}), + ...(prContext !== null ? { prStatus: prContext.status } : {}), }; }); + const mergePullRequest: ReviewService["Service"]["mergePullRequest"] = Effect.fn( + "ReviewService.mergePullRequest", + )(function* (input) { + const mapProjectionError = (cause: unknown) => + new ReviewMergeError({ + threadId: input.threadId, + detail: `Failed to read the thread projection: ${String(cause)}`, + }); + const threadOption = yield* projectionSnapshotQuery + .getThreadDetailById(input.threadId) + .pipe(Effect.mapError(mapProjectionError)); + if (Option.isNone(threadOption)) { + return yield* new ReviewThreadNotFoundError({ threadId: input.threadId }); + } + const thread = threadOption.value; + const projectOption = yield* projectionSnapshotQuery + .getProjectShellById(thread.projectId) + .pipe(Effect.mapError(mapProjectionError)); + const cwd = resolveThreadWorkspaceCwd({ + thread, + projects: Option.isSome(projectOption) ? [projectOption.value] : [], + }); + if (cwd === undefined || thread.branch === null) { + return yield* new ReviewMergeError({ + threadId: input.threadId, + detail: "Thread has no resolvable workspace or branch to merge from.", + }); + } + + // Re-validate against LIVE GitHub state: in a merge queue, an earlier + // merge may have landed since the review ran and made this branch + // conflict (or someone merged/closed the PR out of band). + const prContext = yield* investigateThreadPr(cwd, thread.branch); + if (prContext === null || prContext.status.number !== input.pullRequestNumber) { + return { + threadId: input.threadId, + outcome: "not-ready" as const, + detail: "The pull request could not be re-validated against GitHub.", + }; + } + const status = prContext.status; + if (status.state !== "open") { + return { + threadId: input.threadId, + outcome: "already-closed" as const, + detail: `PR #${status.number} is already ${status.state}.`, + }; + } + if (status.mergeable === false) { + return { + threadId: input.threadId, + outcome: "conflict" as const, + detail: `PR #${status.number} no longer merges cleanly onto its base branch.`, + }; + } + if (!status.mergeReady) { + return { + threadId: input.threadId, + outcome: "not-ready" as const, + detail: `PR #${status.number} is not merge-ready (checks: ${String(status.checksPassing)}, review: ${status.reviewDecision ?? "none"}).`, + }; + } + + const mergeResult = yield* gitHubCli + .execute({ + cwd, + args: ["pr", "merge", String(status.number), "--squash"], + timeoutMs: 60_000, + }) + .pipe( + Effect.map(() => ({ merged: true as const, detail: null as string | null })), + Effect.catch((error) => + Effect.succeed({ + merged: false as const, + detail: error instanceof Error ? error.message : String(error), + }), + ), + ); + if (!mergeResult.merged) { + // gh merge failures at this point are usually races (base advanced, + // check flipped). Surface as conflict so the queue hands it to the + // thread's agent rather than aborting the whole run. + return { + threadId: input.threadId, + outcome: "conflict" as const, + detail: mergeResult.detail ?? "gh pr merge failed.", + }; + } + return { threadId: input.threadId, outcome: "merged" as const, detail: null }; + }); + return ReviewService.of({ getDiffPreview, summarizeThread, + mergePullRequest, }); }); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index c98baf9333..e2d943a5f4 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -86,6 +86,7 @@ import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts"; import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; +import * as GitHubCli from "./sourceControl/GitHubCli.ts"; import * as ServerSettings from "./serverSettings.ts"; import * as TextGeneration from "./textGeneration/TextGeneration.ts"; import * as TerminalManager from "./terminal/Manager.ts"; @@ -535,6 +536,11 @@ const buildAppUnderTest = (options?: { ...options?.layers?.projectionSnapshotQuery, }), ), + Layer.provide( + Layer.mock(GitHubCli.GitHubCli)({ + execute: () => Effect.die("GitHubCli not stubbed in this test"), + }), + ), Layer.provide(ServerSettings.layerTest()), ); const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 48091ff3db..4755f30869 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -223,6 +223,7 @@ const ReviewLayerLive = ReviewService.layer.pipe( Layer.provideMerge(GitVcsDriver.layer), Layer.provideMerge(VcsDriverRegistryLayerLive), Layer.provide(TextGeneration.layer), + Layer.provide(GitHubCli.layer), ); const VcsLayerLive = Layer.empty.pipe( diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 0dcf38d1bd..fc5108f200 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -366,6 +366,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu isActive: input.isActive, firstUserMessage: input.firstUserMessage, recentMessages: input.recentMessages, + pullRequest: input.pullRequest, }); const generated = yield* runClaudeJson({ diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 9edf777fcb..4c1b77f1d2 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -410,6 +410,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func isActive: input.isActive, firstUserMessage: input.firstUserMessage, recentMessages: input.recentMessages, + pullRequest: input.pullRequest, }); const generated = yield* runCodexJson({ diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts index 35609b0be8..781b4b1bd1 100644 --- a/apps/server/src/textGeneration/CursorTextGeneration.ts +++ b/apps/server/src/textGeneration/CursorTextGeneration.ts @@ -265,6 +265,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu isActive: input.isActive, firstUserMessage: input.firstUserMessage, recentMessages: input.recentMessages, + pullRequest: input.pullRequest, }); const generated = yield* runCursorJson({ diff --git a/apps/server/src/textGeneration/GrokTextGeneration.ts b/apps/server/src/textGeneration/GrokTextGeneration.ts index 4cf4fcda84..b21b324636 100644 --- a/apps/server/src/textGeneration/GrokTextGeneration.ts +++ b/apps/server/src/textGeneration/GrokTextGeneration.ts @@ -257,6 +257,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi isActive: input.isActive, firstUserMessage: input.firstUserMessage, recentMessages: input.recentMessages, + pullRequest: input.pullRequest, }); const generated = yield* runGrokJson({ diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts index 62c493f63f..1bfc624cec 100644 --- a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts @@ -622,6 +622,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration" isActive: input.isActive, firstUserMessage: input.firstUserMessage, recentMessages: input.recentMessages, + pullRequest: input.pullRequest, }); const generated = yield* runOpenCodeJson({ diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index 14cdaed03a..39f100691a 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -67,6 +67,15 @@ export interface ThreadTitleGenerationResult { title: string; } +export interface ThreadReviewPullRequestContext { + number: number; + state: "open" | "closed" | "merged"; + reviewDecision: string | null; + checksPassing: boolean | null; + mergeable: boolean | null; + recentComments: ReadonlyArray<{ author: string; createdAt: string; body: string }>; +} + export interface ThreadReviewGenerationInput { cwd: string; title: string; @@ -75,6 +84,8 @@ export interface ThreadReviewGenerationInput { isActive: boolean; firstUserMessage: string | null; recentMessages: ReadonlyArray<{ role: "user" | "assistant" | "system"; text: string }>; + /** Live PR state + recent comments when the thread has one. */ + pullRequest?: ThreadReviewPullRequestContext | undefined; /** What model and provider to use for generation. */ modelSelection: ModelSelection; } diff --git a/apps/server/src/textGeneration/TextGenerationPrompts.ts b/apps/server/src/textGeneration/TextGenerationPrompts.ts index ba1e55b74d..b0a5c56250 100644 --- a/apps/server/src/textGeneration/TextGenerationPrompts.ts +++ b/apps/server/src/textGeneration/TextGenerationPrompts.ts @@ -233,6 +233,34 @@ export interface ThreadReviewPromptInput { isActive: boolean; firstUserMessage: string | null; recentMessages: ReadonlyArray; + pullRequest?: + | { + number: number; + state: "open" | "closed" | "merged"; + reviewDecision: string | null; + checksPassing: boolean | null; + mergeable: boolean | null; + recentComments: ReadonlyArray<{ author: string; createdAt: string; body: string }>; + } + | undefined; +} + +function renderPullRequestSection( + pullRequest: NonNullable, +): string { + const lines = [ + `PR #${pullRequest.number}: state=${pullRequest.state}`, + `review decision: ${pullRequest.reviewDecision ?? "none required"}`, + `CI checks passing: ${pullRequest.checksPassing === null ? "unknown" : String(pullRequest.checksPassing)}`, + `mergeable: ${pullRequest.mergeable === null ? "unknown" : String(pullRequest.mergeable)}`, + ]; + if (pullRequest.recentComments.length > 0) { + lines.push("Recent PR comments (newest last):"); + for (const comment of pullRequest.recentComments) { + lines.push(`[${comment.author} @ ${comment.createdAt}] ${comment.body}`); + } + } + return lines.join("\n"); } const THREAD_REVIEW_RECENT_MESSAGE_COUNT = 20; @@ -268,8 +296,21 @@ export function buildThreadReviewPrompt(input: ThreadReviewPromptInput) { "- this thread is still ACTIVE (running or awaiting the user): recommendSettle must be false", ] : []), + ...(input.pullRequest + ? [ + "- weigh the PR context heavily: an open PR awaiting the user's review/merge is NOT settleable; a merged PR with no follow-up work is", + "- if the PR is open, CI is green, reviews approve it, and it is mergeable, nextStep should be to merge it", + ] + : []), "", `Current title: ${input.title}`, + ...(input.pullRequest + ? [ + "", + "Pull request status:", + limitSection(renderPullRequestSection(input.pullRequest), 6_000), + ] + : []), "", "First user message:", limitSection(input.firstUserMessage ?? "(none)", THREAD_REVIEW_MESSAGE_CHAR_LIMIT), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c450c3a0ab..941a421845 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -333,6 +333,7 @@ const RPC_REQUIRED_SCOPE = new Map([ [WS_METHODS.vcsInit, AuthOrchestrationOperateScope], [WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope], [WS_METHODS.reviewSummarizeThread, AuthReviewWriteScope], + [WS_METHODS.reviewMergePullRequest, AuthReviewWriteScope], [WS_METHODS.terminalOpen, AuthTerminalOperateScope], [WS_METHODS.terminalAttach, AuthTerminalOperateScope], [WS_METHODS.terminalWrite, AuthTerminalOperateScope], @@ -1857,6 +1858,10 @@ const makeWsRpcLayer = ( observeRpcEffect(WS_METHODS.reviewSummarizeThread, review.summarizeThread(input), { "rpc.aggregate": "review", }), + [WS_METHODS.reviewMergePullRequest]: (input) => + observeRpcEffect(WS_METHODS.reviewMergePullRequest, review.mergePullRequest(input), { + "rpc.aggregate": "review", + }), [WS_METHODS.terminalOpen]: (input) => observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { "rpc.aggregate": "terminal", diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index 22725af1fe..fe3ad85aea 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -82,6 +82,7 @@ import { type SidebarProjectSnapshot, } from "../sidebarProjectGrouping"; import { publishSweepChangeRequestStates } from "../reviewSweepStore"; +import { ReviewSweepLaunchDialog } from "./reviewSweep/ReviewSweepLaunchDialog"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { useThreadActions } from "../hooks/useThreadActions"; @@ -2205,12 +2206,13 @@ export default function SidebarV2() { openCommandPalette({ open: "new-thread-in" }); }, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]); - // Navigate only — the review-sweep page shows a pre-run summary (thread - // count + models that will be used) and the sweep starts on explicit click. + // Open the launch modal — the sweep itself runs in the background and + // announces completion with a toast, so no navigation happens here. + const [reviewSweepDialogOpen, setReviewSweepDialogOpen] = useState(false); const handleReviewSweepClick = useCallback(() => { if (isMobile) setOpenMobile(false); - void router.navigate({ to: "/review-sweep" }); - }, [isMobile, router, setOpenMobile]); + setReviewSweepDialogOpen(true); + }, [isMobile, setOpenMobile]); const commandPaletteShortcutLabel = shortcutLabelForCommand(keybindings, "commandPalette.toggle"); // Same resolution as v1: prefer the local-thread binding, fall back to @@ -2221,6 +2223,10 @@ export default function SidebarV2() { return ( <> +
diff --git a/apps/web/src/components/reviewSweep/ReviewSweepLaunchDialog.tsx b/apps/web/src/components/reviewSweep/ReviewSweepLaunchDialog.tsx new file mode 100644 index 0000000000..7e6f29c5a0 --- /dev/null +++ b/apps/web/src/components/reviewSweep/ReviewSweepLaunchDialog.tsx @@ -0,0 +1,62 @@ +import { useRouter } from "@tanstack/react-router"; +import { useEffect } from "react"; + +import { setSweepResultsNavigator, useReviewSweepStore } from "../../reviewSweepStore"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { Dialog, DialogDescription, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog"; +import { SweepPreRunSummary } from "./ReviewSweepView"; + +/** Launch modal for the work-review sweep. The sweep itself runs in the + background (module-level runner), so the modal just confirms scope/cost + and closes; a toast announces completion with a link to the results. */ +export function ReviewSweepLaunchDialog({ + open, + onOpenChange, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const router = useRouter(); + const phase = useReviewSweepStore((state) => state.phase); + + // Install the navigator the store's completion toast uses. The dialog is + // mounted for the sidebar's lifetime, so this stays registered. + useEffect(() => { + setSweepResultsNavigator(() => { + void router.navigate({ to: "/review-sweep" }); + }); + return () => setSweepResultsNavigator(null); + }, [router]); + + const handleStarted = () => { + onOpenChange(false); + toastManager.add( + stackedThreadToast({ + type: "info", + title: "Reviewing your work in the background", + description: "You'll get a notification when the results are ready.", + actionVariant: "outline", + actionProps: { + children: "Watch progress", + onClick: () => void router.navigate({ to: "/review-sweep" }), + }, + }), + ); + }; + + return ( + + + + Review unsettled work + + {phase === "running" + ? "A review is already running — results will arrive as a notification." + : "One AI review per unsettled thread, run in the background."} + + + {phase === "running" ? null : } + + + ); +} diff --git a/apps/web/src/components/reviewSweep/ReviewSweepView.tsx b/apps/web/src/components/reviewSweep/ReviewSweepView.tsx index f11c8025cc..43bda96d81 100644 --- a/apps/web/src/components/reviewSweep/ReviewSweepView.tsx +++ b/apps/web/src/components/reviewSweep/ReviewSweepView.tsx @@ -8,6 +8,7 @@ import { ArchiveIcon, ArrowRightIcon, CircleAlertIcon, + GitMergeIcon, InfoIcon, ListChecksIcon, LoaderIcon, @@ -26,7 +27,9 @@ import { applySweepTitle, dismissSweepItem, isSweepCandidate, + mergeSweepItem, retrySweepItem, + runMergeQueue, sortSweepCandidates, startReviewSweep, SWEEP_MAX_THREADS, @@ -56,9 +59,17 @@ import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/to // reading, then no-action-possible tails. // --------------------------------------------------------------------------- -type SweepBucket = "settle" | "title" | "attention" | "inFlight" | "failed" | "reviewing"; +type SweepBucket = + | "mergeReady" + | "settle" + | "title" + | "attention" + | "inFlight" + | "failed" + | "reviewing"; const BUCKET_ORDER: readonly SweepBucket[] = [ + "mergeReady", "settle", "title", "attention", @@ -71,6 +82,12 @@ const BUCKET_META: Record< SweepBucket, { title: string; hint: string; accent: string; icon: typeof ArchiveIcon } > = { + mergeReady: { + title: "Merge ready", + hint: "Open PRs with green CI, approvals, and clean merges.", + accent: "border-s-violet-500/70", + icon: GitMergeIcon, + }, settle: { title: "Ready to settle", hint: "Work concluded — one click clears each from your active list.", @@ -112,6 +129,10 @@ const BUCKET_META: Record< function classifySweepItem(item: SweepItem): SweepBucket { if (item.status === "error") return "failed"; if (item.status !== "done" || item.result === null) return "reviewing"; + // Merge-ready wins over everything: it's the highest-leverage one-click. + // Items stay in the bucket through the queue lifecycle (queued → merging + // → merged/conflicted) so progress is visible in place. + if (item.result.prStatus?.mergeReady && !item.settleApplied) return "mergeReady"; if (item.result.recommendSettle && !item.settleApplied) return "settle"; if (item.result.suggestedTitle && !item.titleApplied) return "title"; // Live shell wins over review-time knowledge: a thread blocked on the user @@ -165,12 +186,44 @@ function SweepItemMetaRow({ {item.branch} ) : null} + {item.result?.prStatus ? ( + + #{item.result.prStatus.number} + + ) : null} {age ? {age} : null}
); } +function MergeStatusBadge({ item }: { item: SweepItem }) { + switch (item.mergeStatus) { + case "queued": + return Queued; + case "merging": + return ( + + + Merging + + ); + case "merged": + return Merged; + case "conflicted": + return Conflict — agent rebasing; + case "failed": + return Merge failed; + default: + return null; + } +} + function SweepItemCard({ item, bucket, @@ -188,7 +241,23 @@ function SweepItemCard({ const meta = BUCKET_META[bucket]; const primaryAction = - bucket === "settle" ? ( + bucket === "mergeReady" ? ( + item.mergeStatus === "idle" || item.mergeStatus === "failed" ? ( + + ) : null + ) : bucket === "settle" ? ( @@ -479,6 +559,7 @@ export function ReviewSweepView() { ).length; const running = phase === "running"; const [applyingAll, setApplyingAll] = useState(false); + const [mergingAll, setMergingAll] = useState(false); return ( @@ -564,6 +645,12 @@ export function ReviewSweepView() { {buckets.map(([bucket, bucketItems]) => { const meta = BUCKET_META[bucket]; const BucketIcon = meta.icon; + const mergeableCount = + bucket === "mergeReady" + ? bucketItems.filter( + (item) => item.mergeStatus === "idle" || item.mergeStatus === "queued", + ).length + : 0; return (
@@ -579,6 +666,21 @@ export function ReviewSweepView() { {meta.hint} ) : null} + {bucket === "mergeReady" && mergeableCount > 0 ? ( + + ) : null}
{bucketItems.map((item) => { diff --git a/apps/web/src/reviewSweepStore.ts b/apps/web/src/reviewSweepStore.ts index 76d54349f7..52f754a1b6 100644 --- a/apps/web/src/reviewSweepStore.ts +++ b/apps/web/src/reviewSweepStore.ts @@ -7,16 +7,19 @@ import { } from "@t3tools/client-runtime/state/thread-settled"; import { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; -import type { - EnvironmentId, - ProjectId, - ReviewThreadSummaryResult, - ScopedThreadRef, +import { + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + type EnvironmentId, + type ProjectId, + type ReviewThreadSummaryResult, + type ScopedThreadRef, } from "@t3tools/contracts"; import { create } from "zustand"; import { stackedThreadToast, toastManager } from "./components/ui/toast"; import { getClientSettings } from "./hooks/useSettings"; +import { newMessageId } from "~/lib/utils"; import { appAtomRegistry } from "./rpc/atomRegistry"; import { readThreadShell, readThreadRefs } from "./state/entities"; import { reviewEnvironment } from "./state/review"; @@ -46,6 +49,10 @@ export const SWEEP_MAX_THREADS = 50; export type SweepItemStatus = "pending" | "running" | "done" | "error"; +/** Merge-queue lifecycle for merge-ready items. "conflicted" means the + merge failed and the thread's agent has been asked to resolve it. */ +export type SweepMergeStatus = "idle" | "queued" | "merging" | "merged" | "conflicted" | "failed"; + export interface SweepItem { readonly ref: ScopedThreadRef; readonly projectId: ProjectId; @@ -59,6 +66,8 @@ export interface SweepItem { readonly titleApplied: boolean; readonly settleApplied: boolean; readonly dismissed: boolean; + readonly mergeStatus: SweepMergeStatus; + readonly mergeDetail: string | null; } export type SweepPhase = "idle" | "running" | "complete"; @@ -202,6 +211,17 @@ async function reviewOne(runId: number, item: SweepItem): Promise { } } +/** Navigation callback installed by the app shell so store-level toasts can + deep-link to /review-sweep without importing the router. */ +let navigateToSweepResults: (() => void) | null = null; +export function setSweepResultsNavigator(navigate: (() => void) | null): void { + navigateToSweepResults = navigate; +} + +function isViewingSweepResults(): boolean { + return window.location.pathname === "/review-sweep"; +} + async function runPool(runId: number, items: ReadonlyArray): Promise { let next = 0; const workers = Array.from({ length: Math.min(SWEEP_CONCURRENCY, items.length) }, async () => { @@ -213,7 +233,35 @@ async function runPool(runId: number, items: ReadonlyArray): Promise< } }); await Promise.all(workers); - useReviewSweepStore.getState().finishRun(runId); + const store = useReviewSweepStore.getState(); + if (store.runId !== runId) return; + store.finishRun(runId); + // The sweep runs in the background; only toast when the user isn't + // already staring at the results page. + if (!isViewingSweepResults()) { + const actionable = Object.values(store.items).filter( + (item) => + !item.dismissed && + ((item.result?.suggestedTitle && !item.titleApplied) || + (item.result?.recommendSettle && !item.settleApplied) || + item.result?.prStatus?.mergeReady === true), + ).length; + toastManager.add( + stackedThreadToast({ + type: "success", + title: "Work review finished", + description: + actionable > 0 + ? `${actionable} ${actionable === 1 ? "thread has" : "threads have"} recommended actions.` + : "No actions recommended — you're caught up.", + actionVariant: "outline", + actionProps: { + children: "View results", + onClick: () => navigateToSweepResults?.(), + }, + }), + ); + } } /** Kick off a sweep over every unsettled thread. Runs outside React so it @@ -235,6 +283,8 @@ export function startReviewSweep(): void { titleApplied: false, settleApplied: false, dismissed: false, + mergeStatus: "idle", + mergeDetail: null, }), ); useReviewSweepStore.getState().startRun({ @@ -372,3 +422,163 @@ export async function applyAllSweepRecommendations(): Promise { export function dismissSweepItem(key: string): void { useReviewSweepStore.getState().patchItem(key, { dismissed: true }); } + +// --------------------------------------------------------------------------- +// Merge queue +// --------------------------------------------------------------------------- + +/** Message sent to a thread's agent when its PR stopped merging cleanly + because earlier queue entries landed first. */ +function conflictHandoffMessage(prNumber: number): string { + return [ + `PR #${prNumber} no longer merges cleanly — other pull requests were merged into the base branch ahead of it.`, + "Please rebase this branch onto the latest base branch, resolve any merge conflicts, verify the build still passes, and push the updated branch.", + ].join(" "); +} + +function isMergeQueueCandidate(item: SweepItem): boolean { + return ( + !item.dismissed && + item.result?.prStatus?.mergeReady === true && + (item.mergeStatus === "idle" || item.mergeStatus === "queued") + ); +} + +let mergeQueueActive = false; + +/** Merge one item's PR and settle its thread on success. On conflict, mark + the card and hand the rebase to the thread's agent. Returns the outcome + for queue accounting. */ +async function mergeOne( + runId: number, + key: string, +): Promise<"merged" | "conflict" | "skipped" | "failed"> { + const store = useReviewSweepStore.getState(); + if (store.runId !== runId) return "skipped"; + const item = store.items[key]; + const prNumber = item?.result?.prStatus?.number; + if (!item || prNumber === undefined) return "skipped"; + store.patchItem(key, { mergeStatus: "merging" }); + + const result = await runAtomCommand( + appAtomRegistry, + reviewEnvironment.mergePullRequest, + { + environmentId: item.ref.environmentId, + input: { threadId: item.ref.threadId, pullRequestNumber: prNumber }, + }, + { reportFailure: false, reportDefect: false }, + ); + + const after = useReviewSweepStore.getState(); + if (after.runId !== runId) return "skipped"; + + if (result._tag === "Failure") { + const error = squashAtomCommandFailure(result); + after.patchItem(key, { + mergeStatus: "failed", + mergeDetail: error instanceof Error ? error.message : "Merge failed.", + }); + return "failed"; + } + + const outcome = result.value.outcome; + if (outcome === "merged" || outcome === "already-closed") { + after.patchItem(key, { mergeStatus: "merged", mergeDetail: result.value.detail }); + // Merged PRs are concluded work: settle right away so the sidebar + // reflects the merge without waiting for auto-settle. + const settleResult = await runAtomCommand( + appAtomRegistry, + threadEnvironment.settle, + { + environmentId: item.ref.environmentId, + input: { threadId: item.ref.threadId }, + }, + { reportFailure: false }, + ); + if (settleResult._tag === "Success") { + useReviewSweepStore.getState().patchItem(key, { settleApplied: true }); + } + return "merged"; + } + + if (outcome === "conflict") { + after.patchItem(key, { mergeStatus: "conflicted", mergeDetail: result.value.detail }); + // Hand the conflict to the thread's own agent: it has the branch + // checked out and the full context to rebase and resolve. + await runAtomCommand( + appAtomRegistry, + threadEnvironment.startTurn, + { + environmentId: item.ref.environmentId, + input: { + threadId: item.ref.threadId, + message: { + messageId: newMessageId(), + role: "user" as const, + text: conflictHandoffMessage(prNumber), + attachments: [], + }, + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: new Date().toISOString(), + }, + }, + { reportFailure: false }, + ); + return "conflict"; + } + + after.patchItem(key, { mergeStatus: "failed", mergeDetail: result.value.detail }); + return "failed"; +} + +/** Merge a single card's PR (per-item button). */ +export async function mergeSweepItem(key: string): Promise { + const { runId } = useReviewSweepStore.getState(); + await mergeOne(runId, key); +} + +/** Merge every merge-ready PR SEQUENTIALLY — one at a time, so each merge + sees the base branch the previous one produced and the server re-check + catches freshly introduced conflicts. Conflicts don't stop the queue: + the item is marked conflicted and its thread's agent is asked to rebase + and resolve; re-run the sweep once it pushes to pick the PR back up. */ +export async function runMergeQueue(): Promise { + if (mergeQueueActive) return; + mergeQueueActive = true; + try { + const { order, items, runId } = useReviewSweepStore.getState(); + const queueKeys = order.filter((key) => { + const item = items[key]; + return item !== undefined && isMergeQueueCandidate(item); + }); + for (const key of queueKeys) { + useReviewSweepStore.getState().patchItem(key, { mergeStatus: "queued" }); + } + + let mergedCount = 0; + let conflictCount = 0; + for (const key of queueKeys) { + const outcome = await mergeOne(runId, key); + if (outcome === "merged") mergedCount += 1; + if (outcome === "conflict") conflictCount += 1; + if (useReviewSweepStore.getState().runId !== runId) return; + } + + if (queueKeys.length > 0) { + toastManager.add( + stackedThreadToast({ + type: conflictCount > 0 ? "warning" : "success", + title: `Merge queue finished: ${mergedCount} of ${queueKeys.length} merged`, + description: + conflictCount > 0 + ? `${conflictCount} ${conflictCount === 1 ? "PR hit a conflict and was" : "PRs hit conflicts and were"} handed to ${conflictCount === 1 ? "its" : "their"} thread's agent to rebase.` + : undefined, + }), + ); + } + } finally { + mergeQueueActive = false; + } +} diff --git a/packages/client-runtime/src/state/review.ts b/packages/client-runtime/src/state/review.ts index 11abb6a405..d834b190b6 100644 --- a/packages/client-runtime/src/state/review.ts +++ b/packages/client-runtime/src/state/review.ts @@ -17,5 +17,9 @@ export function createReviewEnvironmentAtoms( label: "environment-data:review:summarize-thread", tag: WS_METHODS.reviewSummarizeThread, }), + mergePullRequest: createEnvironmentRpcCommand(runtime, { + label: "environment-data:review:merge-pull-request", + tag: WS_METHODS.reviewMergePullRequest, + }), }; } diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index 7bb4f804cb..a0a11c126a 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -53,6 +53,25 @@ export const ReviewThreadDiffStats = Schema.Struct({ }); export type ReviewThreadDiffStats = typeof ReviewThreadDiffStats.Type; +/** Live pull-request context gathered during the review: state, review + verdict, CI, and whether the PR is mergeable as-is. */ +export const ReviewThreadPrStatus = Schema.Struct({ + number: Schema.Int, + url: TrimmedNonEmptyString, + state: Schema.Literals(["open", "closed", "merged"]), + /** GitHub reviewDecision: APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED / + empty (no required reviews). */ + reviewDecision: Schema.NullOr(TrimmedNonEmptyString), + /** Rolled-up CI outcome for the head commit. */ + checksPassing: Schema.NullOr(Schema.Boolean), + /** GitHub mergeable: whether the branch applies cleanly onto base. */ + mergeable: Schema.NullOr(Schema.Boolean), + /** Open + clean merge + CI green + not blocked by requested changes. */ + mergeReady: Schema.Boolean, + recentCommentCount: Schema.Int, +}); +export type ReviewThreadPrStatus = typeof ReviewThreadPrStatus.Type; + export const ReviewThreadSummaryResult = Schema.Struct({ threadId: ThreadId, summary: TrimmedNonEmptyString, @@ -65,6 +84,8 @@ export const ReviewThreadSummaryResult = Schema.Struct({ settleReason: Schema.NullOr(TrimmedNonEmptyString), /** Absent when the thread has no ready checkpoint (or pre-diff servers). */ diffStats: Schema.optionalKey(ReviewThreadDiffStats), + /** Absent when the thread has no PR, the lookup failed, or pre-PR servers. */ + prStatus: Schema.optionalKey(ReviewThreadPrStatus), }); export type ReviewThreadSummaryResult = typeof ReviewThreadSummaryResult.Type; @@ -78,3 +99,41 @@ export const ReviewThreadSummaryError = Schema.Union([ ReviewThreadNotFoundError, ]); export type ReviewThreadSummaryError = typeof ReviewThreadSummaryError.Type; + +export const ReviewMergePullRequestInput = Schema.Struct({ + threadId: ThreadId, + /** The PR number the client saw at review time; the server re-validates + merge-readiness against live GitHub state before merging. */ + pullRequestNumber: Schema.Int, +}); +export type ReviewMergePullRequestInput = typeof ReviewMergePullRequestInput.Type; + +export const ReviewMergePullRequestResult = Schema.Struct({ + threadId: ThreadId, + outcome: Schema.Literals([ + "merged", + /** Branch no longer applies cleanly (e.g. an earlier queue merge landed + first). The client hands the conflict to the thread's agent. */ + "conflict", + /** PR already merged or closed since the review ran. */ + "already-closed", + /** No longer merge-ready (CI regressed, review dismissed, ...). */ + "not-ready", + ]), + detail: Schema.NullOr(TrimmedNonEmptyString), +}); +export type ReviewMergePullRequestResult = typeof ReviewMergePullRequestResult.Type; + +export class ReviewMergeError extends Schema.TaggedErrorClass()( + "ReviewMergeError", + { + threadId: ThreadId, + detail: TrimmedNonEmptyString, + }, +) {} + +export const ReviewMergePullRequestError = Schema.Union([ + ReviewThreadNotFoundError, + ReviewMergeError, +]); +export type ReviewMergePullRequestError = typeof ReviewMergePullRequestError.Type; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index a5e125152b..cfb6645d0d 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -43,6 +43,9 @@ import { ReviewDiffPreviewError, ReviewDiffPreviewInput, ReviewDiffPreviewResult, + ReviewMergePullRequestError, + ReviewMergePullRequestInput, + ReviewMergePullRequestResult, ReviewThreadSummaryError, ReviewThreadSummaryInput, ReviewThreadSummaryResult, @@ -185,6 +188,7 @@ export const WS_METHODS = { // Review methods reviewGetDiffPreview: "review.getDiffPreview", reviewSummarizeThread: "review.summarizeThread", + reviewMergePullRequest: "review.mergePullRequest", // Terminal methods terminalOpen: "terminal.open", @@ -507,6 +511,16 @@ export const WsReviewSummarizeThreadRpc = Rpc.make(WS_METHODS.reviewSummarizeThr error: Schema.Union([ReviewThreadSummaryError, EnvironmentAuthorizationError]), }); +/** Merge a review-sweep thread's PR after re-validating merge readiness + against live GitHub state. Non-exceptional failures (conflict, already + closed, no longer ready) are outcomes, not errors, so the client's merge + queue can branch on them. */ +export const WsReviewMergePullRequestRpc = Rpc.make(WS_METHODS.reviewMergePullRequest, { + payload: ReviewMergePullRequestInput, + success: ReviewMergePullRequestResult, + error: Schema.Union([ReviewMergePullRequestError, EnvironmentAuthorizationError]), +}); + export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, { payload: TerminalOpenInput, success: TerminalSessionSnapshot, @@ -751,6 +765,7 @@ export const WsRpcGroup = RpcGroup.make( WsVcsInitRpc, WsReviewGetDiffPreviewRpc, WsReviewSummarizeThreadRpc, + WsReviewMergePullRequestRpc, WsTerminalOpenRpc, WsTerminalAttachRpc, WsTerminalWriteRpc,