Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadSettled.ts

432 lines16.3 KB

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;
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;
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;
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;
40​
41export function hasQueuedTurnStart(
42 shell: QueuedThreadShell,
43 options: { readonly now: string },
44): boolean {
45 if (
46 shell.runtime?.status === "preparing" ||
47 shell.runtime?.status === "queued" ||
48 shell.runtime?.status === "starting"
49 ) {
50 return true;
51 }
52 if (shell.latestUserMessageAt == null) return false;
53 if (shell.session?.status === "error") return false;
54 const messageAt = Date.parse(shell.latestUserMessageAt);
55 if (Number.isNaN(messageAt)) return false;
56 const nowMs = Date.parse(options.now);
57 if (Number.isNaN(nowMs)) return false;
58 // Bounded on both sides: message timestamps originate on whichever device
59 // sent the message, so a clock ahead of this one yields a negative age
60 // that would otherwise hold the queued state for the whole skew. Mirrors
61 // the decider's guard.
62 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
63 const turn = shell.latestRun ?? shell.latestTurn ?? null;
64 if (turn === null) return true;
65 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
66 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
67 );
69​
70export interface ThreadSnoozeShell extends QueuedThreadShell {
71 readonly source?: Pick<EnvironmentThreadShell["source"], "pendingRuntimeRequest">;
72 readonly snoozedUntil?: string | null;
73 readonly snoozedAt?: string | null;
74 readonly hasPendingApprovals: boolean;
75 readonly hasPendingUserInput: boolean;
76 readonly pendingUserInputAt?: string | null;
77 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
78 readonly pendingGuestMessageCount?: number;
80​
81function pendingQuestionAt(shell: ThreadSnoozeShell): string | null {
82 const request = shell.source?.pendingRuntimeRequest;
83 return (
84 shell.pendingUserInputAt ??
85 (request?.kind === "user_input" ? DateTime.formatIso(request.createdAt) : null)
86 );
88​
89/**
90 * Only a request for the user or a fresh failure ends a snooze early. Completed runs never do:
91 * a snoozed long-running thread keeps waking itself for background work and stays hidden
92 * until its timer.
93 */
94export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
95 const request = shell.source?.pendingRuntimeRequest;
96 if (shell.hasPendingApprovals || (request != null && request.kind !== "user_input")) return true;
97 const questionAt = pendingQuestionAt(shell);
98 // Snoozing an existing question means "ask me later". Only a new question
99 // wakes it early; missing or invalid timestamps keep the request visible.
100 if (
101 (shell.hasPendingUserInput || request?.kind === "user_input") &&
102 (shell.snoozedAt == null ||
103 questionAt == null ||
104 !(Date.parse(questionAt) <= Date.parse(shell.snoozedAt)))
105 ) {
106 return true;
107 }
108 if (shell.pendingSubagentRequest != null) return true;
109 if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
110 const failedAt = failureEdgeAt(shell);
111 return (
112 failedAt !== undefined &&
113 (shell.snoozedAt == null ||
114 (failedAt != null && Date.parse(failedAt) > Date.parse(shell.snoozedAt)))
115 );
117​
118// V2 runtime.updatedAt includes metadata writes, not just failures.
119// Legacy sessions only expose the runtime timestamp.
120function failureEdgeAt(shell: ThreadSnoozeShell): string | null | undefined {
121 const runtime = shell.runtime ?? shell.session ?? null;
122 if (runtime?.status !== "error" && runtime?.status !== "failed") return undefined;
123 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
124 if (latestRun?.status === "failed") {
125 return latestRun.completedAt ?? null;
126 }
127 return runtime.updatedAt ?? null;
129​
130export function canSnooze(
131 shell: Pick<
132 ThreadSnoozeShell,
133 | "hasPendingApprovals"
134 | "hasPendingUserInput"
135 | "pendingSubagentRequest"
136 | "pendingGuestMessageCount"
137 | "latestUserMessageAt"
138 | "latestTurn"
139 | "latestRun"
140 | "session"
141 | "runtime"
142 | "source"
143 >,
144 options: { readonly now: string },
145): boolean {
146 if (shell.hasPendingApprovals) return false;
147 const request = shell.source?.pendingRuntimeRequest;
148 if (request != null && request.kind !== "user_input") return false;
149 if (shell.pendingSubagentRequest != null) return false;
150 // A waiting guest message would wake it at once.
151 if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
152 if (hasQueuedTurnStart(shell, options)) return false;
153 return true;
155​
156export function effectiveSnoozed(
157 shell: ThreadSnoozeShell,
158 options: { readonly now: string },
159): boolean {
160 if (shell.snoozedUntil == null) return false;
161 const wakeAtMs = Date.parse(shell.snoozedUntil);
162 if (Number.isNaN(wakeAtMs)) return false;
163 if (wakeAtMs <= Date.parse(options.now)) return false;
164 return !threadRaisedHandWhileSnoozed(shell);
166​
167export function threadWokeAt(
168 shell: ThreadSnoozeShell,
169 options: { readonly now: string },
170): string | null {
171 if (shell.snoozedUntil == null) return null;
172 const wakeAtMs = Date.parse(shell.snoozedUntil);
173 if (Number.isNaN(wakeAtMs)) return null;
174 // An early hand-raise wake stays authoritative even after the scheduled
175 // wake time passes: reporting snoozedUntil then would resurface a Woke
176 // indicator the user already cleared by visiting (snoozedUntil is newer
177 // than that visit's lastVisitedAt).
178 if (threadRaisedHandWhileSnoozed(shell)) {
179 const failedAt = failureEdgeAt(shell);
180 const questionAt = pendingQuestionAt(shell);
181 const freshFailure =
182 failedAt != null &&
183 (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt));
184 const freshQuestion =
185 questionAt != null &&
186 shell.snoozedAt != null &&
187 Date.parse(questionAt) > Date.parse(shell.snoozedAt);
188 if (freshFailure && (!freshQuestion || Date.parse(failedAt) >= Date.parse(questionAt))) {
189 return failedAt;
190 }
191 if (freshQuestion) return questionAt;
192 const runtime = shell.runtime ?? shell.session ?? null;
193 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
194 }
195 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
197​
198const HOUR_MS = 60 * 60 * 1_000;
199​
200const WEEKDAY_INDEX = {
201 sunday: 0,
202 monday: 1,
203 tuesday: 2,
204 wednesday: 3,
205 thursday: 4,
206 friday: 5,
207 saturday: 6,
208} as const;
209​
210export interface SnoozePreset {
211 readonly id: string;
212 readonly label: string;
213 readonly whenLabel: string;
214 readonly snoozedUntil: string;
216​
217export interface SnoozePresetOptions {
218 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
219 readonly formatTime?: (date: Date) => string;
221​
222function snoozeTimeOfDayLabel(date: Date): string {
223 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
225​
226// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
227// land on the wrong local day across DST transitions (a spring-forward day
228// is 23 hours, so 23:30 + 24h skips the whole next day).
229function addSnoozeDays(base: Date, days: number): Date {
230 const next = DateTime.toDate(DateTime.makeUnsafe(base));
231 next.setDate(next.getDate() + days);
232 return next;
234​
235function pluralize(count: number, unit: string): string {
236 return `${count} ${unit}${count === 1 ? "" : "s"}`;
238​
239/** "3 hours", "90 minutes", "2 days": the largest unit that divides evenly. */
240function formatSnoozeDuration(minutes: number): string {
241 if (minutes % (24 * 60) === 0) return pluralize(minutes / (24 * 60), "day");
242 if (minutes % 60 === 0) return pluralize(minutes / 60, "hour");
243 return pluralize(minutes, "minute");
245​
246function capitalize(word: string): string {
247 return word[0]!.toUpperCase() + word.slice(1);
249​
250function snoozePresetDaysAhead(
251 setting: Extract<SnoozePresetSetting, { kind: "at" }>,
252 now: Date,
253): number {
254 if (setting.day === "today") return 0;
255 if (setting.day === "tomorrow") return 1;
256 return (WEEKDAY_INDEX[setting.day] - now.getDay() + 7) % 7 || 7;
258​
259/** Labels follow the actual day gap, so a Monday option on a Sunday reads "Tomorrow". */
260function snoozePresetLabel(setting: SnoozePresetSetting, daysAhead: number): string {
261 if (setting.kind === "after") return `In ${formatSnoozeDuration(setting.minutes)}`;
262 if (daysAhead === 0) {
263 const hour = Number(setting.time.slice(0, 2));
264 return hour < 12 ? "This morning" : hour < 17 ? "This afternoon" : "This evening";
265 }
266 if (daysAhead === 1) return "Tomorrow";
267 if (setting.day === "monday") return "Next week";
268 return daysAhead === 7 ? `Next ${capitalize(setting.day)}` : capitalize(setting.day);
270​
271export function snoozePresetId(setting: SnoozePresetSetting): string {
272 return setting.kind === "after"
273 ? `after:${setting.minutes}`
274 : `at:${setting.day}:${setting.time}`;
276​
277export function resolveSnoozePreset(
278 setting: SnoozePresetSetting,
279 now: Date,
280 formatTime: (date: Date) => string = snoozeTimeOfDayLabel,
281): SnoozePreset | null {
282 let wake: Date;
283 let daysAhead = 0;
284 if (setting.kind === "after") {
285 wake = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + setting.minutes * 60_000));
286 } else {
287 daysAhead = snoozePresetDaysAhead(setting, now);
288 wake = addSnoozeDays(now, daysAhead);
289 wake.setHours(Number(setting.time.slice(0, 2)), Number(setting.time.slice(3)), 0, 0);
290 // A today option whose time has passed is left out until tomorrow.
291 if (wake.getTime() <= now.getTime()) return null;
292 }
293 const label = snoozePresetLabel(setting, daysAhead);
294 // Durations and "Next week" don't name the wake day, so a wake on another day shows it.
295 const labelNamesDay = setting.kind === "at" && label !== "Next week";
296 const time = formatTime(wake);
297 return {
298 id: snoozePresetId(setting),
299 label,
300 whenLabel:
301 labelNamesDay || wake.toDateString() === now.toDateString()
302 ? time
303 : `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}`,
304 snoozedUntil: wake.toISOString(),
305 };
307​
308/** The snooze menu: soonest first, one row per wake minute. */
309export function resolveSnoozePresets(
310 now: Date,
311 options: SnoozePresetOptions = {},
312): ReadonlyArray<SnoozePreset> {
313 // By minute, so a duration (which keeps the clock's seconds) and a set time in the same
314 // minute tie, and the stable sort keeps whichever comes first in settings.
315 const wakeMinute = (preset: SnoozePreset) => Math.floor(Date.parse(preset.snoozedUntil) / 60_000);
316 const seen = new Set<number>();
317 return (
318 (options.presets ?? DEFAULT_SNOOZE_PRESETS)
319 .flatMap((setting) => resolveSnoozePreset(setting, now, options.formatTime) ?? [])
320 // flatMap returned a new array; Hermes has no `toSorted`.
321 .sort((a, b) => wakeMinute(a) - wakeMinute(b))
322 .filter((preset) => {
323 if (seen.has(wakeMinute(preset))) return false;
324 seen.add(wakeMinute(preset));
325 return true;
326 })
327 );
329​
330/**
331 * A menu choice as picked. A duration re-resolves from its setting (not the deduped menu) so it
332 * starts at selection. A set time keeps the shown wake, which a day change would otherwise shift.
333 */
334export function pickSnoozePreset(input: {
335 readonly shown: ReadonlyArray<SnoozePreset>;
336 readonly id: string;
337 readonly now: Date;
338 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
339 readonly formatTime?: (date: Date) => string;
340}): SnoozePreset | undefined {
341 const original = input.shown.find((preset) => preset.id === input.id);
342 const ahead =
343 original && Date.parse(original.snoozedUntil) > input.now.getTime() ? original : undefined;
344 const setting = (input.presets ?? DEFAULT_SNOOZE_PRESETS).find(
345 (candidate) => candidate.kind === "after" && snoozePresetId(candidate) === input.id,
346 );
347 return (setting && resolveSnoozePreset(setting, input.now, input.formatTime)) ?? ahead;
349​
350export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
351 const wakeMs = Date.parse(snoozedUntil);
352 const nowMs = Date.parse(options.now);
353 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
354 if (wakeMs <= nowMs) return "now";
355 // Count clock minutes: callers pass a minute-floored or live `now`, and durations keep seconds.
356 const minutes = Math.max(1, Math.floor(wakeMs / 60_000) - Math.floor(nowMs / 60_000));
357 if (minutes < 60) return `${minutes}m`;
358 if (minutes < 24 * 60) return `${Math.ceil(minutes / 60)}h`;
359 return `${Math.ceil(minutes / (24 * 60))}d`;
361​
362export type CustomSnoozeInput =
363 | { readonly mode: "date"; readonly date: string; readonly time: string }
364 | {
365 readonly mode: "duration";
366 readonly amount: string;
367 readonly unit: "minutes" | "hours" | "days";
368 };
369​
370export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
371 let wake: Date;
372 if (input.mode === "duration") {
373 const amount = Number(input.amount);
374 if (!Number.isFinite(amount) || amount <= 0) return null;
375 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
376 wake = new Date(now.getTime() + amount * unitMs);
377 } else {
378 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
379 wake = new Date(`${input.date}T${input.time}:00`);
380 // Reject rolled-over dates and nonexistent local times during DST changes.
381 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
382 }
383 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
384 ? wake.toISOString()
385 : null;
387​
388export function localSnoozeDate(date: Date): string {
389 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
391​
392export function localSnoozeTime(date: Date): string {
393 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
395​
396/**
397 * Whether a woken thread woke after the user last saw it. A run that completed
398 * after the last visit counts as seeing it, since the user watched it finish.
399 */
400export function isThreadWokeUnseen(input: {
401 readonly wokeAt: string | null;
402 readonly settled: boolean;
403 readonly lastVisitedAt: string | null | undefined;
404 readonly latestRunCompletedAt: string | null;
405}): boolean {
406 if (input.wokeAt === null || input.settled) return false;
407 const wokeAtMs = Date.parse(input.wokeAt);
408 if (Number.isNaN(wokeAtMs)) return false;
409 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
410 .map((value) => (value ? Date.parse(value) : NaN))
411 .filter((ms) => !Number.isNaN(ms));
412 return seenAt.every((ms) => ms < wokeAtMs);
414​
415/**
416 * Whether the latest run failed after the user last saw the thread. Only the run dates the
417 * failure, since the shell's updatedAt also moves on renames. A failed run without a
418 * completion time, from older data, is dated by its start.
419 */
420export function hasUnseenRunFailure(
421 thread: Pick<EnvironmentThreadShell, "latestRun"> & {
422 readonly lastVisitedAt?: string | null | undefined;
423 },
424): boolean {
425 const run = thread.latestRun;
426 if (run?.status !== "failed") return false;
427 if (!thread.lastVisitedAt) return true;
428 const failedAtMs = Date.parse(run.completedAt ?? run.startedAt ?? run.requestedAt ?? "");
429 const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
430 if (Number.isNaN(failedAtMs) || Number.isNaN(lastVisitedAtMs)) return true;
431 return failedAtMs > lastVisitedAtMs;