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

threadInbox.ts

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