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

threadShell.ts

436 lines17.0 KB

1import type {
2 EnvironmentId,
3 OrchestrationV2ShellSnapshot,
4 ProjectId,
5 ScopedProjectRef,
6 ScopedThreadRef,
7 ThreadId,
8} from "@t3tools/contracts";
9import { isProviderNativeSubagentThread, OrchestrationV2ThreadShell } from "@t3tools/contracts";
10import * as Schema from "effect/Schema";
11import { Atom } from "effect/reactivity";
12​
13import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
14import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
15import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
16import {
17 arrayElementsEqual,
18 parseProjectRefCollectionKey,
19 parseThreadKey,
20 projectRefCollectionKey,
21 threadKey,
22 threadRefsEqual,
23} from "./entities.ts";
24​
25const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([]);
26const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
27const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();
28const EMPTY_SUBAGENT_REQUESTS: ReadonlyMap<ThreadId, PendingSubagentRequest> = new Map();
29const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
30 ProjectId,
31 ReadonlyArray<ScopedThreadRef>
32> = new Map();
33​
34// An async question outlives the subagent's run, but once that run ends the
35// parent is no longer waiting on the answer, so it stops counting as input.
36// The activity run stays set when a follow-up is queued behind a blocked run;
37// older servers omit it, so fall back to the latest run's status.
38const isChildRunLive = (
39 thread: Pick<OrchestrationV2ThreadShell, "activityRunStatus" | "status">,
40) =>
41 thread.activityRunStatus !== undefined
42 ? thread.activityRunStatus !== null
43 : thread.status === "preparing" ||
44 thread.status === "starting" ||
45 thread.status === "running" ||
46 thread.status === "waiting";
47​
48/** Provider-native
49 subagents ask on their parent, so they are skipped. */
50function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {
51 const kind = thread.pendingRuntimeRequest?.kind;
52 if (
53 kind === undefined ||
54 kind === "auth_refresh" ||
55 thread.lineage.relationshipToParent !== "subagent" ||
56 isProviderNativeSubagentThread(thread) ||
57 !isChildRunLive(thread)
58 ) {
59 return null;
60 }
61 return kind === "user_input" ? "user_input" : "approval";
63​
64export function pendingSubagentRequestsByThread(
65 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
66): ReadonlyMap<ThreadId, PendingSubagentRequest> {
67 const requests = new Map<ThreadId, PendingSubagentRequest>();
68 let byId: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> | undefined;
69 for (const child of threads) {
70 const request = subagentRequest(child);
71 if (request === null) continue;
72 byId ??= new Map(threads.map((thread) => [thread.id, thread] as const));
73 const seen = new Set<ThreadId>([child.id]);
74 let current: OrchestrationV2ThreadShell | undefined = child;
75 while (current?.lineage.relationshipToParent === "subagent") {
76 const parentId: ThreadId | null = current.lineage.parentThreadId;
77 if (parentId === null || seen.has(parentId)) break;
78 seen.add(parentId);
79 if (requests.get(parentId) !== "approval") requests.set(parentId, request);
80 current = byId.get(parentId);
81 }
82 }
83 return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests;
85​
86export function childThreadInputsTitle(
87 children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals">>,
88): string {
89 const approvals = children.filter((child) => child.hasPendingApprovals).length;
90 const need = approvals === 0 ? "input" : approvals === children.length ? "approval" : "you";
91 return children.length === 1
92 ? `Subagent needs ${need}`
93 : `${children.length} subagents need ${need}`;
95​
96const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
97​
98// While a run streams, the server bumps the shell's timestamps, item counts and
99// latest message several times a second. Only the zero crossing of the counts
100// says anything (whether the thread has started). Once the run stops every
101// field counts again, so snooze wakes and failure times read the current value.
102function sameApartFromStreaming(
103 previous: EnvironmentThreadShell,
104 next: EnvironmentThreadShell,
105): boolean {
106 if (
107 previous.environmentId !== next.environmentId ||
108 previous.pendingSubagentRequest !== next.pendingSubagentRequest ||
109 !threadRuntimeIsActive(next.runtime)
110 ) {
111 return false;
112 }
113 const before = previous.source;
114 const after = next.source;
115 return (
116 before.itemCount > 0 === after.itemCount > 0 &&
117 before.visibleItemCount > 0 === after.visibleItemCount > 0 &&
118 sameWireThreadShell(
119 {
120 ...before,
121 updatedAt: after.updatedAt,
122 itemCount: after.itemCount,
123 visibleItemCount: after.visibleItemCount,
124 latestVisibleMessage: after.latestVisibleMessage,
125 },
126 after,
127 )
128 );
130​
131export function createEnvironmentThreadShellAtoms(input: {
132 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
133 readonly snapshotAtom: (
134 environmentId: EnvironmentId,
135 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
136}) {
137 // Point reads and aggregate lists share values without keeping an atom alive
138 // for every listed thread. Replaced source objects can be collected.
139 const scopedThreads = new WeakMap<
140 OrchestrationV2ThreadShell,
141 Map<string, EnvironmentThreadShell>
142 >();
143 const scopedThread = (
144 environmentId: EnvironmentId,
145 thread: OrchestrationV2ThreadShell,
146 subagentRequests: ReadonlyMap<ThreadId, PendingSubagentRequest>,
147 ) => {
148 let byEnvironment = scopedThreads.get(thread);
149 if (byEnvironment === undefined) {
150 byEnvironment = new Map();
151 scopedThreads.set(thread, byEnvironment);
152 }
153 const request = subagentRequests.get(thread.id) ?? null;
154 const key = request === null ? environmentId : `${environmentId}:${request}`;
155 let value = byEnvironment.get(key);
156 if (value === undefined) {
157 value = presentThreadShell(environmentId, thread, request);
158 byEnvironment.set(key, value);
159 }
160 return value;
161 };
162​
163 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
164 Atom.make(
165 (get): ReadonlyArray<OrchestrationV2ThreadShell> =>
166 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
167 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
168 );
169​
170 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
171 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
172 const threads = get(environmentThreadsAtom(environmentId));
173 if (threads.length === 0) {
174 return EMPTY_THREAD_INDEX;
175 }
176 return new Map(threads.map((thread) => [thread.id, thread] as const));
177 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
178 );
179​
180 const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {
181 let previous = EMPTY_SUBAGENT_REQUESTS;
182 return Atom.make((get) => {
183 const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId)));
184 if (
185 next.size === previous.size &&
186 [...next].every(([threadId, request]) => previous.get(threadId) === request)
187 ) {
188 return previous;
189 }
190 previous = next;
191 return next;
192 }).pipe(Atom.withLabel(`environment-pending-subagent-requests:${environmentId}`));
193 });
194​
195 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
196 let previous: ReadonlyArray<ScopedThreadRef> = [];
197 return Atom.make((get) => {
198 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
199 environmentId,
200 threadId: thread.id,
201 }));
202 if (threadRefsEqual(previous, next)) {
203 return previous;
204 }
205 previous = next;
206 return next;
207 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
208 });
209​
210 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
211 let previous: ReadonlyMap<
212 ProjectId,
213 ReadonlyArray<ScopedThreadRef>
214 > = EMPTY_THREAD_REFS_BY_PROJECT;
215 return Atom.make((get) => {
216 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
217 for (const thread of get(environmentThreadsAtom(environmentId))) {
218 const refs = grouped.get(thread.projectId);
219 const ref = { environmentId, threadId: thread.id };
220 if (refs === undefined) {
221 grouped.set(thread.projectId, [ref]);
222 } else {
223 refs.push(ref);
224 }
225 }
226 if (grouped.size === 0) {
227 previous = EMPTY_THREAD_REFS_BY_PROJECT;
228 return previous;
229 }
230 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
231 for (const [projectId, refs] of grouped) {
232 const previousRefs = previous.get(projectId);
233 next.set(
234 projectId,
235 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
236 );
237 }
238 const previousProjectIds = [...previous.keys()];
239 if (
240 next.size === previous.size &&
241 [...next].every(
242 ([projectId, refs], index) =>
243 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
244 )
245 ) {
246 return previous;
247 }
248 previous = next;
249 return previous;
250 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
251 });
252​
253 const threadShellAtomFamily = Atom.family((key: string) => {
254 const ref = parseThreadKey(key);
255 return Atom.make((get) => {
256 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
257 return source === null
258 ? null
259 : scopedThread(
260 ref.environmentId,
261 source,
262 get(pendingSubagentRequestsAtom(ref.environmentId)),
263 );
264 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
265 });
266​
267 // Keeps the previous shell while only streaming ticks changed. During a run,
268 // its timestamps, item counts and latest message are as of the last kept
269 // change; anything that needs them current reads threadShellAtom.
270 const quietThreadShellAtomFamily = Atom.family((key: string) => {
271 let previous: EnvironmentThreadShell | null = null;
272 return Atom.make((get) => {
273 const next = get(threadShellAtomFamily(key));
274 if (previous !== null && next !== null && sameApartFromStreaming(previous, next)) {
275 return previous;
276 }
277 previous = next;
278 return next;
279 }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`));
280 });
281​
282 // Child approvals and questions are hidden with their sidebar rows. Read their
283 // shell summaries, without subscribing to every child transcript.
284 const childThreadInputsAtomFamily = Atom.family((key: string) => {
285 const ref = parseThreadKey(key);
286 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
287 return Atom.make((get) => {
288 const children = new Map<ThreadId, OrchestrationV2ThreadShell[]>();
289 for (const thread of get(environmentThreadsAtom(ref.environmentId))) {
290 const parent = thread.lineage.parentThreadId;
291 if (parent === null || thread.lineage.relationshipToParent !== "subagent") continue;
292 const siblings = children.get(parent);
293 if (siblings) siblings.push(thread);
294 else children.set(parent, [thread]);
295 }
296 const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));
297 const seen = new Set<ThreadId>([ref.threadId]);
298 const pending = [ref.threadId];
299 const next: EnvironmentThreadShell[] = [];
300 for (const parent of pending) {
301 for (const child of children.get(parent) ?? []) {
302 if (seen.has(child.id)) continue;
303 seen.add(child.id);
304 pending.push(child.id);
305 if (subagentRequest(child) !== null) {
306 next.push(scopedThread(ref.environmentId, child, subagentRequests));
307 }
308 }
309 }
310 // Indicators read only ids, titles and the request kind, so other shell
311 // updates keep the old array.
312 if (
313 previous.length === next.length &&
314 previous.every(
315 (thread, index) =>
316 thread.id === next[index]?.id &&
317 thread.title === next[index]?.title &&
318 thread.hasPendingApprovals === next[index]?.hasPendingApprovals,
319 )
320 ) {
321 return previous;
322 }
323 previous = next;
324 return next;
325 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
326 });
327​
328 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
329 const projectRefs = parseProjectRefCollectionKey(key);
330 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
331 return Atom.make((get) => {
332 const next: EnvironmentThreadShell[] = [];
333 const seen = new Set<string>();
334 for (const projectRef of projectRefs) {
335 const refs =
336 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
337 projectRef.projectId,
338 ) ?? EMPTY_SCOPED_THREAD_REFS;
339 if (refs.length === 0) continue;
340 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
341 const subagentRequests = get(pendingSubagentRequestsAtom(projectRef.environmentId));
342 for (const ref of refs) {
343 const key = threadKey(ref);
344 if (seen.has(key)) {
345 continue;
346 }
347 seen.add(key);
348 const thread = threads.get(ref.threadId);
349 if (thread !== undefined) {
350 next.push(scopedThread(ref.environmentId, thread, subagentRequests));
351 }
352 }
353 }
354 if (arrayElementsEqual(previous, next)) {
355 return previous;
356 }
357 previous = next;
358 return previous;
359 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
360 });
361​
362 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
363 const threadRefsAtom = Atom.make((get) => {
364 const refs: ScopedThreadRef[] = [];
365 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
366 refs.push(...get(environmentThreadRefsAtom(environmentId)));
367 }
368 if (threadRefsEqual(previousThreadRefs, refs)) {
369 return previousThreadRefs;
370 }
371 previousThreadRefs = refs;
372 return refs;
373 }).pipe(Atom.withLabel("environment-thread-refs"));
374​
375 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
376 const threadShellsAtom = Atom.make((get) => {
377 const next: EnvironmentThreadShell[] = [];
378 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
379 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
380 for (const thread of get(environmentThreadsAtom(environmentId))) {
381 next.push(scopedThread(environmentId, thread, subagentRequests));
382 }
383 }
384 if (arrayElementsEqual(previousThreadShells, next)) {
385 return previousThreadShells;
386 }
387 previousThreadShells = next;
388 return previousThreadShells;
389 }).pipe(Atom.withLabel("environment-thread-shell-list"));
390​
391 // Lists that arrange threads read this, so a running thread's streaming
392 // ticks reach only what reads its live shell.
393 let previousQuietThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
394 const quietThreadShellsAtom = Atom.make((get) => {
395 const next: EnvironmentThreadShell[] = [];
396 for (const ref of get(threadRefsAtom)) {
397 const shell = get(quietThreadShellAtomFamily(threadKey(ref)));
398 if (shell !== null) next.push(shell);
399 }
400 if (arrayElementsEqual(previousQuietThreadShells, next)) return previousQuietThreadShells;
401 previousQuietThreadShells = next;
402 return next;
403 }).pipe(Atom.withLabel("environment-quiet-thread-shell-list"));
404​
405 let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];
406 const navigationThreadShellsAtom = Atom.make((get) => {
407 const next: EnvironmentThreadShell[] = [];
408 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
409 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
410 for (const thread of get(environmentThreadsAtom(environmentId))) {
411 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
412 continue;
413 next.push(scopedThread(environmentId, thread, subagentRequests));
414 }
415 }
416 if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells;
417 previousNavigationShells = next;
418 return next;
419 }).pipe(Atom.withLabel("environment-navigation-thread-shells"));
420​
421 return {
422 environmentThreadsAtom,
423 environmentThreadIndexAtom,
424 environmentThreadRefsAtom,
425 environmentThreadRefsByProjectAtom,
426 threadRefsAtom,
427 threadShellsAtom,
428 quietThreadShellsAtom,
429 navigationThreadShellsAtom,
430 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
431 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
432 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
433 quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),
434 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
435 };