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

threadShell.ts

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