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

threadSettled.ts

317 lines11.5 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 { EnvironmentThreadShell, 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 * Failed starts and stale shells from older servers can leave user messages unadopted.
36 * Bound the pending window so those threads can eventually settle.
37 */
38export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
39const DAY_MS = 24 * 60 * 60 * 1_000;
40​
41export function hasQueuedTurnStart(
42 shell: QueuedThreadShell,
43 options: { readonly now: string },
44): boolean {
45 if (
46 shell.runtime?.status === "preparing" ||
47 shell.runtime?.status === "queued" ||
48 shell.runtime?.status === "starting"
49 ) {
50 return true;
51 }
52 if (shell.latestUserMessageAt == null) return false;
53 if (shell.session?.status === "error") return false;
54 const messageAt = Date.parse(shell.latestUserMessageAt);
55 if (Number.isNaN(messageAt)) return false;
56 const nowMs = Date.parse(options.now);
57 if (Number.isNaN(nowMs)) return false;
58 // Bounded on both sides: message timestamps originate on whichever device
59 // sent the message, so a clock ahead of this one yields a negative age
60 // that would otherwise hold the queued state for the whole skew. Mirrors
61 // the decider's guard.
62 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
63 const turn = shell.latestRun ?? shell.latestTurn ?? null;
64 if (turn === null) return true;
65 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
66 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
67 );
69​
70export interface ThreadSnoozeShell extends QueuedThreadShell {
71 readonly source?: Pick<EnvironmentThreadShell["source"], "pendingRuntimeRequest">;
72 readonly snoozedUntil?: string | null;
73 readonly snoozedAt?: string | null;
74 readonly hasPendingApprovals: boolean;
75 readonly hasPendingUserInput: boolean;
76 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
77 readonly pendingGuestMessageCount?: number;
79​
80/**
81 * Only a request for the user or a fresh failure ends a snooze early. Completed runs never do:
82 * a snoozed long-running thread keeps waking itself for background work and stays hidden
83 * until its timer.
84 */
85export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
86 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
87 if (shell.source?.pendingRuntimeRequest != null) return true;
88 if (shell.pendingSubagentRequest != null) return true;
89 if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
90 const failedAt = failureEdgeAt(shell);
91 return (
92 failedAt !== undefined &&
93 (shell.snoozedAt == null ||
94 (failedAt != null && Date.parse(failedAt) > Date.parse(shell.snoozedAt)))
95 );
97​
98// V2 runtime.updatedAt includes metadata writes; prefer the failed run's completion.
99// Legacy sessions only expose the runtime timestamp.
100function failureEdgeAt(shell: ThreadSnoozeShell): string | null | undefined {
101 const runtime = shell.runtime ?? shell.session ?? null;
102 if (runtime?.status !== "error" && runtime?.status !== "failed") return undefined;
103 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
104 if (latestRun?.status === "failed" && latestRun.completedAt != null) {
105 return latestRun.completedAt;
106 }
107 return runtime.updatedAt ?? null;
109​
110export function canSnooze(
111 shell: Pick<
112 ThreadSnoozeShell,
113 | "hasPendingApprovals"
114 | "hasPendingUserInput"
115 | "pendingSubagentRequest"
116 | "pendingGuestMessageCount"
117 | "latestUserMessageAt"
118 | "latestTurn"
119 | "latestRun"
120 | "session"
121 | "runtime"
122 | "source"
123 >,
124 options: { readonly now: string },
125): boolean {
126 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
127 // The server rejects snoozing even for nonblocking questions.
128 if (shell.source?.pendingRuntimeRequest != null) return false;
129 if (shell.pendingSubagentRequest != null) return false;
130 // A waiting guest message would wake it at once.
131 if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
132 if (hasQueuedTurnStart(shell, options)) return false;
133 return true;
135​
136export function effectiveSnoozed(
137 shell: ThreadSnoozeShell,
138 options: { readonly now: string },
139): boolean {
140 if (shell.snoozedUntil == null) return false;
141 const wakeAtMs = Date.parse(shell.snoozedUntil);
142 if (Number.isNaN(wakeAtMs)) return false;
143 if (wakeAtMs <= Date.parse(options.now)) return false;
144 return !threadRaisedHandWhileSnoozed(shell);
146​
147export function threadWokeAt(
148 shell: ThreadSnoozeShell,
149 options: { readonly now: string },
150): string | null {
151 if (shell.snoozedUntil == null) return null;
152 const wakeAtMs = Date.parse(shell.snoozedUntil);
153 if (Number.isNaN(wakeAtMs)) return null;
154 // An early hand-raise wake stays authoritative even after the scheduled
155 // wake time passes: reporting snoozedUntil then would resurface a Woke
156 // indicator the user already cleared by visiting (snoozedUntil is newer
157 // than that visit's lastVisitedAt).
158 if (threadRaisedHandWhileSnoozed(shell)) {
159 // An old failure must not replace the activity time of an approval or input wake.
160 const failedAt = failureEdgeAt(shell);
161 if (
162 failedAt != null &&
163 (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt))
164 ) {
165 return failedAt;
166 }
167 const runtime = shell.runtime ?? shell.session ?? null;
168 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
169 }
170 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
172​
173const HOUR_MS = 60 * 60 * 1_000;
174const EVENING_HOUR = 18;
175const MORNING_HOUR = 9;
176​
177export type SnoozePresetId = "hour" | "three-hours" | "evening" | "tomorrow" | "next-week";
178​
179export interface SnoozePreset {
180 readonly id: SnoozePresetId;
181 readonly label: string;
182 readonly whenLabel: string;
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 = DateTime.toDate(DateTime.makeUnsafe(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 = DateTime.toDate(DateTime.makeUnsafe(base));
201 next.setDate(next.getDate() + days);
202 return next;
204​
205export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
206 const inAnHour = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + HOUR_MS));
207 const inThreeHours = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + 3 * HOUR_MS));
208 const presets: SnoozePreset[] = [
209 {
210 id: "hour",
211 label: "In 1 hour",
212 whenLabel: snoozeTimeOfDayLabel(inAnHour),
213 snoozedUntil: inAnHour.toISOString(),
214 },
215 {
216 id: "three-hours",
217 label: "In 3 hours",
218 whenLabel: snoozeTimeOfDayLabel(inThreeHours),
219 snoozedUntil: inThreeHours.toISOString(),
220 },
221 ];
222​
223 const evening = snoozeAtHour(now, EVENING_HOUR);
224 if (evening.getTime() - now.getTime() > HOUR_MS) {
225 presets.push({
226 id: "evening",
227 label: "This evening",
228 whenLabel: snoozeTimeOfDayLabel(evening),
229 snoozedUntil: evening.toISOString(),
230 });
231 }
232​
233 const tomorrow = snoozeAtHour(addSnoozeDays(now, 1), MORNING_HOUR);
234 presets.push({
235 id: "tomorrow",
236 label: "Tomorrow",
237 whenLabel: snoozeTimeOfDayLabel(tomorrow),
238 snoozedUntil: tomorrow.toISOString(),
239 });
240​
241 const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
242 const nextWeek = snoozeAtHour(addSnoozeDays(now, daysUntilMonday), MORNING_HOUR);
243 if (nextWeek.getTime() !== tomorrow.getTime()) {
244 presets.push({
245 id: "next-week",
246 label: "Next week",
247 whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${snoozeTimeOfDayLabel(nextWeek)}`,
248 snoozedUntil: nextWeek.toISOString(),
249 });
250 }
251​
252 return presets;
254​
255export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
256 const wakeMs = Date.parse(snoozedUntil);
257 const nowMs = Date.parse(options.now);
258 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
259 const remainingMs = wakeMs - nowMs;
260 if (remainingMs <= 0) return "now";
261 if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
262 if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
263 return `${Math.ceil(remainingMs / DAY_MS)}d`;
265​
266export type CustomSnoozeInput =
267 | { readonly mode: "date"; readonly date: string; readonly time: string }
268 | {
269 readonly mode: "duration";
270 readonly amount: string;
271 readonly unit: "minutes" | "hours" | "days";
272 };
273​
274export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
275 let wake: Date;
276 if (input.mode === "duration") {
277 const amount = Number(input.amount);
278 if (!Number.isFinite(amount) || amount <= 0) return null;
279 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
280 wake = new Date(now.getTime() + amount * unitMs);
281 } else {
282 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
283 wake = new Date(`${input.date}T${input.time}:00`);
284 // Reject rolled-over dates and nonexistent local times during DST changes.
285 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
286 }
287 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
288 ? wake.toISOString()
289 : null;
291​
292export function localSnoozeDate(date: Date): string {
293 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
295​
296export function localSnoozeTime(date: Date): string {
297 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
299​
300/**
301 * Whether a woken thread woke after the user last saw it. A run that completed
302 * after the last visit counts as seeing it, since the user watched it finish.
303 */
304export function isThreadWokeUnseen(input: {
305 readonly wokeAt: string | null;
306 readonly settled: boolean;
307 readonly lastVisitedAt: string | null | undefined;
308 readonly latestRunCompletedAt: string | null;
309}): boolean {
310 if (input.wokeAt === null || input.settled) return false;
311 const wokeAtMs = Date.parse(input.wokeAt);
312 if (Number.isNaN(wokeAtMs)) return false;
313 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
314 .map((value) => (value ? Date.parse(value) : NaN))
315 .filter((ms) => !Number.isNaN(ms));
316 return seenAt.every((ms) => ms < wokeAtMs);