Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadSnoozed.test.ts

505 lines17.6 KB

1// @effect-diagnostics globalDate:off -- Tests exercise local calendar snooze boundaries.
2import * as DateTime from "effect/DateTime";
3import { 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 pickSnoozePreset,
14 resolveSnoozePresets,
15 threadRaisedHandWhileSnoozed,
16 threadWokeAt,
17 isThreadWokeUnseen,
18 type ThreadSnoozeShell,
19} from "./threadSettled.ts";
20​
21const NOW = "2026-04-10T12:00:00.000Z";
22const SNOOZED_AT = "2026-04-10T09:00:00.000Z";
23const FUTURE_WAKE = "2026-04-11T09:00:00.000Z";
24const PAST_WAKE = "2026-04-10T10:00:00.000Z";
25​
26function localDate(year: number, month: number, day: number, hour: number, minute = 0): Date {
27 return new Date(year, month - 1, day, hour, minute, 0, 0);
29​
30function makeShell(input: {
31 readonly snoozedUntil?: string | null;
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 const threadId = ThreadId.make("thread-1");
40 return {
41 snoozedUntil: input.snoozedUntil ?? null,
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
49 : {
50 threadId,
51 status: input.sessionStatus,
52 providerName: "Codex",
53 runtimeMode: "full-access",
54 activeTurnId: null,
55 lastError: input.sessionStatus === "error" ? "boom" : null,
56 updatedAt: "2026-04-10T11:00:00.000Z",
57 },
58 latestTurn:
59 input.turnCompletedAt === undefined
60 ? null
61 : {
62 turnId: TurnId.make("turn-1"),
63 state: "completed",
64 requestedAt: input.turnRequestedAt === undefined ? SNOOZED_AT : input.turnRequestedAt,
65 startedAt: null,
66 completedAt: input.turnCompletedAt,
67 assistantMessageId: null,
68 },
69 };
71​
72type QueuedTurnShell = Parameters<typeof hasQueuedTurnStart>[0];
73​
74function makeQueuedTurnShell(overrides: Partial<QueuedTurnShell> = {}): QueuedTurnShell {
75 return { latestUserMessageAt: null, latestTurn: null, session: null, ...overrides };
77​
78describe("effectiveSnoozed", () => {
79 it("never hides on malformed wake data", () => {
80 expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false);
81 });
82​
83 it("wakes early when the agent is blocked on the user", () => {
84 expect(
85 effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" }), {
86 now: NOW,
87 }),
88 ).toBe(false);
89 expect(
90 effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" }), {
91 now: NOW,
92 }),
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",
157 completedAt: "2026-04-10T08:00:00.000Z",
158 pending: undefined,
159 wokeAt: null,
160 },
161 {
162 reason: "failure without a completion timestamp",
163 completedAt: null,
164 pending: undefined,
165 wokeAt: null,
166 },
167 {
168 reason: "approval without a failure completion timestamp",
169 completedAt: null,
170 pending: "approval",
171 wokeAt: "2026-04-10T11:00:00.000Z",
172 },
173 {
174 reason: "fresh failure",
175 completedAt: "2026-04-10T10:00:00.000Z",
176 pending: undefined,
177 wokeAt: "2026-04-10T10:00:00.000Z",
178 },
179 {
180 reason: "approval after a stale failure",
181 completedAt: "2026-04-10T08:00:00.000Z",
182 pending: "approval",
183 wokeAt: "2026-04-10T11:00:00.000Z",
184 },
185 {
186 reason: "input after a stale failure",
187 completedAt: "2026-04-10T08:00:00.000Z",
188 pending: "user-input",
189 wokeAt: "2026-04-10T11:00:00.000Z",
190 },
191 ] as const)(
192 "uses the wake event time for $reason despite newer metadata",
193 ({ completedAt, pending, wokeAt }) => {
194 const shell: ThreadSnoozeShell = {
195 ...makeShell({ snoozedUntil: FUTURE_WAKE }),
196 hasPendingApprovals: pending === "approval",
197 hasPendingUserInput: pending === "user-input",
198 runtime: { status: "failed", updatedAt: "2026-04-10T11:00:00.000Z" },
199 latestRun: { status: "failed", requestedAt: "2026-04-10T07:00:00.000Z", completedAt },
200 };
201 expect(effectiveSnoozed(shell, { now: NOW })).toBe(wokeAt === null);
202 expect(threadWokeAt(shell, { now: NOW })).toBe(wokeAt);
203 },
204 );
205​
206 it("stays snoozed while the session keeps working — snooze never pauses the agent", () => {
207 expect(
208 effectiveSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "running" }), {
209 now: NOW,
210 }),
211 ).toBe(true);
212 });
213​
214 it("stays snoozed when a run requested after the snooze completes", () => {
215 const shell = {
216 ...makeShell({ snoozedUntil: FUTURE_WAKE }),
217 latestRun: {
218 status: "completed",
219 requestedAt: "2026-04-10T09:00:00.001Z",
220 startedAt: "2026-04-10T09:15:00.000Z",
221 completedAt: "2026-04-10T10:30:00.000Z",
222 },
223 };
224​
225 expect(effectiveSnoozed(shell, { now: NOW })).toBe(true);
226 expect(threadWokeAt(shell, { now: NOW })).toBe(null);
227 });
228});
229​
230describe("threadRaisedHandWhileSnoozed", () => {
231 it("is true for approvals, input, and failures", () => {
232 expect(
233 threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "approval" })),
234 ).toBe(true);
235 expect(
236 threadRaisedHandWhileSnoozed(makeShell({ snoozedUntil: FUTURE_WAKE, pending: "user-input" })),
237 ).toBe(true);
238 expect(
239 threadRaisedHandWhileSnoozed(
240 makeShell({ snoozedUntil: FUTURE_WAKE, sessionStatus: "error" }),
241 ),
242 ).toBe(true);
243 });
244});
245​
246describe("canSnooze", () => {
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);
251 expect(
252 canSnooze(
253 { ...makeShell({ pending: "user-input" }), latestUserMessageAt: null },
254 { now: NOW },
255 ),
256 ).toBe(true);
257 expect(
258 canSnooze(
259 { ...makeShell({}), latestUserMessageAt: null, pendingSubagentRequest: "approval" },
260 { now: NOW },
261 ),
262 ).toBe(false);
263 });
264​
265 it("refuses a queued turn start — same invisible-pending-work rule as settle", () => {
266 expect(
267 canSnooze(
268 { ...makeShell({}), latestUserMessageAt: "2026-04-10T11:59:30.000Z" },
269 { now: NOW },
270 ),
271 ).toBe(false);
272 expect(
273 canSnooze(
274 { ...makeShell({}), latestUserMessageAt: "2026-04-10T11:00:00.000Z" },
275 { now: NOW },
276 ),
277 ).toBe(true);
278 });
279});
280​
281describe("hasQueuedTurnStart", () => {
282 it("clears queued state when a turn adopts the message or the session fails", () => {
283 const messageAt = "2026-04-10T11:59:00.000Z";
284 const adopted = makeQueuedTurnShell({
285 latestUserMessageAt: messageAt,
286 latestTurn: {
287 turnId: TurnId.make("turn-adopted"),
288 state: "running",
289 requestedAt: messageAt,
290 startedAt: null,
291 completedAt: null,
292 assistantMessageId: null,
293 },
294 });
295 const failed = makeQueuedTurnShell({
296 latestUserMessageAt: messageAt,
297 session: {
298 threadId: ThreadId.make("thread-failed"),
299 status: "error",
300 providerName: "Codex",
301 runtimeMode: "full-access",
302 activeTurnId: null,
303 lastError: "failed",
304 updatedAt: NOW,
305 },
306 });
307 expect(hasQueuedTurnStart(adopted, { now: NOW })).toBe(false);
308 expect(hasQueuedTurnStart(failed, { now: NOW })).toBe(false);
309 });
310});
311​
312describe("threadWokeAt", () => {
313 it("reports the timer wake even after an already-requested run completes", () => {
314 expect(threadWokeAt(makeShell({ snoozedUntil: PAST_WAKE }), { now: NOW })).toBe(PAST_WAKE);
315 const shell = makeShell({
316 snoozedUntil: PAST_WAKE,
317 turnCompletedAt: "2026-04-10T09:30:00.000Z",
318 });
319 expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
320 expect(threadWokeAt(shell, { now: NOW })).toBe(PAST_WAKE);
321 });
322​
323 it.each([
324 { reason: "failure", sessionStatus: "error" },
325 { reason: "approval", sessionStatus: "ready", pending: "approval" },
326 { reason: "user input", sessionStatus: "ready", pending: "user-input" },
327 ] as const)("reports $reason activity instead of an already-requested completion", (activity) => {
328 const shell = makeShell({
329 ...activity,
330 snoozedUntil: FUTURE_WAKE,
331 turnCompletedAt: "2026-04-10T10:30:00.000Z",
332 });
333 expect(effectiveSnoozed(shell, { now: NOW })).toBe(false);
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 }),
379 runtime: { status: "failed", updatedAt: "2026-04-10T11:00:00.000Z" },
380 latestRun: {
381 status: "failed",
382 requestedAt: "2026-04-10T09:15:00.000Z",
383 completedAt: "2026-04-10T09:30:00.000Z",
384 },
385 };
386 expect(threadWokeAt(shell, { now: NOW })).toBe("2026-04-10T09:30:00.000Z");
387 });
388});
389​
390describe("resolveSnoozePresets", () => {
391 const formatTime = (date: Date) =>
392 `${date.getHours()}:${String(date.getMinutes()).padStart(2, "0")}`;
393 const menu = (now: Date, presets?: ReadonlyArray<SnoozePresetSetting>) =>
394 resolveSnoozePresets(now, { formatTime, ...(presets ? { presets } : {}) }).map(
395 (preset) => `${preset.label} ${preset.whenLabel}`,
396 );
397​
398 it("lists custom presets soonest first and names the day when the label does not", () => {
399 // Wednesday 20:00.
400 expect(
401 menu(localDate(2026, 4, 8, 20), [
402 { kind: "at", day: "monday", time: "18:00" },
403 { kind: "at", day: "tomorrow", time: "21:00" },
404 { kind: "after", minutes: 360 },
405 { kind: "after", minutes: 180 },
406 ]),
407 ).toEqual(["In 3 hours 23:00", "In 6 hours Thu 2:00", "Tomorrow 21:00", "Next week Mon 18:00"]);
408 });
409​
410 it("drops a today preset once its time passes and moves a weekday on that day to next week", () => {
411 // Monday 18:30.
412 const now = localDate(2026, 4, 13, 18, 30);
413 const presets = resolveSnoozePresets(now, {
414 presets: [
415 { kind: "at", day: "today", time: "18:00" },
416 { kind: "at", day: "monday", time: "09:00" },
417 ],
418 });
419 expect(presets.map((preset) => preset.id)).toEqual(["at:monday:09:00"]);
420 expect(new Date(presets[0]!.snoozedUntil)).toEqual(localDate(2026, 4, 20, 9));
421 });
422​
423 it("names the real day gap: a Monday option on Sunday is Tomorrow, a weekday a week out is Next", () => {
424 const theo: ReadonlyArray<SnoozePresetSetting> = [
425 { kind: "at", day: "tomorrow", time: "21:00" },
426 { kind: "at", day: "monday", time: "18:00" },
427 { kind: "at", day: "friday", time: "17:00" },
428 ];
429 // Sunday 14:00.
430 expect(menu(localDate(2026, 8, 30, 14), theo)).toEqual([
431 "Tomorrow 18:00",
432 "Tomorrow 21:00",
433 "Friday 17:00",
434 ]);
435 // Friday 10:00: today's 17:00 is a week away.
436 expect(menu(localDate(2026, 9, 4, 10), theo)).toEqual([
437 "Tomorrow 21:00",
438 "Next week Mon 18:00",
439 "Next Friday 17:00",
440 ]);
441 });
442​
443 it("shows one row when two presets wake at the same time", () => {
444 // Sunday, so Tomorrow 9:00 and Next week 9:00 are the same Monday.
445 expect(menu(localDate(2026, 8, 30, 7, 1))).toEqual([
446 "In 1 hour 8:01",
447 "In 3 hours 10:01",
448 "This evening 18:00",
449 "Tomorrow 9:00",
450 ]);
451 });
452​
453 it("treats a duration and a set time in the same minute as one row", () => {
454 const now = localDate(2026, 4, 8, 15);
455 now.setSeconds(25);
456 expect(
457 menu(now, [
458 { kind: "after", minutes: 180 },
459 { kind: "at", day: "today", time: "18:00" },
460 ]),
461 ).toEqual(["In 3 hours 18:00"]);
462 });
463});
464​
465describe("pickSnoozePreset", () => {
466 it("starts a duration when it is picked, even when the menu merged it with a set time", () => {
467 const presets: ReadonlyArray<SnoozePresetSetting> = [
468 { kind: "at", day: "today", time: "18:30" },
469 { kind: "after", minutes: 180 },
470 ];
471 // At 15:00 the two differ; at 15:30 "In 3 hours" lands on 18:30 and the menu shows one row.
472 const shown = resolveSnoozePresets(localDate(2026, 4, 8, 15), { presets });
473 const picked = pickSnoozePreset({
474 shown,
475 id: "after:180",
476 now: localDate(2026, 4, 8, 15, 30),
477 presets,
478 });
479 expect(picked?.snoozedUntil).toBe(localDate(2026, 4, 8, 18, 30).toISOString());
480 });
481​
482 it("keeps a set time's shown wake when the day changes while the menu is open", () => {
483 // Sunday 23:59: "Tomorrow" means Monday 9:00, even if the pick lands after midnight.
484 const shown = resolveSnoozePresets(localDate(2026, 8, 30, 23, 59));
485 const picked = pickSnoozePreset({
486 shown,
487 id: "at:tomorrow:09:00",
488 now: localDate(2026, 8, 31, 0, 1),
489 });
490 expect(picked?.snoozedUntil).toBe(localDate(2026, 8, 31, 9).toISOString());
491 });
492});
493​
494it("dismisses a wake at its timestamp without hiding a later wake", () => {
495 const firstWake = "2026-04-10T10:00:00.000Z";
496 const state = {
497 wokeAt: firstWake,
498 settled: false,
499 lastVisitedAt: null,
500 latestRunCompletedAt: null,
501 };
502 expect(isThreadWokeUnseen(state)).toBe(true);
503 expect(isThreadWokeUnseen({ ...state, lastVisitedAt: firstWake })).toBe(false);
504 expect(isThreadWokeUnseen({ ...state, lastVisitedAt: firstWake, wokeAt: NOW })).toBe(true);
505});