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

threadSettled.ts

354 lines13.6 KB

1// @effect-diagnostics globalDate:off -- UI snooze presets use local calendar boundaries and Intl labels.
2import * as DateTime from "effect/DateTime";
3​
4interface SettlementRunLike {
5 readonly turnId?: unknown;
6 readonly assistantMessageId?: unknown;
7 readonly status?: string;
8 readonly state?: string;
9 readonly requestedAt?: string | null;
10 readonly startedAt?: string | null;
11 readonly completedAt?: string | null;
13​
14interface SettlementRuntimeLike {
15 readonly threadId?: unknown;
16 readonly providerName?: unknown;
17 readonly runtimeMode?: unknown;
18 readonly activeTurnId?: unknown;
19 readonly lastError?: unknown;
20 readonly status: string;
21 readonly updatedAt?: string;
23​
24interface QueuedThreadShell {
25 readonly latestUserMessageAt?: string | null;
26 readonly latestTurn?: SettlementRunLike | null;
27 readonly latestRun?: SettlementRunLike | null;
28 readonly session?: SettlementRuntimeLike | null;
29 readonly runtime?: SettlementRuntimeLike | null;
31​
32/**
33 * A queued turn start lives for at most this long: session adoption takes
34 * seconds, so a user message still unadopted after the grace window is a
35 * failed start (or stale data — shells from older servers can carry user
36 * messages with no latestTurn at all), not pending work. Without this bound
37 * such threads would be permanently unsettleable.
38 */
39export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
40const DAY_MS = 24 * 60 * 60 * 1_000;
41​
42/**
43 * A user message no turn has picked up yet: the turn.start command was
44 * dispatched (message-sent + turn-start-requested) but no session has
45 * adopted it, so `session` is still null and the pending work is invisible
46 * to the session-status checks. Detectable as a user message strictly newer
47 * than every timestamp on the latest turn — on adoption the new turn's
48 * requestedAt equals the message time, clearing the condition — and only
49 * within the adoption grace window.
50 */
51export function hasQueuedTurnStart(
52 shell: QueuedThreadShell,
53 options: { readonly now: string },
54): boolean {
55 if (
56 shell.runtime?.status === "preparing" ||
57 shell.runtime?.status === "queued" ||
58 shell.runtime?.status === "starting"
59 ) {
60 return true;
61 }
62 if (shell.latestUserMessageAt == null) return false;
63 // A failed session start clears the queued state: the failure is already
64 // visible (status edge / error).
65 if (shell.session?.status === "error") return false;
66 const messageAt = Date.parse(shell.latestUserMessageAt);
67 if (Number.isNaN(messageAt)) return false;
68 const nowMs = Date.parse(options.now);
69 if (Number.isNaN(nowMs)) return false;
70 // Bounded on both sides: message timestamps originate on whichever device
71 // sent the message, so a clock ahead of this one yields a negative age
72 // that would otherwise hold the queued state for the whole skew. Mirrors
73 // the decider's guard.
74 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
75 const turn = shell.latestRun ?? shell.latestTurn ?? null;
76 if (turn === null) return true;
77 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
78 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
79 );
81​
82/**
83 * The snooze lifecycle fields plus everything needed to detect a raised
84 * hand. Snooze is an overlay on the active state: a snoozed thread stays
85 * "active" in the data model and is only suppressed from the inbox until
86 * its wake time passes or the thread demands attention.
87 */
88export interface ThreadSnoozeShell extends QueuedThreadShell {
89 readonly snoozedUntil?: string | null;
90 readonly snoozedAt?: string | null;
91 readonly hasPendingApprovals: boolean;
92 readonly hasPendingUserInput: boolean;
94​
95/**
96 * A snoozed thread "raises its hand" when something happens that outranks
97 * the user's snooze: the agent is blocked on them (approval / user input),
98 * the session failed, or a run completed after the snooze was set — the
99 * v1 taste of event-based snooze ("something happened" wakes early).
100 * Raising a hand never clears the server-side snooze fields; it only stops
101 * the thread from classifying as snoozed.
102 */
103export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
104 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
105 const runtime = shell.runtime ?? shell.session ?? null;
106 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
107 // Only a FRESH failure raises the hand: a thread snoozed while already
108 // failed stays snoozed — that snooze was the user saying "I saw it, not
109 // now". session.updatedAt stamps the status edge, so an error newer than
110 // the snooze is new information.
111 if (
112 (runtime?.status === "error" || runtime?.status === "failed") &&
113 (shell.snoozedAt == null ||
114 (runtime.updatedAt != null && Date.parse(runtime.updatedAt) > Date.parse(shell.snoozedAt)))
115 ) {
116 return true;
117 }
118 if (
119 shell.snoozedAt != null &&
120 (latestRun?.state === "completed" || latestRun?.status === "completed") &&
121 latestRun.completedAt != null &&
122 Date.parse(latestRun.completedAt) > Date.parse(shell.snoozedAt)
123 ) {
124 return true;
125 }
126 return false;
128​
129/**
130 * A thread may be snoozed unless the agent is blocked on the user: hiding a
131 * pending approval or user-input request defeats the request, and a queued
132 * turn start (a message no turn has adopted yet) is invisible pending work
133 * the same way it is for settle. A running session IS snoozable — snooze
134 * only affects visibility, never the agent. Client-side twin of the server
135 * invariants so the UI can reject before a round trip.
136 */
137export function canSnooze(
138 shell: Pick<
139 ThreadSnoozeShell,
140 | "hasPendingApprovals"
141 | "hasPendingUserInput"
142 | "latestUserMessageAt"
143 | "latestTurn"
144 | "latestRun"
145 | "session"
146 | "runtime"
147 >,
148 options: { readonly now: string },
149): boolean {
150 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
151 if (hasQueuedTurnStart(shell, options)) return false;
152 return true;
154​
155/**
156 * Snoozed resolution: hidden from the inbox while the wake time is in the
157 * future and the thread has not raised its hand. Timer wakes are derived —
158 * no server event fires when snoozedUntil passes; the stale fields simply
159 * stop classifying as snoozed (and feed the woke indicator until the user
160 * visits or re-engages).
161 */
162export function effectiveSnoozed(
163 shell: ThreadSnoozeShell,
164 options: { readonly now: string },
165): boolean {
166 if (shell.snoozedUntil == null) return false;
167 const wakeAtMs = Date.parse(shell.snoozedUntil);
168 // Malformed data never hides a thread.
169 if (Number.isNaN(wakeAtMs)) return false;
170 if (wakeAtMs <= Date.parse(options.now)) return false;
171 return !threadRaisedHandWhileSnoozed(shell);
173​
174/**
175 * When a previously-snoozed thread woke, or null if it never snoozed / is
176 * still snoozed. Used for the "Woke" indicator: the thread reappears in its
177 * original sort position (the inbox sort is deliberately static), so the
178 * wake signal has to carry the weight. Compare against the client's
179 * lastVisitedAt — visiting clears the indicator like it clears unread.
180 *
181 * Timer wakes report the wake time itself; raised-hand wakes report the
182 * triggering timestamp so a visit BEFORE the early wake doesn't suppress
183 * the indicator.
184 */
185export function threadWokeAt(
186 shell: ThreadSnoozeShell,
187 options: { readonly now: string },
188): string | null {
189 if (shell.snoozedUntil == null) return null;
190 const wakeAtMs = Date.parse(shell.snoozedUntil);
191 if (Number.isNaN(wakeAtMs)) return null;
192 // An early hand-raise wake stays authoritative even after the scheduled
193 // wake time passes: reporting snoozedUntil then would resurface a Woke
194 // indicator the user already cleared by visiting (snoozedUntil is newer
195 // than that visit's lastVisitedAt).
196 if (threadRaisedHandWhileSnoozed(shell)) {
197 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
198 const runtime = shell.runtime ?? shell.session ?? null;
199 if (
200 shell.snoozedAt != null &&
201 (latestRun?.state === "completed" || latestRun?.status === "completed") &&
202 latestRun.completedAt != null &&
203 Date.parse(latestRun.completedAt) > Date.parse(shell.snoozedAt)
204 ) {
205 return latestRun.completedAt;
206 }
207 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
208 }
209 // No raised hand: woke iff the timer elapsed (still-snoozed → null).
210 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
212​
213const HOUR_MS = 60 * 60 * 1_000;
214const EVENING_HOUR = 18;
215const MORNING_HOUR = 9;
216​
217export type SnoozePresetId = "hour" | "three-hours" | "evening" | "tomorrow" | "next-week";
218​
219export interface SnoozePreset {
220 readonly id: SnoozePresetId;
221 readonly label: string;
222 /** Menu-row time column. Complements the label instead of repeating it:
223 "Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
224 readonly whenLabel: string;
225 /** ISO wake time. */
226 readonly snoozedUntil: string;
228​
229function snoozeTimeOfDayLabel(date: Date): string {
230 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
232​
233function snoozeAtHour(base: Date, hour: number): Date {
234 const next = DateTime.toDate(DateTime.makeUnsafe(base));
235 next.setHours(hour, 0, 0, 0);
236 return next;
238​
239// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
240// land on the wrong local day across DST transitions (a spring-forward day
241// is 23 hours, so 23:30 + 24h skips the whole next day).
242function addSnoozeDays(base: Date, days: number): Date {
243 const next = DateTime.toDate(DateTime.makeUnsafe(base));
244 next.setDate(next.getDate() + days);
245 return next;
247​
248/**
249 * Shared "snooze until" choices for every client. "This evening" only
250 * appears while it is meaningfully before evening; after that the calendar
251 * choices start at "Tomorrow". Calendar presets that land on the same
252 * instant collapse: on Sundays "Tomorrow" and "Next week" are both Monday
253 * morning, so only "Tomorrow" is offered.
254 */
255export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
256 const inAnHour = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + HOUR_MS));
257 const inThreeHours = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + 3 * HOUR_MS));
258 const presets: SnoozePreset[] = [
259 {
260 id: "hour",
261 label: "In 1 hour",
262 whenLabel: snoozeTimeOfDayLabel(inAnHour),
263 snoozedUntil: inAnHour.toISOString(),
264 },
265 {
266 id: "three-hours",
267 label: "In 3 hours",
268 whenLabel: snoozeTimeOfDayLabel(inThreeHours),
269 snoozedUntil: inThreeHours.toISOString(),
270 },
271 ];
272​
273 const evening = snoozeAtHour(now, EVENING_HOUR);
274 if (evening.getTime() - now.getTime() > HOUR_MS) {
275 presets.push({
276 id: "evening",
277 label: "This evening",
278 whenLabel: snoozeTimeOfDayLabel(evening),
279 snoozedUntil: evening.toISOString(),
280 });
281 }
282​
283 const tomorrow = snoozeAtHour(addSnoozeDays(now, 1), MORNING_HOUR);
284 presets.push({
285 id: "tomorrow",
286 label: "Tomorrow",
287 whenLabel: snoozeTimeOfDayLabel(tomorrow),
288 snoozedUntil: tomorrow.toISOString(),
289 });
290​
291 const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
292 const nextWeek = snoozeAtHour(addSnoozeDays(now, daysUntilMonday), MORNING_HOUR);
293 if (nextWeek.getTime() !== tomorrow.getTime()) {
294 presets.push({
295 id: "next-week",
296 label: "Next week",
297 whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${snoozeTimeOfDayLabel(nextWeek)}`,
298 snoozedUntil: nextWeek.toISOString(),
299 });
300 }
301​
302 return presets;
304​
305/**
306 * Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
307 * round up so a snooze never reads "0m" while still hidden. Shared by web
308 * and mobile so the same wake time never reads differently per client.
309 */
310export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
311 const wakeMs = Date.parse(snoozedUntil);
312 const nowMs = Date.parse(options.now);
313 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
314 const remainingMs = wakeMs - nowMs;
315 if (remainingMs <= 0) return "now";
316 if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
317 if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
318 return `${Math.ceil(remainingMs / DAY_MS)}d`;
320​
321export type CustomSnoozeInput =
322 | { readonly mode: "date"; readonly date: string; readonly time: string }
323 | {
324 readonly mode: "duration";
325 readonly amount: string;
326 readonly unit: "minutes" | "hours" | "days";
327 };
328​
329/** Resolve local calendar input or elapsed time, rejecting past and invalid dates. */
330export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
331 let wake: Date;
332 if (input.mode === "duration") {
333 const amount = Number(input.amount);
334 if (!Number.isFinite(amount) || amount <= 0) return null;
335 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
336 wake = new Date(now.getTime() + amount * unitMs);
337 } else {
338 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
339 wake = new Date(`${input.date}T${input.time}:00`);
340 // Reject rolled-over dates and nonexistent local times during DST changes.
341 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
342 }
343 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
344 ? wake.toISOString()
345 : null;
347​
348export function localSnoozeDate(date: Date): string {
349 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
351​
352export function localSnoozeTime(date: Date): string {
353 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;