Address bot review feedback on review sweep

- macroscope: guard apply-title/apply-settle completions with the runId
  captured before the RPC so a Re-run mid-flight never stamps applied
  state onto the new run's cards; applyAll re-reads items from the
  store each step so mid-apply dismissals are respected, and bails out
  entirely when the run changes.
- cursor: the server's activity re-check now also treats a queued turn
  start (user message no session has adopted yet) as active, mirroring
  the decider's thread.settle guard; sweep candidate ordering uses
  NaN-safe toSortableTimestamp instead of raw Date.parse.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-23 19:33:45 -07:00
1 parent f8aa8450d1
commit 8aad08dc68
3 files changed
+110 -14

No files matched your search

@@ -369,4 +369,46 @@ describe("ReviewService", () => {
assert.strictEqual(result.settleReason, null);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("summarizeThread treats a queued turn start as active", () =>
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({});
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,
// A just-sent user message with no adopting turn: session still
// null, but the thread has in-flight work. it.effect runs on the
// TestClock (epoch 0), so "just sent" is the epoch.
shellOverrides: {
latestUserMessageAt: "1970-01-01T00:00:00.000Z",
latestTurn: null,
session: null,
},
generateThreadReview: () =>
Effect.succeed({
summary: "Looks finished.",
suggestedTitle: null,
recommendSettle: true,
settleReason: "Done.",
}),
}),
),
);
assert.strictEqual(reviewCalls[0]?.isActive, true);
assert.strictEqual(result.recommendSettle, false);
}).pipe(Effect.provide(NodeServices.layer)),
);
});
+38 -1
View File
@@ -39,6 +39,41 @@ export class ReviewService extends Context.Service<
}
>()("t3/review/ReviewService") {}
// 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;
/** A user message no turn has adopted yet is in-flight work even though the
session is still null. Mirrors the decider's settle guard and the
client's hasQueuedTurnStart: newest user message strictly newer than
every latestTurn timestamp, within the adoption grace window, and not
already surfaced as a failed session start. */
function hasQueuedTurnStart(
shell: {
readonly latestUserMessageAt: string | null;
readonly latestTurn: {
readonly requestedAt: string | null;
readonly startedAt: string | null;
readonly completedAt: string | null;
} | null;
readonly session: { readonly status: string } | null;
},
nowMs: number,
): boolean {
if (shell.latestUserMessageAt === null) return false;
if (shell.session?.status === "error") return false;
const messageAt = Date.parse(shell.latestUserMessageAt);
if (Number.isNaN(messageAt)) return false;
// Bounded on both sides: message timestamps originate on client devices,
// so a clock ahead of the server must not hold the queued state open.
if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
const turn = shell.latestTurn;
if (turn === null) return true;
return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
(candidate) => candidate === null || Date.parse(candidate) < messageAt,
);
}
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
@@ -162,12 +197,14 @@ export const make = Effect.gen(function* () {
.getThreadShellById(input.threadId)
.pipe(Effect.mapError(mapProjectionError));
const shell = Option.isSome(shellOption) ? shellOption.value : null;
const now = yield* DateTime.now;
const serverSideActive =
shell === null ||
shell.hasPendingApprovals ||
shell.hasPendingUserInput ||
shell.session?.status === "starting" ||
shell.session?.status === "running";
shell.session?.status === "running" ||
hasQueuedTurnStart(shell, DateTime.toEpochMillis(now));
const canSettleNow = input.canSettleNow && !serverSideActive;
const isActive = !canSettleNow;
+30 -13
View File
@@ -5,6 +5,7 @@ import {
effectiveSettled,
threadLastActivityAt,
} 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,
@@ -109,11 +110,11 @@ function collectSweepCandidates(): EnvironmentThreadShell[] {
}
// Most recently active first, so the SWEEP_MAX_THREADS cap drops the
// longest-idle threads rather than the oldest-created ones.
candidates.sort(
(a, b) =>
Date.parse(threadLastActivityAt(b) ?? b.createdAt) -
Date.parse(threadLastActivityAt(a) ?? a.createdAt),
);
const activityMs = (shell: EnvironmentThreadShell): number =>
toSortableTimestamp(threadLastActivityAt(shell) ?? undefined) ??
toSortableTimestamp(shell.createdAt) ??
0;
candidates.sort((a, b) => activityMs(b) - activityMs(a));
return candidates;
}
@@ -202,6 +203,7 @@ export function retrySweepItem(key: string): void {
export async function applySweepTitle(key: string): Promise<boolean> {
const store = useReviewSweepStore.getState();
const runId = store.runId;
const item = store.items[key];
const suggestedTitle = item?.result?.suggestedTitle;
if (!item || !suggestedTitle || item.titleApplied) return false;
@@ -225,14 +227,19 @@ export async function applySweepTitle(key: string): Promise<boolean> {
);
return false;
}
useReviewSweepStore
.getState()
.patchItem(key, { titleApplied: true, threadTitle: suggestedTitle });
// The rename itself succeeded either way, but a Re-run mid-flight replaces
// the item set with fresh reviews — don't stamp stale applied-state onto
// the new run's card.
const current = useReviewSweepStore.getState();
if (current.runId === runId) {
current.patchItem(key, { titleApplied: true, threadTitle: suggestedTitle });
}
return true;
}
export async function applySweepSettle(key: string): Promise<boolean> {
const store = useReviewSweepStore.getState();
const runId = store.runId;
const item = store.items[key];
if (!item || !item.result?.recommendSettle || item.settleApplied) return false;
// Re-check against the live shell: the thread may have gone active since
@@ -268,23 +275,33 @@ export async function applySweepSettle(key: string): Promise<boolean> {
);
return false;
}
useReviewSweepStore.getState().patchItem(key, { settleApplied: true });
// Same staleness guard as applySweepTitle: never patch a newer run's item.
const current = useReviewSweepStore.getState();
if (current.runId === runId) {
current.patchItem(key, { settleApplied: true });
}
return true;
}
/** Sequentially apply every un-dismissed recommendation: titles first, then
settles, tolerating per-item failures (each failure already toasts). */
settles, tolerating per-item failures (each failure already toasts).
Items are re-read from the store on every step so dismissals (and
re-runs) mid-apply are respected. */
export async function applyAllSweepRecommendations(): Promise<void> {
const { order, items } = useReviewSweepStore.getState();
const { order, runId } = useReviewSweepStore.getState();
for (const key of order) {
const item = items[key];
const current = useReviewSweepStore.getState();
if (current.runId !== runId) return;
const item = current.items[key];
if (!item || item.dismissed) continue;
if (item.result?.suggestedTitle && !item.titleApplied) {
await applySweepTitle(key);
}
}
for (const key of order) {
const item = useReviewSweepStore.getState().items[key];
const current = useReviewSweepStore.getState();
if (current.runId !== runId) return;
const item = current.items[key];
if (!item || item.dismissed) continue;
if (item.result?.recommendSettle && !item.settleApplied) {
await applySweepSettle(key);