Skip to content
TypeScript

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

Alex Southwelle66c3168a467
diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts
index 248c4369053..3893569c688 100644
--- a/apps/mobile/src/features/home/useThreadListActions.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.ts
@@ -308,9 +308,7 @@ export function useThreadListActions(): {
if (!canSnooze(thread, { now: new Date().toISOString() })) {
Dialog.alert(
"Could not snooze thread",
- thread.hasPendingApprovals ||
- thread.hasPendingUserInput ||
- thread.pendingSubagentRequest != null
+ thread.hasPendingApprovals || thread.pendingSubagentRequest != null
? "This thread is waiting on you. Respond to the pending request before snoozing it."
: "This thread is still starting a turn. Try again once it's running.",
);
diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts
index 7ffd500a1f8..a88f0ddc10a 100644
--- a/apps/mobile/src/features/threads/threadListV2.test.ts
+++ b/apps/mobile/src/features/threads/threadListV2.test.ts
@@ -14,7 +14,7 @@ import {
type ThreadMoveAvailability,
} from "./threadOrder";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
-import { resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
+import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import {
CommandId,
EnvironmentId,
@@ -23,6 +23,7 @@ import {
ProjectId,
ProviderInstanceId,
RunId,
+ RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
@@ -37,6 +38,7 @@ import {
getThreadListV2OrderedSection,
layoutThreadListV2RowMenuActions,
resolveThreadListV2SnoozeMenuSelection,
+ resolveThreadListV2SwipeActions,
resolveThreadListV2SnoozePresets,
resolveThreadListV2Status,
resolveThreadListV2WokeAt,
@@ -209,32 +211,35 @@ describe("resolveThreadListV2Status", () => {
);
});
-describe("queued messages keep a settled thread active", () => {
- const threads = [
- makeThread({ id: ThreadId.make("active"), title: "Active" }),
- makeThread({ id: ThreadId.make("settled"), title: "Settled", settledOverride: "settled" }),
- makeThread({
- id: ThreadId.make("settled-queued"),
- title: "Settled with outbox",
- settledOverride: "settled",
- }),
- ];
- const queuedThreadKeys = new Set([`${environmentId}:settled-queued`]);
+describe("resolveThreadListV2SwipeActions", () => {
+ it("offers snooze for a presented input request and moves it onto the snoozed shelf", () => {
+ const raw = makeRawThreadShell({
+ pendingRuntimeRequest: {
+ id: RuntimeRequestId.make("question"),
+ kind: "user_input",
+ createdAt: DateTime.makeUnsafe(NOW),
+ },
+ });
+ const thread = presentThreadShell(environmentId, raw);
+ expect(thread.pendingUserInputAt).toBe(NOW);
+ expect(
+ resolveThreadListV2SwipeActions({
+ variant: "card",
+ settlementSupported: true,
+ snoozeSupported: true,
+ snoozable: canSnooze(thread, { now: NOW }),
+ }).secondary,
+ ).toBe("snooze");
- it("lists the thread in the active block instead of the settled shelf", () => {
const layout = buildThreadListV2Items({
- threads,
+ threads: [{ ...thread, snoozedAt: NOW, snoozedUntil: "2026-06-03T00:00:00.000Z" }],
environmentId: null,
searchQuery: "",
now: NOW,
- queuedThreadKeys,
+ snoozedShelfExpanded: true,
+ snoozeEnvironmentIds: new Set([environmentId]),
});
- expect(layout.items.map((item) => [item.thread.id, item.variant] as const)).toEqual([
- ["active", "card"],
- ["settled-queued", "card"],
- ["settled", "slim"],
- ]);
- expect(layout.settledCount).toBe(1);
+ expect(layout.snoozedCount).toBe(1);
});
});
@@ -1768,3 +1773,32 @@ describe("Working section beta", () => {
]);
});
});
+
+describe("queued messages keep a settled thread active", () => {
+ const threads = [
+ makeThread({ id: ThreadId.make("active"), title: "Active" }),
+ makeThread({ id: ThreadId.make("settled"), title: "Settled", settledOverride: "settled" }),
+ makeThread({
+ id: ThreadId.make("settled-queued"),
+ title: "Settled with outbox",
+ settledOverride: "settled",
+ }),
+ ];
+ const queuedThreadKeys = new Set([`${environmentId}:settled-queued`]);
+
+ it("lists the thread in the active block instead of the settled shelf", () => {
+ const layout = buildThreadListV2Items({
+ threads,
+ environmentId: null,
+ searchQuery: "",
+ now: NOW,
+ queuedThreadKeys,
+ });
+ expect(layout.items.map((item) => [item.thread.id, item.variant] as const)).toEqual([
+ ["active", "card"],
+ ["settled-queued", "card"],
+ ["settled", "slim"],
+ ]);
+ expect(layout.settledCount).toBe(1);
+ });
+});
diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts
index 9c91aa7d825..1b79c9a15d6 100644
--- a/apps/mobile/src/features/threads/threadListV2.ts
+++ b/apps/mobile/src/features/threads/threadListV2.ts
@@ -183,7 +183,7 @@ export function resolveThreadListV2SnoozeGateExpiryMs(
>,
options: { readonly now: string },
): number | null {
- if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null;
+ if (thread.hasPendingApprovals) return null;
if (thread.pendingSubagentRequest != null) return null;
if (!hasQueuedTurnStart(thread, options)) return null;
const messageAtMs = Date.parse(thread.latestUserMessageAt ?? "");
diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
index c8067947327..6544fafdacb 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
@@ -559,6 +559,14 @@ it.effect(
assert.deepEqual(yield* outbox.listByCommandId(commandId), []);
}
}
+ if (mode === "live") {
+ yield* orchestrator.dispatch({
+ type: "thread.snooze",
+ commandId: CommandId.make("snooze-live-control"),
+ threadId,
+ snoozedUntil: "2099-07-25T09:00:00.000Z",
+ });
+ }
yield* orchestrator.dispatch(
mode === "live"
? {
@@ -583,6 +591,8 @@ it.effect(
assert.equal(response.node?.status, mode === "live" ? "completed" : "cancelled");
assert.equal(response.item?.status, mode === "live" ? "completed" : "cancelled");
if (mode === "live") {
+ assert.isNull((yield* projections.getThread(threadId)).snoozedUntil);
+ assert.isNull((yield* projections.getThread(threadId)).snoozedAt);
assert.deepEqual(response.request?.answers, normalizedAnswers);
assert.equal(response.item?.type, "user_input_request");
if (response.item?.type === "user_input_request") {
@@ -1537,6 +1547,92 @@ it.effect("explicit settle clears snooze atomically and stays idempotent after r
}).pipe(Effect.provide(layerTest)),
);
+it.effect("keeps a snooze when a live question is cancelled or an approval is answered", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const now = yield* DateTime.now;
+ for (const kind of ["user_input", "command"] as const) {
+ const threadId = ThreadId.make(`thread:snoozed-live-${kind}`);
+ const requestId = RuntimeRequestId.make(`request:snoozed-live-${kind}`);
+ const sessionId = ProviderSessionId.make(`session:snoozed-live-${kind}`);
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make(`create-snoozed-live-${kind}`),
+ threadId,
+ projectId: ProjectId.make("project:snoozed-live"),
+ title: "Deferred question",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.snooze",
+ commandId: CommandId.make(`snooze-live-${kind}`),
+ threadId,
+ snoozedUntil: "2099-07-25T09:00:00.000Z",
+ });
+ const before = yield* projections.getThread(threadId);
+ yield* projections.apply({
+ id: EventId.make(`attach-snoozed-live-${kind}`),
+ type: "provider-session.attached",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: sessionId,
+ driver: adapter.driver,
+ providerInstanceId: instanceId,
+ status: "ready",
+ cwd: "/repo",
+ model: modelSelection.model,
+ capabilities: CodexProviderCapabilitiesV2,
+ createdAt: now,
+ updatedAt: now,
+ lastError: null,
+ },
+ });
+ yield* projections.apply({
+ id: EventId.make(`request-snoozed-live-${kind}`),
+ type: "runtime-request.updated",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: requestId,
+ nodeId: NodeId.make(`node:snoozed-live-${kind}`),
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind,
+ status: "pending",
+ responseCapability: { type: "live", providerSessionId: sessionId },
+ createdAt: now,
+ resolvedAt: null,
+ },
+ });
+ const commandId = CommandId.make(`respond-snoozed-live-${kind}`);
+ yield* orchestrator.dispatch({
+ type: "runtime-request.respond",
+ commandId,
+ threadId,
+ requestId,
+ decision: kind === "user_input" ? "cancel" : "accept",
+ });
+ const after = yield* projections.getThread(threadId);
+ assert.deepEqual(after.snoozedUntil, before.snoozedUntil);
+ assert.deepEqual(after.snoozedAt, before.snoozedAt);
+ assert.equal((yield* projections.getRuntimeRequest(threadId, requestId))?.status, "resolved");
+ assert.equal(
+ (yield* outbox.listByCommandId(commandId))[0]?.request.type,
+ "runtime-request.respond",
+ );
+ }
+ }).pipe(Effect.provide(layerTest)),
+);
+
it.effect("dispatch records the command outcome and its duration", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index a6b876db1de..daf64a2d438 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -3526,11 +3526,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `Thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future.`,
});
}
- if (projection.runtimeRequests.some((request) => request.status === "pending")) {
+ if (
+ projection.runtimeRequests.some(
+ (request) => request.status === "pending" && request.kind !== "user_input",
+ )
+ ) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: `Thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed.`,
+ cause: `Thread ${command.threadId} has a pending approval and cannot be snoozed.`,
});
}
const queuedRuns = projection.runs.filter((run) => run.status === "queued");
@@ -8854,6 +8858,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(command.delivery === undefined ? {} : { delivery: command.delivery }),
secretStatus: command.secretStatus,
};
+ if (
+ !unchanged &&
+ command.secretStatus === "saved" &&
+ projection.thread.snoozedUntil != null
+ ) {
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.unsnoozed",
+ threadId: command.threadId,
+ providerInstanceId: projection.thread.providerInstanceId,
+ occurredAt: now,
+ payload: { ...projection.thread, snoozedUntil: null, snoozedAt: null, updatedAt: now },
+ });
+ }
yield* emit(
events,
command,
@@ -8980,6 +9000,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
updatedAt: now,
type: "link_request",
};
+ if (!unchanged && command.linkStatus === "linked" && projection.thread.snoozedUntil != null) {
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.unsnoozed",
+ threadId: command.threadId,
+ providerInstanceId: projection.thread.providerInstanceId,
+ occurredAt: now,
+ payload: { ...projection.thread, snoozedUntil: null, snoozedAt: null, updatedAt: now },
+ });
+ }
yield* emit(
events,
command,
@@ -9401,6 +9433,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return yield* recordSubagentFollowup(answer, events).pipe(mapDispatchError(answer));
}
if (providerSessionId === null) return;
+ if (runtimeRequest.kind === "user_input" && resolvedNodeStatus === "completed") {
+ const thread = yield* projectionStore
+ .getThread(command.threadId)
+ .pipe(mapDispatchError(command));
+ if (thread.snoozedUntil != null) {
+ yield* emitEvent({
+ type: "thread.unsnoozed",
+ threadId: command.threadId,
+ providerInstanceId: thread.providerInstanceId,
+ occurredAt: now,
+ payload: { ...thread, snoozedUntil: null, snoozedAt: null, updatedAt: now },
+ });
+ }
+ }
yield* Ref.update(effects, (existing) => [
...existing,
{
diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
index 1352e17585b..825bc5d7ce5 100644
--- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
@@ -5,6 +5,7 @@ import {
NodeId,
type OrchestrationV2AppThread,
type OrchestrationV2Run,
+ type OrchestrationV2RuntimeRequest,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
@@ -20,7 +21,11 @@ import * as Layer from "effect/Layer";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
-import { isAutoSettlementCandidate, resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
+import {
+ isAutoSettlementCandidate,
+ isSnoozed,
+ resolveAutoSettlementAt,
+} from "./ThreadSettlementService.ts";
const layerSql = ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
@@ -136,6 +141,75 @@ const createItem = Effect.fn(function* (
});
});
+it.effect.each([["sql", layerSql]] as const)(
+ "%s: pending approvals wake a snoozed question even with older creation times",
+ ([, testLayer]) =>
+ Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = yield* createThread("snoozed-question-approval", {
+ snoozedAt: now,
+ snoozedUntil: DateTime.add(now, { days: 1 }),
+ });
+ const question: OrchestrationV2RuntimeRequest = {
+ id: RuntimeRequestId.make("question"),
+ nodeId: NodeId.make("node:question"),
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "user_input",
+ status: "pending",
+ responseCapability: { type: "message" },
+ createdAt: DateTime.subtract(now, { hours: 1 }),
+ resolvedAt: null,
+ };
+ const approval: OrchestrationV2RuntimeRequest = {
+ ...question,
+ id: RuntimeRequestId.make("approval"),
+ kind: "command",
+ createdAt: old,
+ };
+ const newerApproval = {
+ ...approval,
+ id: RuntimeRequestId.make("newer-approval"),
+ createdAt: DateTime.add(old, { hours: 1 }),
+ };
+ const setRequest = (request: OrchestrationV2RuntimeRequest) =>
+ store.apply({
+ id: EventId.make(`event:${request.id}:${request.status}`),
+ type: "runtime-request.updated",
+ threadId,
+ occurredAt: now,
+ payload: request,
+ });
+ const assertPending = (expected: RuntimeRequestId, snoozed: boolean) =>
+ Effect.gen(function* () {
+ const snapshot = yield* store.getShellSnapshot();
+ const shell = snapshot.threads.find((thread) => thread.id === threadId)!;
+ const projection = yield* store.getThreadProjection(threadId);
+ for (const candidate of [shell, ProjectionStore.threadShellFromProjection(projection)]) {
+ assert.equal(candidate.pendingRuntimeRequest?.id, expected);
+ assert.equal(isSnoozed(candidate, DateTime.toEpochMillis(now)), snoozed);
+ }
+ });
+ yield* setRequest({
+ ...question,
+ id: RuntimeRequestId.make("older-question"),
+ createdAt: old,
+ });
+ yield* setRequest(question);
+ yield* assertPending(question.id, true);
+
+ // A request becoming pending can retain a creation time older than the snooze.
+ yield* setRequest(approval);
+ yield* assertPending(approval.id, false);
+ yield* setRequest(newerApproval);
+ yield* assertPending(newerApproval.id, false);
+ yield* setRequest({ ...newerApproval, status: "resolved", resolvedAt: now });
+ yield* assertPending(approval.id, false);
+ yield* setRequest({ ...approval, status: "resolved", resolvedAt: now });
+ yield* assertPending(question.id, true);
+ }).pipe(Effect.provide(testLayer)),
+);
+
it.effect(
"sql: discovers settlement work with the same activity and background semantics as the shell",
() =>
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index c1772916022..c584dd27a8d 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -6605,6 +6605,46 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
},
});
+ for (const responseCapability of [
+ { type: "live", providerSessionId: ProviderSessionId.make("session:pending-secret") },
+ { type: "message" },
+ ] as const) {
+ for (const fresh of [true, false]) {
+ yield* projectionStore.apply({
+ id: EventId.make("event:" + suffix + ":fresh-" + fresh),
+ type: "runtime-request.updated",
+ threadId,
+ runId,
+ nodeId,
+ driver,
+ occurredAt: now,
+ payload: {
+ id: requestId,
+ nodeId,
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "user_input",
+ status: "pending",
+ responseCapability,
+ createdAt: fresh
+ ? DateTime.add(now, { seconds: 5 })
+ : DateTime.subtract(now, { seconds: 1 }),
+ resolvedAt: null,
+ },
+ });
+ for (const shell of [
+ (yield* projectionStore.getShellSnapshot()).threads.find(
+ (thread) => thread.id === threadId,
+ ),
+ ProjectionStore.threadShellFromProjection(
+ yield* projectionStore.getThreadProjection(threadId),
+ ),
+ ]) {
+ assert.equal(shell?.pendingRuntimeRequest?.id, fresh ? requestId : "secret:b");
+ }
+ }
+ }
+
for (const status of [
"preparing",
"starting",
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index bd6a61db903..23874c6014f 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -1559,9 +1559,11 @@ export function threadShellFromProjection(
.filter((request) => request.status === "pending")
.toSorted(
(left, right) =>
+ Number(left.kind === "user_input") - Number(right.kind === "user_input") ||
DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
)[0] ?? null,
);
+
const userMessages = projection.messages
.filter((message) => message.role === "user" && idleCompactionOf(message) === undefined)
.toSorted(
@@ -1570,20 +1572,26 @@ export function threadShellFromProjection(
);
const latestUserAuthoredMessageAt =
userMessages.find((message) => message.createdBy === "user")?.updatedAt ?? null;
- if (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) {
- pendingRuntimeRequest =
- secretRequestAsPendingInput(
- projection.turnItems
- .filter(
- (item) =>
- item.status === "waiting" &&
- waitsOnUser(item, liveRunIds, latestUserAuthoredMessageAt),
- )
- .toSorted(
- (left, right) =>
- DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
- )[0] ?? null,
- ) ?? pendingRuntimeRequest;
+ if (pendingRuntimeRequest === null || pendingRuntimeRequest.kind === "user_input") {
+ const waitingCard = secretRequestAsPendingInput(
+ projection.turnItems
+ .filter(
+ (item) =>
+ item.status === "waiting" && waitsOnUser(item, liveRunIds, latestUserAuthoredMessageAt),
+ )
+ .toSorted(
+ (left, right) =>
+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
+ )[0] ?? null,
+ );
+ if (
+ waitingCard !== null &&
+ (pendingRuntimeRequest === null ||
+ DateTime.toEpochMillis(waitingCard.createdAt) >=
+ DateTime.toEpochMillis(pendingRuntimeRequest.createdAt))
+ ) {
+ pendingRuntimeRequest = waitingCard;
+ }
}
const latestUserMessage = userMessages[0] ?? null;
const pendingBackgroundTasks = derivePendingBackgroundWork({
@@ -6230,7 +6238,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
FROM orchestration_v2_projection_runtime_requests request
WHERE request.thread_id = t.thread_id
AND request.status = 'pending'
- ORDER BY request.created_at DESC, request.runtime_request_id DESC
+ ORDER BY (request.kind = 'user_input') ASC,
+ request.created_at DESC, request.runtime_request_id DESC
LIMIT 1
) AS pending_request_payload_json,
(
@@ -6760,16 +6769,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
)
: null;
if (
- (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) &&
+ (pendingRuntimeRequest === null || pendingRuntimeRequest.kind === "user_input") &&
waitingCards.length > 0
) {
- pendingRuntimeRequest =
- secretRequestAsPendingInput(
- waitingCards.toSorted(
- (left, right) =>
- DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
- )[0] ?? null,
- ) ?? pendingRuntimeRequest;
+ const waitingCard = secretRequestAsPendingInput(
+ waitingCards.toSorted(
+ (left, right) =>
+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
+ )[0] ?? null,
+ );
+ if (
+ waitingCard !== null &&
+ (pendingRuntimeRequest === null ||
+ DateTime.toEpochMillis(waitingCard.createdAt) >=
+ DateTime.toEpochMillis(pendingRuntimeRequest.createdAt))
+ ) {
+ pendingRuntimeRequest = waitingCard;
+ }
}
let terminalFailureItem =
row.terminal_failure_payload_json === null
diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
index 1d8e5149427..ff5caf6a591 100644
--- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
@@ -6,6 +6,7 @@ import {
ProjectId,
EventId,
ProviderInstanceId,
+ RuntimeRequestId,
RunId,
ThreadId,
TurnItemId,
@@ -1587,6 +1588,37 @@ describe("ThreadSettlementServiceV2 terminals", () => {
describe("isSnoozed", () => {
const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
+ it("defers existing input while new questions and approvals wake the thread", () => {
+ const request = {
+ id: RuntimeRequestId.make("question"),
+ kind: "user_input" as const,
+ createdAt: snoozed.snoozedAt,
+ };
+ expect(
+ ThreadSettlementService.isSnoozed(
+ shell({ ...snoozed, pendingRuntimeRequest: request }),
+ NOW_MS,
+ ),
+ ).toBe(true);
+ expect(
+ ThreadSettlementService.isSnoozed(
+ shell({ ...snoozed, pendingRuntimeRequest: { ...request, createdAt: at(-DAY_MS) } }),
+ NOW_MS,
+ ),
+ ).toBe(false);
+ expect(
+ ThreadSettlementService.isSnoozed(
+ shell({ ...snoozed, pendingRuntimeRequest: { ...request, kind: "command" } }),
+ NOW_MS,
+ ),
+ ).toBe(false);
+ expect(
+ ThreadSettlementService.isSnoozed(
+ shell({ ...snoozed, snoozedAt: null, pendingRuntimeRequest: request }),
+ NOW_MS,
+ ),
+ ).toBe(false);
+ });
it("keeps a run requested and completed after snoozing parked until the timer", () => {
const thread = shell({
...snoozed,
diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts
index 8c2dcfe8868..40c6bf7d057 100644
--- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts
+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts
@@ -174,10 +174,17 @@ export function isSnoozed(
): boolean {
const snoozedUntilMs = toMillis(thread.snoozedUntil);
if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
- if (thread.pendingRuntimeRequest !== null) return false;
// Same as the client: a waiting guest message wakes the thread, and the snooze stays stored.
if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
const snoozedAtMs = toMillis(thread.snoozedAt);
+ if (
+ thread.pendingRuntimeRequest !== null &&
+ (thread.pendingRuntimeRequest.kind !== "user_input" ||
+ snoozedAtMs === null ||
+ DateTime.toEpochMillis(thread.pendingRuntimeRequest.createdAt) > snoozedAtMs)
+ ) {
+ return false;
+ }
const completedAtMs = toMillis(thread.latestRunCompletedAt);
const wokeOnError =
thread.status === "failed" &&
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 17b103f75b8..54ce798da42 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -1616,6 +1616,52 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
type: "message",
});
const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const now = yield* DateTime.now;
+ const beforeSnooze = yield* orchestrator.getThreadProjection(threadId);
+ const snooze = {
+ type: "thread.snooze" as const,
+ commandId: CommandId.make("runtime-async-question-snooze"),
+ threadId,
+ snoozedUntil: "2099-07-25T09:00:00.000Z",
+ };
+ yield* orchestrator.dispatch(snooze);
+ const snoozed = yield* orchestrator.getThreadProjection(threadId);
+ assert.isNotNull(snoozed.thread.snoozedUntil);
+ assert.deepEqual(snoozed.runtimeRequests, beforeSnooze.runtimeRequests);
+ assert.deepEqual(snoozed.turnItems, beforeSnooze.turnItems);
+ assert.deepEqual(snoozed.nodes, beforeSnooze.nodes);
+ assert.deepEqual(snoozed.runs, beforeSnooze.runs);
+
+ // A question arriving after an earlier snooze must be acknowledged even
+ // when the user picks the same wake time again.
+ const priorSnooze = DateTime.makeUnsafe(DateTime.toEpochMillis(now) - 1_000);
+ yield* eventSink.write({
+ commandId: CommandId.make("runtime-async-question-earlier-snooze"),
+ events: [
+ {
+ id: EventId.make("runtime-async-question-earlier-snooze-event"),
+ type: "thread.snoozed",
+ threadId,
+ occurredAt: priorSnooze,
+ payload: { ...snoozed.thread, snoozedAt: priorSnooze },
+ },
+ ],
+ });
+ yield* orchestrator.dispatch({
+ ...snooze,
+ commandId: CommandId.make("runtime-async-question-resnooze"),
+ });
+ assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).thread.snoozedAt, now);
+ yield* orchestrator.dispatch({
+ type: "thread.unsnooze",
+ commandId: CommandId.make("runtime-async-question-wake"),
+ threadId,
+ reason: "user",
+ });
+ const awake = yield* orchestrator.getThreadProjection(threadId);
+ assert.isNull(awake.thread.snoozedUntil);
+ assert.deepEqual(awake.runtimeRequests, beforeSnooze.runtimeRequests);
+
const beforeInvalid = yield* orchestrator.getThreadProjection(threadId);
const beforeSequence = yield* eventSink.latestSequence();
for (const [index, answers] of [
diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts
index c3ca78cbcb6..09f28595499 100644
--- a/apps/server/src/peer/PeerLinkRequests.test.ts
+++ b/apps/server/src/peer/PeerLinkRequests.test.ts
@@ -482,6 +482,31 @@ it.live("the agent asks without waiting, and the user links the box after its tu
{ kind: "user_input" },
);
+ for (const secretStatus of ["pending", "saved"] as const) {
+ yield* a.orchestrator.dispatch({
+ type: "secret_request.record",
+ commandId: CommandId.make("command:secret-" + secretStatus),
+ threadId,
+ runId,
+ nodeId: rootNode,
+ turnItemId: TurnItemId.make("turn-item:snoozed-secret"),
+ label: "Credential",
+ reason: "Connect",
+ secretStatus,
+ });
+ if (secretStatus === "pending") {
+ yield* a.orchestrator.dispatch({
+ type: "thread.snooze",
+ commandId: CommandId.make("command:snooze-secret"),
+ threadId,
+ snoozedUntil: "2099-01-01T00:00:00.000Z",
+ });
+ expect((yield* a.projections.getThread(threadId)).snoozedUntil).not.toBeNull();
+ } else {
+ expect((yield* a.projections.getThread(threadId)).snoozedUntil).toBeNull();
+ }
+ }
+
// The agent ends its turn; the card stays answerable, and the thread still asks.
yield* endRun(a);
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
).toEqual([threadId]);
expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
+ yield* a.orchestrator.dispatch({
+ type: "thread.snooze",
+ commandId: CommandId.make("command:snooze-link"),
+ threadId,
+ snoozedUntil: "2099-01-01T00:00:00.000Z",
+ });
+ expect((yield* a.projections.getThread(threadId)).snoozedUntil).not.toBeNull();
+
// The user's client mints a code on the box and picks more than the agent suggested.
const pairing = yield* b.auth.issuePairingCredential();
yield* a.requests.answer({
@@ -541,6 +574,8 @@ it.live("the agent asks without waiting, and the user links the box after its tu
answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
});
+ expect((yield* a.projections.getThread(threadId)).snoozedUntil).toBeNull();
+
const link = yield* a.links.get(box.environmentId);
expect(Option.getOrUndefined(link)?.access).toBe("auto");
expect(yield* cardOf(a)).toMatchObject({
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 6f848b67957..4829fa3c6b7 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -326,6 +326,8 @@ Choose **Snooze → Custom…** from a thread's menu to pick a date and time in
local time zone, or a duration in minutes, hours, or days. Durations start when
you confirm; one day means 24 hours. On web and desktop, you can also snooze
several selected threads together. Choose **Wake thread** to bring a thread back early.
+
A snoozed thread keeps working and stays hidden until its wake time, even while
-its agent wakes itself for background work. It comes back early only when it needs
-an approval or answer from you, when a run fails, or when you send it a message.
+its agent wakes itself for background work. It comes back early for an approval,
+a new question, a failed run, or a message or answer you send. You can snooze an existing
+question and answer when the thread wakes; the question stays unanswered.
diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.ts
index 6cc9bc91595..dc811ce4e69 100644
--- a/packages/client-runtime/src/state/entities.test.ts
+++ b/packages/client-runtime/src/state/entities.test.ts
@@ -22,7 +22,7 @@ import { canSnooze, effectiveSnoozed } from "./threadSettled.ts";
const environmentId = EnvironmentId.make("environment-v2");
describe("V2 client presentation", () => {
- it("an async question blocks snooze and wakes a snoozed thread", () => {
+ it("an async question allows snooze and wakes an older snooze", () => {
const runId = RunId.make("run-async-question");
const running = {
...v2ThreadShell,
@@ -39,7 +39,17 @@ describe("V2 client presentation", () => {
},
};
const active = presentThreadShell(environmentId, running);
- expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
+ expect(active.hasPendingUserInput).toBe(true);
+ expect(isThreadWorking(active)).toBe(false);
+ expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(true);
+
+ const completed = presentThreadShell(environmentId, {
+ ...running,
+ activeRunId: null,
+ status: "completed",
+ });
+ expect(completed.hasPendingUserInput).toBe(true);
+ expect(isThreadWorking(completed)).toBe(false);
expect(effectiveSnoozed(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
});
diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts
index 196b5ff39e1..098b73141e3 100644
--- a/packages/client-runtime/src/state/models.ts
+++ b/packages/client-runtime/src/state/models.ts
@@ -158,6 +158,7 @@ export interface EnvironmentThreadShell {
readonly latestUserAuthoredMessageAt?: string | null;
readonly hasPendingApprovals: boolean;
readonly hasPendingUserInput: boolean;
+ readonly pendingUserInputAt?: string | null;
readonly pendingSubagentRequest?: PendingSubagentRequest | null;
/** Guest messages waiting for the owner to send or dismiss. */
readonly pendingGuestMessageCount?: number;
@@ -312,6 +313,10 @@ export function presentThreadShell(
thread.pendingRuntimeRequest.kind !== "auth_refresh",
// Async questions count too, so a thread with any open question leaves Working.
hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
+ pendingUserInputAt:
+ thread.pendingRuntimeRequest?.kind === "user_input"
+ ? iso(thread.pendingRuntimeRequest.createdAt)
+ : null,
pendingSubagentRequest,
pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
hasActionableProposedPlan: thread.hasActionableProposedPlan,
diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts
index 5fbfb1225a3..9a723f0f6e0 100644
--- a/packages/client-runtime/src/state/threadCommands.test.ts
+++ b/packages/client-runtime/src/state/threadCommands.test.ts
@@ -498,14 +498,52 @@ describe("remote thread lifecycle commands", () => {
input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
});
const request = yield* Queue.take(h.requests);
- expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
+ if (action === "settle") {
+ expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
+ } else {
+ expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject({
+ snoozedUntil: FUTURE,
+ pendingRuntimeRequest: USER_INPUT,
+ });
+ }
yield* Deferred.succeed(request.reply, { sequence: 2 });
expect((yield* Effect.promise(() => result))._tag).toBe("Success");
expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
);
- expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
+ expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toEqual(
+ action === "settle" ? null : USER_INPUT,
+ );
expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
}),
);
+ it.effect("acknowledges a new question when snoozing again to the same wake time", () =>
+ Effect.gen(function* () {
+ const h = yield* makeHarness();
+ const initial = {
+ ...SNAPSHOT,
+ threads: [
+ {
+ ...SNAPSHOT.threads[0]!,
+ pendingRuntimeRequest: USER_INPUT,
+ snoozedAt: DateTime.makeUnsafe("2026-09-12T09:00:00.000Z"),
+ snoozedUntil: FUTURE,
+ },
+ ],
+ };
+ h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), initial);
+ const result = h.commands.snooze.run(h.registry, {
+ environmentId: ENVIRONMENT_ID,
+ input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
+ });
+ const request = yield* Queue.take(h.requests);
+ const snoozed = h.registry.get(h.visibleAtom)?.threads[0];
+ expect(DateTime.toEpochMillis(snoozed!.snoozedAt!)).toBeGreaterThanOrEqual(
+ DateTime.toEpochMillis(USER_INPUT.createdAt),
+ );
+ expect(snoozed?.pendingRuntimeRequest).toEqual(USER_INPUT);
+ yield* Deferred.succeed(request.reply, { sequence: 2 });
+ expect((yield* Effect.promise(() => result))._tag).toBe("Success");
+ }),
+ );
});
diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts
index 88a5759c5ed..7a8d20830ad 100644
--- a/packages/client-runtime/src/state/threadCommands.ts
+++ b/packages/client-runtime/src/state/threadCommands.ts
@@ -404,13 +404,13 @@ export function createThreadEnvironmentAtoms<R, E>(
})),
snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
(!accepted &&
- (thread.pendingRuntimeRequest !== null ||
+ ((thread.pendingRuntimeRequest !== null &&
+ thread.pendingRuntimeRequest.kind !== "user_input") ||
["preparing", "queued", "starting"].includes(thread.status))) ||
!(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))
? thread
: {
...thread,
- pendingRuntimeRequest: null,
snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil),
snoozedAt: now,
},
diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts
index fa1c33fb834..c247f9d8048 100644
--- a/packages/client-runtime/src/state/threadSettled.ts
+++ b/packages/client-runtime/src/state/threadSettled.ts
@@ -74,18 +74,38 @@ export interface ThreadSnoozeShell extends QueuedThreadShell {
readonly snoozedAt?: string | null;
readonly hasPendingApprovals: boolean;
readonly hasPendingUserInput: boolean;
+ readonly pendingUserInputAt?: string | null;
readonly pendingSubagentRequest?: PendingSubagentRequest | null;
readonly pendingGuestMessageCount?: number;
}
+function pendingQuestionAt(shell: ThreadSnoozeShell): string | null {
+ const request = shell.source?.pendingRuntimeRequest;
+ return (
+ shell.pendingUserInputAt ??
+ (request?.kind === "user_input" ? DateTime.formatIso(request.createdAt) : null)
+ );
+}
+
/**
* Only a request for the user or a fresh failure ends a snooze early. Completed runs never do:
* a snoozed long-running thread keeps waking itself for background work and stays hidden
* until its timer.
*/
export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
- if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
- if (shell.source?.pendingRuntimeRequest != null) return true;
+ const request = shell.source?.pendingRuntimeRequest;
+ if (shell.hasPendingApprovals || (request != null && request.kind !== "user_input")) return true;
+ const questionAt = pendingQuestionAt(shell);
+ // Snoozing an existing question means "ask me later". Only a new question
+ // wakes it early; missing or invalid timestamps keep the request visible.
+ if (
+ (shell.hasPendingUserInput || request?.kind === "user_input") &&
+ (shell.snoozedAt == null ||
+ questionAt == null ||
+ !(Date.parse(questionAt) <= Date.parse(shell.snoozedAt)))
+ ) {
+ return true;
+ }
if (shell.pendingSubagentRequest != null) return true;
if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
const failedAt = failureEdgeAt(shell);
@@ -124,9 +144,9 @@ export function canSnooze(
>,
options: { readonly now: string },
): boolean {
- if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
- // The server rejects snoozing for any pending request.
- if (shell.source?.pendingRuntimeRequest != null) return false;
+ if (shell.hasPendingApprovals) return false;
+ const request = shell.source?.pendingRuntimeRequest;
+ if (request != null && request.kind !== "user_input") return false;
if (shell.pendingSubagentRequest != null) return false;
// A waiting guest message would wake it at once.
if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
@@ -157,14 +177,19 @@ export function threadWokeAt(
// indicator the user already cleared by visiting (snoozedUntil is newer
// than that visit's lastVisitedAt).
if (threadRaisedHandWhileSnoozed(shell)) {
- // An old failure must not replace the activity time of an approval or input wake.
const failedAt = failureEdgeAt(shell);
- if (
+ const questionAt = pendingQuestionAt(shell);
+ const freshFailure =
failedAt != null &&
- (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt))
- ) {
+ (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt));
+ const freshQuestion =
+ questionAt != null &&
+ shell.snoozedAt != null &&
+ Date.parse(questionAt) > Date.parse(shell.snoozedAt);
+ if (freshFailure && (!freshQuestion || Date.parse(failedAt) >= Date.parse(questionAt))) {
return failedAt;
}
+ if (freshQuestion) return questionAt;
const runtime = shell.runtime ?? shell.session ?? null;
return runtime?.updatedAt ?? shell.snoozedAt ?? null;
}
diff --git a/packages/client-runtime/src/state/threadSnoozed.test.ts b/packages/client-runtime/src/state/threadSnoozed.test.ts
index f8f01ec6a1d..5da3be09650 100644
--- a/packages/client-runtime/src/state/threadSnoozed.test.ts
+++ b/packages/client-runtime/src/state/threadSnoozed.test.ts
@@ -1,4 +1,6 @@
// @effect-diagnostics globalDate:off -- Tests exercise local calendar snooze boundaries.
+import * as DateTime from "effect/DateTime";
+import { RuntimeRequestId } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { TurnId } from "@t3tools/contracts";
import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
@@ -30,6 +32,7 @@ function makeShell(input: {
readonly snoozedAt?: string | null;
readonly sessionStatus?: "starting" | "running" | "ready" | "error";
readonly pending?: "approval" | "user-input";
+ readonly pendingUserInputAt?: string | null;
readonly turnRequestedAt?: string | null;
readonly turnCompletedAt?: string | null;
}): ThreadSnoozeShell {
@@ -39,6 +42,7 @@ function makeShell(input: {
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
hasPendingApprovals: input.pending === "approval",
hasPendingUserInput: input.pending === "user-input",
+ pendingUserInputAt: input.pendingUserInputAt ?? null,
session:
input.sessionStatus === undefined
? null
@@ -89,6 +93,64 @@ describe("effectiveSnoozed", () => {
).toBe(false);
});
+ it("defers an existing question until the timer, but wakes for a new question", () => {
+ const shell = makeShell({
+ snoozedUntil: FUTURE_WAKE,
+ pending: "user-input",
+ pendingUserInputAt: SNOOZED_AT,
+ });
+ expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
+ expect(threadWokeAt(shell, { now: NOW })).toBeNull();
+ expect(effectiveSnoozed(shell, { now: FUTURE_WAKE })).toBe(false);
+ expect(threadWokeAt(shell, { now: FUTURE_WAKE })).toBe(FUTURE_WAKE);
+
+ const newQuestion = { ...shell, pendingUserInputAt: "2026-04-10T10:00:00.000Z" };
+ expect(effectiveSnoozed(newQuestion, { now: NOW })).toBe(false);
+ expect(threadWokeAt(newQuestion, { now: NOW })).toBe(newQuestion.pendingUserInputAt);
+ expect(effectiveSnoozed({ ...shell, pendingUserInputAt: "invalid" }, { now: NOW })).toBe(false);
+ });
+
+ it.each([false, true])(
+ "snoozes existing source questions with blocking=%s and wakes for newer ones",
+ (blocking) => {
+ const shell: ThreadSnoozeShell = {
+ ...makeShell({ snoozedUntil: FUTURE_WAKE }),
+ source: {
+ pendingRuntimeRequest: {
+ id: RuntimeRequestId.make("question"),
+ kind: "user_input",
+ blocking,
+ createdAt: DateTime.makeUnsafe(SNOOZED_AT),
+ },
+ },
+ };
+ expect(canSnooze(shell, { now: NOW })).toBe(true);
+ expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
+ const newQuestion = {
+ ...shell,
+ source: {
+ pendingRuntimeRequest: {
+ ...shell.source!.pendingRuntimeRequest!,
+ createdAt: DateTime.makeUnsafe("2026-04-10T10:00:00.000Z"),
+ },
+ },
+ };
+ expect(effectiveSnoozed(newQuestion, { now: NOW })).toBe(false);
+ expect(threadWokeAt(newQuestion, { now: NOW })).toBe("2026-04-10T10:00:00.000Z");
+ const approval = {
+ ...shell,
+ source: {
+ pendingRuntimeRequest: {
+ ...shell.source!.pendingRuntimeRequest!,
+ kind: "command" as const,
+ },
+ },
+ };
+ expect(canSnooze(approval, { now: NOW })).toBe(false);
+ expect(effectiveSnoozed(approval, { now: NOW })).toBe(false);
+ },
+ );
+
it.each([
{
reason: "stale failure",
@@ -182,7 +244,7 @@ describe("threadRaisedHandWhileSnoozed", () => {
});
describe("canSnooze", () => {
- it("refuses blocked-on-you work", () => {
+ it("allows deferring user input while refusing approvals and subagent requests", () => {
expect(
canSnooze({ ...makeShell({ pending: "approval" }), latestUserMessageAt: null }, { now: NOW }),
).toBe(false);
@@ -191,7 +253,7 @@ describe("canSnooze", () => {
{ ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
{ now: NOW },
),
- ).toBe(false);
+ ).toBe(true);
expect(
canSnooze(
{ ...makeShell({}), latestUserMessageAt: null, pendingSubagentRequest: "approval" },
@@ -272,6 +334,45 @@ describe("threadWokeAt", () => {
expect(threadWokeAt(shell, { now: NOW })).toBe("2026-04-10T11:00:00.000Z");
});
+ it.each(["failure", "subagent request"] as const)(
+ "keeps an old question from masking a newer %s wake",
+ (wake) => {
+ const shell = {
+ ...makeShell({
+ snoozedUntil: FUTURE_WAKE,
+ pending: "user-input",
+ pendingUserInputAt: SNOOZED_AT,
+ sessionStatus: wake === "failure" ? "error" : "running",
+ }),
+ pendingSubagentRequest: wake === "subagent request" ? ("user_input" as const) : null,
+ };
+ const lastVisitedAt = "2026-04-10T10:00:00.000Z";
+ expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
+ const wokeAt = threadWokeAt(shell, { now: NOW });
+ expect(wokeAt).toBe("2026-04-10T11:00:00.000Z");
+ expect(Date.parse(wokeAt!)).toBeGreaterThan(Date.parse(lastVisitedAt));
+ },
+ );
+
+ it.each([
+ ["error", "2026-04-10T10:00:00.000Z", "2026-04-10T11:00:00.000Z"],
+ ["failed", "2026-04-10T10:00:00.000Z", "2026-04-10T11:00:00.000Z"],
+ ["failed", "2026-04-10T11:30:00.000Z", "2026-04-10T11:30:00.000Z"],
+ ["running", "2026-04-10T10:00:00.000Z", "2026-04-10T10:00:00.000Z"],
+ ] as const)(
+ "uses the latest wake event for a %s runtime and a question at %s",
+ (status, pendingUserInputAt, expectedWakeAt) => {
+ const shell = {
+ ...makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input", pendingUserInputAt }),
+ runtime: { status, updatedAt: "2026-04-10T11:00:00.000Z" },
+ };
+ const lastVisitedAt = "2026-04-10T10:30:00.000Z";
+ const wokeAt = threadWokeAt(shell, { now: NOW });
+ expect(wokeAt).toBe(expectedWakeAt);
+ expect(Date.parse(wokeAt!) > Date.parse(lastVisitedAt)).toBe(status !== "running");
+ },
+ );
+
it("keeps the early wake authoritative after the scheduled time passes", () => {
const shell: ThreadSnoozeShell = {
...makeShell({ snoozedUntil: PAST_WAKE }),