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

threadSettled.ts

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