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

threadShell.ts

835 lines34.3 KB

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