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",