The best way to control Claude Code, Codex and more from any computer or phone

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