Open History to see the last commit
1// @effect-diagnostics globalDate:off -- UI snooze presets use local calendar boundaries and Intl labels.
2import type { OrchestrationThreadShell } from "@t3tools/contracts";
3
4export type ChangeRequestStateLike = "open" | "closed" | "merged";
5
6const DAY_MS = 24 * 60 * 60 * 1_000;
7
8export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
9 const candidates = [
10 shell.latestUserMessageAt,
11 shell.latestTurn?.requestedAt,
12 shell.latestTurn?.startedAt,
13 shell.latestTurn?.completedAt,
14 ];
15 let latest: string | null = null;
16 let latestTimestamp = Number.NEGATIVE_INFINITY;
17
18 for (const candidate of candidates) {
19 if (candidate === null || candidate === undefined) continue;
20 const timestamp = Date.parse(candidate);
21 if (timestamp > latestTimestamp) {
22 latest = candidate;
23 latestTimestamp = timestamp;
24 }
25 }
26
27 return latest;
28}
29
30/**
31 * A queued turn start lives for at most this long: session adoption takes
32 * seconds, so a user message still unadopted after the grace window is a
33 * failed start (or stale data — shells from older servers can carry user
34 * messages with no latestTurn at all), not pending work. Without this bound
35 * such threads would be permanently unsettleable.
36 */
37export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
38
39/**
40 * A user message no turn has picked up yet: the turn.start command was
41 * dispatched (message-sent + turn-start-requested) but no session has
42 * adopted it, so `session` is still null and the pending work is invisible
43 * to the session-status checks. Detectable as a user message strictly newer
44 * than every timestamp on the latest turn — on adoption the new turn's
45 * requestedAt equals the message time, clearing the condition — and only
46 * within the adoption grace window.
47 */
48export function hasQueuedTurnStart(
49 shell: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn" | "session">,
50 options: { readonly now: string },
51): boolean {
52 if (shell.latestUserMessageAt == null) return false;
53 // A failed session start clears the queued state: the failure is already
54 // visible (status edge / error).
55 if (shell.session?.status === "error") return false;
56 const messageAt = Date.parse(shell.latestUserMessageAt);
57 if (Number.isNaN(messageAt)) return false;
58 const nowMs = Date.parse(options.now);
59 if (Number.isNaN(nowMs)) return false;
60 // Bounded on both sides: message timestamps originate on whichever device
61 // sent the message, so a clock ahead of this one yields a negative age
62 // that would otherwise hold the queued state for the whole skew. Mirrors
63 // the decider's guard.
64 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
65 const turn = shell.latestTurn;
66 if (turn === null) return true;
67 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
68 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
69 );
70}
71
72/**
73 * A thread may be settled only when none of effectiveSettled's activity
74 * blockers hold. This is deliberately the same list: anything the partition
75 * refuses to CLASSIFY as settled must also be refused as a settle TARGET.
76 * The server enforces its own invariants; this client-side twin exists so
77 * the UI can disable/reject before a round trip.
78 */
79export function canSettle(
80 shell: Pick<
81 OrchestrationThreadShell,
82 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "latestUserMessageAt" | "latestTurn"
83 >,
84 options: { readonly now: string },
85): boolean {
86 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
87 if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
88 // Queued work is as blocked-on-progress as a live session: settling it
89 // (or auto-settling it on a closed PR) would hide a just-requested turn.
90 if (hasQueuedTurnStart(shell, options)) return false;
91 return true;
92}
93
94/**
95 * The snooze lifecycle fields plus everything needed to detect a raised
96 * hand. Snooze is an overlay on the active state: a snoozed thread stays
97 * "active" in the data model and is only suppressed from the inbox until
98 * its wake time passes or the thread demands attention.
99 */
100export type ThreadSnoozeShell = Pick<
101 OrchestrationThreadShell,
102 | "snoozedUntil"
103 | "snoozedAt"
104 | "hasPendingApprovals"
105 | "hasPendingUserInput"
106 | "session"
107 | "latestTurn"
108>;
109
110/**
111 * A snoozed thread "raises its hand" when something happens that outranks
112 * the user's snooze: the agent is blocked on them (approval / user input),
113 * the session failed, or a run completed after the snooze was set — the
114 * v1 taste of event-based snooze ("something happened" wakes early).
115 * Raising a hand never clears the server-side snooze fields; it only stops
116 * the thread from CLASSIFYING as snoozed, exactly like blocked work and
117 * effectiveSettled.
118 */
119export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
120 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
121 // Only a FRESH failure raises the hand: a thread snoozed while already
122 // failed stays snoozed — that snooze was the user saying "I saw it, not
123 // now". session.updatedAt stamps the status edge, so an error newer than
124 // the snooze is new information.
125 if (
126 shell.session?.status === "error" &&
127 (shell.snoozedAt == null || Date.parse(shell.session.updatedAt) > Date.parse(shell.snoozedAt))
128 ) {
129 return true;
130 }
131 if (
132 shell.snoozedAt != null &&
133 shell.latestTurn?.state === "completed" &&
134 shell.latestTurn.completedAt != null &&
135 Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
136 ) {
137 return true;
138 }
139 return false;
140}
141
142/**
143 * A thread may be snoozed unless the agent is blocked on the user: hiding a
144 * pending approval or user-input request defeats the request, and a queued
145 * turn start (a message no turn has adopted yet) is invisible pending work
146 * the same way it is for settle. A running session IS snoozable — snooze
147 * only affects visibility, never the agent. Client-side twin of the server
148 * invariants so the UI can reject before a round trip.
149 */
150export function canSnooze(
151 shell: Pick<
152 OrchestrationThreadShell,
153 "hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
154 >,
155 options: { readonly now: string },
156): boolean {
157 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
158 if (hasQueuedTurnStart(shell, options)) return false;
159 return true;
160}
161
162/**
163 * Snoozed resolution: hidden from the inbox while the wake time is in the
164 * future and the thread has not raised its hand. Timer wakes are derived —
165 * no server event fires when snoozedUntil passes; the stale fields simply
166 * stop classifying as snoozed (and feed the woke indicator until the user
167 * visits or re-engages).
168 */
169export function effectiveSnoozed(
170 shell: ThreadSnoozeShell,
171 options: { readonly now: string },
172): boolean {
173 if (shell.snoozedUntil == null) return false;
174 const wakeAtMs = Date.parse(shell.snoozedUntil);
175 // Malformed data never hides a thread.
176 if (Number.isNaN(wakeAtMs)) return false;
177 if (wakeAtMs <= Date.parse(options.now)) return false;
178 return !threadRaisedHandWhileSnoozed(shell);
179}
180
181/**
182 * When a previously-snoozed thread woke, or null if it never snoozed / is
183 * still snoozed. Used for the "Woke" indicator: the thread reappears in its
184 * original sort position (the inbox sort is deliberately static), so the
185 * wake signal has to carry the weight. Compare against the client's
186 * lastVisitedAt — visiting clears the indicator like it clears unread.
187 *
188 * Timer wakes report the wake time itself; raised-hand wakes report the
189 * triggering timestamp so a visit BEFORE the early wake doesn't suppress
190 * the indicator.
191 */
192export function threadWokeAt(
193 shell: ThreadSnoozeShell,
194 options: { readonly now: string },
195): string | null {
196 if (shell.snoozedUntil == null) return null;
197 const wakeAtMs = Date.parse(shell.snoozedUntil);
198 if (Number.isNaN(wakeAtMs)) return null;
199 // An early hand-raise wake stays authoritative even after the scheduled
200 // wake time passes: reporting snoozedUntil then would resurface a Woke
201 // indicator the user already cleared by visiting (snoozedUntil is newer
202 // than that visit's lastVisitedAt).
203 if (threadRaisedHandWhileSnoozed(shell)) {
204 if (
205 shell.snoozedAt != null &&
206 shell.latestTurn?.state === "completed" &&
207 shell.latestTurn.completedAt != null &&
208 Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
209 ) {
210 return shell.latestTurn.completedAt;
211 }
212 return shell.session?.updatedAt ?? shell.snoozedAt ?? null;
213 }
214 // No raised hand: woke iff the timer elapsed (still-snoozed → null).
215 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
216}
217
218/**
219 * Settled resolution over the server-backed settled lifecycle. Activity
220 * blockers (pending approval/user-input, a live session, an unadjudicated
221 * queued turn) are checked first and hold a thread active regardless of any
222 * override. Past the blockers, the explicit user override (thread.settle /
223 * thread.unsettle commands, projected into settledOverride + settledAt)
224 * wins in both directions; without one, a thread auto-settles on a
225 * merged/closed PR immediately or on inactivity past the window — except
226 * that an open PR blocks the inactivity path entirely. The server
227 * un-settles on real activity (user message, session start, approval/
228 * user-input request), so an override never goes stale silently.
229 */
230export function effectiveSettled(
231 shell: OrchestrationThreadShell,
232 options: {
233 readonly now: string;
234 readonly autoSettleAfterDays: number | null;
235 readonly changeRequestState?: ChangeRequestStateLike | null;
236 },
237): boolean {
238 // Blocked work must remain visible even when a user explicitly settled it.
239 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
240 if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
241 if (hasQueuedTurnStart(shell, { now: options.now })) {
242 // The queued-turn blocker alone is forgivable: it is clock-derived, and
243 // list callers pass a coarser `now` than the settle action used. When
244 // the server already adjudicated the queued message by accepting a
245 // settle after it (settledAt stamps server accept time), trust that
246 // ruling — otherwise a settle near the grace boundary leaves the row
247 // pinned active until the caller's clock ticks over. A message NEWER
248 // than settledAt is genuinely new work and keeps the block until the
249 // server's auto-unsettle lands.
250 const serverAdjudicated =
251 shell.settledOverride === "settled" &&
252 shell.settledAt !== null &&
253 shell.latestUserMessageAt !== null &&
254 Date.parse(shell.settledAt) >= Date.parse(shell.latestUserMessageAt);
255 if (!serverAdjudicated) return false;
256 }
257 if (shell.settledOverride === "settled") return true;
258 // "active" is the explicit keep-active pin: it suppresses auto-settle
259 // until real activity clears it server-side.
260 if (shell.settledOverride === "active") return false;
261 if (options.changeRequestState === "merged" || options.changeRequestState === "closed") {
262 return true;
263 }
264 // An open PR is unfinished business regardless of how long the thread has
265 // been quiet: review can take days, and hiding the thread would bury the
266 // work waiting on it. Only merge/close (above) or an explicit user settle
267 // resolves it.
268 if (options.changeRequestState === "open") return false;
269 if (options.autoSettleAfterDays === null) return false;
270
271 const lastActivityAt = threadLastActivityAt(shell);
272 if (lastActivityAt === null) return false;
273
274 // threadLastActivityAt only returns candidates whose Date.parse beat
275 // -Infinity, so this parse is a real number; a malformed `now` yields NaN,
276 // the comparison is false, and the thread stays active (never a surprise
277 // auto-settle on bad input).
278 return (
279 Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
280 );
281}
282
283const HOUR_MS = 60 * 60 * 1_000;
284const EVENING_HOUR = 18;
285const MORNING_HOUR = 9;
286
287export type SnoozePresetId = "hour" | "evening" | "tomorrow" | "next-week";
288
289export interface SnoozePreset {
290 readonly id: SnoozePresetId;
291 readonly label: string;
292 /** Menu-row time column. Complements the label instead of repeating it:
293 "Tomorrow" pairs with "9:00 AM", not "tomorrow 9:00 AM". */
294 readonly whenLabel: string;
295 /** ISO wake time. */
296 readonly snoozedUntil: string;
297}
298
299function snoozeTimeOfDayLabel(date: Date): string {
300 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
301}
302
303function snoozeAtHour(base: Date, hour: number): Date {
304 const next = new Date(base);
305 next.setHours(hour, 0, 0, 0);
306 return next;
307}
308
309// Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
310// land on the wrong local day across DST transitions (a spring-forward day
311// is 23 hours, so 23:30 + 24h skips the whole next day).
312function addSnoozeDays(base: Date, days: number): Date {
313 const next = new Date(base);
314 next.setDate(next.getDate() + days);
315 return next;
316}
317
318/**
319 * Shared "snooze until" choices for every client. "This evening" only
320 * appears while it is meaningfully before evening; after that the list
321 * starts at "Tomorrow".
322 */
323export function resolveSnoozePresets(now: Date): ReadonlyArray<SnoozePreset> {
324 const inAnHour = new Date(now.getTime() + HOUR_MS);
325 const presets: SnoozePreset[] = [
326 {
327 id: "hour",
328 label: "In 1 hour",
329 whenLabel: snoozeTimeOfDayLabel(inAnHour),
330 snoozedUntil: inAnHour.toISOString(),
331 },
332 ];
333
334 const evening = snoozeAtHour(now, EVENING_HOUR);
335 if (evening.getTime() - now.getTime() > HOUR_MS) {
336 presets.push({
337 id: "evening",
338 label: "This evening",
339 whenLabel: snoozeTimeOfDayLabel(evening),
340 snoozedUntil: evening.toISOString(),
341 });
342 }
343
344 const tomorrow = snoozeAtHour(addSnoozeDays(now, 1), MORNING_HOUR);
345 presets.push({
346 id: "tomorrow",
347 label: "Tomorrow",
348 whenLabel: snoozeTimeOfDayLabel(tomorrow),
349 snoozedUntil: tomorrow.toISOString(),
350 });
351
352 const daysUntilMonday = (1 - now.getDay() + 7) % 7 || 7;
353 const nextWeek = snoozeAtHour(addSnoozeDays(now, daysUntilMonday), MORNING_HOUR);
354 presets.push({
355 id: "next-week",
356 label: "Next week",
357 whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${snoozeTimeOfDayLabel(nextWeek)}`,
358 snoozedUntil: nextWeek.toISOString(),
359 });
360
361 return presets;
362}
363
364/**
365 * Compact "wakes in" label for snoozed rows: "2h", "18h", "3d". Minutes
366 * round up so a snooze never reads "0m" while still hidden. Shared by web
367 * and mobile so the same wake time never reads differently per client.
368 */
369export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: string }): string {
370 const wakeMs = Date.parse(snoozedUntil);
371 const nowMs = Date.parse(options.now);
372 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return "now";
373 const remainingMs = wakeMs - nowMs;
374 if (remainingMs <= 0) return "now";
375 if (remainingMs < HOUR_MS) return `${Math.max(1, Math.ceil(remainingMs / 60_000))}m`;
376 if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
377 return `${Math.ceil(remainingMs / DAY_MS)}d`;
378}