Harden PR monitoring after adversarial review

Findings from a multi-agent review panel (23 confirmed after two-lens
adversarial verification), grouped by root cause:

Lifecycle identity
- Thread a monitor generation through monitor commands, events, and the
  projected monitor state; reject updates/ends whose generation is not
  the active one, and make every registry removal generation-conditional
  so a delayed lifecycle event cannot delete a newer monitor
- Re-validate registration, projected monitor status, archive state,
  generation, and claim at the wake send boundary (after the fresh fetch,
  not before it)

Event loss
- Diff before the readiness exit: actionable activity now wins over
  ending as ready, so a bot comment landing in the same poll as green CI
  is never discarded
- Persist non-actionable cursor transitions so resolved→reopened is
  still detectable
- Acknowledge the cursor only if the wake claim still exists, so a
  user-turn release is not overwritten

Readiness
- Collapse reviews to each reviewer's latest opinionated review, so an
  approval supersedes that reviewer's earlier changes-requested
- Re-include pre-monitor review threads once they are edited or reopened

Snapshot integrity
- Final terminal/head revalidation after pagination, with one bounded
  refetch on head change
- Fetch the last 10 comments per review thread and track per-thread
  updatedAt so edits to non-final comments are visible
- Reopened threads wake regardless of self-authorship
- Include the changes-requested review body in the wake prompt

Lifecycle events
- Archive atomically emits thread.monitor-ended before thread.archived,
  mirroring settle
- Treat a queued-but-unadopted user turn as busy at the send boundary
- Boot reconciliation isolates per-thread failures (Bugbot)

UI
- Gate ready-state PR actions on the checkout PR matching the monitored
  PR number
- Wake snoozed threads on monitor ready/needs-attention/session-ended
- Legacy sidebar renders the ready payoff and a needs-attention state;
  session failure outranks Monitoring
- Reset merge confirmation when PR or monitor status changes
- endThreadMonitor honors a caller-provided endedAt

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-26 19:39:43 -07:00
1 parent 2ff63fb2b7
commit 0c1de35f5a
25 files changed
+873 -166

No files matched your search

@@ -86,6 +86,7 @@ const monitorStart = Effect.fn("MonitorToolkit.monitorStart")(function* ({
type: "thread.monitor.start",
commandId,
threadId: invocation.threadId,
generation,
prNumber,
blockersSummary: warning ?? "",
headSha: snapshot.headSha,
@@ -156,6 +156,7 @@ export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect<vo
type: "thread.monitor.end",
commandId,
threadId,
generation: registration.value.generation,
reason: "session-ended",
blockersSummary: "",
endedAt,
@@ -1,6 +1,7 @@
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
@@ -11,6 +12,7 @@ import {
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as DateTime from "effect/DateTime";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
@@ -25,7 +27,7 @@ import {
} from "../sourceControl/gitHubPullRequestMonitor.ts";
import * as MonitorRegistry from "./MonitorRegistry.ts";
import { cursorFromSnapshot } from "./monitorDiff.ts";
import { make, PullRequestSnapshotFetcher } from "./PullRequestMonitor.ts";
import { make, PullRequestMonitor, PullRequestSnapshotFetcher } from "./PullRequestMonitor.ts";
const threadId = ThreadId.make("monitor-thread");
const now = "2026-07-23T00:00:00.000Z";
@@ -92,7 +94,17 @@ const thread = (busy = false): OrchestrationThread => ({
archivedAt: null,
settledOverride: null,
settledAt: null,
monitor: null,
monitor: {
generation: 1,
prNumber: 42,
status: "monitoring",
blockersSummary: "",
headSha: "head-1",
wakeCount: 0,
startedAt: now,
endedAt: null,
endedReason: null,
},
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -110,7 +122,11 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: {
readonly failFreshFetch?: boolean;
readonly reconcileFailures?: number;
readonly reconcileThreadId?: ThreadId;
readonly reconcileThreadIds?: ReadonlyArray<ThreadId>;
readonly failReconcileThreadId?: ThreadId;
readonly releaseWakeOnDispatch?: boolean;
readonly busy?: { value: boolean };
readonly queuedUserTurn?: boolean;
readonly afterUpdate?: () => void;
readonly changeGenerationAfterUpdate?: boolean;
}) {
@@ -125,6 +141,7 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: {
};
const commands: OrchestrationCommand[] = [];
const ordering: string[] = [];
let monitorService: PullRequestMonitor["Service"] | undefined;
const registry = MonitorRegistry.MonitorRegistry.of({
registerIfAbsent: (next) =>
Effect.sync(() => {
@@ -202,6 +219,29 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: {
}
if (command.type === "thread.turn.start") {
ordering.push("dispatch");
if (input.releaseWakeOnDispatch && monitorService) {
return monitorService
.handleDomainEvent({
sequence: 1,
eventId: EventId.make("user-turn"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("user-turn"),
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.turn-start-requested",
payload: {
threadId,
messageId: MessageId.make("user-message"),
runtimeMode: "full-access",
interactionMode: "default",
createdAt: now,
},
})
.pipe(Effect.as({ sequence: commands.length }));
}
if (input.failWake) {
return Effect.fail(
new OrchestrationCommandInvariantError({
@@ -219,6 +259,17 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: {
}),
);
}
if (
command.type === "thread.monitor.end" &&
command.threadId === input.failReconcileThreadId
) {
return Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "reconcile rejected",
}),
);
}
return Effect.succeed({ sequence: commands.length });
},
});
@@ -258,40 +309,71 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: {
return Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: input.reconcileThreadId
? [
{
...thread(),
id: input.reconcileThreadId,
monitor: {
status: "monitoring" as const,
prNumber: 42,
startedAt: now,
blockersSummary: "",
headSha: "head-1",
wakeCount: 0,
updatedAt: now,
endedAt: null,
endedReason: null,
},
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
},
]
: [],
threads: (
input.reconcileThreadIds ??
(input.reconcileThreadId ? [input.reconcileThreadId] : [])
).map((id) => ({
...thread(),
id,
monitor: {
generation: 1,
status: "monitoring" as const,
prNumber: 42,
startedAt: now,
blockersSummary: "",
headSha: "head-1",
wakeCount: 0,
updatedAt: now,
endedAt: null,
endedReason: null,
},
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
})),
updatedAt: now,
});
},
getThreadDetailById: () =>
Effect.succeed(Option.some(thread(input.busy?.value ?? false))),
Effect.map(DateTime.now, (currentDateTime) => {
const detail = thread(input.busy?.value ?? false);
const currentTime = DateTime.formatIso(currentDateTime);
return Option.some(
input.queuedUserTurn
? {
...detail,
messages: [
{
id: MessageId.make("queued-message"),
role: "user" as const,
text: "user work",
attachments: [],
turnId: null,
streaming: false,
createdAt: currentTime,
updatedAt: currentTime,
},
],
}
: detail,
);
}),
}),
NodeServices.layer,
),
),
);
return { monitor, commands, ordering, getRegistration: () => registration };
monitorService = monitor;
return {
monitor,
commands,
ordering,
getRegistration: () => registration,
replaceGeneration: (generation: number) => {
if (registration) registration = { ...registration, generation };
},
};
});
const endReason = (commands: ReadonlyArray<OrchestrationCommand>) =>
@@ -319,7 +401,10 @@ describe("PullRequestMonitor dispatch protocol", () => {
const ready = snapshot({
checkRuns: [{ ...snapshot().checkRuns[0]!, status: "completed", conclusion: "success" }],
});
const h = yield* harness({ initial: snapshot(), current: { value: ready } });
const h = yield* harness({
initial: snapshot(),
current: { value: ready },
});
yield* h.monitor.pollOnce;
assert.deepStrictEqual(
h.commands.map((command) => command.type),
@@ -333,12 +418,16 @@ describe("PullRequestMonitor dispatch protocol", () => {
const oldComment = {
...comment("old"),
createdAt: "2026-07-22T00:00:00.000Z",
updatedAt: "2026-07-22T00:00:00.000Z",
};
const ready = snapshot({
reviewThreads: [oldComment],
checkRuns: [{ ...snapshot().checkRuns[0]!, status: "completed", conclusion: "success" }],
});
const h = yield* harness({ initial: snapshot(), current: { value: ready } });
const h = yield* harness({
initial: snapshot({ reviewThreads: [oldComment] }),
current: { value: ready },
});
yield* h.monitor.pollOnce;
assert.strictEqual(endReason(h.commands)?.type, "thread.monitor.end");
}),
@@ -356,6 +445,31 @@ describe("PullRequestMonitor dispatch protocol", () => {
}),
);
it.effect("ready defers to an actionable diff", () =>
Effect.gen(function* () {
const h = yield* harness({
initial: snapshot(),
current: {
value: snapshot({
reviewThreads: [comment("one")],
checkRuns: [
{ ...snapshot().checkRuns[0]!, status: "completed", conclusion: "success" },
],
}),
},
});
yield* h.monitor.pollOnce;
assert.strictEqual(
h.commands.some((command) => command.type === "thread.turn.start"),
true,
);
assert.strictEqual(
h.commands.some((command) => command.type === "thread.monitor.end"),
false,
);
}),
);
it.effect("failed-dispatch-preserves-cursor", () =>
Effect.gen(function* () {
const initial = snapshot();
@@ -370,6 +484,19 @@ describe("PullRequestMonitor dispatch protocol", () => {
}),
);
it.effect("conditional ack preserves a user-turn release", () =>
Effect.gen(function* () {
const initial = snapshot();
const h = yield* harness({
initial,
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
releaseWakeOnDispatch: true,
});
yield* h.monitor.pollOnce;
assert.deepStrictEqual(h.getRegistration()?.cursor, cursorFromSnapshot(initial));
}),
);
it.effect("failed-send-boundary-fetch-discards-wake-without-acking", () =>
Effect.gen(function* () {
const initial = snapshot();
@@ -463,6 +590,21 @@ describe("PullRequestMonitor dispatch protocol", () => {
}),
);
it.effect("queued user turn blocks a monitor wake", () =>
Effect.gen(function* () {
const h = yield* harness({
initial: snapshot(),
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
queuedUserTurn: true,
});
yield* h.monitor.pollOnce;
assert.strictEqual(
h.commands.some((command) => command.type === "thread.turn.start"),
false,
);
}),
);
it.effect("coalesces events while a wake is in flight", () =>
Effect.gen(function* () {
const current = { value: snapshot({ reviewThreads: [comment("one")] }) };
@@ -521,49 +663,30 @@ describe("PullRequestMonitor dispatch protocol", () => {
}),
);
it.effect("archives by projecting stopped before removing the registration", () =>
it.effect("delayed ended event preserves a newer generation", () =>
Effect.gen(function* () {
const h = yield* harness({ initial: snapshot(), current: { value: snapshot() } });
h.replaceGeneration(2);
yield* h.monitor.handleDomainEvent({
sequence: 1,
eventId: EventId.make("archived"),
eventId: EventId.make("ended"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("archived"),
commandId: CommandId.make("ended"),
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.archived",
payload: { threadId, archivedAt: now, updatedAt: now },
type: "thread.monitor-ended",
payload: {
threadId,
generation: 1,
reason: "stopped",
blockersSummary: "",
endedAt: now,
},
});
const ended = endReason(h.commands);
assert.strictEqual(ended?.type === "thread.monitor.end" && ended.reason, "stopped");
assert.strictEqual(h.getRegistration(), undefined);
}),
);
it.effect("removes an archived registration when projecting monitor end fails", () =>
Effect.gen(function* () {
const h = yield* harness({
initial: snapshot(),
current: { value: snapshot() },
failEnd: true,
});
yield* h.monitor.handleDomainEvent({
sequence: 1,
eventId: EventId.make("archived"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("archived"),
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.archived",
payload: { threadId, archivedAt: now, updatedAt: now },
});
assert.strictEqual(h.getRegistration(), undefined);
assert.strictEqual(h.getRegistration()?.generation, 2);
}),
);
@@ -594,4 +717,24 @@ describe("PullRequestMonitor dispatch protocol", () => {
);
}),
);
it.effect("boot reconcile continues past a per-thread failure", () =>
Effect.gen(function* () {
const failing = ThreadId.make("failing-orphan");
const succeeding = ThreadId.make("succeeding-orphan");
const h = yield* harness({
initial: snapshot(),
current: { value: snapshot() },
reconcileThreadIds: [failing, succeeding],
failReconcileThreadId: failing,
});
yield* h.monitor.pollOnce;
assert.strictEqual(
h.commands.some(
(command) => command.type === "thread.monitor.end" && command.threadId === succeeding,
),
true,
);
}),
);
});
+115 -38
View File
@@ -24,6 +24,7 @@ import { buildWakePrompt, formatBlockersSummary } from "./wakePrompt.ts";
const POLL_INTERVAL = Duration.seconds(30);
const MAX_BACKOFF = Duration.minutes(5);
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
interface WakeClaim {
readonly generation: number;
@@ -123,6 +124,7 @@ export const make = Effect.gen(function* () {
const dispatchUpdate = Effect.fn("PullRequestMonitor.dispatchUpdate")(function* (
threadId: ThreadId,
generation: number,
blockersSummary: string,
headSha: string,
wakeCount: number,
@@ -132,6 +134,7 @@ export const make = Effect.gen(function* () {
type: "thread.monitor.update",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId,
generation,
blockersSummary,
headSha,
wakeCount,
@@ -156,6 +159,7 @@ export const make = Effect.gen(function* () {
type: "thread.monitor.end",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId,
generation: expectedGeneration,
reason,
blockersSummary,
endedAt,
@@ -185,7 +189,6 @@ export const make = Effect.gen(function* () {
});
if (!claimed) return;
const current = yield* registry.get(registration.threadId);
// Fresh terminal read at the send boundary (I1): the poll's snapshot is
// seconds stale by now, and a merge in that window must veto the wake —
// the cached `latestStates` alone cannot see it.
@@ -202,11 +205,42 @@ export const make = Effect.gen(function* () {
return;
}
const state = freshState.value;
const current = yield* registry.get(registration.threadId);
const thread = yield* snapshots.getThreadDetailById(registration.threadId);
const validRegistration =
Option.isSome(current) && current.value.generation === registration.generation;
Option.isSome(current) &&
current.value.generation === registration.generation &&
Option.isSome(thread) &&
thread.value.archivedAt === null &&
thread.value.monitor?.status === "monitoring" &&
thread.value.monitor.generation === registration.generation;
const latestUserMessageAt = Option.isSome(thread)
? thread.value.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
)
: Number.NEGATIVE_INFINITY;
const latestTurnAt =
Option.isSome(thread) && thread.value.latestTurn !== null
? Math.max(
...[
thread.value.latestTurn.requestedAt,
thread.value.latestTurn.startedAt,
thread.value.latestTurn.completedAt,
].map((value) => (value === null ? Number.NEGATIVE_INFINITY : Date.parse(value))),
)
: Number.NEGATIVE_INFINITY;
const createdAt = DateTime.formatIso(yield* DateTime.now);
const queuedUserTurn =
Option.isSome(thread) &&
thread.value.session?.status !== "error" &&
Number.isFinite(latestUserMessageAt) &&
latestUserMessageAt > latestTurnAt &&
Math.abs(Date.parse(createdAt) - latestUserMessageAt) <= QUEUED_TURN_START_GRACE_MS;
const busy =
Option.isNone(thread) ||
queuedUserTurn ||
thread.value.latestTurn?.state === "running" ||
(thread.value.session?.activeTurnId !== null &&
thread.value.session?.activeTurnId !== undefined) ||
@@ -221,7 +255,6 @@ export const make = Effect.gen(function* () {
return;
}
const createdAt = DateTime.formatIso(yield* DateTime.now);
yield* engine
.dispatch({
type: "thread.turn.start",
@@ -253,7 +286,13 @@ export const make = Effect.gen(function* () {
),
),
Effect.tap(() =>
registry.updateCursor(registration.threadId, nextCursor, registration.generation),
Ref.get(claims).pipe(
Effect.flatMap((currentClaims) =>
currentClaims.get(registration.threadId)?.commandId === commandId
? registry.updateCursor(registration.threadId, nextCursor, registration.generation)
: Effect.void,
),
),
),
Effect.tapError(() =>
mutateClaim(registration.threadId, (claim) =>
@@ -264,6 +303,7 @@ export const make = Effect.gen(function* () {
const wakeCount = yield* registry.incrementWake(registration.threadId, registration.generation);
yield* dispatchUpdate(
registration.threadId,
registration.generation,
formatBlockersSummary(computeReadiness(snapshot)),
snapshot.headSha,
wakeCount,
@@ -281,16 +321,18 @@ export const make = Effect.gen(function* () {
...fetchedSnapshot,
monitoringStartedAt: registration.startedAt,
};
const readiness = computeReadiness(snapshot);
const readiness = computeReadiness(snapshot, registration.cursor.threadVersions);
const summary = formatBlockersSummary(readiness);
const diff = diffPullRequestMonitorSnapshot(registration.cursor, snapshot);
if (snapshot.state !== "open") {
yield* end(registration.threadId, "terminal", summary, registration.generation);
return;
}
if (readiness.ready) {
if (readiness.ready && diff.actionableEvents.length === 0) {
yield* dispatchUpdate(
registration.threadId,
registration.generation,
summary,
snapshot.headSha,
registration.wakeCount,
@@ -299,9 +341,17 @@ export const make = Effect.gen(function* () {
return;
}
const diff = diffPullRequestMonitorSnapshot(registration.cursor, snapshot);
yield* dispatchUpdate(registration.threadId, summary, snapshot.headSha, registration.wakeCount);
if (diff.actionableEvents.length === 0) return;
yield* dispatchUpdate(
registration.threadId,
registration.generation,
summary,
snapshot.headSha,
registration.wakeCount,
);
if (diff.actionableEvents.length === 0) {
yield* registry.updateCursor(registration.threadId, diff.nextCursor, registration.generation);
return;
}
if (registration.wakeCount >= 10) {
yield* end(registration.threadId, "needs-attention", summary, registration.generation);
return;
@@ -335,12 +385,19 @@ export const make = Effect.gen(function* () {
type: "thread.monitor.end",
commandId: CommandId.make(`monitor-boot-reconcile:${thread.id}:${endedAt}`),
threadId: thread.id,
generation: thread.monitor!.generation,
reason: "session-ended",
blockersSummary: "",
endedAt,
});
});
}),
Effect.catchCause((cause) =>
Effect.logWarning("pull request monitor orphan reconcile failed", {
threadId: thread.id,
cause,
}),
),
),
{ discard: true },
);
@@ -378,41 +435,61 @@ export const make = Effect.gen(function* () {
const onEvent = (event: OrchestrationEvent) => {
const threadId = threadIdOf(event);
if (threadId === undefined) return Effect.void;
if (event.type === "thread.archived") {
return registry.get(threadId).pipe(
Effect.flatMap((registration) =>
Option.isNone(registration)
? Effect.void
: end(threadId, "stopped", "", registration.value.generation).pipe(
Effect.catch((error) =>
Effect.logWarning(
"pull request monitor archive projection stuck; removing registration",
{
threadId,
error,
},
).pipe(
Effect.andThen(registry.remove(threadId, registration.value.generation)),
if (event.type === "thread.monitor-ended") {
return registry
.remove(threadId, event.payload.generation)
.pipe(
Effect.andThen(
mutateClaim(threadId, (claim) =>
claim?.generation === event.payload.generation ? undefined : claim,
),
),
Effect.asVoid,
);
}
if (event.type === "thread.settled") {
return Effect.all([registry.get(threadId), snapshots.getThreadDetailById(threadId)]).pipe(
Effect.flatMap(([registration, thread]) => {
if (
Option.isNone(registration) ||
Option.isNone(thread) ||
thread.value.monitor?.generation !== registration.value.generation
)
return Effect.void;
return registry
.remove(threadId, registration.value.generation)
.pipe(
Effect.andThen(
mutateClaim(threadId, (claim) =>
claim?.generation === registration.value.generation ? undefined : claim,
),
),
);
}),
Effect.catchCause((cause) =>
Effect.logWarning("pull request monitor settled cleanup failed", { threadId, cause }),
),
Effect.asVoid,
);
}
if (event.type === "thread.deleted") {
return registry
.get(threadId)
.pipe(
Effect.flatMap((registration) =>
Option.isNone(registration)
? Effect.void
: registry
.remove(threadId, registration.value.generation)
.pipe(
Effect.andThen(
mutateClaim(threadId, (claim) =>
claim?.generation === registration.value.generation ? undefined : claim,
),
),
Effect.asVoid,
),
),
),
),
);
}
if (
event.type === "thread.deleted" ||
event.type === "thread.settled" ||
event.type === "thread.monitor-ended"
) {
return registry
.remove(threadId)
.pipe(Effect.andThen(mutateClaim(threadId, () => undefined)), Effect.asVoid);
),
);
}
if (event.type === "thread.turn-start-requested") {
// A turn we didn't start won the thread. Drop our claim — and if our
+14 -5
View File
@@ -18,7 +18,11 @@ export interface PullRequestMonitorCursor {
export type PullRequestMonitorActionableEvent =
| { readonly kind: "new-review-comment"; readonly threadId: string; readonly edited: boolean }
| { readonly kind: "changes-requested-review"; readonly reviewId: string }
| {
readonly kind: "changes-requested-review";
readonly reviewId: string;
readonly body: string;
}
| { readonly kind: "check-failed"; readonly checkRunId: string; readonly checkName: string }
| { readonly kind: "behind-base" };
@@ -69,11 +73,12 @@ export function diffPullRequestMonitorSnapshot(
const actionableEvents: PullRequestMonitorActionableEvent[] = [];
for (const thread of snapshot.reviewThreads) {
const previous = previousCursor.threadVersions[thread.id];
if (
const reopened = previous?.resolved === true && !thread.resolved;
const changedComment =
!thread.latestCommentByViewer &&
!thread.resolved &&
(!previous || previous.resolved || previous.updatedAt !== thread.updatedAt)
) {
(!previous || previous.updatedAt !== thread.updatedAt);
if (reopened || changedComment) {
actionableEvents.push({
kind: "new-review-comment",
threadId: thread.id,
@@ -97,7 +102,11 @@ export function diffPullRequestMonitorSnapshot(
review.state === "changes-requested" &&
previousCursor.reviewStates[review.id] !== "changes-requested"
) {
actionableEvents.push({ kind: "changes-requested-review", reviewId: review.id });
actionableEvents.push({
kind: "changes-requested-review",
reviewId: review.id,
body: review.body.slice(0, 500),
});
}
}
for (const check of snapshot.checkRuns.filter((item) => item.headSha === snapshot.headSha)) {
+29
View File
@@ -42,6 +42,7 @@ describe("pull request monitor readiness", () => {
state: "changes-requested",
submittedAt: "2026-01-01T00:00:00Z",
commitSha: "head-1",
body: "",
},
],
}),
@@ -62,6 +63,7 @@ describe("pull request monitor readiness", () => {
state: "changes-requested",
submittedAt: "2026-01-01T00:00:00Z",
commitSha: "head-2",
body: "",
},
],
}),
@@ -81,6 +83,7 @@ describe("pull request monitor readiness", () => {
state: "approved",
submittedAt: "2026-01-01T00:00:00Z",
commitSha: "head-1",
body: "",
},
],
}),
@@ -89,6 +92,32 @@ describe("pull request monitor readiness", () => {
assert.strictEqual(result.ready, true);
});
it("unblocks a changes request superseded by the same reviewer's approval", () => {
const result = computeReadiness(
snapshot({
reviews: [
{
id: "changes",
author: { login: "reviewer", type: "user" },
state: "changes-requested",
submittedAt: "2026-01-01T00:00:00Z",
commitSha: "head-1",
body: "Please fix this",
},
{
id: "approval",
author: { login: "reviewer", type: "user" },
state: "approved",
submittedAt: "2026-01-02T00:00:00Z",
commitSha: "head-2",
body: "",
},
],
}),
);
assert.strictEqual(result.ready, true);
});
it("does not report ready when no check runs exist", () => {
const result = computeReadiness(snapshot({ checkRuns: [] }));
assert.strictEqual(result.ready, false);
+17 -4
View File
@@ -18,6 +18,9 @@ export interface PullRequestMonitorReadiness {
export function computeReadiness(
snapshot: PullRequestMonitorSnapshot,
previousThreadVersions: Readonly<
Record<string, { readonly updatedAt: string; readonly resolved: boolean }>
> = {},
): PullRequestMonitorReadiness {
const blockers: PullRequestMonitorBlocker[] = [];
if (snapshot.state !== "open") blockers.push({ kind: "terminal", state: snapshot.state });
@@ -38,7 +41,15 @@ export function computeReadiness(
blockers.push({ kind: "check-failed", checkName: check.name });
}
}
const latestOpinionatedReviews = new Map<string, (typeof snapshot.reviews)[number]>();
for (const review of snapshot.reviews) {
if (review.state !== "changes-requested" && review.state !== "approved") continue;
const previous = latestOpinionatedReviews.get(review.author.login);
if (previous === undefined || (review.submittedAt ?? "") > (previous.submittedAt ?? "")) {
latestOpinionatedReviews.set(review.author.login, review);
}
}
for (const review of latestOpinionatedReviews.values()) {
// Stale approvals must not count toward green, but a changes-requested
// review blocks regardless of which commit it reviewed — GitHub keeps it
// active until dismissed or superseded by a re-review.
@@ -47,10 +58,12 @@ export function computeReadiness(
}
}
for (const thread of snapshot.reviewThreads) {
if (
!thread.resolved &&
(!snapshot.monitoringStartedAt || thread.createdAt >= snapshot.monitoringStartedAt)
) {
const previous = previousThreadVersions[thread.id];
const changedSinceStart =
snapshot.monitoringStartedAt === undefined ||
thread.updatedAt > snapshot.monitoringStartedAt ||
(previous?.resolved === true && !thread.resolved);
if (!thread.resolved && changedSinceStart) {
blockers.push({ kind: "unresolved-thread", threadId: thread.id });
}
}
+2 -1
View File
@@ -52,7 +52,8 @@ function formatEvent(
}
case "changes-requested-review": {
const review = snapshot.reviews.find((item) => item.id === event.reviewId);
return `- ${review?.author.login ?? "Reviewer"} requested changes`;
const detail = excerpt(event.body);
return `- ${review?.author.login ?? "Reviewer"} requested changes${detail ? `: ${detail}` : ""}`;
}
case "check-failed": {
const check = snapshot.checkRuns.find((item) => item.id === event.checkRunId);
@@ -722,6 +722,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
monitor: {
generation: event.payload.generation,
prNumber: event.payload.prNumber,
status: "monitoring",
blockersSummary: event.payload.blockersSummary,
@@ -740,7 +741,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow) || existingRow.value.monitor === null) return;
if (
Option.isNone(existingRow) ||
existingRow.value.monitor?.generation !== event.payload.generation
)
return;
yield* projectionThreadRepository.upsert({
...existingRow.value,
monitor: {
@@ -758,7 +763,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow) || existingRow.value.monitor === null) return;
if (
Option.isNone(existingRow) ||
existingRow.value.monitor?.generation !== event.payload.generation
)
return;
yield* projectionThreadRepository.upsert({
...existingRow.value,
monitor: {
@@ -46,6 +46,7 @@ const makeReadModel = (monitor: OrchestrationThread["monitor"] = null): Orchestr
});
const activeMonitor: NonNullable<OrchestrationThread["monitor"]> = {
generation: 1,
prNumber: 42,
status: "monitoring",
blockersSummary: "waiting",
@@ -66,6 +67,7 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
type: "thread.monitor.start" as const,
commandId: commandId("start"),
threadId,
generation: 1,
prNumber: 42,
blockersSummary: "",
headSha: "abc",
@@ -100,6 +102,7 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
type: "thread.monitor.start",
commandId: commandId("different"),
threadId,
generation: 2,
prNumber: 43,
blockersSummary: "",
headSha: "def",
@@ -114,6 +117,7 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
type: "thread.monitor.update",
commandId: commandId("update"),
threadId,
generation: 1,
blockersSummary: "CI",
headSha: "def",
wakeCount: 1,
@@ -129,6 +133,7 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
type: "thread.monitor.end",
commandId: commandId("end"),
threadId,
generation: 1,
reason: "ready",
blockersSummary: "",
endedAt: NOW,
@@ -146,6 +151,7 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
type: "thread.monitor.update" as const,
commandId: commandId("bad-update"),
threadId,
generation: 1,
blockersSummary: "",
headSha: "abc",
wakeCount: 0,
@@ -155,6 +161,7 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
type: "thread.monitor.end" as const,
commandId: commandId("bad-end"),
threadId,
generation: 1,
reason: "stopped" as const,
blockersSummary: "",
endedAt: NOW,
@@ -176,4 +183,20 @@ it.layer(NodeServices.layer)("monitor decider", (it) => {
]);
}),
);
it.effect("archive emits monitor-ended before archived", () =>
Effect.gen(function* () {
const archived = yield* decideOrchestrationCommand({
command: { type: "thread.archive", commandId: commandId("archive"), threadId },
readModel: makeReadModel(activeMonitor),
});
expect(Array.isArray(archived) ? archived.map((event) => event.type) : []).toEqual([
"thread.monitor-ended",
"thread.archived",
]);
if (Array.isArray(archived) && archived[0]?.type === "thread.monitor-ended") {
expect(archived[0].payload.generation).toBe(1);
}
}),
);
});
+39 -2
View File
@@ -401,13 +401,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.archive": {
yield* requireThreadNotArchived({
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = yield* nowIso;
return {
const archivedEvent: PlannedOrchestrationEvent = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
@@ -421,6 +421,26 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: occurredAt,
},
};
if (thread.monitor?.status !== "monitoring") return archivedEvent;
return [
{
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.monitor-ended",
payload: {
threadId: command.threadId,
generation: thread.monitor.generation,
reason: "stopped",
blockersSummary: thread.monitor.blockersSummary,
endedAt: occurredAt,
},
},
archivedEvent,
];
}
case "thread.unarchive": {
@@ -516,6 +536,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "thread.monitor-ended",
payload: {
threadId: command.threadId,
generation: thread.monitor.generation,
reason: "stopped",
blockersSummary: thread.monitor.blockersSummary,
endedAt: occurredAt,
@@ -547,6 +568,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "thread.monitor-started",
payload: {
threadId: command.threadId,
generation: command.generation,
prNumber: command.prNumber,
blockersSummary:
thread.monitor?.status === "monitoring"
@@ -596,6 +618,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
detail: `thread ${command.threadId} has no active monitor`,
});
}
if (command.generation !== undefined && command.generation !== thread.monitor.generation) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} monitor generation does not match`,
});
}
return {
...(yield* withEventBase({
aggregateKind: "thread",
@@ -606,6 +634,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "thread.monitor-snapshot-updated",
payload: {
threadId: command.threadId,
generation: thread.monitor.generation,
blockersSummary: command.blockersSummary,
headSha: command.headSha,
wakeCount: command.wakeCount,
@@ -626,6 +655,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
detail: `thread ${command.threadId} has no active monitor`,
});
}
const generation = command.generation ?? thread.monitor.generation;
if (generation !== thread.monitor.generation) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} monitor generation does not match`,
});
}
return {
...(yield* withEventBase({
aggregateKind: "thread",
@@ -636,6 +672,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "thread.monitor-ended",
payload: {
threadId: command.threadId,
generation,
reason: command.reason,
blockersSummary: command.blockersSummary,
endedAt: command.endedAt,
@@ -32,6 +32,7 @@ it.effect("projects the monitor lifecycle without changing settledOverride", ()
createEmptyReadModel(NOW),
event(1, "thread.created", {
threadId: ThreadId.make("thread-1"),
generation: 1,
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
@@ -47,6 +48,7 @@ it.effect("projects the monitor lifecycle without changing settledOverride", ()
model,
event(2, "thread.monitor-started", {
threadId: ThreadId.make("thread-1"),
generation: 1,
prNumber: 42,
blockersSummary: "draft",
headSha: "abc",
@@ -60,6 +62,7 @@ it.effect("projects the monitor lifecycle without changing settledOverride", ()
model,
event(3, "thread.monitor-snapshot-updated", {
threadId: ThreadId.make("thread-1"),
generation: 1,
blockersSummary: "CI",
headSha: "def",
wakeCount: 2,
@@ -71,6 +74,7 @@ it.effect("projects the monitor lifecycle without changing settledOverride", ()
model,
event(4, "thread.monitor-ended", {
threadId: ThreadId.make("thread-1"),
generation: 1,
reason: "ready",
blockersSummary: "",
endedAt: NOW,
+3 -2
View File
@@ -403,6 +403,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
monitor: {
generation: payload.generation,
prNumber: payload.prNumber,
status: "monitoring",
blockersSummary: payload.blockersSummary,
@@ -427,7 +428,7 @@ export function projectEvent(
Effect.map((payload) => ({
...nextBase,
threads: nextBase.threads.map((thread) =>
thread.id === payload.threadId && thread.monitor != null
thread.id === payload.threadId && thread.monitor?.generation === payload.generation
? {
...thread,
monitor: {
@@ -448,7 +449,7 @@ export function projectEvent(
Effect.map((payload) => ({
...nextBase,
threads: nextBase.threads.map((thread) =>
thread.id === payload.threadId && thread.monitor != null
thread.id === payload.threadId && thread.monitor?.generation === payload.generation
? {
...thread,
monitor: {
@@ -17,6 +17,7 @@ export interface PullRequestMonitorReview {
readonly state: "approved" | "changes-requested" | "commented" | "dismissed" | "pending";
readonly submittedAt: string | null;
readonly commitSha: string | null;
readonly body: string;
}
export interface PullRequestMonitorReviewThread {
@@ -82,6 +83,7 @@ const ReviewSchema = Schema.Struct({
state: Schema.String,
submittedAt: Schema.NullOr(Schema.String),
commit: Schema.NullOr(Schema.Struct({ oid: Schema.String })),
body: Schema.String,
});
const ThreadSchema = Schema.Struct({
id: Schema.String,
@@ -153,6 +155,19 @@ const CheckRunsSchema = Schema.Struct({
}),
),
});
const FinalPullRequestStateSchema = Schema.Struct({
data: Schema.Struct({
repository: Schema.Struct({
pullRequest: Schema.NullOr(
Schema.Struct({
state: Schema.String,
merged: Schema.Boolean,
headRefOid: Schema.String,
}),
),
}),
}),
});
export class GitHubPullRequestMonitorDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestMonitorDecodeError>()(
"GitHubPullRequestMonitorDecodeError",
@@ -230,6 +245,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna
function* (input: {
readonly cwd: string;
readonly pullRequestNumber: number;
readonly refetchAttempt?: number;
}): Effect.fn.Return<
PullRequestMonitorSnapshot,
GitHubPullRequestMonitorError,
@@ -270,7 +286,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna
>
| undefined;
do {
const query = `query($owner:String!,$name:String!,$number:Int!,$reviews:String,$threads:String){viewer{login} repository(owner:$owner,name:$name){pullRequest(number:$number){state isDraft merged mergeable headRefOid baseRefName reviews(first:100,after:$reviews){nodes{id author{login __typename} state submittedAt commit{oid}} pageInfo{hasNextPage endCursor}} reviewThreads(first:100,after:$threads){nodes{id isResolved comments(last:1){nodes{author{login __typename} body path line createdAt updatedAt}}} pageInfo{hasNextPage endCursor}}}}}`;
const query = `query($owner:String!,$name:String!,$number:Int!,$reviews:String,$threads:String){viewer{login} repository(owner:$owner,name:$name){pullRequest(number:$number){state isDraft merged mergeable headRefOid baseRefName reviews(first:100,after:$reviews){nodes{id author{login __typename} state submittedAt commit{oid} body} pageInfo{hasNextPage endCursor}} reviewThreads(first:100,after:$threads){nodes{id isResolved comments(last:10){nodes{author{login __typename} body path line createdAt updatedAt}}} pageInfo{hasNextPage endCursor}}}}}`;
const result: VcsProcess.VcsProcessOutput = yield* github.execute({
cwd: input.cwd,
args: [
@@ -326,6 +342,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna
state: normalizeReviewState(review.state),
submittedAt: review.submittedAt,
commitSha: review.commit?.oid ?? null,
body: review.body,
});
}
reviewsComplete = !pr.reviews.pageInfo.hasNextPage;
@@ -333,7 +350,13 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna
}
if (!threadsComplete) {
for (const thread of pr.reviewThreads.nodes) {
const comment = thread.comments.nodes[0];
const comment = thread.comments.nodes.reduce<
(typeof thread.comments.nodes)[number] | undefined
>(
(latest, candidate) =>
latest === undefined || candidate.updatedAt > latest.updatedAt ? candidate : latest,
undefined,
);
if (comment) {
reviewThreads.set(thread.id, {
id: thread.id,
@@ -427,6 +450,53 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna
if (response.check_runs.length < 100) break;
}
const finalQuery = `query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){state merged headRefOid}}}`;
const finalResult = yield* github.execute({
cwd: input.cwd,
args: [
"api",
"graphql",
"-f",
`query=${finalQuery}`,
"-F",
`owner=${owner}`,
"-F",
`name=${name}`,
"-F",
`number=${input.pullRequestNumber}`,
],
});
const finalPage = yield* decode(
FinalPullRequestStateSchema,
finalResult.stdout,
input.cwd,
"GitHub GraphQL returned invalid final pull request state JSON.",
);
const finalPr = finalPage.data.repository.pullRequest;
if (finalPr === null) {
return yield* new GitHubPullRequestMonitorDecodeError({
command: "gh",
cwd: input.cwd,
detail: "GitHub pull request disappeared during monitor fetch.",
cause: input.pullRequestNumber,
});
}
const finalState: PullRequestMonitorSnapshot["state"] = finalPr.merged
? "merged"
: finalPr.state === "CLOSED"
? "closed"
: "open";
if (finalState !== "open") metadata = { ...metadata, state: finalState };
if (finalState === "open" && finalPr.headRefOid !== metadata.headSha) {
if ((input.refetchAttempt ?? 0) === 0) {
return yield* getPullRequestMonitorSnapshot({
...input,
refetchAttempt: 1,
});
}
metadata = { ...metadata, headSha: finalPr.headRefOid };
}
return {
...metadata,
behindBaseBy: null,
+10 -5
View File
@@ -2337,12 +2337,17 @@ function ChatViewContent(props: ChatViewProps) {
// ready-state "View PR"/"Merge…" affordances, and a stop handler that ends
// the monitor via the same command path the server drives.
const openPrLink = useOpenPrLink();
const checkoutPr = resolveThreadPr({
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
hasDedicatedWorktree: activeThread?.worktreePath != null,
});
// Monitoring can target a PR other than the checkout's current PR, so never
// let the ready actions open a differently numbered pull request.
const monitorPrUrl =
resolveThreadPr({
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
hasDedicatedWorktree: activeThread?.worktreePath != null,
})?.url ?? null;
checkoutPr !== null && checkoutPr.number === activeThread?.monitor?.prNumber
? checkoutPr.url
: null;
const handleStopMonitoring = useCallback(() => {
if (activeThread == null || activeThread.monitor == null) return;
void endThreadMonitor({
+25 -4
View File
@@ -1,6 +1,6 @@
import type { OrchestrationThreadMonitor } from "@t3tools/contracts";
import { ExternalLinkIcon, GitMergeIcon } from "lucide-react";
import { type MouseEvent, useState } from "react";
import { type MouseEvent, useEffect, useState } from "react";
import { cn } from "~/lib/utils";
import { resolveMonitorReadyLabel, resolveMonitorSidebarState } from "./Sidebar.logic";
@@ -42,9 +42,13 @@ export function MonitorStrip({
}) {
const [mergeConfirmOpen, setMergeConfirmOpen] = useState(false);
const state = resolveMonitorSidebarState(monitor);
useEffect(() => {
setMergeConfirmOpen(false);
}, [monitor.prNumber, monitor.status]);
// Only the meaningful, live-ish states get a strip: an actively monitoring
// PR, the ready payoff, or a dead-session floor marker. Terminal/user-stop/
// needs-attention monitors hand off to the normal settled/status treatment.
// PR, the ready payoff, the needs-attention escalation, or a dead-session
// floor marker. Other terminal/user-stop monitors hand off to the normal
// settled/status treatment.
if (state === null) return null;
const blockers = monitor.blockersSummary.trim();
@@ -65,6 +69,22 @@ export function MonitorStrip({
);
}
if (state === "needs-attention") {
return (
<div className="px-3 pt-2 sm:px-5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-amber-500/40 bg-amber-500/[0.07] px-3 py-2">
<span className="inline-flex items-center gap-1.5 text-xs font-semibold text-amber-700 dark:text-amber-300">
<span className="size-1.5 rounded-full bg-amber-500 dark:bg-amber-400" aria-hidden />
Monitoring paused — needs your attention
</span>
{blockers !== "" ? (
<span className="min-w-0 truncate text-xs text-muted-foreground">{blockers}</span>
) : null}
</div>
</div>
);
}
const isReady = state === "ready";
const handleOpenPr = (event: MouseEvent<HTMLElement>) => {
if (prUrl) onOpenPr(event, prUrl);
@@ -145,8 +165,9 @@ export function MonitorStrip({
rather than inventing a new server mutation (out of P3 scope). */}
<Button
variant="default"
disabled={prUrl === null}
disabled={!isReady || prUrl === null}
onClick={(event) => {
if (!isReady || prUrl === null) return;
setMergeConfirmOpen(false);
handleOpenPr(event);
}}
+62 -3
View File
@@ -920,6 +920,7 @@ describe("resolveThreadStatusPill", () => {
});
const activeMonitor = {
generation: 1,
prNumber: 4412,
status: "monitoring" as const,
blockersSummary: "2 checks pending · waiting on Bugbot",
@@ -938,7 +939,7 @@ describe("resolveThreadStatusPill", () => {
).toMatchObject({ label: "Monitoring", pulse: false });
});
it("never lets Monitoring swallow a blocked state (I4)", () => {
it("never lets Monitoring swallow a blocked or failed state (I4)", () => {
expect(
resolveThreadStatusPill({
thread: { ...baseThread, monitor: activeMonitor, hasPendingApprovals: true },
@@ -949,6 +950,63 @@ describe("resolveThreadStatusPill", () => {
thread: { ...baseThread, monitor: activeMonitor, hasPendingUserInput: true },
}),
).toMatchObject({ label: "Awaiting Input" });
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
monitor: activeMonitor,
session: { ...baseThread.session, status: "error", lastError: "boom" },
},
}),
).toMatchObject({ label: "Failed" });
});
it("shows a prominent Needs attention pill for monitor escalation", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
monitor: {
...activeMonitor,
status: "needs-attention",
endedAt: "2026-03-09T10:05:00.000Z",
endedReason: "needs-attention",
},
session: { ...baseThread.session, status: "ready", activeTurnId: null },
},
}),
).toMatchObject({ label: "Needs attention", pulse: false });
});
it("shows a ready monitor payoff until its end has been visited", () => {
const readyMonitor = {
...activeMonitor,
status: "ready" as const,
endedAt: "2026-03-09T10:05:00.000Z",
endedReason: "ready" as const,
};
const idleSession = { ...baseThread.session, status: "ready" as const, activeTurnId: null };
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
monitor: readyMonitor,
lastVisitedAt: "2026-03-09T10:04:00.000Z",
session: idleSession,
},
}),
).toMatchObject({ label: "Ready to merge", pulse: false });
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
monitor: readyMonitor,
lastVisitedAt: "2026-03-09T10:06:00.000Z",
session: idleSession,
},
}),
).toBeNull();
});
it("suppresses the Completed pill for wake-turn completions while monitoring", () => {
@@ -985,6 +1043,7 @@ describe("resolveThreadStatusPill", () => {
describe("resolveMonitorSidebarState", () => {
const monitor = {
generation: 1,
prNumber: 4412,
status: "monitoring" as const,
blockersSummary: "",
@@ -1007,7 +1066,7 @@ describe("resolveMonitorSidebarState", () => {
);
});
it("marks only a session-ended stop, deferring other terminal reasons", () => {
it("maps needs-attention and only marks session-ended stops", () => {
expect(
resolveMonitorSidebarState({
...monitor,
@@ -1024,7 +1083,7 @@ describe("resolveMonitorSidebarState", () => {
status: "needs-attention",
endedReason: "needs-attention",
}),
).toBeNull();
).toBe("needs-attention");
});
});
+57 -10
View File
@@ -100,6 +100,10 @@ export interface ThreadStatusPill {
| "Connecting"
| "Completed"
| "Monitoring"
| "Ready to merge"
| "No known blockers"
| "Needs attention"
| "Failed"
| "Pending Approval"
| "Awaiting Input"
| "Plan Ready";
@@ -109,15 +113,19 @@ export interface ThreadStatusPill {
}
const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
"Pending Approval": 6,
"Awaiting Input": 5,
"Pending Approval": 8,
"Awaiting Input": 7,
Failed: 6,
"Needs attention": 5,
// Monitoring outranks Working/Completed so the pill stays steady through
// wake-turn fixes (decision D6), but sits below approval/input so a
// blocked state is never swallowed (invariant I4).
// wake-turn fixes (decision D6), but sits below blocked/failed states so an
// actionable state is never swallowed (invariant I4).
Monitoring: 4,
Working: 3,
Connecting: 3,
"Plan Ready": 2,
"Ready to merge": 1,
"No known blockers": 1,
Completed: 1,
};
@@ -138,7 +146,7 @@ type ThreadStatusInput = Pick<
// The steady sidebar-facing distillation of a thread's PR monitor. Cyan
// while monitoring, emerald at the payoff, a subtle zinc marker for a dead
// babysitter — everything else hands back to the normal status treatment.
export type MonitorSidebarState = "monitoring" | "ready" | "stopped";
export type MonitorSidebarState = "monitoring" | "ready" | "needs-attention" | "stopped";
export function resolveMonitorSidebarState(
monitor: SidebarThreadSummary["monitor"],
@@ -146,10 +154,11 @@ export function resolveMonitorSidebarState(
if (monitor == null) return null;
if (monitor.status === "monitoring") return "monitoring";
if (monitor.status === "ready") return "ready";
if (monitor.status === "needs-attention") return "needs-attention";
// D2 floor: a session-scoped monitor whose session died gets a visible
// "Monitoring stopped" marker so a dead babysitter is distinguishable from
// a quiet, live one. Other terminal reasons (terminal/stopped-by-user/
// needs-attention) defer to the normal settled/status treatment.
// a quiet, live one. Other terminal reasons defer to the normal
// settled/status treatment.
if (monitor.status === "stopped" && monitor.endedReason === "session-ended") return "stopped";
return null;
}
@@ -266,6 +275,17 @@ export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
return completedAt > lastVisitedAt;
}
function hasUnseenMonitorEnd(thread: ThreadStatusInput): boolean {
if (!thread.monitor?.endedAt) return false;
const endedAt = Date.parse(thread.monitor.endedAt);
if (Number.isNaN(endedAt)) return false;
if (!thread.lastVisitedAt) return false;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return endedAt > lastVisitedAt;
}
export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
if (target === null) return true;
return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
@@ -596,11 +616,29 @@ export function resolveThreadStatusPill(input: {
};
}
if (thread.session?.status === "error") {
return {
label: "Failed",
colorClass: "text-red-600 dark:text-red-300/90",
dotClass: "bg-red-500 dark:bg-red-300/90",
pulse: false,
};
}
if (thread.monitor?.status === "needs-attention") {
return {
label: "Needs attention",
colorClass: "text-amber-700 dark:text-amber-300",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
// An active PR monitor keeps a steady "Monitoring" pill for the whole mode,
// including through wake-turn fixes — it outranks Working/Completed but,
// being placed after approval/input above, never swallows a blocked state
// (D6, invariant I4). The PR number and blockers ride in the sub-line.
if (thread.monitor != null && thread.monitor.status === "monitoring") {
// being placed after actionable states above, never swallows a blocked or
// failed state (D6, invariant I4). The PR number and blockers ride in the sub-line.
if (thread.monitor?.status === "monitoring") {
return {
label: "Monitoring",
colorClass: "text-cyan-600 dark:text-cyan-300/90",
@@ -609,6 +647,15 @@ export function resolveThreadStatusPill(input: {
};
}
if (thread.monitor?.status === "ready" && hasUnseenMonitorEnd(thread)) {
return {
label: resolveMonitorReadyLabel(thread.monitor.blockersSummary),
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
+31 -19
View File
@@ -426,19 +426,24 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
const monitorState = resolveMonitorSidebarState(thread.monitor);
const isMonitoring = monitorState === "monitoring";
const isMonitorReady = monitorState === "ready";
const isMonitorNeedsAttention = monitorState === "needs-attention";
const isMonitorStopped = monitorState === "stopped";
// What the PR is waiting on, in place of the branch on the sub-line — the
// legibility that answers "Are you still going?" (mock 4a). No counter.
const monitorBlockers = thread.monitor?.blockersSummary?.trim() ?? "";
const monitorSubLine =
(isMonitoring || isMonitorReady) && monitorBlockers !== "" ? monitorBlockers : null;
(isMonitoring || isMonitorReady || isMonitorNeedsAttention) && monitorBlockers !== ""
? monitorBlockers
: null;
// Same semantics as v1 (never-visited counts as read): flipping the beta
// flag must not light up every historical thread as unread. A ready PR is
// the payoff moment — treat it as unread-prominent — while an actively
// monitoring thread suppresses the success-shaped unread from its quiet
// wake-turn completions (never a blocked state — that surfaces via status).
const isUnread =
isMonitorReady || (!isMonitoring && hasUnseenCompletion({ ...thread, lastVisitedAt }));
isMonitorReady ||
isMonitorNeedsAttention ||
(!isMonitoring && hasUnseenCompletion({ ...thread, lastVisitedAt }));
const status = resolveSidebarV2Status(thread);
// A woken thread reappears at its original position (the sort is
// deliberately static), so the pill has to carry the weight. Snoozing is
@@ -503,34 +508,41 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
className: "text-emerald-700 dark:text-emerald-300",
}
: null;
// Monitoring wraps the base status: a ready PR is the emerald payoff, an
// active monitor is one steady cyan pill through fixes (D6), a dead-session
// monitor gets the subtle zinc floor marker (D2). A genuinely blocked wake
// turn (approval/input/failed) is never swallowed — those keep the base
// pill (invariant I4). A freshly woken snoozed thread also keeps its explicit
// Monitoring wraps the base status: a ready PR is the emerald payoff,
// needs-attention is the prominent amber escalation, an active monitor is one
// steady cyan pill through fixes (D6), and a dead-session monitor gets the
// subtle zinc floor marker (D2). A genuinely blocked wake turn
// (approval/input/failed) is never swallowed — those keep the base pill
// (invariant I4). A freshly woken snoozed thread also keeps its explicit
// user-action pill instead of being swallowed by monitor state.
const isBlockedOrFailed = status === "approval" || status === "input" || status === "failed";
const topStatus = isWoke
? baseTopStatus
: isMonitorReady && !isBlockedOrFailed
: isMonitorNeedsAttention && !isBlockedOrFailed
? {
label: resolveMonitorReadyLabel(thread.monitor?.blockersSummary ?? ""),
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
label: "Needs attention",
icon: null,
className: "text-amber-700 dark:text-amber-300",
}
: isMonitoring && !isBlockedOrFailed
: isMonitorReady && !isBlockedOrFailed
? {
label: "Monitoring",
icon: null,
className: "text-cyan-700 dark:text-cyan-300",
label: resolveMonitorReadyLabel(thread.monitor?.blockersSummary ?? ""),
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
}
: isMonitorStopped && !isBlockedOrFailed
: isMonitoring && !isBlockedOrFailed
? {
label: "Monitoring stopped",
label: "Monitoring",
icon: null,
className: "text-muted-foreground/80",
className: "text-cyan-700 dark:text-cyan-300",
}
: baseTopStatus;
: isMonitorStopped && !isBlockedOrFailed
? {
label: "Monitoring stopped",
icon: null,
className: "text-muted-foreground/80",
}
: baseTopStatus;
const gitCwd = thread.worktreePath ?? props.projectCwd;
const gitStatus = useEnvironmentQuery(
@@ -24,6 +24,7 @@ import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
archiveThread,
createProject,
endThreadMonitor,
settleThread,
stopThreadSession,
unsettleThread,
@@ -171,4 +172,29 @@ describe("environment commands", () => {
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
it.effect("preserves a caller-provided monitor end timestamp", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
const supervisor = yield* makeSupervisor(dispatched);
yield* endThreadMonitor({
commandId: CommandId.make("end-monitor-command"),
threadId: ThreadId.make("thread-1"),
blockersSummary: "Waiting on review",
endedAt: "2026-06-06T00:02:00.000Z",
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
expect(dispatched).toEqual([
{
type: "thread.monitor.end",
commandId: "end-monitor-command",
threadId: "thread-1",
reason: "stopped",
blockersSummary: "Waiting on review",
endedAt: "2026-06-06T00:02:00.000Z",
},
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
});
@@ -218,7 +218,7 @@ export const endThreadMonitor: (input: EndThreadMonitorInput) => CommandEffect =
threadId: input.threadId,
reason: "stopped",
blockersSummary: input.blockersSummary,
endedAt: metadata.createdAt,
endedAt: input.endedAt ?? metadata.createdAt,
});
});
@@ -72,6 +72,7 @@ function makeShell(input: {
input.monitorStatus === undefined
? null
: {
generation: 1,
prNumber: 4412,
status: input.monitorStatus,
blockersSummary: "2 checks pending · waiting on Bugbot",
@@ -104,13 +104,31 @@ export type ThreadSnoozeShell = Pick<
| "hasPendingUserInput"
| "session"
| "latestTurn"
| "monitor"
>;
function monitorRaisedHandAt(shell: ThreadSnoozeShell): string | null {
const monitor = shell.monitor;
if (monitor?.endedAt == null) return null;
if (
monitor.status !== "ready" &&
monitor.status !== "needs-attention" &&
monitor.endedReason !== "session-ended"
) {
return null;
}
if (shell.snoozedAt != null && Date.parse(monitor.endedAt) <= Date.parse(shell.snoozedAt)) {
return null;
}
return monitor.endedAt;
}
/**
* A snoozed thread "raises its hand" when something happens that outranks
* the user's snooze: the agent is blocked on them (approval / user input),
* the session failed, or a run completed after the snooze was set — the
* v1 taste of event-based snooze ("something happened" wakes early).
* the session failed, a run completed, or monitoring reached its payoff or
* escalation after the snooze was set — the v1 taste of event-based snooze
* ("something happened" wakes early).
* Raising a hand never clears the server-side snooze fields; it only stops
* the thread from CLASSIFYING as snoozed, exactly like blocked work and
* effectiveSettled.
@@ -135,7 +153,7 @@ export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean
) {
return true;
}
return false;
return monitorRaisedHandAt(shell) !== null;
}
/**
@@ -200,15 +218,18 @@ export function threadWokeAt(
// indicator the user already cleared by visiting (snoozedUntil is newer
// than that visit's lastVisitedAt).
if (threadRaisedHandWhileSnoozed(shell)) {
if (
const monitorAt = monitorRaisedHandAt(shell);
const completedAt =
shell.snoozedAt != null &&
shell.latestTurn?.state === "completed" &&
shell.latestTurn.completedAt != null &&
Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
) {
return shell.latestTurn.completedAt;
? shell.latestTurn.completedAt
: null;
if (monitorAt !== null && completedAt !== null) {
return Date.parse(monitorAt) > Date.parse(completedAt) ? monitorAt : completedAt;
}
return shell.session?.updatedAt ?? shell.snoozedAt ?? null;
return monitorAt ?? completedAt ?? shell.session?.updatedAt ?? shell.snoozedAt ?? null;
}
// No raised hand: woke iff the timer elapsed (still-snoozed → null).
return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
@@ -21,6 +21,15 @@ function makeShell(input: {
readonly sessionStatus?: "starting" | "running" | "ready" | "error";
readonly pending?: "approval" | "user-input";
readonly turnCompletedAt?: string | null;
readonly monitorStatus?: "monitoring" | "ready" | "stopped" | "needs-attention";
readonly monitorEndedAt?: string | null;
readonly monitorEndedReason?:
| "ready"
| "stopped"
| "terminal"
| "session-ended"
| "needs-attention"
| null;
}): ThreadSnoozeShell {
const threadId = ThreadId.make("thread-1");
return {
@@ -51,6 +60,20 @@ function makeShell(input: {
completedAt: input.turnCompletedAt,
assistantMessageId: null,
},
monitor:
input.monitorStatus === undefined
? null
: {
generation: 1,
prNumber: 4412,
status: input.monitorStatus,
blockersSummary: "Waiting on review",
headSha: "a41c2f9",
wakeCount: 0,
startedAt: "2026-04-10T08:00:00.000Z",
endedAt: input.monitorEndedAt ?? null,
endedReason: input.monitorEndedReason ?? null,
},
};
}
@@ -132,6 +155,58 @@ describe("effectiveSnoozed", () => {
),
).toBe(true);
});
it("wakes early for monitor payoff, escalation, and session teardown after the snooze", () => {
const endedAt = "2026-04-10T11:30:00.000Z";
expect(
effectiveSnoozed(
makeShell({
snoozedUntil: FUTURE_WAKE,
monitorStatus: "ready",
monitorEndedAt: endedAt,
monitorEndedReason: "ready",
}),
{ now: NOW },
),
).toBe(false);
expect(
effectiveSnoozed(
makeShell({
snoozedUntil: FUTURE_WAKE,
monitorStatus: "needs-attention",
monitorEndedAt: endedAt,
monitorEndedReason: "needs-attention",
}),
{ now: NOW },
),
).toBe(false);
expect(
effectiveSnoozed(
makeShell({
snoozedUntil: FUTURE_WAKE,
monitorStatus: "stopped",
monitorEndedAt: endedAt,
monitorEndedReason: "session-ended",
}),
{ now: NOW },
),
).toBe(false);
});
it("keeps a monitor result snoozed when it predates the snooze", () => {
expect(
effectiveSnoozed(
makeShell({
snoozedUntil: FUTURE_WAKE,
snoozedAt: "2026-04-10T11:30:00.000Z",
monitorStatus: "ready",
monitorEndedAt: "2026-04-10T11:00:00.000Z",
monitorEndedReason: "ready",
}),
{ now: NOW },
),
).toBe(true);
});
});
describe("threadRaisedHandWhileSnoozed", () => {
@@ -222,6 +297,20 @@ describe("threadWokeAt", () => {
).toBe("2026-04-10T11:00:00.000Z");
});
it("reports monitor.endedAt for an early monitor-result wake", () => {
expect(
threadWokeAt(
makeShell({
snoozedUntil: FUTURE_WAKE,
monitorStatus: "needs-attention",
monitorEndedAt: "2026-04-10T11:30:00.000Z",
monitorEndedReason: "needs-attention",
}),
{ now: NOW },
),
).toBe("2026-04-10T11:30:00.000Z");
});
it("keeps the early wake authoritative after the scheduled time passes", () => {
// Woke early at 10:30 via run-completed; the scheduled wake (PAST_WAKE
// 10:00 relative to a later now) has ALSO passed. Reporting the
+8
View File
@@ -343,6 +343,7 @@ export const OrchestrationLatestTurn = Schema.Struct({
export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
export const OrchestrationThreadMonitor = Schema.Struct({
generation: NonNegativeInt,
prNumber: NonNegativeInt,
status: Schema.Literals(["monitoring", "ready", "stopped", "needs-attention"]),
blockersSummary: Schema.String,
@@ -636,6 +637,7 @@ const ThreadMonitorStartCommand = Schema.Struct({
type: Schema.Literal("thread.monitor.start"),
commandId: CommandId,
threadId: ThreadId,
generation: NonNegativeInt,
prNumber: NonNegativeInt,
blockersSummary: Schema.String,
headSha: Schema.String,
@@ -646,6 +648,7 @@ const ThreadMonitorUpdateCommand = Schema.Struct({
type: Schema.Literal("thread.monitor.update"),
commandId: CommandId,
threadId: ThreadId,
generation: NonNegativeInt,
blockersSummary: Schema.String,
headSha: Schema.String,
wakeCount: NonNegativeInt,
@@ -656,6 +659,7 @@ const ThreadMonitorEndCommand = Schema.Struct({
type: Schema.Literal("thread.monitor.end"),
commandId: CommandId,
threadId: ThreadId,
generation: NonNegativeInt,
reason: Schema.Literals(["ready", "stopped", "terminal", "session-ended", "needs-attention"]),
blockersSummary: Schema.String,
endedAt: IsoDateTime,
@@ -667,6 +671,7 @@ const ThreadMonitorEndCommand = Schema.Struct({
// forge them, mirroring how ThreadUnsettleCommand only carries "user".
const ClientThreadMonitorEndCommand = Schema.Struct({
...ThreadMonitorEndCommand.fields,
generation: Schema.optional(NonNegativeInt),
reason: Schema.Literal("stopped"),
});
@@ -1065,6 +1070,7 @@ export const ThreadUnsnoozedPayload = Schema.Struct({
export const ThreadMonitorStartedPayload = Schema.Struct({
threadId: ThreadId,
generation: NonNegativeInt,
prNumber: NonNegativeInt,
blockersSummary: Schema.String,
headSha: Schema.String,
@@ -1074,6 +1080,7 @@ export const ThreadMonitorStartedPayload = Schema.Struct({
export const ThreadMonitorSnapshotUpdatedPayload = Schema.Struct({
threadId: ThreadId,
generation: NonNegativeInt,
blockersSummary: Schema.String,
headSha: Schema.String,
wakeCount: NonNegativeInt,
@@ -1082,6 +1089,7 @@ export const ThreadMonitorSnapshotUpdatedPayload = Schema.Struct({
export const ThreadMonitorEndedPayload = Schema.Struct({
threadId: ThreadId,
generation: NonNegativeInt,
reason: Schema.Literals(["ready", "stopped", "terminal", "session-ended", "needs-attention"]),
blockersSummary: Schema.String,
endedAt: IsoDateTime,