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

threadSettled.ts

461 lines18.3 KB

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