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

threadSettled.ts

360 lines13.9 KB

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