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

threadSettled.ts

311 lines12.2 KB

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