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

threadShell.ts

968 lines38.6 KB

1import { mFallback, msg, select, part } from "gt-i18n";
2import type { M } from "gt-i18n";
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 { delegatedChildIsWorking, 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: M = 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`${select(
248 { kind },
249 {
250 sideChat: part`${select(
251 { need },
252 {
253 input: "Side chat needs input",
254 approval: "Side chat needs approval",
255 other: "Side chat needs you",
256 },
257 )}`,
258 other: part`${select(
259 { need },
260 {
261 input: "Subagent needs input",
262 approval: "Subagent needs approval",
263 other: "Subagent needs you",
264 },
265 )}`,
266 },
267 )}`,
268 );
269 }
270 return resolve(
271 msg`${select(
272 { kind },
273 {
274 sideChat: part`${select(
275 { need },
276 {
277 input: part`${{ count: String(count) }} side chats need input`,
278 approval: part`${{ count: String(count) }} side chats need approval`,
279 other: part`${{ count: String(count) }} side chats need you`,
280 },
281 )}`,
282 subagent: part`${select(
283 { need },
284 {
285 input: part`${{ count: String(count) }} subagents need input`,
286 approval: part`${{ count: String(count) }} subagents need approval`,
287 other: part`${{ count: String(count) }} subagents need you`,
288 },
289 )}`,
290 other: part`${select(
291 { need },
292 {
293 input: part`${{ count: String(count) }} threads need input`,
294 approval: part`${{ count: String(count) }} threads need approval`,
295 other: part`${{ count: String(count) }} threads need you`,
296 },
297 )}`,
298 },
299 )}`,
300 );
302​
303const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
304​
305// While a run streams, the server bumps the shell's timestamps, item counts and
306// latest message several times a second. Only the zero crossing of the counts
307// says anything (whether the thread has started). Once the run stops every
308// field counts again, so snooze wakes and failure times read the current value.
309function sameApartFromStreaming(
310 previous: EnvironmentThreadShell,
311 next: EnvironmentThreadShell,
312): boolean {
313 if (
314 previous.environmentId !== next.environmentId ||
315 previous.connectionPhase !== next.connectionPhase ||
316 previous.pendingSubagentRequest !== next.pendingSubagentRequest ||
317 previous.remoteWorking !== next.remoteWorking ||
318 !threadRuntimeIsActive(next.runtime)
319 ) {
320 return false;
321 }
322 const before = previous.source;
323 const after = next.source;
324 return (
325 before.itemCount > 0 === after.itemCount > 0 &&
326 before.visibleItemCount > 0 === after.visibleItemCount > 0 &&
327 sameWireThreadShell(
328 {
329 ...before,
330 updatedAt: after.updatedAt,
331 itemCount: after.itemCount,
332 visibleItemCount: after.visibleItemCount,
333 latestVisibleMessage: after.latestVisibleMessage,
334 },
335 after,
336 )
337 );
339​
340export function createEnvironmentThreadShellAtoms(input: {
341 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
342 readonly connectionPhaseAtom: (
343 environmentId: EnvironmentId,
344 ) => Atom.Atom<EnvironmentConnectionPhase | undefined>;
345 readonly snapshotAtom: (
346 environmentId: EnvironmentId,
347 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
348 /** Tags whose threads display lists leave out; null while the filter is off. */
349 readonly hiddenThreadTagsAtom: (
350 environmentId: EnvironmentId,
351 ) => Atom.Atom<ReadonlyArray<string> | null>;
352}) {
353 // Point reads and aggregate lists share values without keeping an atom alive
354 // for every listed thread. Replaced source objects can be collected.
355 const scopedThreads = new WeakMap<
356 OrchestrationV2ThreadShell,
357 Map<string, EnvironmentThreadShell>
358 >();
359 const scopedThread = (
360 environmentId: EnvironmentId,
361 thread: OrchestrationV2ThreadShell,
362 subagentRequests: ReadonlyMap<ThreadId, PendingSubagentRequest>,
363 connectionPhase: EnvironmentConnectionPhase | undefined,
364 remoteWork?: ReadonlySet<string>,
365 ) => {
366 let byEnvironment = scopedThreads.get(thread);
367 if (byEnvironment === undefined) {
368 byEnvironment = new Map();
369 scopedThreads.set(thread, byEnvironment);
370 }
371 const request = subagentRequests.get(thread.id) ?? null;
372 const remote = remoteWork?.has(threadKey({ environmentId, threadId: thread.id })) === true;
373 const key = `${environmentId}:${request ?? ""}:${connectionPhase ?? ""}:${remote}`;
374 let value = byEnvironment.get(key);
375 if (value === undefined) {
376 const shell = presentThreadShell(environmentId, thread, request);
377 // Its own run, background wait or failure outranks work it delegated elsewhere.
378 const ownState =
379 threadRuntimeIsActive(shell.runtime) ||
380 shell.runtime?.status === "idle" ||
381 shell.runtime?.status === "failed";
382 value = { ...shell, connectionPhase, remoteWorking: remote && !ownState };
383 byEnvironment.set(key, value);
384 }
385 return value;
386 };
387​
388 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
389 Atom.make(
390 (get): ReadonlyArray<OrchestrationV2ThreadShell> =>
391 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
392 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
393 );
394​
395 // Parents with a task at work on another connected environment.
396 let previousRemoteWork: ReadonlySet<string> = new Set();
397 const remoteWorkAtom = Atom.make((get) => {
398 const next = new Set<string>();
399 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
400 if (get(input.connectionPhaseAtom(environmentId)) !== "connected") continue;
401 for (const thread of get(environmentThreadsAtom(environmentId))) {
402 const parent = thread.delegatedFrom;
403 if (
404 parent &&
405 parent.environmentId !== environmentId &&
406 thread.archivedAt === null &&
407 delegatedChildIsWorking(thread)
408 ) {
409 next.add(threadKey(parent));
410 }
411 }
412 }
413 if (
414 next.size === previousRemoteWork.size &&
415 [...next].every((key) => previousRemoteWork.has(key))
416 ) {
417 return previousRemoteWork;
418 }
419 previousRemoteWork = next;
420 return next;
421 }).pipe(Atom.withLabel("environment-remote-work"));
422​
423 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
424 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
425 const threads = get(environmentThreadsAtom(environmentId));
426 if (threads.length === 0) {
427 return EMPTY_THREAD_INDEX;
428 }
429 return new Map(threads.map((thread) => [thread.id, thread] as const));
430 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
431 );
432​
433 // Side chats by parent, built once per change for every parent's row. Without side chats
434 // it stays the same empty map, so those rows do no work.
435 const environmentSideChatsByParentAtom = Atom.family((environmentId: EnvironmentId) =>
436 Atom.make((get) => {
437 let byParent: Map<ThreadId, OrchestrationV2ThreadShell[]> | undefined;
438 for (const thread of get(environmentThreadsAtom(environmentId))) {
439 const parentId = thread.lineage.parentThreadId;
440 if (thread.lineage.sideChat !== true || parentId === null) continue;
441 byParent ??= new Map();
442 const siblings = byParent.get(parentId);
443 if (siblings) siblings.push(thread);
444 else byParent.set(parentId, [thread]);
445 }
446 return byParent ?? EMPTY_SIDE_CHATS_BY_PARENT;
447 }).pipe(Atom.withLabel(`environment-side-chats-by-parent:${environmentId}`)),
448 );
449​
450 // What an environment's own subagents ask. Kept apart from the tasks other
451 // environments run for it, so two environments delegating to each other
452 // never read each other's totals.
453 const localSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {
454 let previous: ReadonlyMap<ThreadId, RolledUpRequest> = EMPTY_SUBAGENT_REQUESTS;
455 return Atom.make((get) => {
456 const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId)));
457 if (sameRequests(previous, next)) return previous;
458 previous = next;
459 return next;
460 }).pipe(Atom.withLabel(`environment-local-subagent-requests:${environmentId}`));
461 });
462​
463 // Flags for environments whose threads delegated tasks, counting what each task
464 // or anything it delegated on asks. Each pass settles one more hop of a chain;
465 // flags only grow, so environments delegating to each other settle too.
466 const delegatedSubagentRequestsAtom = Atom.make((get) => {
467 const tasksByDelegator = new Map<
468 EnvironmentId,
469 Array<{
470 readonly runsIn: EnvironmentId;
471 readonly thread: OrchestrationV2ThreadShell;
472 readonly parentThreadId: ThreadId;
473 }>
474 >();
475 for (const runsIn of enabledEnvironmentIds(get(input.catalogValueAtom))) {
476 for (const thread of get(environmentThreadsAtom(runsIn))) {
477 const from = thread.delegatedFrom;
478 if (from === undefined || from.environmentId === runsIn) continue;
479 const task = { runsIn, thread, parentThreadId: from.threadId };
480 const tasks = tasksByDelegator.get(from.environmentId);
481 if (tasks === undefined) tasksByDelegator.set(from.environmentId, [task]);
482 else tasks.push(task);
483 }
484 }
485 let flags = new Map<EnvironmentId, ReadonlyMap<ThreadId, RolledUpRequest>>();
486 const requestsOf = (environmentId: EnvironmentId) =>
487 flags.get(environmentId) ?? get(localSubagentRequestsAtom(environmentId));
488 for (let changed = tasksByDelegator.size > 0; changed;) {
489 changed = false;
490 const next = new Map(flags);
491 for (const [environmentId, tasks] of tasksByDelegator) {
492 const delegated = tasks.flatMap(({ runsIn, thread, parentThreadId }) => {
493 const own = rolledUpRequest(thread, subagentRequest(thread));
494 const nested = requestsOf(runsIn).get(thread.id);
495 const request = own === "approval" ? own : (nested ?? own);
496 return request === null ? [] : [{ parentThreadId, request }];
497 });
498 if (delegated.length === 0) continue;
499 const requests = pendingSubagentRequestsByThread(
500 get(environmentThreadsAtom(environmentId)),
501 delegated,
502 );
503 if (sameRequests(requestsOf(environmentId), requests)) continue;
504 next.set(environmentId, requests);
505 changed = true;
506 }
507 flags = next;
508 }
509 return flags;
510 }).pipe(Atom.withLabel("environment-delegated-subagent-requests"));
511​
512 const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {
513 let previous: ReadonlyMap<ThreadId, PendingSubagentRequest> = EMPTY_SUBAGENT_REQUESTS;
514 return Atom.make((get) => {
515 const rolledUp =
516 get(delegatedSubagentRequestsAtom).get(environmentId) ??
517 get(localSubagentRequestsAtom(environmentId));
518 const next = new Map<ThreadId, PendingSubagentRequest>();
519 for (const [threadId, request] of rolledUp) {
520 next.set(threadId, request === "user_only_input" ? "user_input" : request);
521 }
522 if (sameRequests(previous, next)) return previous;
523 previous = next;
524 return next;
525 }).pipe(Atom.withLabel(`environment-pending-subagent-requests:${environmentId}`));
526 });
527​
528 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
529 let previous: ReadonlyArray<ScopedThreadRef> = [];
530 return Atom.make((get) => {
531 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
532 environmentId,
533 threadId: thread.id,
534 }));
535 if (threadRefsEqual(previous, next)) {
536 return previous;
537 }
538 previous = next;
539 return next;
540 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
541 });
542​
543 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
544 let previous: ReadonlyMap<
545 ProjectId,
546 ReadonlyArray<ScopedThreadRef>
547 > = EMPTY_THREAD_REFS_BY_PROJECT;
548 return Atom.make((get) => {
549 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
550 for (const thread of get(environmentThreadsAtom(environmentId))) {
551 const refs = grouped.get(thread.projectId);
552 const ref = { environmentId, threadId: thread.id };
553 if (refs === undefined) {
554 grouped.set(thread.projectId, [ref]);
555 } else {
556 refs.push(ref);
557 }
558 }
559 if (grouped.size === 0) {
560 previous = EMPTY_THREAD_REFS_BY_PROJECT;
561 return previous;
562 }
563 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
564 for (const [projectId, refs] of grouped) {
565 const previousRefs = previous.get(projectId);
566 next.set(
567 projectId,
568 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
569 );
570 }
571 const previousProjectIds = [...previous.keys()];
572 if (
573 next.size === previous.size &&
574 [...next].every(
575 ([projectId, refs], index) =>
576 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
577 )
578 ) {
579 return previous;
580 }
581 previous = next;
582 return previous;
583 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
584 });
585​
586 // A removed environment's snapshot outlives it while a screen still reads it.
587 const environmentRemovedAtom = Atom.family((environmentId: EnvironmentId) =>
588 Atom.make((get) => {
589 const catalog = get(input.catalogValueAtom);
590 return catalog.isReady && !catalog.entries.has(environmentId);
591 }).pipe(Atom.withLabel(`environment-removed:${environmentId}`)),
592 );
593​
594 const threadShellAtomFamily = Atom.family((key: string) => {
595 const ref = parseThreadKey(key);
596 return Atom.make((get) => {
597 if (get(environmentRemovedAtom(ref.environmentId))) return null;
598 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
599 return source === null
600 ? null
601 : scopedThread(
602 ref.environmentId,
603 source,
604 get(pendingSubagentRequestsAtom(ref.environmentId)),
605 get(input.connectionPhaseAtom(ref.environmentId)),
606 get(remoteWorkAtom),
607 );
608 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
609 });
610​
611 // Keeps the previous shell while only streaming ticks changed. During a run,
612 // its timestamps, item counts and latest message are as of the last kept
613 // change; anything that needs them current reads threadShellAtom.
614 const quietThreadShellAtomFamily = Atom.family((key: string) => {
615 let previous: EnvironmentThreadShell | null = null;
616 return Atom.make((get) => {
617 const next = get(threadShellAtomFamily(key));
618 if (previous !== null && next !== null && sameApartFromStreaming(previous, next)) {
619 return previous;
620 }
621 previous = next;
622 return next;
623 }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`));
624 });
625​
626 const hasChildThreadInputsAtom = Atom.make((get) => {
627 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
628 if (get(environmentThreadsAtom(environmentId)).some(asksParent)) return true;
629 }
630 return false;
631 }).pipe(Atom.withLabel("environment-has-child-thread-inputs"));
632​
633 // Child approvals and questions are hidden with their sidebar rows. Read their
634 // shell summaries, without subscribing to every child transcript. A task
635 // delegated to a linked environment is a child too, with its own subagents.
636 const childThreadInputsAtomFamily = Atom.family((key: string) => {
637 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
638 return Atom.make((get) => {
639 if (!get(hasChildThreadInputsAtom)) {
640 if (previous.length !== 0) previous = [];
641 return previous;
642 }
643 const children = new Map<
644 string,
645 Array<{ environmentId: EnvironmentId; thread: OrchestrationV2ThreadShell }>
646 >();
647 const addChild = (
648 parent: ScopedThreadRef,
649 environmentId: EnvironmentId,
650 thread: OrchestrationV2ThreadShell,
651 ) => {
652 const siblings = children.get(threadKey(parent));
653 if (siblings) siblings.push({ environmentId, thread });
654 else children.set(threadKey(parent), [{ environmentId, thread }]);
655 };
656 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
657 for (const thread of get(environmentThreadsAtom(environmentId))) {
658 const parent = thread.lineage.parentThreadId;
659 if (
660 parent !== null &&
661 (thread.lineage.relationshipToParent === "subagent" || thread.lineage.sideChat === true)
662 ) {
663 addChild({ environmentId, threadId: parent }, environmentId, thread);
664 } else if (thread.delegatedFrom !== undefined) {
665 addChild(thread.delegatedFrom, environmentId, thread);
666 }
667 }
668 }
669 const seen = new Set<string>([key]);
670 const pending = [key];
671 const next: EnvironmentThreadShell[] = [];
672 for (const parent of pending) {
673 for (const { environmentId, thread } of children.get(parent) ?? []) {
674 const childKey = threadKey({ environmentId, threadId: thread.id });
675 if (seen.has(childKey)) continue;
676 seen.add(childKey);
677 pending.push(childKey);
678 if (asksParent(thread)) {
679 next.push(
680 scopedThread(
681 environmentId,
682 thread,
683 get(pendingSubagentRequestsAtom(environmentId)),
684 get(input.connectionPhaseAtom(environmentId)),
685 ),
686 );
687 }
688 }
689 }
690 // Indicators read only ids, titles and the request kind, so other shell
691 // updates keep the old array.
692 if (
693 previous.length === next.length &&
694 previous.every(
695 (thread, index) =>
696 thread.environmentId === next[index]?.environmentId &&
697 thread.id === next[index]?.id &&
698 thread.title === next[index]?.title &&
699 thread.hasPendingApprovals === next[index]?.hasPendingApprovals,
700 )
701 ) {
702 return previous;
703 }
704 previous = next;
705 return next;
706 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
707 });
708​
709 // A parent's side chats. Rows read only ids, titles and whether one needs the user, so
710 // streaming updates keep the old array.
711 const sideChatsAtomFamily = Atom.family((key: string) => {
712 const ref = parseThreadKey(key);
713 let previous = EMPTY_THREAD_SHELLS;
714 return Atom.make((get) => {
715 const sideChats = get(environmentSideChatsByParentAtom(ref.environmentId)).get(ref.threadId);
716 if (sideChats === undefined) {
717 previous = EMPTY_THREAD_SHELLS;
718 return previous;
719 }
720 const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));
721 const next = sideChats.map((thread) =>
722 scopedThread(
723 ref.environmentId,
724 thread,
725 subagentRequests,
726 get(input.connectionPhaseAtom(ref.environmentId)),
727 ),
728 );
729 if (
730 previous.length === next.length &&
731 previous.every(
732 (thread, index) =>
733 thread.id === next[index]?.id &&
734 thread.title === next[index]?.title &&
735 thread.hasPendingApprovals === next[index]?.hasPendingApprovals &&
736 thread.hasPendingUserInput === next[index]?.hasPendingUserInput &&
737 thread.pendingSubagentRequest === next[index]?.pendingSubagentRequest,
738 )
739 ) {
740 return previous;
741 }
742 previous = next;
743 return next;
744 }).pipe(Atom.withLabel(`environment-side-chats:${key}`));
745 });
746​
747 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
748 const projectRefs = parseProjectRefCollectionKey(key);
749 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
750 return Atom.make((get) => {
751 const next: EnvironmentThreadShell[] = [];
752 const remote = get(remoteWorkAtom);
753 const seen = new Set<string>();
754 for (const projectRef of projectRefs) {
755 const refs =
756 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
757 projectRef.projectId,
758 ) ?? EMPTY_SCOPED_THREAD_REFS;
759 if (refs.length === 0) continue;
760 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
761 const subagentRequests = get(pendingSubagentRequestsAtom(projectRef.environmentId));
762 const connectionPhase = get(input.connectionPhaseAtom(projectRef.environmentId));
763 for (const ref of refs) {
764 const key = threadKey(ref);
765 if (seen.has(key)) {
766 continue;
767 }
768 seen.add(key);
769 const thread = threads.get(ref.threadId);
770 if (thread !== undefined) {
771 next.push(
772 scopedThread(ref.environmentId, thread, subagentRequests, connectionPhase, remote),
773 );
774 }
775 }
776 }
777 if (arrayElementsEqual(previous, next)) {
778 return previous;
779 }
780 previous = next;
781 return previous;
782 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
783 });
784​
785 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
786 const threadRefsAtom = Atom.make((get) => {
787 const refs: ScopedThreadRef[] = [];
788 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
789 refs.push(...get(environmentThreadRefsAtom(environmentId)));
790 }
791 if (threadRefsEqual(previousThreadRefs, refs)) {
792 return previousThreadRefs;
793 }
794 previousThreadRefs = refs;
795 return refs;
796 }).pipe(Atom.withLabel("environment-thread-refs"));
797​
798 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
799 const threadShellsAtom = Atom.make((get) => {
800 const next: EnvironmentThreadShell[] = [];
801 const remote = get(remoteWorkAtom);
802 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
803 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
804 const connectionPhase = get(input.connectionPhaseAtom(environmentId));
805 for (const thread of get(environmentThreadsAtom(environmentId))) {
806 next.push(scopedThread(environmentId, thread, subagentRequests, connectionPhase, remote));
807 }
808 }
809 if (arrayElementsEqual(previousThreadShells, next)) {
810 return previousThreadShells;
811 }
812 previousThreadShells = next;
813 return previousThreadShells;
814 }).pipe(Atom.withLabel("environment-thread-shell-list"));
815​
816 // Point reads and threadShellsAtom stay complete, so code that asks whether a thread
817 // exists (outboxes, drafts, removals) never mistakes a hidden thread for a missing one.
818 let previousHiddenThreadKeys: ReadonlySet<string> = NO_HIDDEN_THREADS;
819 const hiddenThreadKeysAtom = Atom.make((get) => {
820 const environments = Array.from(
821 enabledEnvironmentIds(get(input.catalogValueAtom)),
822 (environmentId) => ({
823 environmentId,
824 hiddenTags: get(input.hiddenThreadTagsAtom(environmentId)),
825 }),
826 );
827 // Read shells only while some environment hides tags, so streaming ticks cost nothing otherwise.
828 if (!environments.some((environment) => environment.hiddenTags !== null)) {
829 previousHiddenThreadKeys = NO_HIDDEN_THREADS;
830 return NO_HIDDEN_THREADS;
831 }
832 const next = hiddenThreadKeys(
833 environments.map((environment) => ({
834 ...environment,
835 threads: get(environmentThreadsAtom(environment.environmentId)),
836 })),
837 );
838 if (
839 next.size === previousHiddenThreadKeys.size &&
840 [...next].every((key) => previousHiddenThreadKeys.has(key))
841 ) {
842 return previousHiddenThreadKeys;
843 }
844 previousHiddenThreadKeys = next;
845 return next;
846 }).pipe(Atom.withLabel("environment-hidden-thread-keys"));
847​
848 const anyEnvironmentHidingAtom = Atom.make((get) =>
849 Array.from(enabledEnvironmentIds(get(input.catalogValueAtom))).some(
850 (environmentId) => get(input.hiddenThreadTagsAtom(environmentId)) !== null,
851 ),
852 ).pipe(Atom.withLabel("environment-any-hiding-thread-tags"));
853​
854 /** threadShellsAtom without the threads the tag filter hides, for pickers and palettes. */
855 let previousVisibleThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
856 const visibleThreadShellsAtom = Atom.make((get) => {
857 const threads = get(threadShellsAtom);
858 const hidden = get(hiddenThreadKeysAtom);
859 if (hidden.size === 0) return threads;
860 const next = threads.filter(
861 (thread) =>
862 !hidden.has(threadKey({ environmentId: thread.environmentId, threadId: thread.id })),
863 );
864 if (arrayElementsEqual(previousVisibleThreadShells, next)) return previousVisibleThreadShells;
865 previousVisibleThreadShells = next;
866 return next;
867 }).pipe(Atom.withLabel("environment-visible-thread-shell-list"));
868​
869 // Lists that arrange threads read this, so a running thread's streaming
870 // ticks reach only what reads its live shell.
871 let previousQuietThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
872 const quietThreadShellsAtom = Atom.make((get) => {
873 const next: EnvironmentThreadShell[] = [];
874 const hidden = get(hiddenThreadKeysAtom);
875 for (const ref of get(threadRefsAtom)) {
876 if (hidden.has(threadKey(ref))) continue;
877 const shell = get(quietThreadShellAtomFamily(threadKey(ref)));
878 if (shell !== null) next.push(shell);
879 }
880 if (arrayElementsEqual(previousQuietThreadShells, next)) return previousQuietThreadShells;
881 previousQuietThreadShells = next;
882 return next;
883 }).pipe(Atom.withLabel("environment-quiet-thread-shell-list"));
884​
885 let previousDelegatedUnderParent: ReadonlySet<string> = new Set();
886 const delegatedUnderParentAtom = Atom.make((get) => {
887 const environmentIds = new Set(enabledEnvironmentIds(get(input.catalogValueAtom)));
888 const next = new Set<string>();
889 for (const environmentId of environmentIds) {
890 for (const thread of get(environmentThreadsAtom(environmentId))) {
891 const parent = thread.delegatedFrom;
892 if (
893 parent !== undefined &&
894 environmentIds.has(parent.environmentId) &&
895 // An archived parent leaves navigation; its task there stays listed on its own.
896 get(environmentThreadIndexAtom(parent.environmentId)).get(parent.threadId)?.archivedAt ===
897 null
898 ) {
899 next.add(threadKey({ environmentId, threadId: thread.id }));
900 }
901 }
902 }
903 if (
904 next.size === previousDelegatedUnderParent.size &&
905 [...next].every((key) => previousDelegatedUnderParent.has(key))
906 ) {
907 return previousDelegatedUnderParent;
908 }
909 previousDelegatedUnderParent = next;
910 return next;
911 }).pipe(Atom.withLabel("environment-delegated-under-parent"));
912​
913 let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];
914 const navigationThreadShellsAtom = Atom.make((get) => {
915 const next: EnvironmentThreadShell[] = [];
916 const underParent = get(delegatedUnderParentAtom);
917 const hidden = get(hiddenThreadKeysAtom);
918 const remote = get(remoteWorkAtom);
919 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
920 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
921 const connectionPhase = get(input.connectionPhaseAtom(environmentId));
922 for (const thread of get(environmentThreadsAtom(environmentId))) {
923 if (
924 thread.archivedAt !== null ||
925 isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent) ||
926 hidden.has(threadKey({ environmentId, threadId: thread.id }))
927 ) {
928 continue;
929 }
930 next.push(scopedThread(environmentId, thread, subagentRequests, connectionPhase, remote));
931 }
932 }
933 const movedCopies = movedThreadCopyKeys(next);
934 if (movedCopies.size > 0) {
935 const listed = next.filter(
936 (thread) =>
937 !movedCopies.has(threadKey({ environmentId: thread.environmentId, threadId: thread.id })),
938 );
939 next.length = 0;
940 next.push(...listed);
941 }
942 if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells;
943 previousNavigationShells = next;
944 return next;
945 }).pipe(Atom.withLabel("environment-navigation-thread-shells"));
946​
947 return {
948 environmentThreadsAtom,
949 environmentThreadIndexAtom,
950 environmentThreadRefsAtom,
951 environmentThreadRefsByProjectAtom,
952 threadRefsAtom,
953 threadShellsAtom,
954 visibleThreadShellsAtom,
955 hiddenThreadKeysAtom,
956 anyEnvironmentHidingAtom,
957 quietThreadShellsAtom,
958 navigationThreadShellsAtom,
959 delegatedUnderParentAtom,
960 pendingSubagentRequestsAtom,
961 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
962 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
963 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
964 quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),
965 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
966 sideChatsAtom: (ref: ScopedThreadRef) => sideChatsAtomFamily(threadKey(ref)),
967 };