Open History to see the last commit
1// @effect-diagnostics globalDate:off -- Tests exercise local calendar snooze boundaries.
2import * as DateTime from "effect/DateTime";
3import { RunId, RuntimeRequestId } from "@t3tools/contracts";
4import { ThreadId } from "@t3tools/contracts";
5import { TurnId } from "@t3tools/contracts";
6import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
7import { describe, expect, it } from "vite-plus/test";
8
9import {
10 canSnooze,
11 effectiveSnoozed,
12 hasQueuedTurnStart,
13 hasUnseenRunFailure,
14 pickSnoozePreset,
15 INDEFINITE_SNOOZE_UNTIL,
16 resolveSnoozePresets,
17 snoozeWakeLabel,
18 threadRaisedHandWhileSnoozed,
19 threadWokeAt,
20 isThreadWokeUnseen,
21 type ThreadSnoozeShell,
22} from "./threadSettled.ts";
23
24const NOW = "2026-04-10T12:00:00.000Z";
25const SNOOZED_AT = "2026-04-10T09:00:00.000Z";
26const FUTURE_WAKE = "2026-04-11T09:00:00.000Z";
27const PAST_WAKE = "2026-04-10T10:00:00.000Z";
28
29function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
30 return new Date(year, month - 1, day, hour, minute, 0, 0);
31}
32
33function makeShell(input: {
34 readonly snoozedUntil?: string | null;
35 readonly snoozedAt?: string | null;
36 readonly sessionStatus?: "starting" | "running" | "ready" | "error";
37 readonly pending?: "approval" | "user-input";
38 readonly pendingUserInputAt?: string | null;
39 readonly turnRequestedAt?: string | null;
40 readonly turnCompletedAt?: string | null;
41}): ThreadSnoozeShell {
42 const threadId = ThreadId.make("thread-1");
43 return {
44 snoozedUntil: input.snoozedUntil ?? null,
45 snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? SNOOZED_AT : null),
46 hasPendingApprovals: input.pending === "approval",
47 hasPendingUserInput: input.pending === "user-input",
48 pendingUserInputAt: input.pendingUserInputAt ?? null,
49 session:
50 input.sessionStatus === undefined
51 ? null
52 : {
53 threadId,
54 status: input.sessionStatus,
55 providerName: "Codex",
56 runtimeMode: "full-access",
57 activeTurnId: null,
58 lastError: input.sessionStatus === "error" ? "boom" : null,
59 updatedAt: "2026-04-10T11:00:00.000Z",
60 },
61 latestTurn:
62 input.turnCompletedAt === undefined
63 ? null
64 : {
65 turnId: TurnId.make("turn-1"),
66 state: "completed",
67 requestedAt: input.turnRequestedAt === undefined ? SNOOZED_AT : input.turnRequestedAt,
68 startedAt: null,
69 completedAt: input.turnCompletedAt,
70 assistantMessageId: null,
71 },
72 };
73}
74
75type QueuedTurnShell = Parameters<typeof hasQueuedTurnStart>[0];
76
77function makeQueuedTurnShell(overrides: Partial<QueuedTurnShell> = {}): QueuedTurnShell {
78 return { latestUserMessageAt: null, latestTurn: null, session: null, ...overrides };
79}
80
81describe("effectiveSnoozed", () => {
82 it("never hides on malformed wake data", () => {
83 expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false);
84 });
85
86 it("defers an existing question until the timer, but wakes for a new question", () => {
87 const shell = makeShell({
88 snoozedUntil: FUTURE_WAKE,
89 pending: "user-input",
90 pendingUserInputAt: SNOOZED_AT,
91 });
92 expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
93 expect(threadWokeAt(shell, { now: NOW })).toBeNull();
94 expect(effectiveSnoozed(shell, { now: FUTURE_WAKE })).toBe(false);
95 expect(threadWokeAt(shell, { now: FUTURE_WAKE })).toBe(FUTURE_WAKE);
96
97 const newQuestion = { ...shell, pendingUserInputAt: "2026-04-10T10:00:00.000Z" };
98 expect(effectiveSnoozed(newQuestion, { now: NOW })).toBe(false);
99 expect(threadWokeAt(newQuestion, { now: NOW })).toBe(newQuestion.pendingUserInputAt);
100 expect(effectiveSnoozed({ ...shell, pendingUserInputAt: "invalid" }, { now: NOW })).toBe(false);
101 });
102
103 it.each([false, true])(
104 "snoozes existing source questions with blocking=%s and wakes for newer ones",
105 (blocking) => {
106 const shell: ThreadSnoozeShell = {
107 ...makeShell({ snoozedUntil: FUTURE_WAKE }),
108 source: {
109 pendingRuntimeRequest: {
110 id: RuntimeRequestId.make("question"),
111 kind: "user_input",
112 blocking,
113 createdAt: DateTime.makeUnsafe(SNOOZED_AT),
114 },
115 },
116 };
117 expect(canSnooze(shell, { now: NOW })).toBe(true);
118 expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
119 const newQuestion = {
120 ...shell,
121 source: {
122 pendingRuntimeRequest: {
123 ...shell.source!.pendingRuntimeRequest!,
124 createdAt: DateTime.makeUnsafe("2026-04-10T10:00:00.000Z"),
125 },
126 },
127 };
128 expect(effectiveSnoozed(newQuestion, { now: NOW })).toBe(false);
129 expect(threadWokeAt(newQuestion, { now: NOW })).toBe("2026-04-10T10:00:00.000Z");
130 const approval = {
131 ...shell,
132 source: {
133 pendingRuntimeRequest: {
134 ...shell.source!.pendingRuntimeRequest!,
135 kind: "command" as const,
136 },
137 },
138 };
139 expect(canSnooze(approval, { now: NOW })).toBe(false);
140 expect(effectiveSnoozed(approval, { now: NOW })).toBe(false);
141 },
142 );
143
144 it.each([
145 {
146 reason: "stale failure",
147 completedAt: "2026-04-10T08:00:00.000Z",
148 pending: undefined,
149 wokeAt: null,
150 },
151 {
152 reason: "failure without a completion timestamp",
153 completedAt: null,
154 pending: undefined,
155 wokeAt: null,
156 },
157 {
158 reason: "approval without a failure completion timestamp",
159 completedAt: null,
160 pending: "approval",
161 wokeAt: "2026-04-10T11:00:00.000Z",
162 },
163 {
164 reason: "fresh failure",
165 completedAt: "2026-04-10T10:00:00.000Z",
166 pending: undefined,
167 wokeAt: "2026-04-10T10:00:00.000Z",
168 },
169 {
170 reason: "approval after a stale failure",
171 completedAt: "2026-04-10T08:00:00.000Z",
172 pending: "approval",
173 wokeAt: "2026-04-10T11:00:00.000Z",
174 },
175 {
176 reason: "input after a stale failure",
177 completedAt: "2026-04-10T08:00:00.000Z",
178 pending: "user-input",
179 wokeAt: "2026-04-10T11:00:00.000Z",
180 },
181 ] as const)(
182 "uses the wake event time for $reason despite newer metadata",
183 ({ completedAt, pending, wokeAt }) => {
184 const shell: ThreadSnoozeShell = {
185 ...makeShell({ snoozedUntil: FUTURE_WAKE }),
186 hasPendingApprovals: pending === "approval",
187 hasPendingUserInput: pending === "user-input",
188 runtime: { status: "failed", updatedAt: "2026-04-10T11:00:00.000Z" },
189 latestRun: { status: "failed", requestedAt: "2026-04-10T07:00:00.000Z", completedAt },
190 };
191 expect(effectiveSnoozed(shell, { now: NOW })).toBe(wokeAt === null);
192 expect(threadWokeAt(shell, { now: NOW })).toBe(wokeAt);
193 },
194 );
195
196 it("stays snoozed while the session keeps working — snooze never pauses the agent", () => {
197 expect(
198 effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "running" }), {
199 now: NOW,
200 }),
201 ).toBe(true);
202 });
203
204 it("stays snoozed when a run requested after the snooze completes", () => {
205 const shell = {
206 ...makeShell({ snoozedUntil: FUTURE_WAKE }),
207 latestRun: {
208 status: "completed",
209 requestedAt: "2026-04-10T09:00:00.001Z",
210 startedAt: "2026-04-10T09:15:00.000Z",
211 completedAt: "2026-04-10T10:30:00.000Z",
212 },
213 };
214
215 expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
216 expect(threadWokeAt(shell, { now: NOW })).toBe(null);
217 });
218});
219
220describe("hasUnseenRunFailure", () => {
221 it("dates a failure by its run, falling back to the run's start when it never completed", () => {
222 const run = {
223 runId: RunId.make("run-failed"),
224 status: "failed" as const,
225 requestedAt: "2026-04-10T09:00:00.000Z",
226 startedAt: "2026-04-10T09:01:00.000Z",
227 completedAt: "2026-04-10T09:05:00.000Z",
228 assistantMessageId: null,
229 };
230 const visitedAt = "2026-04-10T09:06:00.000Z";
231
232 expect(hasUnseenRunFailure({ latestRun: run, lastVisitedAt: null })).toBe(true);
233 expect(hasUnseenRunFailure({ latestRun: run, lastVisitedAt: visitedAt })).toBe(false);
234 const failedAgain = { ...run, completedAt: "2026-04-10T09:10:00.000Z" };
235 expect(hasUnseenRunFailure({ latestRun: failedAgain, lastVisitedAt: visitedAt })).toBe(true);
236
237 const undated = { ...run, completedAt: null };
238 expect(hasUnseenRunFailure({ latestRun: undated, lastVisitedAt: visitedAt })).toBe(false);
239 expect(
240 hasUnseenRunFailure({ latestRun: undated, lastVisitedAt: "2026-04-10T09:00:30.000Z" }),
241 ).toBe(true);
242 });
243});
244
245describe("threadRaisedHandWhileSnoozed", () => {
246 it("is true for approvals, input, and failures", () => {
247 expect(
248 threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" })),
249 ).toBe(true);
250 expect(
251 threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" })),
252 ).toBe(true);
253 expect(
254 threadRaisedHandWhileSnoozed(
255 makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }),
256 ),
257 ).toBe(true);
258 });
259});
260
261describe("canSnooze", () => {
262 it("allows deferring user input while refusing approvals and subagent requests", () => {
263 expect(
264 canSnooze({ ...makeShell({ pending: "approval" }), latestUserMessageAt: null }, { now: NOW }),
265 ).toBe(false);
266 expect(
267 canSnooze(
268 { ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
269 { now: NOW },
270 ),
271 ).toBe(true);
272 expect(
273 canSnooze(
274 { ...makeShell({}), latestUserMessageAt: null, pendingSubagentRequest: "approval" },
275 { now: NOW },
276 ),
277 ).toBe(false);
278 });
279
280 it("refuses a queued turn start — same invisible-pending-work rule as settle", () => {
281 expect(
282 canSnooze(
283 { ...makeShell({}), latestUserMessageAt: "2026-04-10T11:59:30.000Z" },
284 { now: NOW },
285 ),
286 ).toBe(false);
287 expect(
288 canSnooze(
289 { ...makeShell({}), latestUserMessageAt: "2026-04-10T11:00:00.000Z" },
290 { now: NOW },
291 ),
292 ).toBe(true);
293 });
294});
295
296describe("hasQueuedTurnStart", () => {
297 it("clears queued state when a turn adopts the message or the session fails", () => {
298 const messageAt = "2026-04-10T11:59:00.000Z";
299 const adopted = makeQueuedTurnShell({
300 latestUserMessageAt: messageAt,
301 latestTurn: {
302 turnId: TurnId.make("turn-adopted"),
303 state: "running",
304 requestedAt: messageAt,
305 startedAt: null,
306 completedAt: null,
307 assistantMessageId: null,
308 },
309 });
310 const failed = makeQueuedTurnShell({
311 latestUserMessageAt: messageAt,
312 session: {
313 threadId: ThreadId.make("thread-failed"),
314 status: "error",
315 providerName: "Codex",
316 runtimeMode: "full-access",
317 activeTurnId: null,
318 lastError: "failed",
319 updatedAt: NOW,
320 },
321 });
322 expect(hasQueuedTurnStart(adopted, { now: NOW })).toBe(false);
323 expect(hasQueuedTurnStart(failed, { now: NOW })).toBe(false);
324 });
325});
326
327describe("threadWokeAt", () => {
328 it("reports the timer wake even after an already-requested run completes", () => {
329 expect(threadWokeAt(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(PAST_WAKE);
330 const shell = makeShell({
331 snoozedUntil: PAST_WAKE,
332 turnCompletedAt: "2026-04-10T09:30:00.000Z",
333 });
334 expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
335 expect(threadWokeAt(shell, { now: NOW })).toBe(PAST_WAKE);
336 });
337
338 it.each([
339 { reason: "failure", sessionStatus: "error" },
340 { reason: "approval", sessionStatus: "ready", pending: "approval" },
341 { reason: "user input", sessionStatus: "ready", pending: "user-input" },
342 ] as const)("reports $reason activity instead of an already-requested completion", (activity) => {
343 const shell = makeShell({
344 ...activity,
345 snoozedUntil: FUTURE_WAKE,
346 turnCompletedAt: "2026-04-10T10:30:00.000Z",
347 });
348 expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
349 expect(threadWokeAt(shell, { now: NOW })).toBe("2026-04-10T11:00:00.000Z");
350 });
351
352 it.each(["failure", "subagent request"] as const)(
353 "keeps an old question from masking a newer %s wake",
354 (wake) => {
355 const shell = {
356 ...makeShell({
357 snoozedUntil: FUTURE_WAKE,
358 pending: "user-input",
359 pendingUserInputAt: SNOOZED_AT,
360 sessionStatus: wake === "failure" ? "error" : "running",
361 }),
362 pendingSubagentRequest: wake === "subagent request" ? ("user_input" as const) : null,
363 };
364 const lastVisitedAt = "2026-04-10T10:00:00.000Z";
365 expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
366 const wokeAt = threadWokeAt(shell, { now: NOW });
367 expect(wokeAt).toBe("2026-04-10T11:00:00.000Z");
368 expect(Date.parse(wokeAt!)).toBeGreaterThan(Date.parse(lastVisitedAt));
369 },
370 );
371
372 it.each([
373 ["error", "2026-04-10T10:00:00.000Z", "2026-04-10T11:00:00.000Z"],
374 ["failed", "2026-04-10T10:00:00.000Z", "2026-04-10T11:00:00.000Z"],
375 ["failed", "2026-04-10T11:30:00.000Z", "2026-04-10T11:30:00.000Z"],
376 ["running", "2026-04-10T10:00:00.000Z", "2026-04-10T10:00:00.000Z"],
377 ] as const)(
378 "uses the latest wake event for a %s runtime and a question at %s",
379 (status, pendingUserInputAt, expectedWakeAt) => {
380 const shell = {
381 ...makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input", pendingUserInputAt }),
382 runtime: { status, updatedAt: "2026-04-10T11:00:00.000Z" },
383 };
384 const lastVisitedAt = "2026-04-10T10:30:00.000Z";
385 const wokeAt = threadWokeAt(shell, { now: NOW });
386 expect(wokeAt).toBe(expectedWakeAt);
387 expect(Date.parse(wokeAt!) > Date.parse(lastVisitedAt)).toBe(status !== "running");
388 },
389 );
390
391 it("keeps the early wake authoritative after the scheduled time passes", () => {
392 const shell: ThreadSnoozeShell = {
393 ...makeShell({ snoozedUntil: PAST_WAKE }),
394 runtime: { status: "failed", updatedAt: "2026-04-10T11:00:00.000Z" },
395 latestRun: {
396 status: "failed",
397 requestedAt: "2026-04-10T09:15:00.000Z",
398 completedAt: "2026-04-10T09:30:00.000Z",
399 },
400 };
401 expect(threadWokeAt(shell, { now: NOW })).toBe("2026-04-10T09:30:00.000Z");
402 });
403});
404
405describe("resolveSnoozePresets", () => {
406 const formatTime = (date: Date) =>
407 `${date.getHours()}:${String(date.getMinutes()).padStart(2, "0")}`;
408 const menu = (now: Date, presets?: ReadonlyArray<SnoozePresetSetting>) =>
409 resolveSnoozePresets(now, { formatTime, ...(presets ? { presets } : {}) })
410 .filter((preset) => preset.id !== "indefinite")
411 .map((preset) => `${preset.label} ${preset.whenLabel}`);
412
413 it("always ends with an indefinite snooze that never wakes", () => {
414 const presets = resolveSnoozePresets(localDate(2026, 4, 8, 20), { presets: [] });
415 expect(presets).toEqual([
416 {
417 id: "indefinite",
418 label: "Indefinitely",
419 whenLabel: "",
420 snoozedUntil: INDEFINITE_SNOOZE_UNTIL,
421 },
422 ]);
423 expect(snoozeWakeLabel(INDEFINITE_SNOOZE_UNTIL, { now: NOW })).toBe("∞");
424 });
425
426 it("lists custom presets soonest first and names the day when the label does not", () => {
427 // Wednesday 20:00.
428 expect(
429 menu(localDate(2026, 4, 8, 20), [
430 { kind: "at", day: "monday", time: "18:00" },
431 { kind: "at", day: "tomorrow", time: "21:00" },
432 { kind: "after", minutes: 360 },
433 { kind: "after", minutes: 180 },
434 ]),
435 ).toEqual(["In 3 hours 23:00", "In 6 hours Thu 2:00", "Tomorrow 21:00", "Next week Mon 18:00"]);
436 });
437
438 it("uses the German weekday with the caller's clock format", () => {
439 const options = {
440 locale: "de",
441 formatTime,
442 presets: [{ kind: "at", day: "monday", time: "18:00" }] as const,
443 };
444 const [preset] = resolveSnoozePresets(localDate(2026, 4, 8, 20), options);
445
446 expect(preset?.whenLabel).toMatch(/^Mo\.? 18:00$/);
447 });
448
449 it("drops a today preset once its time passes and moves a weekday on that day to next week", () => {
450 // Monday 18:30.
451 const now = localDate(2026, 4, 13, 18, 30);
452 const presets = resolveSnoozePresets(now, {
453 presets: [
454 { kind: "at", day: "today", time: "18:00" },
455 { kind: "at", day: "monday", time: "09:00" },
456 ],
457 });
458 expect(presets.map((preset) => preset.id)).toEqual(["at:monday:09:00", "indefinite"]);
459 expect(new Date(presets[0]!.snoozedUntil)).toEqual(localDate(2026, 4, 20, 9));
460 });
461
462 it("names the real day gap: a Monday option on Sunday is Tomorrow, a weekday a week out is Next", () => {
463 const theo: ReadonlyArray<SnoozePresetSetting> = [
464 { kind: "at", day: "tomorrow", time: "21:00" },
465 { kind: "at", day: "monday", time: "18:00" },
466 { kind: "at", day: "friday", time: "17:00" },
467 ];
468 // Sunday 14:00.
469 expect(menu(localDate(2026, 8, 30, 14), theo)).toEqual([
470 "Tomorrow 18:00",
471 "Tomorrow 21:00",
472 "Friday 17:00",
473 ]);
474 // Friday 10:00: today's 17:00 is a week away.
475 expect(menu(localDate(2026, 9, 4, 10), theo)).toEqual([
476 "Tomorrow 21:00",
477 "Next week Mon 18:00",
478 "Next Friday 17:00",
479 ]);
480 });
481
482 it("shows one row when two presets wake at the same time", () => {
483 // Sunday, so Tomorrow 9:00 and Next week 9:00 are the same Monday.
484 expect(menu(localDate(2026, 8, 30, 7, 1))).toEqual([
485 "In 1 hour 8:01",
486 "In 3 hours 10:01",
487 "This evening 18:00",
488 "Tomorrow 9:00",
489 ]);
490 });
491
492 it("treats a duration and a set time in the same minute as one row", () => {
493 const now = localDate(2026, 4, 8, 15);
494 now.setSeconds(25);
495 expect(
496 menu(now, [
497 { kind: "after", minutes: 180 },
498 { kind: "at", day: "today", time: "18:00" },
499 ]),
500 ).toEqual(["In 3 hours 18:00"]);
501 });
502});
503
504describe("pickSnoozePreset", () => {
505 it("starts a duration when it is picked, even when the menu merged it with a set time", () => {
506 const presets: ReadonlyArray<SnoozePresetSetting> = [
507 { kind: "at", day: "today", time: "18:30" },
508 { kind: "after", minutes: 180 },
509 ];
510 // At 15:00 the two differ; at 15:30 "In 3 hours" lands on 18:30 and the menu shows one row.
511 const shown = resolveSnoozePresets(localDate(2026, 4, 8, 15), { presets });
512 const picked = pickSnoozePreset({
513 shown,
514 id: "after:180",
515 now: localDate(2026, 4, 8, 15, 30),
516 presets,
517 });
518 expect(picked?.snoozedUntil).toBe(localDate(2026, 4, 8, 18, 30).toISOString());
519 });
520
521 it("keeps a set time's shown wake when the day changes while the menu is open", () => {
522 // Sunday 23:59: "Tomorrow" means Monday 9:00, even if the pick lands after midnight.
523 const shown = resolveSnoozePresets(localDate(2026, 8, 30, 23, 59));
524 const picked = pickSnoozePreset({
525 shown,
526 id: "at:tomorrow:09:00",
527 now: localDate(2026, 8, 31, 0, 1),
528 });
529 expect(picked?.snoozedUntil).toBe(localDate(2026, 8, 31, 9).toISOString());
530 });
531});
532
533describe("snoozeWakeLabel", () => {
534 it("reads a one-hour snooze as 1h on minute and live clocks", () => {
535 const wake = "2026-04-10T13:00:30.000Z";
536 expect(snoozeWakeLabel(wake, { now: NOW })).toBe("1h");
537 expect(snoozeWakeLabel(wake, { now: "2026-04-10T12:00:40.000Z" })).toBe("1h");
538 expect(snoozeWakeLabel("2026-04-10T15:00:30.000Z", { now: NOW })).toBe("3h");
539 expect(snoozeWakeLabel(wake, { now: "2026-04-10T12:01:00.000Z" })).toBe("59m");
540 expect(snoozeWakeLabel(wake, { now: "2026-04-10T13:00:10.000Z" })).toBe("1m");
541 expect(snoozeWakeLabel(wake, { now: "2026-04-10T13:00:30.000Z" })).toBe("now");
542 });
543});
544
545it("dismisses a wake at its timestamp without hiding a later wake", () => {
546 const firstWake = "2026-04-10T10:00:00.000Z";
547 const state = {
548 wokeAt: firstWake,
549 settled: false,
550 lastVisitedAt: null,
551 latestRunCompletedAt: null,
552 };
553 expect(isThreadWokeUnseen(state)).toBe(true);
554 expect(isThreadWokeUnseen({ ...state, lastVisitedAt: firstWake })).toBe(false);
555 expect(isThreadWokeUnseen({ ...state, lastVisitedAt: firstWake, wokeAt: NOW })).toBe(true);
556});