Background sweep, launch modal, PR investigation, and merge queue

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 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-24 05:36:14 -07:00
1 parent ade848702d
commit 3e757bd28b
19 files changed
+1000 -15

No files matched your search

@@ -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<OrchestrationThreadShell> = {},
@@ -56,6 +81,7 @@ function makeLayer(input: {
readonly shellOverrides?: Partial<OrchestrationThreadShell>;
readonly generateThreadReview?: TextGeneration.TextGeneration["Service"]["generateThreadReview"];
readonly reviewCalls?: Array<TextGeneration.ThreadReviewGenerationInput>;
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<TextGeneration.ThreadReviewGenerationInput> = [];
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<TextGeneration.ThreadReviewGenerationInput> = [];
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;
+254
View File
@@ -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<ReviewThreadSummaryResult, ReviewThreadSummaryError>;
readonly mergePullRequest: (
input: ReviewMergePullRequestInput,
) => Effect.Effect<ReviewMergePullRequestResult, ReviewMergePullRequestError>;
}
>()("t3/review/ReviewService") {}
// ---------------------------------------------------------------------------
// PR investigation
// ---------------------------------------------------------------------------
/** Shape of `gh pr view --json <fields>` 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<ThreadPrContext | null, never> {
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,
});
});
+6
View File
@@ -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
+1
View File
@@ -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(
@@ -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({
@@ -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({
@@ -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({
@@ -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({
@@ -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({
@@ -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;
}
@@ -233,6 +233,34 @@ export interface ThreadReviewPromptInput {
isActive: boolean;
firstUserMessage: string | null;
recentMessages: ReadonlyArray<ThreadReviewMessage>;
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<ThreadReviewPromptInput["pullRequest"]>,
): 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),
+5
View File
@@ -333,6 +333,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[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",
+10 -4
View File
@@ -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 (
<>
<SidebarChromeHeader isElectron={isElectron} />
<ReviewSweepLaunchDialog
open={reviewSweepDialogOpen}
onOpenChange={setReviewSweepDialogOpen}
/>
<SidebarContent className="gap-0">
<SidebarGroup className="px-2 pb-2 pt-3">
<div className="flex items-center gap-1">
@@ -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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogPopup className="max-w-lg">
<DialogHeader>
<DialogTitle>Review unsettled work</DialogTitle>
<DialogDescription>
{phase === "running"
? "A review is already running — results will arrive as a notification."
: "One AI review per unsettled thread, run in the background."}
</DialogDescription>
</DialogHeader>
{phase === "running" ? null : <SweepPreRunSummary onStarted={handleStarted} />}
</DialogPopup>
</Dialog>
);
}
@@ -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}
</span>
) : null}
{item.result?.prStatus ? (
<a
href={item.result.prStatus.url}
target="_blank"
rel="noopener noreferrer"
className="shrink-0 font-mono text-[11px] text-muted-foreground hover:text-foreground hover:underline"
>
#{item.result.prStatus.number}
</a>
) : null}
{age ? <span className="shrink-0">{age}</span> : null}
<DiffStatsLabel item={item} />
</div>
);
}
function MergeStatusBadge({ item }: { item: SweepItem }) {
switch (item.mergeStatus) {
case "queued":
return <Badge variant="secondary">Queued</Badge>;
case "merging":
return (
<Badge variant="info">
<Spinner className="me-1 size-3" />
Merging
</Badge>
);
case "merged":
return <Badge variant="success">Merged</Badge>;
case "conflicted":
return <Badge variant="warning">Conflict — agent rebasing</Badge>;
case "failed":
return <Badge variant="error">Merge failed</Badge>;
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" ? (
<Button
size="xs"
variant="outline"
className="shrink-0"
disabled={applying}
onClick={() => {
setApplying(true);
void mergeSweepItem(key).finally(() => setApplying(false));
}}
>
<GitMergeIcon className="me-1 size-3.5" />
Merge & settle
</Button>
) : null
) : bucket === "settle" ? (
<Button
size="xs"
variant="outline"
@@ -246,6 +315,7 @@ function SweepItemCard({
{bucket === "settle" && item.settleApplied ? (
<Badge variant="outline">Settled</Badge>
) : null}
{bucket === "mergeReady" ? <MergeStatusBadge item={item} /> : null}
<div className="ms-auto flex shrink-0 items-center gap-1">
{result?.summary ? (
<Tooltip>
@@ -282,6 +352,8 @@ function SweepItemCard({
{item.status === "error" ? (
<p className="line-clamp-2 text-sm text-red-400/90">{item.errorMessage}</p>
) : item.mergeStatus === "conflicted" || item.mergeStatus === "failed" ? (
<p className="line-clamp-2 text-sm text-warning-foreground">{item.mergeDetail}</p>
) : nextStep ? (
<p className="line-clamp-2 text-sm text-foreground/90">{nextStep}</p>
) : null}
@@ -313,8 +385,10 @@ function SweepItemCard({
const SWEEP_COST_NOTE_THRESHOLD = 15;
/** Pre-run summary: how many threads a sweep would cover and which model
each environment's server will use, so starting is an informed choice. */
function SweepPreRunSummary() {
each environment's server will use, so starting is an informed choice.
Rendered on the idle /review-sweep page and inside the sidebar's launch
modal. `onStarted` lets the modal close itself when the sweep kicks off. */
export function SweepPreRunSummary({ onStarted }: { onStarted?: () => void } = {}) {
const shells = useThreadShells();
const serverConfigs = useServerConfigs();
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
@@ -405,7 +479,13 @@ function SweepPreRunSummary() {
<div>Model is configurable under Settings → Models (text generation).</div>
)}
</div>
<Button size="sm" onClick={() => startReviewSweep()}>
<Button
size="sm"
onClick={() => {
startReviewSweep();
onStarted?.();
}}
>
<ListChecksIcon className="me-1.5 size-4" />
Review {reviewedCount} {reviewedCount === 1 ? "thread" : "threads"}
</Button>
@@ -479,6 +559,7 @@ export function ReviewSweepView() {
).length;
const running = phase === "running";
const [applyingAll, setApplyingAll] = useState(false);
const [mergingAll, setMergingAll] = useState(false);
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
@@ -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 (
<section key={bucket} className="flex flex-col gap-2">
<div className="flex items-baseline gap-2">
@@ -579,6 +666,21 @@ export function ReviewSweepView() {
{meta.hint}
</span>
) : null}
{bucket === "mergeReady" && mergeableCount > 0 ? (
<Button
size="xs"
variant="outline"
className="ms-auto shrink-0"
disabled={mergingAll}
onClick={() => {
setMergingAll(true);
void runMergeQueue().finally(() => setMergingAll(false));
}}
>
<GitMergeIcon className="me-1 size-3.5" />
Merge all ({mergeableCount})
</Button>
) : null}
</div>
<div className="grid grid-cols-1 gap-2.5 md:grid-cols-2 xl:grid-cols-3">
{bucketItems.map((item) => {
+216 -6
View File
@@ -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<void> {
}
}
/** 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<SweepItem>): Promise<void> {
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<SweepItem>): 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<void> {
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<void> {
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<void> {
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;
}
}
@@ -17,5 +17,9 @@ export function createReviewEnvironmentAtoms<R, E>(
label: "environment-data:review:summarize-thread",
tag: WS_METHODS.reviewSummarizeThread,
}),
mergePullRequest: createEnvironmentRpcCommand(runtime, {
label: "environment-data:review:merge-pull-request",
tag: WS_METHODS.reviewMergePullRequest,
}),
};
}
+59
View File
@@ -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>()(
"ReviewMergeError",
{
threadId: ThreadId,
detail: TrimmedNonEmptyString,
},
) {}
export const ReviewMergePullRequestError = Schema.Union([
ReviewThreadNotFoundError,
ReviewMergeError,
]);
export type ReviewMergePullRequestError = typeof ReviewMergePullRequestError.Type;
+15
View File
@@ -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,