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