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

threadShell.ts

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