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";
3
4import type { PendingSubagentRequest } from "./models.ts";
5
6interface SettlementRunLike {
7 readonly turnId?: unknown;
8 readonly assistantMessageId?: unknown;
9 readonly status?: string;
10 readonly state?: string;
11 readonly requestedAt?: string | null;
12 readonly startedAt?: string | null;
13 readonly completedAt?: string | null;
14}
15
16interface SettlementRuntimeLike {
17 readonly threadId?: unknown;
18 readonly providerName?: unknown;
19 readonly runtimeMode?: unknown;
20 readonly activeTurnId?: unknown;
21 readonly lastError?: unknown;
22 readonly status: string;
23 readonly updatedAt?: string;
24}
25
26interface QueuedThreadShell {
27 readonly latestUserMessageAt?: string | null;
28 readonly latestTurn?: SettlementRunLike | null;
29 readonly latestRun?: SettlementRunLike | null;
30 readonly session?: SettlementRuntimeLike | null;
31 readonly runtime?: SettlementRuntimeLike | null;
32}
33
34/**
35 * A queued turn start lives for at most this long: session adoption takes
36 * seconds, so a user message still unadopted after the grace window is a
37 * failed start (or stale data — shells from older servers can carry user
38 * messages with no latestTurn at all), not pending work. Without this bound
39 * such threads would be permanently unsettleable.
40 */
41export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
42const DAY_MS = 24 * 60 * 60 * 1_000;
43
44export function hasQueuedTurnStart(
45 shell: QueuedThreadShell,
46 options: { readonly now: string },
47): boolean {
48 if (
49 shell.runtime?.status === "preparing" ||
50 shell.runtime?.status === "queued" ||
51 shell.runtime?.status === "starting"
52 ) {
53 return true;
54 }
55 if (shell.latestUserMessageAt == null) return false;
56 if (shell.session?.status === "error") return false;
57 const messageAt = Date.parse(shell.latestUserMessageAt);
58 if (Number.isNaN(messageAt)) return false;
59 const nowMs = Date.parse(options.now);
60 if (Number.isNaN(nowMs)) return false;
61 // Bounded on both sides: message timestamps originate on whichever device
62 // sent the message, so a clock ahead of this one yields a negative age
63 // that would otherwise hold the queued state for the whole skew. Mirrors
64 // the decider's guard.
65 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
66 const turn = shell.latestRun ?? shell.latestTurn ?? null;
67 if (turn === null) return true;
68 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
69 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
70 );
71}
72
73export interface ThreadSnoozeShell extends QueuedThreadShell {
74 readonly snoozedUntil?: string | null;
75 readonly snoozedAt?: string | null;
76 readonly hasPendingApprovals: boolean;
77 readonly hasPendingUserInput: boolean;
78 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
79}
80
81export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
82 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
83 if (shell.pendingSubagentRequest != null) return true;
84 const runtime = shell.runtime ?? shell.session ?? null;
85 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
86 if (
87 (runtime?.status === "error" || runtime?.status === "failed") &&
88 (shell.snoozedAt == null ||
89 (runtime.updatedAt != null && Date.parse(runtime.updatedAt) > Date.parse(shell.snoozedAt)))
90 ) {
91 return true;
92 }
93 if (
94 shell.snoozedAt != null &&
95 (latestRun?.state === "completed" || latestRun?.status === "completed") &&
96 latestRun.completedAt != null &&
97 Date.parse(latestRun.completedAt) > Date.parse(shell.snoozedAt)
98 ) {
99 return true;
100 }
101 return false;
102}
103
104export function canSnooze(
105 shell: Pick<
106 ThreadSnoozeShell,
107 | "hasPendingApprovals"
108 | "hasPendingUserInput"
109 | "pendingSubagentRequest"
110 | "latestUserMessageAt"
111 | "latestTurn"
112 | "latestRun"
113 | "session"
114 | "runtime"
115 >,
116 options: { readonly now: string },
117): boolean {
118 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
119 if (shell.pendingSubagentRequest != null) return false;
120 if (hasQueuedTurnStart(shell, options)) return false;
121 return true;
122}
123
124export function effectiveSnoozed(
125 shell: ThreadSnoozeShell,
126 options: { readonly now: string },
127): boolean {
128 if (shell.snoozedUntil == null) return false;
129 const wakeAtMs = Date.parse(shell.snoozedUntil);
130 if (Number.isNaN(wakeAtMs)) return false;
131 if (wakeAtMs <= Date.parse(options.now)) return false;
132 return !threadRaisedHandWhileSnoozed(shell);
133}
134
135export function threadWokeAt(
136 shell: ThreadSnoozeShell,
137 options: { readonly now: string },
138): string | null {
139 if (shell.snoozedUntil == null) return null;
140 const wakeAtMs = Date.parse(shell.snoozedUntil);
141 if (Number.isNaN(wakeAtMs)) return null;
142 // An early hand-raise wake stays authoritative even after the scheduled
143 // wake time passes: reporting snoozedUntil then would resurface a Woke
144 // indicator the user already cleared by visiting (snoozedUntil is newer
145 // than that visit's lastVisitedAt).
146 if (threadRaisedHandWhileSnoozed(shell)) {
147 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
148 const runtime = shell.runtime ?? shell.session ?? null;
149 if (
150 shell.snoozedAt != null &&
151 (latestRun?.state === "completed" || latestRun?.status === "completed") &&
152 latestRun.completedAt != null &&
153 Date.parse(latestRun.completedAt) > Date.parse(shell.snoozedAt)
154 ) {
155 return latestRun.completedAt;
156 }
157 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
158 }
159 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
160}
161
162const HOUR_MS = 60 * 60 * 1_000;
163const EVENING_HOUR = 18;
164const MORNING_HOUR = 9;
165
166export type SnoozePresetId = "hour" | "three-hours" | "evening" | "tomorrow" | "next-week";
167
168export interface SnoozePreset {
169 readonly id: SnoozePresetId;
170 readonly label: string;
171 readonly whenLabel: string;
172 readonly snoozedUntil: string;
173}
174
175function snoozeTimeOfDayLabel(date: Date): string {
176 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
177}
178
179function snoozeAtHour(base: Date, hour: number): Date {
180 const next = DateTime.toDate(DateTime.makeUnsafe(base));
181 next.setHours(hour, 0, 0, 0);
182 return next;
183}
184
185// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
186// land on the wrong local day across DST transitions (a spring-forward day
187// is 23 hours, so 23:30 + 24h skips the whole next day).
188function addSnoozeDays(base: Date, days: number): Date {
189 const next = DateTime.toDate(DateTime.makeUnsafe(base));
190 next.setDate(next.getDate() + days);
191 return next;
192}
193
194export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
195 const inAnHour = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + HOUR_MS));
196 const inThreeHours = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + 3 * HOUR_MS));
197 const presets: SnoozePreset[] = [
198 {
199 id: "hour",
200 label: "In 1 hour",
201 whenLabel: snoozeTimeOfDayLabel(inAnHour),
202 snoozedUntil: inAnHour.toISOString(),
203 },
204 {
205 id: "three-hours",
206 label: "In 3 hours",
207 whenLabel: snoozeTimeOfDayLabel(inThreeHours),
208 snoozedUntil: inThreeHours.toISOString(),
209 },
210 ];
211
212 const evening = snoozeAtHour(now, EVENING_HOUR);
213 if (evening.getTime() - now.getTime() > HOUR_MS) {
214 presets.push({
215 id: "evening",
216 label: "This evening",
217 whenLabel: snoozeTimeOfDayLabel(evening),
218 snoozedUntil: evening.toISOString(),
219 });
220 }
221
222 const tomorrow = snoozeAtHour(addSnoozeDays(now, 1), MORNING_HOUR);
223 presets.push({
224 id: "tomorrow",
225 label: "Tomorrow",
226 whenLabel: snoozeTimeOfDayLabel(tomorrow),
227 snoozedUntil: tomorrow.toISOString(),
228 });
229
230 const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
231 const nextWeek = snoozeAtHour(addSnoozeDays(now, daysUntilMonday), MORNING_HOUR);
232 if (nextWeek.getTime() !== tomorrow.getTime()) {
233 presets.push({
234 id: "next-week",
235 label: "Next week",
236 whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${snoozeTimeOfDayLabel(nextWeek)}`,
237 snoozedUntil: nextWeek.toISOString(),
238 });
239 }
240
241 return presets;
242}
243
244export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
245 const wakeMs = Date.parse(snoozedUntil);
246 const nowMs = Date.parse(options.now);
247 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
248 const remainingMs = wakeMs - nowMs;
249 if (remainingMs <= 0) return "now";
250 if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
251 if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
252 return `${Math.ceil(remainingMs / DAY_MS)}d`;
253}
254
255export type CustomSnoozeInput =
256 | { readonly mode: "date"; readonly date: string; readonly time: string }
257 | {
258 readonly mode: "duration";
259 readonly amount: string;
260 readonly unit: "minutes" | "hours" | "days";
261 };
262
263export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
264 let wake: Date;
265 if (input.mode === "duration") {
266 const amount = Number(input.amount);
267 if (!Number.isFinite(amount) || amount <= 0) return null;
268 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
269 wake = new Date(now.getTime() + amount * unitMs);
270 } else {
271 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
272 wake = new Date(`${input.date}T${input.time}:00`);
273 // Reject rolled-over dates and nonexistent local times during DST changes.
274 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
275 }
276 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
277 ? wake.toISOString()
278 : null;
279}
280
281export function localSnoozeDate(date: Date): string {
282 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
283}
284
285export function localSnoozeTime(date: Date): string {
286 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
287}