Skip to content
TypeScript

fix(threads): snoozed threads no longer wake early after background updates (#16517)

Rakshith Bhat69ba80dfae93
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index 34fc75a64d2..990ec2a6e86 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -664,6 +664,124 @@ it.effect("memory projection keeps restart-cancelled work through a stale run.up
restartCancelledWorkSurvivesStaleRunUpdate.pipe(Effect.provide(ProjectionStore.layerMemory)),
);
+const backgroundThreadUpdatesKeepTimestamp = Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const createdAt = DateTime.makeUnsafe("2026-10-06T14:00:00.000Z");
+ const threadId = ThreadId.make("thread:background-updates");
+ const thread = {
+ createdBy: "user" as const,
+ creationSource: "web" as const,
+ id: threadId,
+ projectId: ProjectId.make("project:background-updates"),
+ title: "Background updates",
+ providerInstanceId,
+ modelSelection,
+ runtimeMode: "full-access" as const,
+ interactionMode: "default" as const,
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt,
+ updatedAt: createdAt,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ };
+ yield* store.apply({
+ id: EventId.make("event:background-updates:created"),
+ type: "thread.created",
+ threadId,
+ occurredAt: createdAt,
+ payload: thread,
+ });
+ const readActivity = Effect.gen(function* () {
+ const projection = yield* store.getThreadProjection(threadId);
+ const thread = yield* store.getThread(threadId);
+ const shell = yield* store.getThreadShell(threadId);
+ const listed = (yield* store.getShellSnapshot()).threads.find((entry) => entry.id === threadId);
+ assert.deepEqual(projection.thread.updatedAt, createdAt);
+ assert.deepEqual(thread.updatedAt, createdAt);
+ assert.deepEqual(shell?.updatedAt, createdAt);
+ assert.deepEqual(listed?.updatedAt, createdAt);
+ return projection;
+ });
+ const link = {
+ host: "github.com",
+ repository: "owner/repository",
+ number: 42,
+ url: "https://github.com/owner/repository/pull/42",
+ source: "manual" as const,
+ linkedAt: DateTime.formatIso(createdAt),
+ snapshot: null,
+ stack: null,
+ };
+ yield* store.apply({
+ id: EventId.make("event:background-updates:pull-request-synced"),
+ type: "thread.pull-request-synced",
+ threadId,
+ occurredAt: DateTime.add(createdAt, { minutes: 45 }),
+ payload: { ...thread, pullRequests: [link] },
+ });
+ const synced = yield* readActivity;
+ assert.deepEqual(synced.updatedAt, createdAt);
+ assert.equal(synced.thread.pullRequests?.[0]?.number, 42);
+
+ const snapshot = {
+ state: "open" as const,
+ title: "Ship it",
+ headBranch: "feature",
+ baseBranch: "main",
+ isDraft: false,
+ updatedAt: DateTime.formatIso(DateTime.add(createdAt, { minutes: 46 })),
+ syncedAt: DateTime.formatIso(DateTime.add(createdAt, { minutes: 47 })),
+ closedAt: null,
+ mergedAt: null,
+ };
+ yield* store.apply({
+ id: EventId.make("event:background-updates:pull-request-link-updated"),
+ type: "thread.pull-request-link-updated",
+ threadId,
+ occurredAt: DateTime.add(createdAt, { minutes: 48 }),
+ payload: { ...link, snapshot },
+ });
+ const refreshed = yield* readActivity;
+ assert.deepEqual(refreshed.updatedAt, createdAt);
+ assert.deepEqual(refreshed.thread.pullRequests?.[0]?.snapshot, snapshot);
+
+ yield* store.apply({
+ id: EventId.make("event:background-updates:active-reordered"),
+ type: "thread.active-reordered",
+ threadId,
+ occurredAt: DateTime.add(createdAt, { minutes: 50 }),
+ payload: { ...refreshed.thread, activeOrderKey: "a" },
+ });
+ const reordered = yield* readActivity;
+ assert.deepEqual(reordered.updatedAt, createdAt);
+ assert.equal(reordered.thread.activeOrderKey, "a");
+
+ // An already-unpinned thread keeps its activity time even when replay's envelope advances.
+ yield* store.apply({
+ id: EventId.make("event:background-updates:already-unpinned"),
+ type: "thread.unpinned",
+ threadId,
+ occurredAt: DateTime.add(createdAt, { minutes: 55 }),
+ payload: { ...reordered.thread, pinnedAt: null, pinOrderKey: null },
+ });
+ yield* readActivity;
+});
+
+it.effect("memory projection keeps background thread updates out of updatedAt", () =>
+ backgroundThreadUpdatesKeepTimestamp.pipe(Effect.provide(ProjectionStore.layerMemory)),
+);
+
+it.effect("SQL projection keeps background thread updates out of updatedAt", () =>
+ backgroundThreadUpdatesKeepTimestamp.pipe(Effect.provide(layerTest)),
+);
+
it.effect("memory recovery selection ignores unfinished items from rolled-back runs", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index fedd86a4841..d04149f911c 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -734,7 +734,7 @@ export function applyToProjection(
switch (event.type) {
case "thread.pull-request-link-updated":
return {
- ...base,
+ ...projection,
thread: applyThreadPullRequestLinkUpdate(projection.thread, event.payload),
};
case "thread.created":
@@ -749,9 +749,7 @@ export function applyToProjection(
case "thread.pinned":
case "thread.unpinned":
case "thread.pin-reordered":
- case "thread.active-reordered":
case "thread.metadata-updated":
- case "thread.pull-request-synced":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
case "thread.model-selection-updated":
@@ -760,6 +758,14 @@ export function applyToProjection(
...base,
thread: event.payload,
};
+ // Reordering and PR refreshes preserve the orchestrator's activity timestamp.
+ case "thread.active-reordered":
+ case "thread.pull-request-synced":
+ return {
+ ...base,
+ thread: event.payload,
+ updatedAt: event.payload.updatedAt,
+ };
case "thread.visited":
case "thread.marked-unread":
return {
@@ -1568,7 +1574,7 @@ export function threadShellFromProjection(
itemCount: activeLocalTurnItems(projection).length,
visibleItemCount: projection.visibleTurnItems.length,
createdAt: projection.thread.createdAt,
- updatedAt: projection.updatedAt,
+ updatedAt: projection.thread.updatedAt,
archivedAt: projection.thread.archivedAt,
settledOverride: projection.thread.settledOverride,
settledAt: projection.thread.settledAt,
@@ -2705,9 +2711,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
event.type !== "thread.pinned" &&
event.type !== "thread.unpinned" &&
event.type !== "thread.pin-reordered" &&
+ event.type !== "thread.active-reordered" &&
event.type !== "thread.visited" &&
event.type !== "thread.marked-unread" &&
event.type !== "thread.metadata-updated" &&
+ event.type !== "thread.pull-request-synced" &&
+ event.type !== "thread.pull-request-link-updated" &&
event.type !== "thread.runtime-mode-updated" &&
event.type !== "thread.interaction-mode-updated" &&
event.type !== "thread.model-selection-updated" &&
diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts
index af89742160d..c7172c33000 100644
--- a/packages/client-runtime/src/state/threadSettled.ts
+++ b/packages/client-runtime/src/state/threadSettled.ts
@@ -81,12 +81,12 @@ export interface ThreadSnoozeShell extends QueuedThreadShell {
export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
if (shell.pendingSubagentRequest != null) return true;
- const runtime = shell.runtime ?? shell.session ?? null;
const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
+ const failedAt = failureEdgeAt(shell);
if (
- (runtime?.status === "error" || runtime?.status === "failed") &&
+ failedAt !== undefined &&
(shell.snoozedAt == null ||
- (runtime.updatedAt != null && Date.parse(runtime.updatedAt) > Date.parse(shell.snoozedAt)))
+ (failedAt != null && Date.parse(failedAt) > Date.parse(shell.snoozedAt)))
) {
return true;
}
@@ -101,6 +101,18 @@ export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean
return false;
}
+// V2 runtime.updatedAt includes metadata writes; prefer the failed run's completion.
+// Legacy sessions only expose the runtime timestamp.
+function failureEdgeAt(shell: ThreadSnoozeShell): string | null | undefined {
+ const runtime = shell.runtime ?? shell.session ?? null;
+ if (runtime?.status !== "error" && runtime?.status !== "failed") return undefined;
+ const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
+ if (latestRun?.status === "failed" && latestRun.completedAt != null) {
+ return latestRun.completedAt;
+ }
+ return runtime.updatedAt ?? null;
+}
+
export function canSnooze(
shell: Pick<
ThreadSnoozeShell,
@@ -145,7 +157,6 @@ export function threadWokeAt(
// than that visit's lastVisitedAt).
if (threadRaisedHandWhileSnoozed(shell)) {
const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
- const runtime = shell.runtime ?? shell.session ?? null;
if (
shell.snoozedAt != null &&
(latestRun?.state === "completed" || latestRun?.status === "completed") &&
@@ -154,6 +165,15 @@ export function threadWokeAt(
) {
return latestRun.completedAt;
}
+ // An old failure must not replace the activity time of an approval or input wake.
+ const failedAt = failureEdgeAt(shell);
+ if (
+ failedAt != null &&
+ (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt))
+ ) {
+ return failedAt;
+ }
+ const runtime = shell.runtime ?? shell.session ?? null;
return runtime?.updatedAt ?? shell.snoozedAt ?? null;
}
return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
diff --git a/packages/client-runtime/src/state/threadSnoozed.test.ts b/packages/client-runtime/src/state/threadSnoozed.test.ts
index ff3899ddb9f..d3b11c82a3f 100644
--- a/packages/client-runtime/src/state/threadSnoozed.test.ts
+++ b/packages/client-runtime/src/state/threadSnoozed.test.ts
@@ -119,6 +119,46 @@ describe("effectiveSnoozed", () => {
).toBe(true);
});
+ it.each([
+ {
+ reason: "stale failure",
+ completedAt: "2026-04-10T08:00:00.000Z",
+ pending: undefined,
+ wokeAt: null,
+ },
+ {
+ reason: "fresh failure",
+ completedAt: "2026-04-10T10:00:00.000Z",
+ pending: undefined,
+ wokeAt: "2026-04-10T10:00:00.000Z",
+ },
+ {
+ reason: "approval after a stale failure",
+ completedAt: "2026-04-10T08:00:00.000Z",
+ pending: "approval",
+ wokeAt: "2026-04-10T11:00:00.000Z",
+ },
+ {
+ reason: "input after a stale failure",
+ completedAt: "2026-04-10T08:00:00.000Z",
+ pending: "user-input",
+ wokeAt: "2026-04-10T11:00:00.000Z",
+ },
+ ] as const)(
+ "uses the wake event time for $reason despite newer metadata",
+ ({ completedAt, pending, wokeAt }) => {
+ const shell: ThreadSnoozeShell = {
+ ...makeShell({ snoozedUntil: FUTURE_WAKE }),
+ hasPendingApprovals: pending === "approval",
+ hasPendingUserInput: pending === "user-input",
+ runtime: { status: "failed", updatedAt: "2026-04-10T11:00:00.000Z" },
+ latestRun: { status: "failed", requestedAt: "2026-04-10T07:00:00.000Z", completedAt },
+ };
+ expect(effectiveSnoozed(shell, { now: NOW })).toBe(wokeAt === null);
+ expect(threadWokeAt(shell, { now: NOW })).toBe(wokeAt);
+ },
+ );
+
it("stays snoozed while the session keeps working — snooze never pauses the agent", () => {
expect(
effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "running" }), {