@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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