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