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