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