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