Open History to see the last commit
1import type { OrchestrationThreadShell } from "@t3tools/contracts";
2
3export type ChangeRequestStateLike = "open" | "closed" | "merged";
4
5const DAY_MS = 24 * 60 * 60 * 1_000;
6
7export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
8 const candidates = [
9 shell.latestUserMessageAt,
10 shell.latestTurn?.requestedAt,
11 shell.latestTurn?.startedAt,
12 shell.latestTurn?.completedAt,
13 ];
14 let latest: string | null = null;
15 let latestTimestamp = Number.NEGATIVE_INFINITY;
16
17 for (const candidate of candidates) {
18 if (candidate === null || candidate === undefined) continue;
19 const timestamp = Date.parse(candidate);
20 if (timestamp > latestTimestamp) {
21 latest = candidate;
22 latestTimestamp = timestamp;
23 }
24 }
25
26 return latest;
27}
28
29/**
30 * A queued turn start lives for at most this long: session adoption takes
31 * seconds, so a user message still unadopted after the grace window is a
32 * failed start (or stale data — shells from older servers can carry user
33 * messages with no latestTurn at all), not pending work. Without this bound
34 * such threads would be permanently unsettleable.
35 */
36export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
37
38/**
39 * A user message no turn has picked up yet: the turn.start command was
40 * dispatched (message-sent + turn-start-requested) but no session has
41 * adopted it, so `session` is still null and the pending work is invisible
42 * to the session-status checks. Detectable as a user message strictly newer
43 * than every timestamp on the latest turn — on adoption the new turn's
44 * requestedAt equals the message time, clearing the condition — and only
45 * within the adoption grace window.
46 */
47export function hasQueuedTurnStart(
48 shell: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn" | "session">,
49 options: { readonly now: string },
50): boolean {
51 if (shell.latestUserMessageAt == null) return false;
52 // A failed session start clears the queued state: the failure is already
53 // visible (status edge / error).
54 if (shell.session?.status === "error") return false;
55 const messageAt = Date.parse(shell.latestUserMessageAt);
56 if (Number.isNaN(messageAt)) return false;
57 const nowMs = Date.parse(options.now);
58 if (Number.isNaN(nowMs)) return false;
59 // Bounded on both sides: message timestamps originate on whichever device
60 // sent the message, so a clock ahead of this one yields a negative age
61 // that would otherwise hold the queued state for the whole skew. Mirrors
62 // the decider's guard.
63 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
64 const turn = shell.latestTurn;
65 if (turn === null) return true;
66 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
67 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
68 );
69}
70
71/**
72 * A thread may be settled only when none of effectiveSettled's activity
73 * blockers hold. This is deliberately the same list: anything the partition
74 * refuses to CLASSIFY as settled must also be refused as a settle TARGET.
75 * The server enforces its own invariants; this client-side twin exists so
76 * the UI can disable/reject before a round trip.
77 */
78export function canSettle(
79 shell: Pick<
80 OrchestrationThreadShell,
81 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "latestUserMessageAt" | "latestTurn"
82 >,
83 options: { readonly now: string },
84): boolean {
85 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
86 if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
87 // Queued work is as blocked-on-progress as a live session: settling it
88 // (or auto-settling it on a closed PR) would hide a just-requested turn.
89 if (hasQueuedTurnStart(shell, options)) return false;
90 return true;
91}
92
93/**
94 * The snooze lifecycle fields plus everything needed to detect a raised
95 * hand. Snooze is an overlay on the active state: a snoozed thread stays
96 * "active" in the data model and is only suppressed from the inbox until
97 * its wake time passes or the thread demands attention.
98 */
99export type ThreadSnoozeShell = Pick<
100 OrchestrationThreadShell,
101 | "snoozedUntil"
102 | "snoozedAt"
103 | "hasPendingApprovals"
104 | "hasPendingUserInput"
105 | "session"
106 | "latestTurn"
107>;
108
109/**
110 * A snoozed thread "raises its hand" when something happens that outranks
111 * the user's snooze: the agent is blocked on them (approval / user input),
112 * the session failed, or a run completed after the snooze was set — the
113 * v1 taste of event-based snooze ("something happened" wakes early).
114 * Raising a hand never clears the server-side snooze fields; it only stops
115 * the thread from CLASSIFYING as snoozed, exactly like blocked work and
116 * effectiveSettled.
117 */
118export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
119 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
120 // Only a FRESH failure raises the hand: a thread snoozed while already
121 // failed stays snoozed — that snooze was the user saying "I saw it, not
122 // now". session.updatedAt stamps the status edge, so an error newer than
123 // the snooze is new information.
124 if (
125 shell.session?.status === "error" &&
126 (shell.snoozedAt == null || Date.parse(shell.session.updatedAt) > Date.parse(shell.snoozedAt))
127 ) {
128 return true;
129 }
130 if (
131 shell.snoozedAt != null &&
132 shell.latestTurn?.state === "completed" &&
133 shell.latestTurn.completedAt != null &&
134 Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
135 ) {
136 return true;
137 }
138 return false;
139}
140
141/**
142 * A thread may be snoozed unless the agent is blocked on the user: hiding a
143 * pending approval or user-input request defeats the request, and a queued
144 * turn start (a message no turn has adopted yet) is invisible pending work
145 * the same way it is for settle. A running session IS snoozable — snooze
146 * only affects visibility, never the agent. Client-side twin of the server
147 * invariants so the UI can reject before a round trip.
148 */
149export function canSnooze(
150 shell: Pick<
151 OrchestrationThreadShell,
152 "hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
153 >,
154 options: { readonly now: string },
155): boolean {
156 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
157 if (hasQueuedTurnStart(shell, options)) return false;
158 return true;
159}
160
161/**
162 * Snoozed resolution: hidden from the inbox while the wake time is in the
163 * future and the thread has not raised its hand. Timer wakes are derived —
164 * no server event fires when snoozedUntil passes; the stale fields simply
165 * stop classifying as snoozed (and feed the woke indicator until the user
166 * visits or re-engages).
167 */
168export function effectiveSnoozed(
169 shell: ThreadSnoozeShell,
170 options: { readonly now: string },
171): boolean {
172 if (shell.snoozedUntil == null) return false;
173 const wakeAtMs = Date.parse(shell.snoozedUntil);
174 // Malformed data never hides a thread.
175 if (Number.isNaN(wakeAtMs)) return false;
176 if (wakeAtMs <= Date.parse(options.now)) return false;
177 return !threadRaisedHandWhileSnoozed(shell);
178}
179
180/**
181 * When a previously-snoozed thread woke, or null if it never snoozed / is
182 * still snoozed. Used for the "Woke" indicator: the thread reappears in its
183 * original sort position (the inbox sort is deliberately static), so the
184 * wake signal has to carry the weight. Compare against the client's
185 * lastVisitedAt — visiting clears the indicator like it clears unread.
186 *
187 * Timer wakes report the wake time itself; raised-hand wakes report the
188 * triggering timestamp so a visit BEFORE the early wake doesn't suppress
189 * the indicator.
190 */
191export function threadWokeAt(
192 shell: ThreadSnoozeShell,
193 options: { readonly now: string },
194): string | null {
195 if (shell.snoozedUntil == null) return null;
196 const wakeAtMs = Date.parse(shell.snoozedUntil);
197 if (Number.isNaN(wakeAtMs)) return null;
198 // An early hand-raise wake stays authoritative even after the scheduled
199 // wake time passes: reporting snoozedUntil then would resurface a Woke
200 // indicator the user already cleared by visiting (snoozedUntil is newer
201 // than that visit's lastVisitedAt).
202 if (threadRaisedHandWhileSnoozed(shell)) {
203 if (
204 shell.snoozedAt != null &&
205 shell.latestTurn?.state === "completed" &&
206 shell.latestTurn.completedAt != null &&
207 Date.parse(shell.latestTurn.completedAt) > Date.parse(shell.snoozedAt)
208 ) {
209 return shell.latestTurn.completedAt;
210 }
211 return shell.session?.updatedAt ?? shell.snoozedAt ?? null;
212 }
213 // No raised hand: woke iff the timer elapsed (still-snoozed → null).
214 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
215}
216
217/**
218 * A merged/closed change request settles its thread only once the thread has
219 * been idle this long. Without the idle guard the merge signal is permanent:
220 * sending a message to a merged-PR thread would un-settle the row only until
221 * its turn completed, then the still-merged PR would snap it straight back
222 * into the settled tail. An hour keeps the follow-up conversation visible
223 * while it is warm; once the burst goes stale the merge signal settles it
224 * again. Activity timestamps can originate on another device while `now` is
225 * this caller's clock: skew shortens or stretches the window by its size,
226 * the same exposure the inactivity auto-settle already accepts — worst case
227 * is a row changing lists early or late, never lost work.
228 */
229export const CHANGE_REQUEST_SETTLE_IDLE_MS = 60 * 60 * 1_000;
230
231/**
232 * Settled resolution over the server-backed settled lifecycle. Activity
233 * blockers (pending approval/user-input, a live session, an unadjudicated
234 * queued turn) are checked first and hold a thread active regardless of any
235 * override. Past the blockers, the explicit user override (thread.settle /
236 * thread.unsettle commands, projected into settledOverride + settledAt)
237 * wins in both directions; without one, a thread auto-settles on a
238 * merged/closed PR (once idle) or inactivity past the window. The server
239 * un-settles on real activity (user message, session start, approval/
240 * user-input request), so an override never goes stale silently.
241 */
242export function effectiveSettled(
243 shell: OrchestrationThreadShell,
244 options: {
245 readonly now: string;
246 readonly autoSettleAfterDays: number | null;
247 readonly changeRequestState?: ChangeRequestStateLike | null;
248 },
249): boolean {
250 // Blocked work must remain visible even when a user explicitly settled it.
251 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
252 if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
253 if (hasQueuedTurnStart(shell, { now: options.now })) {
254 // The queued-turn blocker alone is forgivable: it is clock-derived, and
255 // list callers pass a coarser `now` than the settle action used. When
256 // the server already adjudicated the queued message by accepting a
257 // settle after it (settledAt stamps server accept time), trust that
258 // ruling — otherwise a settle near the grace boundary leaves the row
259 // pinned active until the caller's clock ticks over. A message NEWER
260 // than settledAt is genuinely new work and keeps the block until the
261 // server's auto-unsettle lands.
262 const serverAdjudicated =
263 shell.settledOverride === "settled" &&
264 shell.settledAt !== null &&
265 shell.latestUserMessageAt !== null &&
266 Date.parse(shell.settledAt) >= Date.parse(shell.latestUserMessageAt);
267 if (!serverAdjudicated) return false;
268 }
269 if (shell.settledOverride === "settled") return true;
270 // "active" is the explicit keep-active pin: it suppresses auto-settle
271 // until real activity clears it server-side.
272 if (shell.settledOverride === "active") return false;
273 if (options.changeRequestState === "merged" || options.changeRequestState === "closed") {
274 // Only an idle thread settles on the merge signal: the signal itself
275 // never clears, so without this guard fresh activity (a message sent in
276 // a settled thread) would re-settle the moment its turn completed.
277 const lastActivityAt = threadLastActivityAt(shell);
278 if (
279 lastActivityAt === null ||
280 Date.parse(lastActivityAt) < Date.parse(options.now) - CHANGE_REQUEST_SETTLE_IDLE_MS
281 ) {
282 return true;
283 }
284 }
285 if (options.autoSettleAfterDays === null) return false;
286
287 const lastActivityAt = threadLastActivityAt(shell);
288 if (lastActivityAt === null) return false;
289
290 // threadLastActivityAt only returns candidates whose Date.parse beat
291 // -Infinity, so this parse is a real number; a malformed `now` yields NaN,
292 // the comparison is false, and the thread stays active (never a surprise
293 // auto-settle on bad input).
294 return (
295 Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
296 );
297}