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