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 latestRun = shell.latestRun ?? shell.latestTurn ?? null;
85 const failedAt = failureEdgeAt(shell);
86 if (
87 failedAt !== undefined &&
88 (shell.snoozedAt == null ||
89 (failedAt != null && Date.parse(failedAt) > 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
104// V2 runtime.updatedAt includes metadata writes; prefer the failed run's completion.
105// Legacy sessions only expose the runtime timestamp.
106function failureEdgeAt(shell: ThreadSnoozeShell): string | null | undefined {
107 const runtime = shell.runtime ?? shell.session ?? null;
108 if (runtime?.status !== "error" && runtime?.status !== "failed") return undefined;
109 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
110 if (latestRun?.status === "failed" && latestRun.completedAt != null) {
111 return latestRun.completedAt;
112 }
113 return runtime.updatedAt ?? null;
114}
115
116export function canSnooze(
117 shell: Pick<
118 ThreadSnoozeShell,
119 | "hasPendingApprovals"
120 | "hasPendingUserInput"
121 | "pendingSubagentRequest"
122 | "latestUserMessageAt"
123 | "latestTurn"
124 | "latestRun"
125 | "session"
126 | "runtime"
127 >,
128 options: { readonly now: string },
129): boolean {
130 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
131 if (shell.pendingSubagentRequest != null) return false;
132 if (hasQueuedTurnStart(shell, options)) return false;
133 return true;
134}
135
136export function effectiveSnoozed(
137 shell: ThreadSnoozeShell,
138 options: { readonly now: string },
139): boolean {
140 if (shell.snoozedUntil == null) return false;
141 const wakeAtMs = Date.parse(shell.snoozedUntil);
142 if (Number.isNaN(wakeAtMs)) return false;
143 if (wakeAtMs <= Date.parse(options.now)) return false;
144 return !threadRaisedHandWhileSnoozed(shell);
145}
146
147export function threadWokeAt(
148 shell: ThreadSnoozeShell,
149 options: { readonly now: string },
150): string | null {
151 if (shell.snoozedUntil == null) return null;
152 const wakeAtMs = Date.parse(shell.snoozedUntil);
153 if (Number.isNaN(wakeAtMs)) return null;
154 // An early hand-raise wake stays authoritative even after the scheduled
155 // wake time passes: reporting snoozedUntil then would resurface a Woke
156 // indicator the user already cleared by visiting (snoozedUntil is newer
157 // than that visit's lastVisitedAt).
158 if (threadRaisedHandWhileSnoozed(shell)) {
159 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
160 if (
161 shell.snoozedAt != null &&
162 (latestRun?.state === "completed" || latestRun?.status === "completed") &&
163 latestRun.completedAt != null &&
164 Date.parse(latestRun.completedAt) > Date.parse(shell.snoozedAt)
165 ) {
166 return latestRun.completedAt;
167 }
168 // An old failure must not replace the activity time of an approval or input wake.
169 const failedAt = failureEdgeAt(shell);
170 if (
171 failedAt != null &&
172 (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt))
173 ) {
174 return failedAt;
175 }
176 const runtime = shell.runtime ?? shell.session ?? null;
177 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
178 }
179 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
180}
181
182const HOUR_MS = 60 * 60 * 1_000;
183const EVENING_HOUR = 18;
184const MORNING_HOUR = 9;
185
186export type SnoozePresetId = "hour" | "three-hours" | "evening" | "tomorrow" | "next-week";
187
188export interface SnoozePreset {
189 readonly id: SnoozePresetId;
190 readonly label: string;
191 readonly whenLabel: string;
192 readonly snoozedUntil: string;
193}
194
195function snoozeTimeOfDayLabel(date: Date): string {
196 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
197}
198
199function snoozeAtHour(base: Date, hour: number): Date {
200 const next = DateTime.toDate(DateTime.makeUnsafe(base));
201 next.setHours(hour, 0, 0, 0);
202 return next;
203}
204
205// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
206// land on the wrong local day across DST transitions (a spring-forward day
207// is 23 hours, so 23:30 + 24h skips the whole next day).
208function addSnoozeDays(base: Date, days: number): Date {
209 const next = DateTime.toDate(DateTime.makeUnsafe(base));
210 next.setDate(next.getDate() + days);
211 return next;
212}
213
214export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
215 const inAnHour = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + HOUR_MS));
216 const inThreeHours = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + 3 * HOUR_MS));
217 const presets: SnoozePreset[] = [
218 {
219 id: "hour",
220 label: "In 1 hour",
221 whenLabel: snoozeTimeOfDayLabel(inAnHour),
222 snoozedUntil: inAnHour.toISOString(),
223 },
224 {
225 id: "three-hours",
226 label: "In 3 hours",
227 whenLabel: snoozeTimeOfDayLabel(inThreeHours),
228 snoozedUntil: inThreeHours.toISOString(),
229 },
230 ];
231
232 const evening = snoozeAtHour(now, EVENING_HOUR);
233 if (evening.getTime() - now.getTime() > HOUR_MS) {
234 presets.push({
235 id: "evening",
236 label: "This evening",
237 whenLabel: snoozeTimeOfDayLabel(evening),
238 snoozedUntil: evening.toISOString(),
239 });
240 }
241
242 const tomorrow = snoozeAtHour(addSnoozeDays(now, 1), MORNING_HOUR);
243 presets.push({
244 id: "tomorrow",
245 label: "Tomorrow",
246 whenLabel: snoozeTimeOfDayLabel(tomorrow),
247 snoozedUntil: tomorrow.toISOString(),
248 });
249
250 const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
251 const nextWeek = snoozeAtHour(addSnoozeDays(now, daysUntilMonday), MORNING_HOUR);
252 if (nextWeek.getTime() !== tomorrow.getTime()) {
253 presets.push({
254 id: "next-week",
255 label: "Next week",
256 whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${snoozeTimeOfDayLabel(nextWeek)}`,
257 snoozedUntil: nextWeek.toISOString(),
258 });
259 }
260
261 return presets;
262}
263
264export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
265 const wakeMs = Date.parse(snoozedUntil);
266 const nowMs = Date.parse(options.now);
267 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
268 const remainingMs = wakeMs - nowMs;
269 if (remainingMs <= 0) return "now";
270 if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
271 if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
272 return `${Math.ceil(remainingMs / DAY_MS)}d`;
273}
274
275export type CustomSnoozeInput =
276 | { readonly mode: "date"; readonly date: string; readonly time: string }
277 | {
278 readonly mode: "duration";
279 readonly amount: string;
280 readonly unit: "minutes" | "hours" | "days";
281 };
282
283export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
284 let wake: Date;
285 if (input.mode === "duration") {
286 const amount = Number(input.amount);
287 if (!Number.isFinite(amount) || amount <= 0) return null;
288 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
289 wake = new Date(now.getTime() + amount * unitMs);
290 } else {
291 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
292 wake = new Date(`${input.date}T${input.time}:00`);
293 // Reject rolled-over dates and nonexistent local times during DST changes.
294 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
295 }
296 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
297 ? wake.toISOString()
298 : null;
299}
300
301export function localSnoozeDate(date: Date): string {
302 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
303}
304
305export function localSnoozeTime(date: Date): string {
306 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
307}