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