@devries-cameron20 / t3code-1 / commits / e66c3168a4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(threads): allow snoozing pending input requests (#20058)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Alex Southwell committed Nov 5, 2026 at 18:50 UTC e66c3168a46743e97af7c48ca2da02a2fa9e6889
19 files changed +676 -71
apps/mobile/src/features/home/useThreadListActions.ts
+1 -3
@@ -308,9 +308,7 @@ export function useThreadListActions(): {
308 if (!canSnooze(thread, { now: new Date().toISOString() })) {
309 Dialog.alert(
310 "Could not snooze thread",
311 - thread.hasPendingApprovals ||
312 - thread.hasPendingUserInput ||
313 - thread.pendingSubagentRequest != null
311 + thread.hasPendingApprovals || thread.pendingSubagentRequest != null
312 ? "This thread is waiting on you. Respond to the pending request before snoozing it."
313 : "This thread is still starting a turn. Try again once it's running.",
314 );
apps/mobile/src/features/threads/threadListV2.test.ts
+55 -21
@@ -14,7 +14,7 @@ import {
14 type ThreadMoveAvailability,
15 } from "./threadOrder";
16 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
17 -import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
17 +import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
18 import {
19 CommandId,
20 EnvironmentId,
@@ -23,6 +23,7 @@ import {
23 ProjectId,
24 ProviderInstanceId,
25 RunId,
26 + RuntimeRequestId,
27 ThreadId,
28 } from "@t3tools/contracts";
29 import type { MenuAction } from "@react-native-menu/menu";
@@ -37,6 +38,7 @@ import {
38 getThreadListV2OrderedSection,
39 layoutThreadListV2RowMenuActions,
40 resolveThreadListV2SnoozeMenuSelection,
41 + resolveThreadListV2SwipeActions,
42 resolveThreadListV2SnoozePresets,
43 resolveThreadListV2Status,
44 resolveThreadListV2WokeAt,
@@ -209,32 +211,35 @@ describe("resolveThreadListV2Status", () => {
211 );
212 });
213
212 -describe("queued messages keep a settled thread active", () => {
213 - const threads = [
214 - makeThread({ id: ThreadId.make("active"), title: "Active" }),
215 - makeThread({ id: ThreadId.make("settled"), title: "Settled", settledOverride: "settled" }),
216 - makeThread({
217 - id: ThreadId.make("settled-queued"),
218 - title: "Settled with outbox",
219 - settledOverride: "settled",
220 - }),
221 - ];
222 - const queuedThreadKeys = new Set([`${environmentId}:settled-queued`]);
214 +describe("resolveThreadListV2SwipeActions", () => {
215 + it("offers snooze for a presented input request and moves it onto the snoozed shelf", () => {
216 + const raw = makeRawThreadShell({
217 + pendingRuntimeRequest: {
218 + id: RuntimeRequestId.make("question"),
219 + kind: "user_input",
220 + createdAt: DateTime.makeUnsafe(NOW),
221 + },
222 + });
223 + const thread = presentThreadShell(environmentId, raw);
224 + expect(thread.pendingUserInputAt).toBe(NOW);
225 + expect(
226 + resolveThreadListV2SwipeActions({
227 + variant: "card",
228 + settlementSupported: true,
229 + snoozeSupported: true,
230 + snoozable: canSnooze(thread, { now: NOW }),
231 + }).secondary,
232 + ).toBe("snooze");
233
224 - it("lists the thread in the active block instead of the settled shelf", () => {
234 const layout = buildThreadListV2Items({
226 - threads,
235 + threads: [{ ...thread, snoozedAt: NOW, snoozedUntil: "2026-06-03T00:00:00.000Z" }],
236 environmentId: null,
237 searchQuery: "",
238 now: NOW,
230 - queuedThreadKeys,
239 + snoozedShelfExpanded: true,
240 + snoozeEnvironmentIds: new Set([environmentId]),
241 });
232 - expect(layout.items.map((item) => [item.thread.id, item.variant] as const)).toEqual([
233 - ["active", "card"],
234 - ["settled-queued", "card"],
235 - ["settled", "slim"],
236 - ]);
237 - expect(layout.settledCount).toBe(1);
242 + expect(layout.snoozedCount).toBe(1);
243 });
244 });
245
@@ -1768,3 +1773,32 @@ describe("Working section beta", () => {
1773 ]);
1774 });
1775 });
1776 +
1777 +describe("queued messages keep a settled thread active", () => {
1778 + const threads = [
1779 + makeThread({ id: ThreadId.make("active"), title: "Active" }),
1780 + makeThread({ id: ThreadId.make("settled"), title: "Settled", settledOverride: "settled" }),
1781 + makeThread({
1782 + id: ThreadId.make("settled-queued"),
1783 + title: "Settled with outbox",
1784 + settledOverride: "settled",
1785 + }),
1786 + ];
1787 + const queuedThreadKeys = new Set([`${environmentId}:settled-queued`]);
1788 +
1789 + it("lists the thread in the active block instead of the settled shelf", () => {
1790 + const layout = buildThreadListV2Items({
1791 + threads,
1792 + environmentId: null,
1793 + searchQuery: "",
1794 + now: NOW,
1795 + queuedThreadKeys,
1796 + });
1797 + expect(layout.items.map((item) => [item.thread.id, item.variant] as const)).toEqual([
1798 + ["active", "card"],
1799 + ["settled-queued", "card"],
1800 + ["settled", "slim"],
1801 + ]);
1802 + expect(layout.settledCount).toBe(1);
1803 + });
1804 +});
apps/mobile/src/features/threads/threadListV2.ts
+1 -1
@@ -183,7 +183,7 @@ export function resolveThreadListV2SnoozeGateExpiryMs(
183 >,
184 options: { readonly now: string },
185 ): number | null {
186 - if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
186 + if (thread.hasPendingApprovals) return null;
187 if (thread.pendingSubagentRequest != null) return null;
188 if (!hasQueuedTurnStart(thread, options)) return null;
189 const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+96
@@ -559,6 +559,14 @@ it.effect(
559 assert.deepEqual(yield* outbox.listByCommandId(commandId), []);
560 }
561 }
562 + if (mode === "live") {
563 + yield* orchestrator.dispatch({
564 + type: "thread.snooze",
565 + commandId: CommandId.make("snooze-live-control"),
566 + threadId,
567 + snoozedUntil: "2099-07-25T09:00:00.000Z",
568 + });
569 + }
570 yield* orchestrator.dispatch(
571 mode === "live"
572 ? {
@@ -583,6 +591,8 @@ it.effect(
591 assert.equal(response.node?.status, mode === "live" ? "completed" : "cancelled");
592 assert.equal(response.item?.status, mode === "live" ? "completed" : "cancelled");
593 if (mode === "live") {
594 + assert.isNull((yield* projections.getThread(threadId)).snoozedUntil);
595 + assert.isNull((yield* projections.getThread(threadId)).snoozedAt);
596 assert.deepEqual(response.request?.answers, normalizedAnswers);
597 assert.equal(response.item?.type, "user_input_request");
598 if (response.item?.type === "user_input_request") {
@@ -1537,6 +1547,92 @@ it.effect("explicit settle clears snooze atomically and stays idempotent after r
1547 }).pipe(Effect.provide(layerTest)),
1548 );
1549
1550 +it.effect("keeps a snooze when a live question is cancelled or an approval is answered", () =>
1551 + Effect.gen(function* () {
1552 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1553 + const projections = yield* ProjectionStore.ProjectionStoreV2;
1554 + const outbox = yield* EffectOutbox.EffectOutboxV2;
1555 + const now = yield* DateTime.now;
1556 + for (const kind of ["user_input", "command"] as const) {
1557 + const threadId = ThreadId.make(`thread:snoozed-live-${kind}`);
1558 + const requestId = RuntimeRequestId.make(`request:snoozed-live-${kind}`);
1559 + const sessionId = ProviderSessionId.make(`session:snoozed-live-${kind}`);
1560 + yield* orchestrator.dispatch({
1561 + type: "thread.create",
1562 + commandId: CommandId.make(`create-snoozed-live-${kind}`),
1563 + threadId,
1564 + projectId: ProjectId.make("project:snoozed-live"),
1565 + title: "Deferred question",
1566 + modelSelection,
1567 + runtimeMode: "full-access",
1568 + interactionMode: "default",
1569 + branch: null,
1570 + worktreePath: null,
1571 + createdBy: "user",
1572 + creationSource: "web",
1573 + });
1574 + yield* orchestrator.dispatch({
1575 + type: "thread.snooze",
1576 + commandId: CommandId.make(`snooze-live-${kind}`),
1577 + threadId,
1578 + snoozedUntil: "2099-07-25T09:00:00.000Z",
1579 + });
1580 + const before = yield* projections.getThread(threadId);
1581 + yield* projections.apply({
1582 + id: EventId.make(`attach-snoozed-live-${kind}`),
1583 + type: "provider-session.attached",
1584 + threadId,
1585 + occurredAt: now,
1586 + payload: {
1587 + id: sessionId,
1588 + driver: adapter.driver,
1589 + providerInstanceId: instanceId,
1590 + status: "ready",
1591 + cwd: "/repo",
1592 + model: modelSelection.model,
1593 + capabilities: CodexProviderCapabilitiesV2,
1594 + createdAt: now,
1595 + updatedAt: now,
1596 + lastError: null,
1597 + },
1598 + });
1599 + yield* projections.apply({
1600 + id: EventId.make(`request-snoozed-live-${kind}`),
1601 + type: "runtime-request.updated",
1602 + threadId,
1603 + occurredAt: now,
1604 + payload: {
1605 + id: requestId,
1606 + nodeId: NodeId.make(`node:snoozed-live-${kind}`),
1607 + providerTurnId: null,
1608 + nativeRequestRef: null,
1609 + kind,
1610 + status: "pending",
1611 + responseCapability: { type: "live", providerSessionId: sessionId },
1612 + createdAt: now,
1613 + resolvedAt: null,
1614 + },
1615 + });
1616 + const commandId = CommandId.make(`respond-snoozed-live-${kind}`);
1617 + yield* orchestrator.dispatch({
1618 + type: "runtime-request.respond",
1619 + commandId,
1620 + threadId,
1621 + requestId,
1622 + decision: kind === "user_input" ? "cancel" : "accept",
1623 + });
1624 + const after = yield* projections.getThread(threadId);
1625 + assert.deepEqual(after.snoozedUntil, before.snoozedUntil);
1626 + assert.deepEqual(after.snoozedAt, before.snoozedAt);
1627 + assert.equal((yield* projections.getRuntimeRequest(threadId, requestId))?.status, "resolved");
1628 + assert.equal(
1629 + (yield* outbox.listByCommandId(commandId))[0]?.request.type,
1630 + "runtime-request.respond",
1631 + );
1632 + }
1633 + }).pipe(Effect.provide(layerTest)),
1634 +);
1635 +
1636 it.effect("dispatch records the command outcome and its duration", () =>
1637 Effect.gen(function* () {
1638 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/orchestration-v2/Orchestrator.ts
+48 -2
@@ -3526,11 +3526,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3526 cause: `Thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future.`,
3527 });
3528 }
3529 - if (projection.runtimeRequests.some((request) => request.status === "pending")) {
3529 + if (
3530 + projection.runtimeRequests.some(
3531 + (request) => request.status === "pending" && request.kind !== "user_input",
3532 + )
3533 + ) {
3534 return yield* new OrchestratorDispatchError({
3535 commandId: command.commandId,
3536 commandType: command.type,
3533 - cause: `Thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed.`,
3537 + cause: `Thread ${command.threadId} has a pending approval and cannot be snoozed.`,
3538 });
3539 }
3540 const queuedRuns = projection.runs.filter((run) => run.status === "queued");
@@ -8854,6 +8858,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8858 ...(command.delivery === undefined ? {} : { delivery: command.delivery }),
8859 secretStatus: command.secretStatus,
8860 };
8861 + if (
8862 + !unchanged &&
8863 + command.secretStatus === "saved" &&
8864 + projection.thread.snoozedUntil != null
8865 + ) {
8866 + yield* emit(
8867 + events,
8868 + command,
8869 + )({
8870 + type: "thread.unsnoozed",
8871 + threadId: command.threadId,
8872 + providerInstanceId: projection.thread.providerInstanceId,
8873 + occurredAt: now,
8874 + payload: { ...projection.thread, snoozedUntil: null, snoozedAt: null, updatedAt: now },
8875 + });
8876 + }
8877 yield* emit(
8878 events,
8879 command,
@@ -8980,6 +9000,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9000 updatedAt: now,
9001 type: "link_request",
9002 };
9003 + if (!unchanged && command.linkStatus === "linked" && projection.thread.snoozedUntil != null) {
9004 + yield* emit(
9005 + events,
9006 + command,
9007 + )({
9008 + type: "thread.unsnoozed",
9009 + threadId: command.threadId,
9010 + providerInstanceId: projection.thread.providerInstanceId,
9011 + occurredAt: now,
9012 + payload: { ...projection.thread, snoozedUntil: null, snoozedAt: null, updatedAt: now },
9013 + });
9014 + }
9015 yield* emit(
9016 events,
9017 command,
@@ -9401,6 +9433,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9433 return yield* recordSubagentFollowup(answer, events).pipe(mapDispatchError(answer));
9434 }
9435 if (providerSessionId === null) return;
9436 + if (runtimeRequest.kind === "user_input" && resolvedNodeStatus === "completed") {
9437 + const thread = yield* projectionStore
9438 + .getThread(command.threadId)
9439 + .pipe(mapDispatchError(command));
9440 + if (thread.snoozedUntil != null) {
9441 + yield* emitEvent({
9442 + type: "thread.unsnoozed",
9443 + threadId: command.threadId,
9444 + providerInstanceId: thread.providerInstanceId,
9445 + occurredAt: now,
9446 + payload: { ...thread, snoozedUntil: null, snoozedAt: null, updatedAt: now },
9447 + });
9448 + }
9449 + }
9450 yield* Ref.update(effects, (existing) => [
9451 ...existing,
9452 {
apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
+75 -1
@@ -5,6 +5,7 @@ import {
5 NodeId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2Run,
8 + type OrchestrationV2RuntimeRequest,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
@@ -20,7 +21,11 @@ import * as Layer from "effect/Layer";
21
22 import * as SqlitePersistence from "../persistence/Sqlite.ts";
23 import * as ProjectionStore from "./ProjectionStore.ts";
23 -import { isAutoSettlementCandidate, resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
24 +import {
25 + isAutoSettlementCandidate,
26 + isSnoozed,
27 + resolveAutoSettlementAt,
28 +} from "./ThreadSettlementService.ts";
29
30 const layerSql = ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
31 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
@@ -136,6 +141,75 @@ const createItem = Effect.fn(function* (
141 });
142 });
143
144 +it.effect.each([["sql", layerSql]] as const)(
145 + "%s: pending approvals wake a snoozed question even with older creation times",
146 + ([, testLayer]) =>
147 + Effect.gen(function* () {
148 + const store = yield* ProjectionStore.ProjectionStoreV2;
149 + const threadId = yield* createThread("snoozed-question-approval", {
150 + snoozedAt: now,
151 + snoozedUntil: DateTime.add(now, { days: 1 }),
152 + });
153 + const question: OrchestrationV2RuntimeRequest = {
154 + id: RuntimeRequestId.make("question"),
155 + nodeId: NodeId.make("node:question"),
156 + providerTurnId: null,
157 + nativeRequestRef: null,
158 + kind: "user_input",
159 + status: "pending",
160 + responseCapability: { type: "message" },
161 + createdAt: DateTime.subtract(now, { hours: 1 }),
162 + resolvedAt: null,
163 + };
164 + const approval: OrchestrationV2RuntimeRequest = {
165 + ...question,
166 + id: RuntimeRequestId.make("approval"),
167 + kind: "command",
168 + createdAt: old,
169 + };
170 + const newerApproval = {
171 + ...approval,
172 + id: RuntimeRequestId.make("newer-approval"),
173 + createdAt: DateTime.add(old, { hours: 1 }),
174 + };
175 + const setRequest = (request: OrchestrationV2RuntimeRequest) =>
176 + store.apply({
177 + id: EventId.make(`event:${request.id}:${request.status}`),
178 + type: "runtime-request.updated",
179 + threadId,
180 + occurredAt: now,
181 + payload: request,
182 + });
183 + const assertPending = (expected: RuntimeRequestId, snoozed: boolean) =>
184 + Effect.gen(function* () {
185 + const snapshot = yield* store.getShellSnapshot();
186 + const shell = snapshot.threads.find((thread) => thread.id === threadId)!;
187 + const projection = yield* store.getThreadProjection(threadId);
188 + for (const candidate of [shell, ProjectionStore.threadShellFromProjection(projection)]) {
189 + assert.equal(candidate.pendingRuntimeRequest?.id, expected);
190 + assert.equal(isSnoozed(candidate, DateTime.toEpochMillis(now)), snoozed);
191 + }
192 + });
193 + yield* setRequest({
194 + ...question,
195 + id: RuntimeRequestId.make("older-question"),
196 + createdAt: old,
197 + });
198 + yield* setRequest(question);
199 + yield* assertPending(question.id, true);
200 +
201 + // A request becoming pending can retain a creation time older than the snooze.
202 + yield* setRequest(approval);
203 + yield* assertPending(approval.id, false);
204 + yield* setRequest(newerApproval);
205 + yield* assertPending(newerApproval.id, false);
206 + yield* setRequest({ ...newerApproval, status: "resolved", resolvedAt: now });
207 + yield* assertPending(approval.id, false);
208 + yield* setRequest({ ...approval, status: "resolved", resolvedAt: now });
209 + yield* assertPending(question.id, true);
210 + }).pipe(Effect.provide(testLayer)),
211 +);
212 +
213 it.effect(
214 "sql: discovers settlement work with the same activity and background semantics as the shell",
215 () =>
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+40
@@ -6605,6 +6605,46 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
6605 },
6606 });
6607
6608 + for (const responseCapability of [
6609 + { type: "live", providerSessionId: ProviderSessionId.make("session:pending-secret") },
6610 + { type: "message" },
6611 + ] as const) {
6612 + for (const fresh of [true, false]) {
6613 + yield* projectionStore.apply({
6614 + id: EventId.make("event:" + suffix + ":fresh-" + fresh),
6615 + type: "runtime-request.updated",
6616 + threadId,
6617 + runId,
6618 + nodeId,
6619 + driver,
6620 + occurredAt: now,
6621 + payload: {
6622 + id: requestId,
6623 + nodeId,
6624 + providerTurnId: null,
6625 + nativeRequestRef: null,
6626 + kind: "user_input",
6627 + status: "pending",
6628 + responseCapability,
6629 + createdAt: fresh
6630 + ? DateTime.add(now, { seconds: 5 })
6631 + : DateTime.subtract(now, { seconds: 1 }),
6632 + resolvedAt: null,
6633 + },
6634 + });
6635 + for (const shell of [
6636 + (yield* projectionStore.getShellSnapshot()).threads.find(
6637 + (thread) => thread.id === threadId,
6638 + ),
6639 + ProjectionStore.threadShellFromProjection(
6640 + yield* projectionStore.getThreadProjection(threadId),
6641 + ),
6642 + ]) {
6643 + assert.equal(shell?.pendingRuntimeRequest?.id, fresh ? requestId : "secret:b");
6644 + }
6645 + }
6646 + }
6647 +
6648 for (const status of [
6649 "preparing",
6650 "starting",
apps/server/src/orchestration-v2/ProjectionStore.ts
+39 -23
@@ -1559,9 +1559,11 @@ export function threadShellFromProjection(
1559 .filter((request) => request.status === "pending")
1560 .toSorted(
1561 (left, right) =>
1562 + Number(left.kind === "user_input") - Number(right.kind === "user_input") ||
1563 DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
1564 )[0] ?? null,
1565 );
1566 +
1567 const userMessages = projection.messages
1568 .filter((message) => message.role === "user" && idleCompactionOf(message) === undefined)
1569 .toSorted(
@@ -1570,20 +1572,26 @@ export function threadShellFromProjection(
1572 );
1573 const latestUserAuthoredMessageAt =
1574 userMessages.find((message) => message.createdBy === "user")?.updatedAt ?? null;
1573 - if (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) {
1574 - pendingRuntimeRequest =
1575 - secretRequestAsPendingInput(
1576 - projection.turnItems
1577 - .filter(
1578 - (item) =>
1579 - item.status === "waiting" &&
1580 - waitsOnUser(item, liveRunIds, latestUserAuthoredMessageAt),
1581 - )
1582 - .toSorted(
1583 - (left, right) =>
1584 - DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
1585 - )[0] ?? null,
1586 - ) ?? pendingRuntimeRequest;
1575 + if (pendingRuntimeRequest === null || pendingRuntimeRequest.kind === "user_input") {
1576 + const waitingCard = secretRequestAsPendingInput(
1577 + projection.turnItems
1578 + .filter(
1579 + (item) =>
1580 + item.status === "waiting" && waitsOnUser(item, liveRunIds, latestUserAuthoredMessageAt),
1581 + )
1582 + .toSorted(
1583 + (left, right) =>
1584 + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
1585 + )[0] ?? null,
1586 + );
1587 + if (
1588 + waitingCard !== null &&
1589 + (pendingRuntimeRequest === null ||
1590 + DateTime.toEpochMillis(waitingCard.createdAt) >=
1591 + DateTime.toEpochMillis(pendingRuntimeRequest.createdAt))
1592 + ) {
1593 + pendingRuntimeRequest = waitingCard;
1594 + }
1595 }
1596 const latestUserMessage = userMessages[0] ?? null;
1597 const pendingBackgroundTasks = derivePendingBackgroundWork({
@@ -6230,7 +6238,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6238 FROM orchestration_v2_projection_runtime_requests request
6239 WHERE request.thread_id = t.thread_id
6240 AND request.status = 'pending'
6233 - ORDER BY request.created_at DESC, request.runtime_request_id DESC
6241 + ORDER BY (request.kind = 'user_input') ASC,
6242 + request.created_at DESC, request.runtime_request_id DESC
6243 LIMIT 1
6244 ) AS pending_request_payload_json,
6245 (
@@ -6760,16 +6769,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6769 )
6770 : null;
6771 if (
6763 - (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) &&
6772 + (pendingRuntimeRequest === null || pendingRuntimeRequest.kind === "user_input") &&
6773 waitingCards.length > 0
6774 ) {
6766 - pendingRuntimeRequest =
6767 - secretRequestAsPendingInput(
6768 - waitingCards.toSorted(
6769 - (left, right) =>
6770 - DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
6771 - )[0] ?? null,
6772 - ) ?? pendingRuntimeRequest;
6775 + const waitingCard = secretRequestAsPendingInput(
6776 + waitingCards.toSorted(
6777 + (left, right) =>
6778 + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
6779 + )[0] ?? null,
6780 + );
6781 + if (
6782 + waitingCard !== null &&
6783 + (pendingRuntimeRequest === null ||
6784 + DateTime.toEpochMillis(waitingCard.createdAt) >=
6785 + DateTime.toEpochMillis(pendingRuntimeRequest.createdAt))
6786 + ) {
6787 + pendingRuntimeRequest = waitingCard;
6788 + }
6789 }
6790 let terminalFailureItem =
6791 row.terminal_failure_payload_json === null
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+32
@@ -6,6 +6,7 @@ import {
6 ProjectId,
7 EventId,
8 ProviderInstanceId,
9 + RuntimeRequestId,
10 RunId,
11 ThreadId,
12 TurnItemId,
@@ -1587,6 +1588,37 @@ describe("ThreadSettlementServiceV2 terminals", () => {
1588
1589 describe("isSnoozed", () => {
1590 const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
1591 + it("defers existing input while new questions and approvals wake the thread", () => {
1592 + const request = {
1593 + id: RuntimeRequestId.make("question"),
1594 + kind: "user_input" as const,
1595 + createdAt: snoozed.snoozedAt,
1596 + };
1597 + expect(
1598 + ThreadSettlementService.isSnoozed(
1599 + shell({ ...snoozed, pendingRuntimeRequest: request }),
1600 + NOW_MS,
1601 + ),
1602 + ).toBe(true);
1603 + expect(
1604 + ThreadSettlementService.isSnoozed(
1605 + shell({ ...snoozed, pendingRuntimeRequest: { ...request, createdAt: at(-DAY_MS) } }),
1606 + NOW_MS,
1607 + ),
1608 + ).toBe(false);
1609 + expect(
1610 + ThreadSettlementService.isSnoozed(
1611 + shell({ ...snoozed, pendingRuntimeRequest: { ...request, kind: "command" } }),
1612 + NOW_MS,
1613 + ),
1614 + ).toBe(false);
1615 + expect(
1616 + ThreadSettlementService.isSnoozed(
1617 + shell({ ...snoozed, snoozedAt: null, pendingRuntimeRequest: request }),
1618 + NOW_MS,
1619 + ),
1620 + ).toBe(false);
1621 + });
1622 it("keeps a run requested and completed after snoozing parked until the timer", () => {
1623 const thread = shell({
1624 ...snoozed,
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+8 -1
@@ -174,10 +174,17 @@ export function isSnoozed(
174 ): boolean {
175 const snoozedUntilMs = toMillis(thread.snoozedUntil);
176 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
177 - if (thread.pendingRuntimeRequest !== null) return false;
177 // Same as the client: a waiting guest message wakes the thread, and the snooze stays stored.
178 if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
179 const snoozedAtMs = toMillis(thread.snoozedAt);
180 + if (
181 + thread.pendingRuntimeRequest !== null &&
182 + (thread.pendingRuntimeRequest.kind !== "user_input" ||
183 + snoozedAtMs === null ||
184 + DateTime.toEpochMillis(thread.pendingRuntimeRequest.createdAt) > snoozedAtMs)
185 + ) {
186 + return false;
187 + }
188 const completedAtMs = toMillis(thread.latestRunCompletedAt);
189 const wokeOnError =
190 thread.status === "failed" &&
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+46
@@ -1616,6 +1616,52 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
1616 type: "message",
1617 });
1618 const outbox = yield* EffectOutbox.EffectOutboxV2;
1619 + const now = yield* DateTime.now;
1620 + const beforeSnooze = yield* orchestrator.getThreadProjection(threadId);
1621 + const snooze = {
1622 + type: "thread.snooze" as const,
1623 + commandId: CommandId.make("runtime-async-question-snooze"),
1624 + threadId,
1625 + snoozedUntil: "2099-07-25T09:00:00.000Z",
1626 + };
1627 + yield* orchestrator.dispatch(snooze);
1628 + const snoozed = yield* orchestrator.getThreadProjection(threadId);
1629 + assert.isNotNull(snoozed.thread.snoozedUntil);
1630 + assert.deepEqual(snoozed.runtimeRequests, beforeSnooze.runtimeRequests);
1631 + assert.deepEqual(snoozed.turnItems, beforeSnooze.turnItems);
1632 + assert.deepEqual(snoozed.nodes, beforeSnooze.nodes);
1633 + assert.deepEqual(snoozed.runs, beforeSnooze.runs);
1634 +
1635 + // A question arriving after an earlier snooze must be acknowledged even
1636 + // when the user picks the same wake time again.
1637 + const priorSnooze = DateTime.makeUnsafe(DateTime.toEpochMillis(now) - 1_000);
1638 + yield* eventSink.write({
1639 + commandId: CommandId.make("runtime-async-question-earlier-snooze"),
1640 + events: [
1641 + {
1642 + id: EventId.make("runtime-async-question-earlier-snooze-event"),
1643 + type: "thread.snoozed",
1644 + threadId,
1645 + occurredAt: priorSnooze,
1646 + payload: { ...snoozed.thread, snoozedAt: priorSnooze },
1647 + },
1648 + ],
1649 + });
1650 + yield* orchestrator.dispatch({
1651 + ...snooze,
1652 + commandId: CommandId.make("runtime-async-question-resnooze"),
1653 + });
1654 + assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).thread.snoozedAt, now);
1655 + yield* orchestrator.dispatch({
1656 + type: "thread.unsnooze",
1657 + commandId: CommandId.make("runtime-async-question-wake"),
1658 + threadId,
1659 + reason: "user",
1660 + });
1661 + const awake = yield* orchestrator.getThreadProjection(threadId);
1662 + assert.isNull(awake.thread.snoozedUntil);
1663 + assert.deepEqual(awake.runtimeRequests, beforeSnooze.runtimeRequests);
1664 +
1665 const beforeInvalid = yield* orchestrator.getThreadProjection(threadId);
1666 const beforeSequence = yield* eventSink.latestSequence();
1667 for (const [index, answers] of [
apps/server/src/peer/PeerLinkRequests.test.ts
+35
@@ -482,6 +482,31 @@ it.live("the agent asks without waiting, and the user links the box after its tu
482 { kind: "user_input" },
483 );
484
485 + for (const secretStatus of ["pending", "saved"] as const) {
486 + yield* a.orchestrator.dispatch({
487 + type: "secret_request.record",
488 + commandId: CommandId.make("command:secret-" + secretStatus),
489 + threadId,
490 + runId,
491 + nodeId: rootNode,
492 + turnItemId: TurnItemId.make("turn-item:snoozed-secret"),
493 + label: "Credential",
494 + reason: "Connect",
495 + secretStatus,
496 + });
497 + if (secretStatus === "pending") {
498 + yield* a.orchestrator.dispatch({
499 + type: "thread.snooze",
500 + commandId: CommandId.make("command:snooze-secret"),
501 + threadId,
502 + snoozedUntil: "2099-01-01T00:00:00.000Z",
503 + });
504 + expect((yield* a.projections.getThread(threadId)).snoozedUntil).not.toBeNull();
505 + } else {
506 + expect((yield* a.projections.getThread(threadId)).snoozedUntil).toBeNull();
507 + }
508 + }
509 +
510 // The agent ends its turn; the card stays answerable, and the thread still asks.
511 yield* endRun(a);
512 expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
@@ -533,6 +558,14 @@ it.live("the agent asks without waiting, and the user links the box after its tu
558 ).toEqual([threadId]);
559 expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
560
561 + yield* a.orchestrator.dispatch({
562 + type: "thread.snooze",
563 + commandId: CommandId.make("command:snooze-link"),
564 + threadId,
565 + snoozedUntil: "2099-01-01T00:00:00.000Z",
566 + });
567 + expect((yield* a.projections.getThread(threadId)).snoozedUntil).not.toBeNull();
568 +
569 // The user's client mints a code on the box and picks more than the agent suggested.
570 const pairing = yield* b.auth.issuePairingCredential();
571 yield* a.requests.answer({
@@ -541,6 +574,8 @@ it.live("the agent asks without waiting, and the user links the box after its tu
574 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
575 });
576
577 + expect((yield* a.projections.getThread(threadId)).snoozedUntil).toBeNull();
578 +
579 const link = yield* a.links.get(box.environmentId);
580 expect(Option.getOrUndefined(link)?.access).toBe("auto");
581 expect(yield* cardOf(a)).toMatchObject({
docs/user/thread-sidebar.md
+4 -2
@@ -326,6 +326,8 @@ Choose **Snooze → Custom…** from a thread's menu to pick a date and time in
326 local time zone, or a duration in minutes, hours, or days. Durations start when
327 you confirm; one day means 24 hours. On web and desktop, you can also snooze
328 several selected threads together. Choose **Wake thread** to bring a thread back early.
329 +
330 A snoozed thread keeps working and stays hidden until its wake time, even while
330 -its agent wakes itself for background work. It comes back early only when it needs
331 -an approval or answer from you, when a run fails, or when you send it a message.
331 +its agent wakes itself for background work. It comes back early for an approval,
332 +a new question, a failed run, or a message or answer you send. You can snooze an existing
333 +question and answer when the thread wakes; the question stays unanswered.
packages/client-runtime/src/state/entities.test.ts
+12 -2
@@ -22,7 +22,7 @@ import { canSnooze, effectiveSnoozed } from "./threadSettled.ts";
22 const environmentId = EnvironmentId.make("environment-v2");
23
24 describe("V2 client presentation", () => {
25 - it("an async question blocks snooze and wakes a snoozed thread", () => {
25 + it("an async question allows snooze and wakes an older snooze", () => {
26 const runId = RunId.make("run-async-question");
27 const running = {
28 ...v2ThreadShell,
@@ -39,7 +39,17 @@ describe("V2 client presentation", () => {
39 },
40 };
41 const active = presentThreadShell(environmentId, running);
42 - expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
42 + expect(active.hasPendingUserInput).toBe(true);
43 + expect(isThreadWorking(active)).toBe(false);
44 + expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(true);
45 +
46 + const completed = presentThreadShell(environmentId, {
47 + ...running,
48 + activeRunId: null,
49 + status: "completed",
50 + });
51 + expect(completed.hasPendingUserInput).toBe(true);
52 + expect(isThreadWorking(completed)).toBe(false);
53 expect(effectiveSnoozed(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
54 });
55
packages/client-runtime/src/state/models.ts
+5
@@ -158,6 +158,7 @@ export interface EnvironmentThreadShell {
158 readonly latestUserAuthoredMessageAt?: string | null;
159 readonly hasPendingApprovals: boolean;
160 readonly hasPendingUserInput: boolean;
161 + readonly pendingUserInputAt?: string | null;
162 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
163 /** Guest messages waiting for the owner to send or dismiss. */
164 readonly pendingGuestMessageCount?: number;
@@ -312,6 +313,10 @@ export function presentThreadShell(
313 thread.pendingRuntimeRequest.kind !== "auth_refresh",
314 // Async questions count too, so a thread with any open question leaves Working.
315 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
316 + pendingUserInputAt:
317 + thread.pendingRuntimeRequest?.kind === "user_input"
318 + ? iso(thread.pendingRuntimeRequest.createdAt)
319 + : null,
320 pendingSubagentRequest,
321 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
322 hasActionableProposedPlan: thread.hasActionableProposedPlan,
packages/client-runtime/src/state/threadCommands.test.ts
+40 -2
@@ -498,14 +498,52 @@ describe("remote thread lifecycle commands", () => {
498 input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
499 });
500 const request = yield* Queue.take(h.requests);
501 - expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
501 + if (action === "settle") {
502 + expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
503 + } else {
504 + expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
505 + snoozedUntil: FUTURE,
506 + pendingRuntimeRequest: USER_INPUT,
507 + });
508 + }
509 yield* Deferred.succeed(request.reply, { sequence: 2 });
510 expect((yield* Effect.promise(() => result))._tag).toBe("Success");
511 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
512 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
513 );
507 - expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
514 + expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toEqual(
515 + action === "settle" ? null : USER_INPUT,
516 + );
517 expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
518 }),
519 );
520 + it.effect("acknowledges a new question when snoozing again to the same wake time", () =>
521 + Effect.gen(function* () {
522 + const h = yield* makeHarness();
523 + const initial = {
524 + ...SNAPSHOT,
525 + threads: [
526 + {
527 + ...SNAPSHOT.threads[0]!,
528 + pendingRuntimeRequest: USER_INPUT,
529 + snoozedAt: DateTime.makeUnsafe("2026-09-12T09:00:00.000Z"),
530 + snoozedUntil: FUTURE,
531 + },
532 + ],
533 + };
534 + h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), initial);
535 + const result = h.commands.snooze.run(h.registry, {
536 + environmentId: ENVIRONMENT_ID,
537 + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
538 + });
539 + const request = yield* Queue.take(h.requests);
540 + const snoozed = h.registry.get(h.visibleAtom)?.threads[0];
541 + expect(DateTime.toEpochMillis(snoozed!.snoozedAt!)).toBeGreaterThanOrEqual(
542 + DateTime.toEpochMillis(USER_INPUT.createdAt),
543 + );
544 + expect(snoozed?.pendingRuntimeRequest).toEqual(USER_INPUT);
545 + yield* Deferred.succeed(request.reply, { sequence: 2 });
546 + expect((yield* Effect.promise(() => result))._tag).toBe("Success");
547 + }),
548 + );
549 });
packages/client-runtime/src/state/threadCommands.ts
+2 -2
@@ -404,13 +404,13 @@ export function createThreadEnvironmentAtoms<R, E>(
404 })),
405 snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
406 (!accepted &&
407 - (thread.pendingRuntimeRequest !== null ||
407 + ((thread.pendingRuntimeRequest !== null &&
408 + thread.pendingRuntimeRequest.kind !== "user_input") ||
409 ["preparing", "queued", "starting"].includes(thread.status))) ||
410 !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))
411 ? thread
412 : {
413 ...thread,
413 - pendingRuntimeRequest: null,
414 snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil),
415 snoozedAt: now,
416 },
packages/client-runtime/src/state/threadSettled.ts
+34 -9
@@ -74,18 +74,38 @@ export interface ThreadSnoozeShell extends QueuedThreadShell {
74 readonly snoozedAt?: string | null;
75 readonly hasPendingApprovals: boolean;
76 readonly hasPendingUserInput: boolean;
77 + readonly pendingUserInputAt?: string | null;
78 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
79 readonly pendingGuestMessageCount?: number;
80 }
81
82 +function pendingQuestionAt(shell: ThreadSnoozeShell): string | null {
83 + const request = shell.source?.pendingRuntimeRequest;
84 + return (
85 + shell.pendingUserInputAt ??
86 + (request?.kind === "user_input" ? DateTime.formatIso(request.createdAt) : null)
87 + );
88 +}
89 +
90 /**
91 * Only a request for the user or a fresh failure ends a snooze early. Completed runs never do:
92 * a snoozed long-running thread keeps waking itself for background work and stays hidden
93 * until its timer.
94 */
95 export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
87 - if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
88 - if (shell.source?.pendingRuntimeRequest != null) return true;
96 + const request = shell.source?.pendingRuntimeRequest;
97 + if (shell.hasPendingApprovals || (request != null && request.kind !== "user_input")) return true;
98 + const questionAt = pendingQuestionAt(shell);
99 + // Snoozing an existing question means "ask me later". Only a new question
100 + // wakes it early; missing or invalid timestamps keep the request visible.
101 + if (
102 + (shell.hasPendingUserInput || request?.kind === "user_input") &&
103 + (shell.snoozedAt == null ||
104 + questionAt == null ||
105 + !(Date.parse(questionAt) <= Date.parse(shell.snoozedAt)))
106 + ) {
107 + return true;
108 + }
109 if (shell.pendingSubagentRequest != null) return true;
110 if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
111 const failedAt = failureEdgeAt(shell);
@@ -124,9 +144,9 @@ export function canSnooze(
144 >,
145 options: { readonly now: string },
146 ): boolean {
127 - if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
128 - // The server rejects snoozing for any pending request.
129 - if (shell.source?.pendingRuntimeRequest != null) return false;
147 + if (shell.hasPendingApprovals) return false;
148 + const request = shell.source?.pendingRuntimeRequest;
149 + if (request != null && request.kind !== "user_input") return false;
150 if (shell.pendingSubagentRequest != null) return false;
151 // A waiting guest message would wake it at once.
152 if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
@@ -157,14 +177,19 @@ export function threadWokeAt(
177 // indicator the user already cleared by visiting (snoozedUntil is newer
178 // than that visit's lastVisitedAt).
179 if (threadRaisedHandWhileSnoozed(shell)) {
160 - // An old failure must not replace the activity time of an approval or input wake.
180 const failedAt = failureEdgeAt(shell);
162 - if (
181 + const questionAt = pendingQuestionAt(shell);
182 + const freshFailure =
183 failedAt != null &&
164 - (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt))
165 - ) {
184 + (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt));
185 + const freshQuestion =
186 + questionAt != null &&
187 + shell.snoozedAt != null &&
188 + Date.parse(questionAt) > Date.parse(shell.snoozedAt);
189 + if (freshFailure && (!freshQuestion || Date.parse(failedAt) >= Date.parse(questionAt))) {
190 return failedAt;
191 }
192 + if (freshQuestion) return questionAt;
193 const runtime = shell.runtime ?? shell.session ?? null;
194 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
195 }
packages/client-runtime/src/state/threadSnoozed.test.ts
+103 -2
@@ -1,4 +1,6 @@
1 // @effect-diagnostics globalDate:off -- Tests exercise local calendar snooze boundaries.
2 +import * as DateTime from "effect/DateTime";
3 +import { RuntimeRequestId } from "@t3tools/contracts";
4 import { ThreadId } from "@t3tools/contracts";
5 import { TurnId } from "@t3tools/contracts";
6 import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
@@ -30,6 +32,7 @@ function makeShell(input: {
32 readonly snoozedAt?: string | null;
33 readonly sessionStatus?: "starting" | "running" | "ready" | "error";
34 readonly pending?: "approval" | "user-input";
35 + readonly pendingUserInputAt?: string | null;
36 readonly turnRequestedAt?: string | null;
37 readonly turnCompletedAt?: string | null;
38 }): ThreadSnoozeShell {
@@ -39,6 +42,7 @@ function makeShell(input: {
42 snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
43 hasPendingApprovals: input.pending === "approval",
44 hasPendingUserInput: input.pending === "user-input",
45 + pendingUserInputAt: input.pendingUserInputAt ?? null,
46 session:
47 input.sessionStatus === undefined
48 ? null
@@ -89,6 +93,64 @@ describe("effectiveSnoozed", () => {
93 ).toBe(false);
94 });
95
96 + it("defers an existing question until the timer, but wakes for a new question", () => {
97 + const shell = makeShell({
98 + snoozedUntil: FUTURE_WAKE,
99 + pending: "user-input",
100 + pendingUserInputAt: SNOOZED_AT,
101 + });
102 + expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
103 + expect(threadWokeAt(shell, { now: NOW })).toBeNull();
104 + expect(effectiveSnoozed(shell, { now: FUTURE_WAKE })).toBe(false);
105 + expect(threadWokeAt(shell, { now: FUTURE_WAKE })).toBe(FUTURE_WAKE);
106 +
107 + const newQuestion = { ...shell, pendingUserInputAt: "2026-04-10T10:00:00.000Z" };
108 + expect(effectiveSnoozed(newQuestion, { now: NOW })).toBe(false);
109 + expect(threadWokeAt(newQuestion, { now: NOW })).toBe(newQuestion.pendingUserInputAt);
110 + expect(effectiveSnoozed({ ...shell, pendingUserInputAt: "invalid" }, { now: NOW })).toBe(false);
111 + });
112 +
113 + it.each([false, true])(
114 + "snoozes existing source questions with blocking=%s and wakes for newer ones",
115 + (blocking) => {
116 + const shell: ThreadSnoozeShell = {
117 + ...makeShell({ snoozedUntil: FUTURE_WAKE }),
118 + source: {
119 + pendingRuntimeRequest: {
120 + id: RuntimeRequestId.make("question"),
121 + kind: "user_input",
122 + blocking,
123 + createdAt: DateTime.makeUnsafe(SNOOZED_AT),
124 + },
125 + },
126 + };
127 + expect(canSnooze(shell, { now: NOW })).toBe(true);
128 + expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
129 + const newQuestion = {
130 + ...shell,
131 + source: {
132 + pendingRuntimeRequest: {
133 + ...shell.source!.pendingRuntimeRequest!,
134 + createdAt: DateTime.makeUnsafe("2026-04-10T10:00:00.000Z"),
135 + },
136 + },
137 + };
138 + expect(effectiveSnoozed(newQuestion, { now: NOW })).toBe(false);
139 + expect(threadWokeAt(newQuestion, { now: NOW })).toBe("2026-04-10T10:00:00.000Z");
140 + const approval = {
141 + ...shell,
142 + source: {
143 + pendingRuntimeRequest: {
144 + ...shell.source!.pendingRuntimeRequest!,
145 + kind: "command" as const,
146 + },
147 + },
148 + };
149 + expect(canSnooze(approval, { now: NOW })).toBe(false);
150 + expect(effectiveSnoozed(approval, { now: NOW })).toBe(false);
151 + },
152 + );
153 +
154 it.each([
155 {
156 reason: "stale failure",
@@ -182,7 +244,7 @@ describe("threadRaisedHandWhileSnoozed", () => {
244 });
245
246 describe("canSnooze", () => {
185 - it("refuses blocked-on-you work", () => {
247 + it("allows deferring user input while refusing approvals and subagent requests", () => {
248 expect(
249 canSnooze({ ...makeShell({ pending: "approval" }), latestUserMessageAt: null }, { now: NOW }),
250 ).toBe(false);
@@ -191,7 +253,7 @@ describe("canSnooze", () => {
253 { ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
254 { now: NOW },
255 ),
194 - ).toBe(false);
256 + ).toBe(true);
257 expect(
258 canSnooze(
259 { ...makeShell({}), latestUserMessageAt: null, pendingSubagentRequest: "approval" },
@@ -272,6 +334,45 @@ describe("threadWokeAt", () => {
334 expect(threadWokeAt(shell, { now: NOW })).toBe("2026-04-10T11:00:00.000Z");
335 });
336
337 + it.each(["failure", "subagent request"] as const)(
338 + "keeps an old question from masking a newer %s wake",
339 + (wake) => {
340 + const shell = {
341 + ...makeShell({
342 + snoozedUntil: FUTURE_WAKE,
343 + pending: "user-input",
344 + pendingUserInputAt: SNOOZED_AT,
345 + sessionStatus: wake === "failure" ? "error" : "running",
346 + }),
347 + pendingSubagentRequest: wake === "subagent request" ? ("user_input" as const) : null,
348 + };
349 + const lastVisitedAt = "2026-04-10T10:00:00.000Z";
350 + expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
351 + const wokeAt = threadWokeAt(shell, { now: NOW });
352 + expect(wokeAt).toBe("2026-04-10T11:00:00.000Z");
353 + expect(Date.parse(wokeAt!)).toBeGreaterThan(Date.parse(lastVisitedAt));
354 + },
355 + );
356 +
357 + it.each([
358 + ["error", "2026-04-10T10:00:00.000Z", "2026-04-10T11:00:00.000Z"],
359 + ["failed", "2026-04-10T10:00:00.000Z", "2026-04-10T11:00:00.000Z"],
360 + ["failed", "2026-04-10T11:30:00.000Z", "2026-04-10T11:30:00.000Z"],
361 + ["running", "2026-04-10T10:00:00.000Z", "2026-04-10T10:00:00.000Z"],
362 + ] as const)(
363 + "uses the latest wake event for a %s runtime and a question at %s",
364 + (status, pendingUserInputAt, expectedWakeAt) => {
365 + const shell = {
366 + ...makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input", pendingUserInputAt }),
367 + runtime: { status, updatedAt: "2026-04-10T11:00:00.000Z" },
368 + };
369 + const lastVisitedAt = "2026-04-10T10:30:00.000Z";
370 + const wokeAt = threadWokeAt(shell, { now: NOW });
371 + expect(wokeAt).toBe(expectedWakeAt);
372 + expect(Date.parse(wokeAt!) > Date.parse(lastVisitedAt)).toBe(status !== "running");
373 + },
374 + );
375 +
376 it("keeps the early wake authoritative after the scheduled time passes", () => {
377 const shell: ThreadSnoozeShell = {
378 ...makeShell({ snoozedUntil: PAST_WAKE }),