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

threadSettled.ts

513 lines18.5 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, plural, part } from "gt-i18n";
7import type { M } from "gt-i18n";
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​
212/** A wake so far out it never comes; the thread stays snoozed until woken by hand. */
213export const INDEFINITE_SNOOZE_UNTIL = "9999-12-31T23:59:59.000Z";
214​
215export function isIndefiniteSnooze(snoozedUntil: string): boolean {
216 return Date.parse(snoozedUntil) >= Date.parse(INDEFINITE_SNOOZE_UNTIL);
218​
219export interface SnoozePreset {
220 readonly id: string;
221 readonly label: string;
222 readonly whenLabel: string;
223 readonly snoozedUntil: string;
225​
226export interface SnoozePresetOptions {
227 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
228 readonly formatTime?: (date: Date) => string;
229 readonly locale?: string | undefined;
231​
232function snoozeTimeOfDayLabel(date: Date): string {
233 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
235​
236// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
237// land on the wrong local day across DST transitions (a spring-forward day
238// is 23 hours, so 23:30 + 24h skips the whole next day).
239function addSnoozeDays(base: Date, days: number): Date {
240 const next = DateTime.toDate(DateTime.makeUnsafe(base));
241 next.setDate(next.getDate() + days);
242 return next;
244​
245/** "In 3 hours", "In 90 minutes", "In 2 days": the largest unit that divides evenly. */
246function snoozeDurationLabel(minutes: number, resolve: M): string {
247 if (minutes % (24 * 60) === 0) {
248 return resolve(
249 msg`${plural(
250 { count: minutes / (24 * 60) },
251 {
252 one: part`In ${{ count: minutes / (24 * 60) }} day`,
253 other: part`In ${{ count: minutes / (24 * 60) }} days`,
254 },
255 )}`,
256 );
257 }
258 if (minutes % 60 === 0) {
259 return resolve(
260 msg`${plural(
261 { count: minutes / 60 },
262 {
263 one: part`In ${{ count: minutes / 60 }} hour`,
264 other: part`In ${{ count: minutes / 60 }} hours`,
265 },
266 )}`,
267 );
268 }
269 return resolve(
270 msg`${plural(
271 { count: minutes },
272 {
273 one: part`In ${{ count: minutes }} minute`,
274 other: part`In ${{ count: minutes }} minutes`,
275 },
276 )}`,
277 );
279​
280const WEEKDAY_LABELS = {
281 sunday: msg("Sunday"),
282 monday: msg("Monday"),
283 tuesday: msg("Tuesday"),
284 wednesday: msg("Wednesday"),
285 thursday: msg("Thursday"),
286 friday: msg("Friday"),
287 saturday: msg("Saturday"),
288} satisfies Record<keyof typeof WEEKDAY_INDEX, string>;
289​
290const NEXT_WEEKDAY_LABELS = {
291 sunday: msg("Next Sunday"),
292 monday: msg("Next Monday"),
293 tuesday: msg("Next Tuesday"),
294 wednesday: msg("Next Wednesday"),
295 thursday: msg("Next Thursday"),
296 friday: msg("Next Friday"),
297 saturday: msg("Next Saturday"),
298} satisfies Record<keyof typeof WEEKDAY_INDEX, string>;
299​
300function snoozePresetDaysAhead(
301 setting: Extract<SnoozePresetSetting, { kind: "at" }>,
302 now: Date,
303): number {
304 if (setting.day === "today") return 0;
305 if (setting.day === "tomorrow") return 1;
306 return (WEEKDAY_INDEX[setting.day] - now.getDay() + 7) % 7 || 7;
308​
309/** Labels follow the actual day gap, so a Monday option on a Sunday reads "Tomorrow". */
310function snoozePresetLabel(setting: SnoozePresetSetting, daysAhead: number, resolve: M): string {
311 if (setting.kind === "after") return snoozeDurationLabel(setting.minutes, resolve);
312 if (daysAhead === 0) {
313 const hour = Number(setting.time.slice(0, 2));
314 return hour < 12
315 ? resolve(msg("This morning"))
316 : hour < 17
317 ? resolve(msg("This afternoon"))
318 : resolve(msg("This evening"));
319 }
320 if (daysAhead === 1) return resolve(msg("Tomorrow"));
321 if (setting.day === "monday") return resolve(msg("Next week"));
322 if (setting.day === "today" || setting.day === "tomorrow") return "";
323 return resolve(daysAhead === 7 ? NEXT_WEEKDAY_LABELS[setting.day] : WEEKDAY_LABELS[setting.day]);
325​
326export function snoozePresetId(setting: SnoozePresetSetting): string {
327 return setting.kind === "after"
328 ? `after:${setting.minutes}`
329 : `at:${setting.day}:${setting.time}`;
331​
332export function resolveSnoozePreset(
333 setting: SnoozePresetSetting,
334 now: Date,
335 formatTime: (date: Date) => string = snoozeTimeOfDayLabel,
336 resolve: M = mFallback,
337 locale?: string,
338): SnoozePreset | null {
339 let wake: Date;
340 let daysAhead = 0;
341 if (setting.kind === "after") {
342 wake = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + setting.minutes * 60_000));
343 } else {
344 daysAhead = snoozePresetDaysAhead(setting, now);
345 wake = addSnoozeDays(now, daysAhead);
346 wake.setHours(Number(setting.time.slice(0, 2)), Number(setting.time.slice(3)), 0, 0);
347 // A today option whose time has passed is left out until tomorrow.
348 if (wake.getTime() <= now.getTime()) return null;
349 }
350 const label = snoozePresetLabel(setting, daysAhead, resolve);
351 // Durations and "Next week" don't name the wake day, so a wake on another day shows it.
352 const labelNamesDay = setting.kind === "at" && !(daysAhead > 1 && setting.day === "monday");
353 const time = formatTime(wake);
354 return {
355 id: snoozePresetId(setting),
356 label,
357 whenLabel:
358 labelNamesDay || wake.toDateString() === now.toDateString()
359 ? time
360 : `${wake.toLocaleDateString(locale, { weekday: "short" })} ${time}`,
361 snoozedUntil: wake.toISOString(),
362 };
364​
365/** The snooze menu: soonest first, one row per wake minute. */
366export function resolveSnoozePresets(
367 now: Date,
368 options: SnoozePresetOptions = {},
369 resolve: M = mFallback,
370): ReadonlyArray<SnoozePreset> {
371 // By minute, so a duration (which keeps the clock's seconds) and a set time in the same
372 // minute tie, and the stable sort keeps whichever comes first in settings.
373 const wakeMinute = (preset: SnoozePreset) => Math.floor(Date.parse(preset.snoozedUntil) / 60_000);
374 const seen = new Set<number>();
375 return (
376 (options.presets ?? DEFAULT_SNOOZE_PRESETS)
377 .flatMap(
378 (setting) =>
379 resolveSnoozePreset(setting, now, options.formatTime, resolve, options.locale) ?? [],
380 )
381 // flatMap returned a new array; Hermes has no `toSorted`.
382 .sort((a, b) => wakeMinute(a) - wakeMinute(b))
383 .filter((preset) => {
384 if (seen.has(wakeMinute(preset))) return false;
385 seen.add(wakeMinute(preset));
386 return true;
387 })
388 .concat({
389 id: "indefinite",
390 label: resolve(msg({ context: "snooze until woken by hand" })`Indefinitely`),
391 whenLabel: "",
392 snoozedUntil: INDEFINITE_SNOOZE_UNTIL,
393 })
394 );
396​
397/**
398 * A menu choice as picked. A duration re-resolves from its setting (not the deduped menu) so it
399 * starts at selection. A set time keeps the shown wake, which a day change would otherwise shift.
400 */
401export function pickSnoozePreset(input: {
402 readonly shown: ReadonlyArray<SnoozePreset>;
403 readonly id: string;
404 readonly now: Date;
405 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
406 readonly formatTime?: (date: Date) => string;
407 readonly locale?: string | undefined;
408 readonly resolve?: M;
409}): SnoozePreset | undefined {
410 const original = input.shown.find((preset) => preset.id === input.id);
411 const ahead =
412 original && Date.parse(original.snoozedUntil) > input.now.getTime() ? original : undefined;
413 const setting = (input.presets ?? DEFAULT_SNOOZE_PRESETS).find(
414 (candidate) => candidate.kind === "after" && snoozePresetId(candidate) === input.id,
415 );
416 return (
417 (setting &&
418 resolveSnoozePreset(setting, input.now, input.formatTime, input.resolve, input.locale)) ??
419 ahead
420 );
422​
423export function snoozeWakeLabel(
424 snoozedUntil: string,
425 options: { readonly now: string },
426 resolve: M = mFallback,
427): string {
428 if (isIndefiniteSnooze(snoozedUntil)) return "∞";
429 const wakeMs = Date.parse(snoozedUntil);
430 const nowMs = Date.parse(options.now);
431 const now = () => resolve(msg({ context: "a snoozed thread wakes now" })`now`);
432 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return now();
433 if (wakeMs <= nowMs) return now();
434 // Count clock minutes: callers pass a minute-floored or live `now`, and durations keep seconds.
435 const minutes = Math.max(1, Math.floor(wakeMs / 60_000) - Math.floor(nowMs / 60_000));
436 if (minutes < 60) return resolve(msg`${{ minutes: String(minutes) }}m`);
437 if (minutes < 24 * 60) {
438 return resolve(msg`${{ hours: String(Math.ceil(minutes / 60)) }}h`);
439 }
440 return resolve(msg`${{ days: String(Math.ceil(minutes / (24 * 60))) }}d`);
442​
443export type CustomSnoozeInput =
444 | { readonly mode: "date"; readonly date: string; readonly time: string }
445 | {
446 readonly mode: "duration";
447 readonly amount: string;
448 readonly unit: "minutes" | "hours" | "days";
449 };
450​
451export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
452 let wake: Date;
453 if (input.mode === "duration") {
454 const amount = Number(input.amount);
455 if (!Number.isFinite(amount) || amount <= 0) return null;
456 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
457 wake = new Date(now.getTime() + amount * unitMs);
458 } else {
459 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
460 wake = new Date(`${input.date}T${input.time}:00`);
461 // Reject rolled-over dates and nonexistent local times during DST changes.
462 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
463 }
464 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
465 ? wake.toISOString()
466 : null;
468​
469export function localSnoozeDate(date: Date): string {
470 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
472​
473export function localSnoozeTime(date: Date): string {
474 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
476​
477/**
478 * Whether a woken thread woke after the user last saw it. A run that completed
479 * after the last visit counts as seeing it, since the user watched it finish.
480 */
481export function isThreadWokeUnseen(input: {
482 readonly wokeAt: string | null;
483 readonly settled: boolean;
484 readonly lastVisitedAt: string | null | undefined;
485 readonly latestRunCompletedAt: string | null;
486}): boolean {
487 if (input.wokeAt === null || input.settled) return false;
488 const wokeAtMs = Date.parse(input.wokeAt);
489 if (Number.isNaN(wokeAtMs)) return false;
490 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
491 .map((value) => (value ? Date.parse(value) : NaN))
492 .filter((ms) => !Number.isNaN(ms));
493 return seenAt.every((ms) => ms < wokeAtMs);
495​
496/**
497 * Whether the latest run failed after the user last saw the thread. Only the run dates the
498 * failure, since the shell's updatedAt also moves on renames. A failed run without a
499 * completion time, from older data, is dated by its start.
500 */
501export function hasUnseenRunFailure(
502 thread: Pick<EnvironmentThreadShell, "latestRun"> & {
503 readonly lastVisitedAt?: string | null | undefined;
504 },
505): boolean {
506 const run = thread.latestRun;
507 if (run?.status !== "failed") return false;
508 if (!thread.lastVisitedAt) return true;
509 const failedAtMs = Date.parse(run.completedAt ?? run.startedAt ?? run.requestedAt ?? "");
510 const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
511 if (Number.isNaN(failedAtMs) || Number.isNaN(lastVisitedAtMs)) return true;
512 return failedAtMs > lastVisitedAtMs;