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

threadSettled.ts

274 lines11.4 KB

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;
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 );
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;
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;
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;
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);
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;
216​
217/**
218 * Settled resolution over the server-backed settled lifecycle. Activity
219 * blockers (pending approval/user-input, a live session, an unadjudicated
220 * queued turn) are checked first and hold a thread active regardless of any
221 * override. Past the blockers, the explicit user override (thread.settle /
222 * thread.unsettle commands, projected into settledOverride + settledAt)
223 * wins in both directions; without one, a thread auto-settles on a
224 * merged/closed PR immediately or on inactivity past the window. The server
225 * un-settles on real activity (user message, session start, approval/
226 * user-input request), so an override never goes stale silently.
227 */
228export function effectiveSettled(
229 shell: OrchestrationThreadShell,
230 options: {
231 readonly now: string;
232 readonly autoSettleAfterDays: number | null;
233 readonly changeRequestState?: ChangeRequestStateLike | null;
234 },
235): boolean {
236 // Blocked work must remain visible even when a user explicitly settled it.
237 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
238 if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
239 if (hasQueuedTurnStart(shell, { now: options.now })) {
240 // The queued-turn blocker alone is forgivable: it is clock-derived, and
241 // list callers pass a coarser `now` than the settle action used. When
242 // the server already adjudicated the queued message by accepting a
243 // settle after it (settledAt stamps server accept time), trust that
244 // ruling — otherwise a settle near the grace boundary leaves the row
245 // pinned active until the caller's clock ticks over. A message NEWER
246 // than settledAt is genuinely new work and keeps the block until the
247 // server's auto-unsettle lands.
248 const serverAdjudicated =
249 shell.settledOverride === "settled" &&
250 shell.settledAt !== null &&
251 shell.latestUserMessageAt !== null &&
252 Date.parse(shell.settledAt) >= Date.parse(shell.latestUserMessageAt);
253 if (!serverAdjudicated) return false;
254 }
255 if (shell.settledOverride === "settled") return true;
256 // "active" is the explicit keep-active pin: it suppresses auto-settle
257 // until real activity clears it server-side.
258 if (shell.settledOverride === "active") return false;
259 if (options.changeRequestState === "merged" || options.changeRequestState === "closed") {
260 return true;
261 }
262 if (options.autoSettleAfterDays === null) return false;
263​
264 const lastActivityAt = threadLastActivityAt(shell);
265 if (lastActivityAt === null) return false;
266​
267 // threadLastActivityAt only returns candidates whose Date.parse beat
268 // -Infinity, so this parse is a real number; a malformed `now` yields NaN,
269 // the comparison is false, and the thread stays active (never a surprise
270 // auto-settle on bad input).
271 return (
272 Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
273 );