Open History to see the last commit
1// @effect-diagnostics globalDate:off -- UI snooze presets use local calendar boundaries and Intl labels.
2import * as DateTime from "effect/DateTime";
3import { DEFAULT_SNOOZE_PRESETS, type SnoozePresetSetting } from "@t3tools/contracts/settings";
4
5import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
6
7interface SettlementRunLike {
8 readonly turnId?: unknown;
9 readonly assistantMessageId?: unknown;
10 readonly status?: string;
11 readonly state?: string;
12 readonly requestedAt?: string | null;
13 readonly startedAt?: string | null;
14 readonly completedAt?: string | null;
15}
16
17interface SettlementRuntimeLike {
18 readonly threadId?: unknown;
19 readonly providerName?: unknown;
20 readonly runtimeMode?: unknown;
21 readonly activeTurnId?: unknown;
22 readonly lastError?: unknown;
23 readonly status: string;
24 readonly updatedAt?: string;
25}
26
27interface QueuedThreadShell {
28 readonly latestUserMessageAt?: string | null;
29 readonly latestTurn?: SettlementRunLike | null;
30 readonly latestRun?: SettlementRunLike | null;
31 readonly session?: SettlementRuntimeLike | null;
32 readonly runtime?: SettlementRuntimeLike | null;
33}
34
35/**
36 * Failed starts and stale shells from older servers can leave user messages unadopted.
37 * Bound the pending window so those threads can eventually settle.
38 */
39export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
40const DAY_MS = 24 * 60 * 60 * 1_000;
41
42export function hasQueuedTurnStart(
43 shell: QueuedThreadShell,
44 options: { readonly now: string },
45): boolean {
46 if (
47 shell.runtime?.status === "preparing" ||
48 shell.runtime?.status === "queued" ||
49 shell.runtime?.status === "starting"
50 ) {
51 return true;
52 }
53 if (shell.latestUserMessageAt == null) return false;
54 if (shell.session?.status === "error") return false;
55 const messageAt = Date.parse(shell.latestUserMessageAt);
56 if (Number.isNaN(messageAt)) return false;
57 const nowMs = Date.parse(options.now);
58 if (Number.isNaN(nowMs)) return false;
59 // Bounded on both sides: message timestamps originate on whichever device
60 // sent the message, so a clock ahead of this one yields a negative age
61 // that would otherwise hold the queued state for the whole skew. Mirrors
62 // the decider's guard.
63 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
64 const turn = shell.latestRun ?? shell.latestTurn ?? null;
65 if (turn === null) return true;
66 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
67 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
68 );
69}
70
71export interface ThreadSnoozeShell extends QueuedThreadShell {
72 readonly source?: Pick<EnvironmentThreadShell["source"], "pendingRuntimeRequest">;
73 readonly snoozedUntil?: string | null;
74 readonly snoozedAt?: string | null;
75 readonly hasPendingApprovals: boolean;
76 readonly hasPendingUserInput: boolean;
77 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
78 readonly pendingGuestMessageCount?: number;
79}
80
81/**
82 * Only a request for the user or a fresh failure ends a snooze early. Completed runs never do:
83 * a snoozed long-running thread keeps waking itself for background work and stays hidden
84 * until its timer.
85 */
86export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
87 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
88 if (shell.source?.pendingRuntimeRequest != null) return true;
89 if (shell.pendingSubagentRequest != null) return true;
90 if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
91 const failedAt = failureEdgeAt(shell);
92 return (
93 failedAt !== undefined &&
94 (shell.snoozedAt == null ||
95 (failedAt != null && Date.parse(failedAt) > Date.parse(shell.snoozedAt)))
96 );
97}
98
99// V2 runtime.updatedAt includes metadata writes; prefer the failed run's completion.
100// Legacy sessions only expose the runtime timestamp.
101function failureEdgeAt(shell: ThreadSnoozeShell): string | null | undefined {
102 const runtime = shell.runtime ?? shell.session ?? null;
103 if (runtime?.status !== "error" && runtime?.status !== "failed") return undefined;
104 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
105 if (latestRun?.status === "failed" && latestRun.completedAt != null) {
106 return latestRun.completedAt;
107 }
108 return runtime.updatedAt ?? null;
109}
110
111export function canSnooze(
112 shell: Pick<
113 ThreadSnoozeShell,
114 | "hasPendingApprovals"
115 | "hasPendingUserInput"
116 | "pendingSubagentRequest"
117 | "pendingGuestMessageCount"
118 | "latestUserMessageAt"
119 | "latestTurn"
120 | "latestRun"
121 | "session"
122 | "runtime"
123 | "source"
124 >,
125 options: { readonly now: string },
126): boolean {
127 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
128 // The server rejects snoozing even for nonblocking questions.
129 if (shell.source?.pendingRuntimeRequest != null) return false;
130 if (shell.pendingSubagentRequest != null) return false;
131 // A waiting guest message would wake it at once.
132 if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
133 if (hasQueuedTurnStart(shell, options)) return false;
134 return true;
135}
136
137export function effectiveSnoozed(
138 shell: ThreadSnoozeShell,
139 options: { readonly now: string },
140): boolean {
141 if (shell.snoozedUntil == null) return false;
142 const wakeAtMs = Date.parse(shell.snoozedUntil);
143 if (Number.isNaN(wakeAtMs)) return false;
144 if (wakeAtMs <= Date.parse(options.now)) return false;
145 return !threadRaisedHandWhileSnoozed(shell);
146}
147
148export function threadWokeAt(
149 shell: ThreadSnoozeShell,
150 options: { readonly now: string },
151): string | null {
152 if (shell.snoozedUntil == null) return null;
153 const wakeAtMs = Date.parse(shell.snoozedUntil);
154 if (Number.isNaN(wakeAtMs)) return null;
155 // An early hand-raise wake stays authoritative even after the scheduled
156 // wake time passes: reporting snoozedUntil then would resurface a Woke
157 // indicator the user already cleared by visiting (snoozedUntil is newer
158 // than that visit's lastVisitedAt).
159 if (threadRaisedHandWhileSnoozed(shell)) {
160 // An old failure must not replace the activity time of an approval or input wake.
161 const failedAt = failureEdgeAt(shell);
162 if (
163 failedAt != null &&
164 (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt))
165 ) {
166 return failedAt;
167 }
168 const runtime = shell.runtime ?? shell.session ?? null;
169 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
170 }
171 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
172}
173
174const HOUR_MS = 60 * 60 * 1_000;
175
176const WEEKDAY_INDEX = {
177 sunday: 0,
178 monday: 1,
179 tuesday: 2,
180 wednesday: 3,
181 thursday: 4,
182 friday: 5,
183 saturday: 6,
184} as const;
185
186export interface SnoozePreset {
187 readonly id: string;
188 readonly label: string;
189 readonly whenLabel: string;
190 readonly snoozedUntil: string;
191}
192
193export interface SnoozePresetOptions {
194 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
195 readonly formatTime?: (date: Date) => string;
196}
197
198function snoozeTimeOfDayLabel(date: Date): string {
199 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
200}
201
202// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
203// land on the wrong local day across DST transitions (a spring-forward day
204// is 23 hours, so 23:30 + 24h skips the whole next day).
205function addSnoozeDays(base: Date, days: number): Date {
206 const next = DateTime.toDate(DateTime.makeUnsafe(base));
207 next.setDate(next.getDate() + days);
208 return next;
209}
210
211function pluralize(count: number, unit: string): string {
212 return `${count} ${unit}${count === 1 ? "" : "s"}`;
213}
214
215/** "3 hours", "90 minutes", "2 days": the largest unit that divides evenly. */
216function formatSnoozeDuration(minutes: number): string {
217 if (minutes % (24 * 60) === 0) return pluralize(minutes / (24 * 60), "day");
218 if (minutes % 60 === 0) return pluralize(minutes / 60, "hour");
219 return pluralize(minutes, "minute");
220}
221
222function capitalize(word: string): string {
223 return word[0]!.toUpperCase() + word.slice(1);
224}
225
226function snoozePresetDaysAhead(
227 setting: Extract<SnoozePresetSetting, { kind: "at" }>,
228 now: Date,
229): number {
230 if (setting.day === "today") return 0;
231 if (setting.day === "tomorrow") return 1;
232 return (WEEKDAY_INDEX[setting.day] - now.getDay() + 7) % 7 || 7;
233}
234
235/** Labels follow the actual day gap, so a Monday option on a Sunday reads "Tomorrow". */
236function snoozePresetLabel(setting: SnoozePresetSetting, daysAhead: number): string {
237 if (setting.kind === "after") return `In ${formatSnoozeDuration(setting.minutes)}`;
238 if (daysAhead === 0) {
239 const hour = Number(setting.time.slice(0, 2));
240 return hour < 12 ? "This morning" : hour < 17 ? "This afternoon" : "This evening";
241 }
242 if (daysAhead === 1) return "Tomorrow";
243 if (setting.day === "monday") return "Next week";
244 return daysAhead === 7 ? `Next ${capitalize(setting.day)}` : capitalize(setting.day);
245}
246
247export function snoozePresetId(setting: SnoozePresetSetting): string {
248 return setting.kind === "after"
249 ? `after:${setting.minutes}`
250 : `at:${setting.day}:${setting.time}`;
251}
252
253export function resolveSnoozePreset(
254 setting: SnoozePresetSetting,
255 now: Date,
256 formatTime: (date: Date) => string = snoozeTimeOfDayLabel,
257): SnoozePreset | null {
258 let wake: Date;
259 let daysAhead = 0;
260 if (setting.kind === "after") {
261 wake = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + setting.minutes * 60_000));
262 } else {
263 daysAhead = snoozePresetDaysAhead(setting, now);
264 wake = addSnoozeDays(now, daysAhead);
265 wake.setHours(Number(setting.time.slice(0, 2)), Number(setting.time.slice(3)), 0, 0);
266 // A today option whose time has passed is left out until tomorrow.
267 if (wake.getTime() <= now.getTime()) return null;
268 }
269 const label = snoozePresetLabel(setting, daysAhead);
270 // Durations and "Next week" don't name the wake day, so a wake on another day shows it.
271 const labelNamesDay = setting.kind === "at" && label !== "Next week";
272 const time = formatTime(wake);
273 return {
274 id: snoozePresetId(setting),
275 label,
276 whenLabel:
277 labelNamesDay || wake.toDateString() === now.toDateString()
278 ? time
279 : `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}`,
280 snoozedUntil: wake.toISOString(),
281 };
282}
283
284/** The snooze menu: soonest first, one row per wake minute. */
285export function resolveSnoozePresets(
286 now: Date,
287 options: SnoozePresetOptions = {},
288): ReadonlyArray<SnoozePreset> {
289 // By minute, so a duration (which keeps the clock's seconds) and a set time in the same
290 // minute tie, and the stable sort keeps whichever comes first in settings.
291 const wakeMinute = (preset: SnoozePreset) => Math.floor(Date.parse(preset.snoozedUntil) / 60_000);
292 const seen = new Set<number>();
293 return (
294 (options.presets ?? DEFAULT_SNOOZE_PRESETS)
295 .flatMap((setting) => resolveSnoozePreset(setting, now, options.formatTime) ?? [])
296 // flatMap returned a new array; Hermes has no `toSorted`.
297 .sort((a, b) => wakeMinute(a) - wakeMinute(b))
298 .filter((preset) => {
299 if (seen.has(wakeMinute(preset))) return false;
300 seen.add(wakeMinute(preset));
301 return true;
302 })
303 );
304}
305
306/**
307 * A menu choice as picked. A duration re-resolves from its setting (not the deduped menu) so it
308 * starts at selection. A set time keeps the shown wake, which a day change would otherwise shift.
309 */
310export function pickSnoozePreset(input: {
311 readonly shown: ReadonlyArray<SnoozePreset>;
312 readonly id: string;
313 readonly now: Date;
314 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
315 readonly formatTime?: (date: Date) => string;
316}): SnoozePreset | undefined {
317 const original = input.shown.find((preset) => preset.id === input.id);
318 const ahead =
319 original && Date.parse(original.snoozedUntil) > input.now.getTime() ? original : undefined;
320 const setting = (input.presets ?? DEFAULT_SNOOZE_PRESETS).find(
321 (candidate) => candidate.kind === "after" && snoozePresetId(candidate) === input.id,
322 );
323 return (setting && resolveSnoozePreset(setting, input.now, input.formatTime)) ?? ahead;
324}
325
326export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
327 const wakeMs = Date.parse(snoozedUntil);
328 const nowMs = Date.parse(options.now);
329 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
330 const remainingMs = wakeMs - nowMs;
331 if (remainingMs <= 0) return "now";
332 if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
333 if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
334 return `${Math.ceil(remainingMs / DAY_MS)}d`;
335}
336
337export type CustomSnoozeInput =
338 | { readonly mode: "date"; readonly date: string; readonly time: string }
339 | {
340 readonly mode: "duration";
341 readonly amount: string;
342 readonly unit: "minutes" | "hours" | "days";
343 };
344
345export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
346 let wake: Date;
347 if (input.mode === "duration") {
348 const amount = Number(input.amount);
349 if (!Number.isFinite(amount) || amount <= 0) return null;
350 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
351 wake = new Date(now.getTime() + amount * unitMs);
352 } else {
353 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
354 wake = new Date(`${input.date}T${input.time}:00`);
355 // Reject rolled-over dates and nonexistent local times during DST changes.
356 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
357 }
358 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
359 ? wake.toISOString()
360 : null;
361}
362
363export function localSnoozeDate(date: Date): string {
364 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
365}
366
367export function localSnoozeTime(date: Date): string {
368 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
369}
370
371/**
372 * Whether a woken thread woke after the user last saw it. A run that completed
373 * after the last visit counts as seeing it, since the user watched it finish.
374 */
375export function isThreadWokeUnseen(input: {
376 readonly wokeAt: string | null;
377 readonly settled: boolean;
378 readonly lastVisitedAt: string | null | undefined;
379 readonly latestRunCompletedAt: string | null;
380}): boolean {
381 if (input.wokeAt === null || input.settled) return false;
382 const wokeAtMs = Date.parse(input.wokeAt);
383 if (Number.isNaN(wokeAtMs)) return false;
384 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
385 .map((value) => (value ? Date.parse(value) : NaN))
386 .filter((ms) => !Number.isNaN(ms));
387 return seenAt.every((ms) => ms < wokeAtMs);
388}