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

+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;
}
}