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

threadInbox.ts

280 lines9.8 KB

1// @effect-diagnostics globalTimers:off - Shelf placement timers run in web and native clients, outside an Effect runtime.
2import { threadRuntimeIsActive, type EnvironmentThreadShell } from "./models.ts";
3import { toSortableTimestamp } from "./threadSort.ts";
4import { effectiveSnoozed } from "./threadSettled.ts";
5​
6type WorkingThreadInput = Pick<
7 EnvironmentThreadShell,
8 | "hasActionableProposedPlan"
9 | "hasPendingApprovals"
10 | "hasPendingUserInput"
11 | "pendingSubagentRequest"
12 | "interactionMode"
13 | "latestRun"
14 | "runtime"
15>;
16​
17export function isThreadWorking(thread: WorkingThreadInput): boolean {
18 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return false;
19 if (thread.pendingSubagentRequest != null) return false;
20 if (!threadRuntimeIsActive(thread.runtime) && thread.runtime?.status !== "idle") return false;
21 const run = thread.latestRun;
22 const runSettled =
23 run !== null &&
24 run.status !== "preparing" &&
25 run.status !== "queued" &&
26 run.status !== "starting" &&
27 run.status !== "running" &&
28 run.status !== "waiting" &&
29 thread.runtime?.activeRunId !== run.runId;
30 return !(thread.interactionMode === "plan" && thread.hasActionableProposedPlan && runSettled);
32​
33/**
34 * A thread its own client is launching reads as preparing until its first run lands.
35 * The server commits the thread before its run, so the list would otherwise place it twice.
36 */
37export function asLaunchingThread<T extends EnvironmentThreadShell>(thread: T): T {
38 if (thread.latestRun !== null || thread.runtime !== null) return thread;
39 return {
40 ...thread,
41 runtime: {
42 status: "preparing",
43 activeRunId: null,
44 providerInstanceId: thread.providerInstanceId,
45 providerName: null,
46 lastError: null,
47 updatedAt: thread.updatedAt,
48 },
49 };
51​
52type InboxThreadInput = Pick<
53 EnvironmentThreadShell,
54 "id" | "environmentId" | "createdAt" | "unsettledAt" | "latestRun"
55>;
56​
57export function sortInboxThreadsByReturn<T extends InboxThreadInput>(
58 threads: readonly T[],
59 observedReturnAt?: (thread: T) => number | undefined,
60): T[] {
61 const timestamps = new Map(
62 threads.map((thread) => [
63 thread,
64 Math.max(
65 toSortableTimestamp(thread.createdAt) ?? 0,
66 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
67 toSortableTimestamp(thread.latestRun?.requestedAt ?? undefined) ?? 0,
68 toSortableTimestamp(thread.latestRun?.completedAt ?? undefined) ?? 0,
69 observedReturnAt?.(thread) ?? 0,
70 ),
71 ]),
72 );
73 return sortNewestFirst(threads, timestamps);
75​
76type WorkingSortInput = Pick<
77 EnvironmentThreadShell,
78 "id" | "environmentId" | "createdAt" | "latestRun" | "latestUserAuthoredMessageAt"
79>;
80​
81export function sortWorkingThreadsBySend<T extends WorkingSortInput>(threads: readonly T[]): T[] {
82 const timestamps = new Map(
83 threads.map((thread) => [
84 thread,
85 Math.max(
86 toSortableTimestamp(thread.createdAt) ?? 0,
87 toSortableTimestamp(
88 (thread.latestUserAuthoredMessageAt === undefined
89 ? thread.latestRun?.requestedAt
90 : thread.latestUserAuthoredMessageAt) ?? undefined,
91 ) ?? 0,
92 ),
93 ]),
94 );
95 return sortNewestFirst(threads, timestamps);
97​
98function sortNewestFirst<T extends Pick<EnvironmentThreadShell, "id" | "environmentId">>(
99 threads: readonly T[],
100 timestamps: ReadonlyMap<T, number>,
101): T[] {
102 return [...threads].sort(
103 (left, right) =>
104 timestamps.get(right)! - timestamps.get(left)! ||
105 left.id.localeCompare(right.id) ||
106 left.environmentId.localeCompare(right.environmentId),
107 );
109​
110type TrackedInboxThread = WorkingThreadInput &
111 InboxThreadInput &
112 Partial<
113 Pick<
114 EnvironmentThreadShell,
115 | "archivedAt"
116 | "deletedAt"
117 | "pinnedAt"
118 | "settledOverride"
119 | "settledAt"
120 | "snoozedAt"
121 | "snoozedUntil"
122 | "activeOrderKey"
123 | "pendingGuestMessageCount"
124 >
125 >;
126​
127type ThreadKeyInput = Pick<EnvironmentThreadShell, "environmentId" | "id">;
128​
129/**
130 * How long a thread that stopped working keeps reading as working. An orchestrator
131 * run can end moments before its continuation starts, so clients wait this long
132 * before treating the thread as done.
133 */
134const WORKING_EXIT_GRACE_MS = 2_000;
135​
136/**
137 * A run that ended this long ago has no continuation about to start, so its thread gets no
138 * grace. A client sees this for work that ended while it was closed or disconnected; the
139 * margin is wide so a client clock that runs ahead of the server does not cancel the grace.
140 */
141const STALE_EXIT_MS = 60_000;
142​
143/**
144 * Keep one at module scope so placement survives routes that unmount the list. Call
145 * `observe` when the shells or the snapshot version change, or with null while the beta
146 * is off. Its result stays fixed, so a list built from it can be cached.
147 */
148export function createInboxReturnTracker() {
149 const keyOf = (thread: ThreadKeyInput) => `${thread.environmentId}:${thread.id}`;
150 const states = new Map<
151 string,
152 {
153 working: boolean;
154 deadline: number | null;
155 placement: string | null;
156 endedAt: number | null;
157 }
158 >();
159 const returns = new Map<string, number>();
160 const listeners = new Set<() => void>();
161 let timer: ReturnType<typeof setTimeout> | undefined;
162 let version = 0;
163 const now = () => {
164 // @effect-diagnostics-next-line globalDate:off - The grace deadline is wall-clock time shared by web and native clients.
165 return Date.now();
166 };
167 const schedule = () => {
168 clearTimeout(timer);
169 timer = undefined;
170 let next = Infinity;
171 for (const state of states.values()) {
172 if (state.deadline !== null) next = Math.min(next, state.deadline);
173 }
174 if (next === Infinity) return;
175 timer = setTimeout(
176 () => {
177 const at = now();
178 for (const [key, state] of states) {
179 if (state.deadline !== null && state.deadline <= at) {
180 state.working = false;
181 state.deadline = null;
182 returns.set(key, at);
183 }
184 }
185 schedule();
186 version++;
187 for (const listener of listeners) listener();
188 },
189 Math.max(0, next - now()),
190 );
191 };
192 return {
193 subscribe(listener: () => void) {
194 listeners.add(listener);
195 return () => {
196 listeners.delete(listener);
197 };
198 },
199 getSnapshot: () => version,
200 observe(threads: readonly TrackedInboxThread[] | null): {
201 readonly isWorking: (thread: WorkingThreadInput & ThreadKeyInput) => boolean;
202 readonly returnedAt: (thread: ThreadKeyInput) => number | undefined;
203 } {
204 if (threads === null) {
205 clearTimeout(timer);
206 timer = undefined;
207 states.clear();
208 returns.clear();
209 return { isWorking: isThreadWorking, returnedAt: () => undefined };
210 }
211 const present = new Set<string>();
212 const at = now();
213 // @effect-diagnostics-next-line globalDate:off - Snooze checks compare wall-clock ISO times.
214 const observedAt = new Date(at).toISOString();
215 for (const thread of threads) {
216 const key = keyOf(thread);
217 present.add(key);
218 const previous = states.get(key);
219 const actual = isThreadWorking(thread);
220 const placement =
221 actual || previous?.working
222 ? JSON.stringify([
223 thread.archivedAt,
224 thread.deletedAt,
225 thread.pinnedAt,
226 thread.settledOverride,
227 thread.settledAt,
228 thread.snoozedAt,
229 thread.snoozedUntil,
230 thread.activeOrderKey,
231 ])
232 : null;
233 const actionable =
234 thread.hasPendingApprovals ||
235 thread.hasPendingUserInput ||
236 thread.pendingSubagentRequest != null ||
237 (thread.pendingGuestMessageCount ?? 0) > 0 ||
238 (thread.interactionMode === "plan" && thread.hasActionableProposedPlan) ||
239 thread.runtime?.lastError != null ||
240 thread.latestRun?.status === "failed";
241 const moved = previous !== undefined && previous.placement !== placement;
242 const excluded =
243 thread.archivedAt != null ||
244 thread.deletedAt != null ||
245 thread.pinnedAt != null ||
246 thread.settledOverride === "settled" ||
247 effectiveSnoozed(thread, { now: observedAt });
248 // Only shelf placement is held: execution state and attention requests stay authoritative.
249 const endedAt = toSortableTimestamp(thread.latestRun?.completedAt ?? undefined);
250 // A run end already seen while the thread kept working (background subagents) is not stale.
251 const endedLongAgo =
252 endedAt !== null && endedAt <= at - STALE_EXIT_MS && previous?.endedAt !== endedAt;
253 const deadline =
254 !actual && previous?.working && !actionable && !moved && !excluded && !endedLongAgo
255 ? (previous.deadline ?? at + WORKING_EXIT_GRACE_MS)
256 : null;
257 const working = actual || (deadline !== null && deadline > at);
258 if (previous?.working && !working) returns.set(key, at);
259 states.set(key, { working, deadline: working ? deadline : null, placement, endedAt });
260 }
261 for (const key of states.keys()) {
262 if (!present.has(key)) {
263 states.delete(key);
264 returns.delete(key);
265 }
266 }
267 schedule();
268 const observedWorking = new Map<string, boolean>();
269 states.forEach((state, key) => observedWorking.set(key, state.working));
270 const observedReturns = new Map(returns);
271 return {
272 isWorking: (thread) => observedWorking.get(keyOf(thread)) ?? isThreadWorking(thread),
273 returnedAt: (thread) => observedReturns.get(keyOf(thread)),
274 };
275 },
276 isWorking: (thread: WorkingThreadInput & ThreadKeyInput) =>
277 states.get(keyOf(thread))?.working ?? isThreadWorking(thread),
278 returnedAt: (thread: ThreadKeyInput) => returns.get(keyOf(thread)),
279 };