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

threadShell.ts

673 lines27.0 KB

1import type {
2 EnvironmentId,
3 OrchestrationV2ShellSnapshot,
4 ProjectId,
5 ScopedProjectRef,
6 ScopedThreadRef,
7 ThreadId,
8} from "@t3tools/contracts";
9import {
10 isListedThreadLineage,
11 isProviderNativeSubagentThread,
12 OrchestrationV2ThreadShell,
13} from "@t3tools/contracts";
14import * as Schema from "effect/Schema";
15import { Atom } from "effect/reactivity";
16​
17import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
18import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
19import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
20import {
21 arrayElementsEqual,
22 parseProjectRefCollectionKey,
23 parseThreadKey,
24 projectRefCollectionKey,
25 threadKey,
26 threadRefsEqual,
27} from "./entities.ts";
28​
29const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([]);
30const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
31const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();
32const EMPTY_SUBAGENT_REQUESTS: ReadonlyMap<ThreadId, PendingSubagentRequest> = new Map();
33const EMPTY_SIDE_CHATS_BY_PARENT: ReadonlyMap<
34 ThreadId,
35 ReadonlyArray<OrchestrationV2ThreadShell>
36> = new Map();
37const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = Object.freeze([]);
38const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
39 ProjectId,
40 ReadonlyArray<ScopedThreadRef>
41> = new Map();
42​
43// An async question outlives the subagent's run, but once that run ends the
44// parent is no longer waiting on the answer, so it stops counting as input.
45// The activity run stays set when a follow-up is queued behind a blocked run;
46// older servers omit it, so fall back to the latest run's status.
47const isChildRunLive = (
48 thread: Pick<OrchestrationV2ThreadShell, "activityRunStatus" | "status">,
49) =>
50 thread.activityRunStatus !== undefined
51 ? thread.activityRunStatus !== null
52 : thread.status === "preparing" ||
53 thread.status === "starting" ||
54 thread.status === "running" ||
55 thread.status === "waiting";
56​
57/**
58 * Whether a thread shows under its parent rather than in thread lists: a
59 * subagent, a side chat, or a task a linked environment delegated here whose parent the
60 * client lists (`delegatedUnderParent`, by thread key). A task whose parent
61 * the client cannot list stays in the lists, so its work is never out of reach.
62 */
63export function isShownUnderParent(
64 ref: ScopedThreadRef,
65 lineage: OrchestrationV2ThreadShell["lineage"],
66 delegatedUnderParent: ReadonlySet<string>,
67): boolean {
68 return !isListedThreadLineage(lineage) || delegatedUnderParent.has(threadKey(ref));
70​
71/** Provider-native
72 subagents ask on their parent, so they are skipped. */
73function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {
74 const kind = thread.pendingRuntimeRequest?.kind;
75 if (
76 kind === undefined ||
77 kind === "auth_refresh" ||
78 (thread.lineage.relationshipToParent !== "subagent" && thread.delegatedFrom === undefined) ||
79 isProviderNativeSubagentThread(thread) ||
80 !isChildRunLive(thread)
81 ) {
82 return null;
83 }
84 return kind === "user_input" ? "user_input" : "approval";
86​
87/** A side chat asks its user directly, so questions roll up to the parent as well as approvals. */
88function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {
89 const kind = thread.pendingRuntimeRequest?.kind;
90 if (kind === undefined || kind === "auth_refresh" || thread.lineage.sideChat !== true) {
91 return null;
92 }
93 return kind === "user_input" ? "user_input" : "approval";
95​
96/**
97 * The threads to flag for a subagent's live approval, up its
98 * subagent chain and through a side chat to its parent. `delegated` are tasks this
99 * environment's threads delegated to linked environments, with what each one, or its
100 * own subagents, asks.
101 */
102function pendingSubagentRequestsByThread(
103 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
104 delegated: ReadonlyArray<{
105 readonly parentThreadId: ThreadId;
106 readonly request: PendingSubagentRequest;
107 }> = [],
108): ReadonlyMap<ThreadId, PendingSubagentRequest> {
109 const requests = new Map<ThreadId, PendingSubagentRequest>();
110 let byId: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> | undefined;
111 const flag = (
112 firstParentId: ThreadId | null,
113 request: PendingSubagentRequest,
114 seen: Set<ThreadId>,
115 ) => {
116 // The coordinator answers child questions; only approvals need user attention.
117 if (request === "user_input") return;
118 byId ??= new Map(threads.map((thread) => [thread.id, thread] as const));
119 let parentId = firstParentId;
120 while (parentId !== null && !seen.has(parentId)) {
121 seen.add(parentId);
122 if (requests.get(parentId) !== "approval") requests.set(parentId, request);
123 const parent = byId.get(parentId);
124 parentId =
125 parent?.lineage.relationshipToParent === "subagent" || parent?.lineage.sideChat === true
126 ? parent.lineage.parentThreadId
127 : null;
128 }
129 };
130 for (const child of threads) {
131 const parentId = child.lineage.parentThreadId;
132 if (child.lineage.sideChat === true) {
133 const request = sideChatRequest(child);
134 if (parentId !== null && request !== null && requests.get(parentId) !== "approval") {
135 requests.set(parentId, request);
136 }
137 continue;
138 }
139 if (child.lineage.relationshipToParent !== "subagent") continue;
140 const request = subagentRequest(child);
141 if (request !== null) flag(parentId, request, new Set([child.id]));
142 }
143 for (const task of delegated) flag(task.parentThreadId, task.request, new Set());
144 return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests;
146​
147const sameRequests = (
148 left: ReadonlyMap<ThreadId, PendingSubagentRequest>,
149 right: ReadonlyMap<ThreadId, PendingSubagentRequest>,
150) =>
151 left.size === right.size &&
152 [...right].every(([threadId, request]) => left.get(threadId) === request);
153​
154export function childThreadInputsTitle(
155 children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals" | "lineage">>,
156): string {
157 const approvals = children.filter((child) => child.hasPendingApprovals).length;
158 const need = approvals === 0 ? "input" : approvals === children.length ? "approval" : "you";
159 const sideChats = children.filter((child) => child.lineage.sideChat === true).length;
160 const noun =
161 sideChats === children.length ? "side chat" : sideChats === 0 ? "subagent" : "thread";
162 return children.length === 1
163 ? `${noun === "side chat" ? "Side chat" : "Subagent"} needs ${need}`
164 : `${children.length} ${noun}s need ${need}`;
166​
167const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
168​
169// While a run streams, the server bumps the shell's timestamps, item counts and
170// latest message several times a second. Only the zero crossing of the counts
171// says anything (whether the thread has started). Once the run stops every
172// field counts again, so snooze wakes and failure times read the current value.
173function sameApartFromStreaming(
174 previous: EnvironmentThreadShell,
175 next: EnvironmentThreadShell,
176): boolean {
177 if (
178 previous.environmentId !== next.environmentId ||
179 previous.pendingSubagentRequest !== next.pendingSubagentRequest ||
180 !threadRuntimeIsActive(next.runtime)
181 ) {
182 return false;
183 }
184 const before = previous.source;
185 const after = next.source;
186 return (
187 before.itemCount > 0 === after.itemCount > 0 &&
188 before.visibleItemCount > 0 === after.visibleItemCount > 0 &&
189 sameWireThreadShell(
190 {
191 ...before,
192 updatedAt: after.updatedAt,
193 itemCount: after.itemCount,
194 visibleItemCount: after.visibleItemCount,
195 latestVisibleMessage: after.latestVisibleMessage,
196 },
197 after,
198 )
199 );
201​
202export function createEnvironmentThreadShellAtoms(input: {
203 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
204 readonly snapshotAtom: (
205 environmentId: EnvironmentId,
206 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
207}) {
208 // Point reads and aggregate lists share values without keeping an atom alive
209 // for every listed thread. Replaced source objects can be collected.
210 const scopedThreads = new WeakMap<
211 OrchestrationV2ThreadShell,
212 Map<string, EnvironmentThreadShell>
213 >();
214 const scopedThread = (
215 environmentId: EnvironmentId,
216 thread: OrchestrationV2ThreadShell,
217 subagentRequests: ReadonlyMap<ThreadId, PendingSubagentRequest>,
218 ) => {
219 let byEnvironment = scopedThreads.get(thread);
220 if (byEnvironment === undefined) {
221 byEnvironment = new Map();
222 scopedThreads.set(thread, byEnvironment);
223 }
224 const request = subagentRequests.get(thread.id) ?? null;
225 const key = request === null ? environmentId : `${environmentId}:${request}`;
226 let value = byEnvironment.get(key);
227 if (value === undefined) {
228 value = presentThreadShell(environmentId, thread, request);
229 byEnvironment.set(key, value);
230 }
231 return value;
232 };
233​
234 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
235 Atom.make(
236 (get): ReadonlyArray<OrchestrationV2ThreadShell> =>
237 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
238 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
239 );
240​
241 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
242 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
243 const threads = get(environmentThreadsAtom(environmentId));
244 if (threads.length === 0) {
245 return EMPTY_THREAD_INDEX;
246 }
247 return new Map(threads.map((thread) => [thread.id, thread] as const));
248 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
249 );
250​
251 // Side chats by parent, built once per change for every parent's row. Without side chats
252 // it stays the same empty map, so those rows do no work.
253 const environmentSideChatsByParentAtom = Atom.family((environmentId: EnvironmentId) =>
254 Atom.make((get) => {
255 let byParent: Map<ThreadId, OrchestrationV2ThreadShell[]> | undefined;
256 for (const thread of get(environmentThreadsAtom(environmentId))) {
257 const parentId = thread.lineage.parentThreadId;
258 if (thread.lineage.sideChat !== true || parentId === null) continue;
259 byParent ??= new Map();
260 const siblings = byParent.get(parentId);
261 if (siblings) siblings.push(thread);
262 else byParent.set(parentId, [thread]);
263 }
264 return byParent ?? EMPTY_SIDE_CHATS_BY_PARENT;
265 }).pipe(Atom.withLabel(`environment-side-chats-by-parent:${environmentId}`)),
266 );
267​
268 // What an environment's own subagents ask. Kept apart from the tasks other
269 // environments run for it, so two environments delegating to each other
270 // never read each other's totals.
271 const localSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {
272 let previous = EMPTY_SUBAGENT_REQUESTS;
273 return Atom.make((get) => {
274 const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId)));
275 if (sameRequests(previous, next)) return previous;
276 previous = next;
277 return next;
278 }).pipe(Atom.withLabel(`environment-local-subagent-requests:${environmentId}`));
279 });
280​
281 // Flags for environments whose threads delegated tasks, counting what each task
282 // or anything it delegated on asks. Each pass settles one more hop of a chain;
283 // flags only grow, so environments delegating to each other settle too.
284 const delegatedSubagentRequestsAtom = Atom.make((get) => {
285 const tasksByDelegator = new Map<
286 EnvironmentId,
287 Array<{
288 readonly runsIn: EnvironmentId;
289 readonly thread: OrchestrationV2ThreadShell;
290 readonly parentThreadId: ThreadId;
291 }>
292 >();
293 for (const runsIn of enabledEnvironmentIds(get(input.catalogValueAtom))) {
294 for (const thread of get(environmentThreadsAtom(runsIn))) {
295 const from = thread.delegatedFrom;
296 if (from === undefined || from.environmentId === runsIn) continue;
297 const task = { runsIn, thread, parentThreadId: from.threadId };
298 const tasks = tasksByDelegator.get(from.environmentId);
299 if (tasks === undefined) tasksByDelegator.set(from.environmentId, [task]);
300 else tasks.push(task);
301 }
302 }
303 let flags = new Map<EnvironmentId, ReadonlyMap<ThreadId, PendingSubagentRequest>>();
304 const requestsOf = (environmentId: EnvironmentId) =>
305 flags.get(environmentId) ?? get(localSubagentRequestsAtom(environmentId));
306 for (let changed = tasksByDelegator.size > 0; changed;) {
307 changed = false;
308 const next = new Map(flags);
309 for (const [environmentId, tasks] of tasksByDelegator) {
310 const delegated = tasks.flatMap(({ runsIn, thread, parentThreadId }) => {
311 const own = subagentRequest(thread);
312 const nested = requestsOf(runsIn).get(thread.id);
313 const request = own === "approval" ? own : (nested ?? own);
314 return request === null ? [] : [{ parentThreadId, request }];
315 });
316 if (delegated.length === 0) continue;
317 const requests = pendingSubagentRequestsByThread(
318 get(environmentThreadsAtom(environmentId)),
319 delegated,
320 );
321 if (sameRequests(requestsOf(environmentId), requests)) continue;
322 next.set(environmentId, requests);
323 changed = true;
324 }
325 flags = next;
326 }
327 return flags;
328 }).pipe(Atom.withLabel("environment-delegated-subagent-requests"));
329​
330 const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {
331 let previous = EMPTY_SUBAGENT_REQUESTS;
332 return Atom.make((get) => {
333 const next =
334 get(delegatedSubagentRequestsAtom).get(environmentId) ??
335 get(localSubagentRequestsAtom(environmentId));
336 if (sameRequests(previous, next)) return previous;
337 previous = next;
338 return next;
339 }).pipe(Atom.withLabel(`environment-pending-subagent-requests:${environmentId}`));
340 });
341​
342 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
343 let previous: ReadonlyArray<ScopedThreadRef> = [];
344 return Atom.make((get) => {
345 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
346 environmentId,
347 threadId: thread.id,
348 }));
349 if (threadRefsEqual(previous, next)) {
350 return previous;
351 }
352 previous = next;
353 return next;
354 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
355 });
356​
357 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
358 let previous: ReadonlyMap<
359 ProjectId,
360 ReadonlyArray<ScopedThreadRef>
361 > = EMPTY_THREAD_REFS_BY_PROJECT;
362 return Atom.make((get) => {
363 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
364 for (const thread of get(environmentThreadsAtom(environmentId))) {
365 const refs = grouped.get(thread.projectId);
366 const ref = { environmentId, threadId: thread.id };
367 if (refs === undefined) {
368 grouped.set(thread.projectId, [ref]);
369 } else {
370 refs.push(ref);
371 }
372 }
373 if (grouped.size === 0) {
374 previous = EMPTY_THREAD_REFS_BY_PROJECT;
375 return previous;
376 }
377 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
378 for (const [projectId, refs] of grouped) {
379 const previousRefs = previous.get(projectId);
380 next.set(
381 projectId,
382 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
383 );
384 }
385 const previousProjectIds = [...previous.keys()];
386 if (
387 next.size === previous.size &&
388 [...next].every(
389 ([projectId, refs], index) =>
390 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
391 )
392 ) {
393 return previous;
394 }
395 previous = next;
396 return previous;
397 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
398 });
399​
400 const threadShellAtomFamily = Atom.family((key: string) => {
401 const ref = parseThreadKey(key);
402 return Atom.make((get) => {
403 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
404 return source === null
405 ? null
406 : scopedThread(
407 ref.environmentId,
408 source,
409 get(pendingSubagentRequestsAtom(ref.environmentId)),
410 );
411 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
412 });
413​
414 // Keeps the previous shell while only streaming ticks changed. During a run,
415 // its timestamps, item counts and latest message are as of the last kept
416 // change; anything that needs them current reads threadShellAtom.
417 const quietThreadShellAtomFamily = Atom.family((key: string) => {
418 let previous: EnvironmentThreadShell | null = null;
419 return Atom.make((get) => {
420 const next = get(threadShellAtomFamily(key));
421 if (previous !== null && next !== null && sameApartFromStreaming(previous, next)) {
422 return previous;
423 }
424 previous = next;
425 return next;
426 }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`));
427 });
428​
429 // Child approvals and questions are hidden with their sidebar rows. Read their
430 // shell summaries, without subscribing to every child transcript. A task
431 // delegated to a linked environment is a child too, with its own subagents.
432 const childThreadInputsAtomFamily = Atom.family((key: string) => {
433 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
434 return Atom.make((get) => {
435 const children = new Map<
436 string,
437 Array<{ environmentId: EnvironmentId; thread: OrchestrationV2ThreadShell }>
438 >();
439 const addChild = (
440 parent: ScopedThreadRef,
441 environmentId: EnvironmentId,
442 thread: OrchestrationV2ThreadShell,
443 ) => {
444 const siblings = children.get(threadKey(parent));
445 if (siblings) siblings.push({ environmentId, thread });
446 else children.set(threadKey(parent), [{ environmentId, thread }]);
447 };
448 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
449 for (const thread of get(environmentThreadsAtom(environmentId))) {
450 const parent = thread.lineage.parentThreadId;
451 if (
452 parent !== null &&
453 (thread.lineage.relationshipToParent === "subagent" || thread.lineage.sideChat === true)
454 ) {
455 addChild({ environmentId, threadId: parent }, environmentId, thread);
456 } else if (thread.delegatedFrom !== undefined) {
457 addChild(thread.delegatedFrom, environmentId, thread);
458 }
459 }
460 }
461 const seen = new Set<string>([key]);
462 const pending = [key];
463 const next: EnvironmentThreadShell[] = [];
464 for (const parent of pending) {
465 for (const { environmentId, thread } of children.get(parent) ?? []) {
466 const childKey = threadKey({ environmentId, threadId: thread.id });
467 if (seen.has(childKey)) continue;
468 seen.add(childKey);
469 pending.push(childKey);
470 if (subagentRequest(thread) !== null || sideChatRequest(thread) !== null) {
471 next.push(
472 scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))),
473 );
474 }
475 }
476 }
477 // Indicators read only ids, titles and the request kind, so other shell
478 // updates keep the old array.
479 if (
480 previous.length === next.length &&
481 previous.every(
482 (thread, index) =>
483 thread.environmentId === next[index]?.environmentId &&
484 thread.id === next[index]?.id &&
485 thread.title === next[index]?.title &&
486 thread.hasPendingApprovals === next[index]?.hasPendingApprovals,
487 )
488 ) {
489 return previous;
490 }
491 previous = next;
492 return next;
493 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
494 });
495​
496 // A parent's side chats. Rows read only ids, titles and whether one needs the user, so
497 // streaming updates keep the old array.
498 const sideChatsAtomFamily = Atom.family((key: string) => {
499 const ref = parseThreadKey(key);
500 let previous = EMPTY_THREAD_SHELLS;
501 return Atom.make((get) => {
502 const sideChats = get(environmentSideChatsByParentAtom(ref.environmentId)).get(ref.threadId);
503 if (sideChats === undefined) {
504 previous = EMPTY_THREAD_SHELLS;
505 return previous;
506 }
507 const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));
508 const next = sideChats.map((thread) =>
509 scopedThread(ref.environmentId, thread, subagentRequests),
510 );
511 if (
512 previous.length === next.length &&
513 previous.every(
514 (thread, index) =>
515 thread.id === next[index]?.id &&
516 thread.title === next[index]?.title &&
517 thread.hasPendingApprovals === next[index]?.hasPendingApprovals &&
518 thread.hasPendingUserInput === next[index]?.hasPendingUserInput &&
519 thread.pendingSubagentRequest === next[index]?.pendingSubagentRequest,
520 )
521 ) {
522 return previous;
523 }
524 previous = next;
525 return next;
526 }).pipe(Atom.withLabel(`environment-side-chats:${key}`));
527 });
528​
529 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
530 const projectRefs = parseProjectRefCollectionKey(key);
531 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
532 return Atom.make((get) => {
533 const next: EnvironmentThreadShell[] = [];
534 const seen = new Set<string>();
535 for (const projectRef of projectRefs) {
536 const refs =
537 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
538 projectRef.projectId,
539 ) ?? EMPTY_SCOPED_THREAD_REFS;
540 if (refs.length === 0) continue;
541 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
542 const subagentRequests = get(pendingSubagentRequestsAtom(projectRef.environmentId));
543 for (const ref of refs) {
544 const key = threadKey(ref);
545 if (seen.has(key)) {
546 continue;
547 }
548 seen.add(key);
549 const thread = threads.get(ref.threadId);
550 if (thread !== undefined) {
551 next.push(scopedThread(ref.environmentId, thread, subagentRequests));
552 }
553 }
554 }
555 if (arrayElementsEqual(previous, next)) {
556 return previous;
557 }
558 previous = next;
559 return previous;
560 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
561 });
562​
563 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
564 const threadRefsAtom = Atom.make((get) => {
565 const refs: ScopedThreadRef[] = [];
566 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
567 refs.push(...get(environmentThreadRefsAtom(environmentId)));
568 }
569 if (threadRefsEqual(previousThreadRefs, refs)) {
570 return previousThreadRefs;
571 }
572 previousThreadRefs = refs;
573 return refs;
574 }).pipe(Atom.withLabel("environment-thread-refs"));
575​
576 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
577 const threadShellsAtom = Atom.make((get) => {
578 const next: EnvironmentThreadShell[] = [];
579 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
580 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
581 for (const thread of get(environmentThreadsAtom(environmentId))) {
582 next.push(scopedThread(environmentId, thread, subagentRequests));
583 }
584 }
585 if (arrayElementsEqual(previousThreadShells, next)) {
586 return previousThreadShells;
587 }
588 previousThreadShells = next;
589 return previousThreadShells;
590 }).pipe(Atom.withLabel("environment-thread-shell-list"));
591​
592 // Lists that arrange threads read this, so a running thread's streaming
593 // ticks reach only what reads its live shell.
594 let previousQuietThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
595 const quietThreadShellsAtom = Atom.make((get) => {
596 const next: EnvironmentThreadShell[] = [];
597 for (const ref of get(threadRefsAtom)) {
598 const shell = get(quietThreadShellAtomFamily(threadKey(ref)));
599 if (shell !== null) next.push(shell);
600 }
601 if (arrayElementsEqual(previousQuietThreadShells, next)) return previousQuietThreadShells;
602 previousQuietThreadShells = next;
603 return next;
604 }).pipe(Atom.withLabel("environment-quiet-thread-shell-list"));
605​
606 let previousDelegatedUnderParent: ReadonlySet<string> = new Set();
607 const delegatedUnderParentAtom = Atom.make((get) => {
608 const environmentIds = new Set(enabledEnvironmentIds(get(input.catalogValueAtom)));
609 const next = new Set<string>();
610 for (const environmentId of environmentIds) {
611 for (const thread of get(environmentThreadsAtom(environmentId))) {
612 const parent = thread.delegatedFrom;
613 if (
614 parent !== undefined &&
615 environmentIds.has(parent.environmentId) &&
616 // An archived parent leaves navigation; its task there stays listed on its own.
617 get(environmentThreadIndexAtom(parent.environmentId)).get(parent.threadId)?.archivedAt ===
618 null
619 ) {
620 next.add(threadKey({ environmentId, threadId: thread.id }));
621 }
622 }
623 }
624 if (
625 next.size === previousDelegatedUnderParent.size &&
626 [...next].every((key) => previousDelegatedUnderParent.has(key))
627 ) {
628 return previousDelegatedUnderParent;
629 }
630 previousDelegatedUnderParent = next;
631 return next;
632 }).pipe(Atom.withLabel("environment-delegated-under-parent"));
633​
634 let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];
635 const navigationThreadShellsAtom = Atom.make((get) => {
636 const next: EnvironmentThreadShell[] = [];
637 const underParent = get(delegatedUnderParentAtom);
638 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
639 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
640 for (const thread of get(environmentThreadsAtom(environmentId))) {
641 if (
642 thread.archivedAt !== null ||
643 isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent)
644 ) {
645 continue;
646 }
647 next.push(scopedThread(environmentId, thread, subagentRequests));
648 }
649 }
650 if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells;
651 previousNavigationShells = next;
652 return next;
653 }).pipe(Atom.withLabel("environment-navigation-thread-shells"));
654​
655 return {
656 environmentThreadsAtom,
657 environmentThreadIndexAtom,
658 environmentThreadRefsAtom,
659 environmentThreadRefsByProjectAtom,
660 threadRefsAtom,
661 threadShellsAtom,
662 quietThreadShellsAtom,
663 navigationThreadShellsAtom,
664 delegatedUnderParentAtom,
665 pendingSubagentRequestsAtom,
666 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
667 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
668 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
669 quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),
670 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
671 sideChatsAtom: (ref: ScopedThreadRef) => sideChatsAtomFamily(threadKey(ref)),
672 };