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

threadShell.ts

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