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

threadSettled.ts

328 lines12.4 KB

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