Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationV2ShellSnapshot,
4 OrchestrationV2ThreadShell,
5 ProjectId,
6 ScopedProjectRef,
7 ScopedThreadRef,
8 ThreadId,
9} from "@t3tools/contracts";
10import { isProviderNativeSubagentThread } from "@t3tools/contracts";
11import { Atom } from "effect/reactivity";
12
13import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
14import { presentThreadShell } from "./models.ts";
15import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
16import {
17 arrayElementsEqual,
18 parseProjectRefCollectionKey,
19 parseThreadKey,
20 projectRefCollectionKey,
21 threadKey,
22 threadRefsEqual,
23} from "./entities.ts";
24
25const EMPTY_THREADS: ReadonlyArray<OrchestrationV2ThreadShell> = Object.freeze([]);
26const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
27const EMPTY_THREAD_INDEX: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> = new Map();
28const EMPTY_SUBAGENT_REQUESTS: ReadonlyMap<ThreadId, PendingSubagentRequest> = new Map();
29const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap<
30 ProjectId,
31 ReadonlyArray<ScopedThreadRef>
32> = new Map();
33
34// An async question outlives the subagent's run, but once that run ends the
35// parent is no longer waiting on the answer, so it stops counting as input.
36// The activity run stays set when a follow-up is queued behind a blocked run;
37// older servers omit it, so fall back to the latest run's status.
38const isChildRunLive = (
39 thread: Pick<OrchestrationV2ThreadShell, "activityRunStatus" | "status">,
40) =>
41 thread.activityRunStatus !== undefined
42 ? thread.activityRunStatus !== null
43 : thread.status === "preparing" ||
44 thread.status === "starting" ||
45 thread.status === "running" ||
46 thread.status === "waiting";
47
48/** Provider-native
49 subagents ask on their parent, so they are skipped. */
50function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {
51 const kind = thread.pendingRuntimeRequest?.kind;
52 if (
53 kind === undefined ||
54 kind === "auth_refresh" ||
55 thread.lineage.relationshipToParent !== "subagent" ||
56 isProviderNativeSubagentThread(thread) ||
57 !isChildRunLive(thread)
58 ) {
59 return null;
60 }
61 return kind === "user_input" ? "user_input" : "approval";
62}
63
64export function pendingSubagentRequestsByThread(
65 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
66): ReadonlyMap<ThreadId, PendingSubagentRequest> {
67 const requests = new Map<ThreadId, PendingSubagentRequest>();
68 let byId: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> | undefined;
69 for (const child of threads) {
70 const request = subagentRequest(child);
71 if (request === null) continue;
72 byId ??= new Map(threads.map((thread) => [thread.id, thread] as const));
73 const seen = new Set<ThreadId>([child.id]);
74 let current: OrchestrationV2ThreadShell | undefined = child;
75 while (current?.lineage.relationshipToParent === "subagent") {
76 const parentId: ThreadId | null = current.lineage.parentThreadId;
77 if (parentId === null || seen.has(parentId)) break;
78 seen.add(parentId);
79 if (requests.get(parentId) !== "approval") requests.set(parentId, request);
80 current = byId.get(parentId);
81 }
82 }
83 return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests;
84}
85
86export function childThreadInputsTitle(
87 children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals">>,
88): string {
89 const approvals = children.filter((child) => child.hasPendingApprovals).length;
90 const need = approvals === 0 ? "input" : approvals === children.length ? "approval" : "you";
91 return children.length === 1
92 ? `Subagent needs ${need}`
93 : `${children.length} subagents need ${need}`;
94}
95
96export function createEnvironmentThreadShellAtoms(input: {
97 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
98 readonly snapshotAtom: (
99 environmentId: EnvironmentId,
100 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
101}) {
102 // Point reads and aggregate lists share values without keeping an atom alive
103 // for every listed thread. Replaced source objects can be collected.
104 const scopedThreads = new WeakMap<
105 OrchestrationV2ThreadShell,
106 Map<string, EnvironmentThreadShell>
107 >();
108 const scopedThread = (
109 environmentId: EnvironmentId,
110 thread: OrchestrationV2ThreadShell,
111 subagentRequests: ReadonlyMap<ThreadId, PendingSubagentRequest>,
112 ) => {
113 let byEnvironment = scopedThreads.get(thread);
114 if (byEnvironment === undefined) {
115 byEnvironment = new Map();
116 scopedThreads.set(thread, byEnvironment);
117 }
118 const request = subagentRequests.get(thread.id) ?? null;
119 const key = request === null ? environmentId : `${environmentId}:${request}`;
120 let value = byEnvironment.get(key);
121 if (value === undefined) {
122 value = presentThreadShell(environmentId, thread, request);
123 byEnvironment.set(key, value);
124 }
125 return value;
126 };
127
128 const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) =>
129 Atom.make(
130 (get): ReadonlyArray<OrchestrationV2ThreadShell> =>
131 get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS,
132 ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)),
133 );
134
135 const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) =>
136 Atom.make((get): ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> => {
137 const threads = get(environmentThreadsAtom(environmentId));
138 if (threads.length === 0) {
139 return EMPTY_THREAD_INDEX;
140 }
141 return new Map(threads.map((thread) => [thread.id, thread] as const));
142 }).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),
143 );
144
145 const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {
146 let previous = EMPTY_SUBAGENT_REQUESTS;
147 return Atom.make((get) => {
148 const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId)));
149 if (
150 next.size === previous.size &&
151 [...next].every(([threadId, request]) => previous.get(threadId) === request)
152 ) {
153 return previous;
154 }
155 previous = next;
156 return next;
157 }).pipe(Atom.withLabel(`environment-pending-subagent-requests:${environmentId}`));
158 });
159
160 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {
161 let previous: ReadonlyArray<ScopedThreadRef> = [];
162 return Atom.make((get) => {
163 const next = get(environmentThreadsAtom(environmentId)).map((thread) => ({
164 environmentId,
165 threadId: thread.id,
166 }));
167 if (threadRefsEqual(previous, next)) {
168 return previous;
169 }
170 previous = next;
171 return next;
172 }).pipe(Atom.withLabel(`environment-thread-refs:${environmentId}`));
173 });
174
175 const environmentThreadRefsByProjectAtom = Atom.family((environmentId: EnvironmentId) => {
176 let previous: ReadonlyMap<
177 ProjectId,
178 ReadonlyArray<ScopedThreadRef>
179 > = EMPTY_THREAD_REFS_BY_PROJECT;
180 return Atom.make((get) => {
181 const grouped = new Map<ProjectId, ScopedThreadRef[]>();
182 for (const thread of get(environmentThreadsAtom(environmentId))) {
183 const refs = grouped.get(thread.projectId);
184 const ref = { environmentId, threadId: thread.id };
185 if (refs === undefined) {
186 grouped.set(thread.projectId, [ref]);
187 } else {
188 refs.push(ref);
189 }
190 }
191 if (grouped.size === 0) {
192 previous = EMPTY_THREAD_REFS_BY_PROJECT;
193 return previous;
194 }
195 const next = new Map<ProjectId, ReadonlyArray<ScopedThreadRef>>();
196 for (const [projectId, refs] of grouped) {
197 const previousRefs = previous.get(projectId);
198 next.set(
199 projectId,
200 previousRefs !== undefined && threadRefsEqual(previousRefs, refs) ? previousRefs : refs,
201 );
202 }
203 const previousProjectIds = [...previous.keys()];
204 if (
205 next.size === previous.size &&
206 [...next].every(
207 ([projectId, refs], index) =>
208 previousProjectIds[index] === projectId && previous.get(projectId) === refs,
209 )
210 ) {
211 return previous;
212 }
213 previous = next;
214 return previous;
215 }).pipe(Atom.withLabel(`environment-thread-refs-by-project:${environmentId}`));
216 });
217
218 const threadShellAtomFamily = Atom.family((key: string) => {
219 const ref = parseThreadKey(key);
220 return Atom.make((get) => {
221 const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null;
222 return source === null
223 ? null
224 : scopedThread(
225 ref.environmentId,
226 source,
227 get(pendingSubagentRequestsAtom(ref.environmentId)),
228 );
229 }).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
230 });
231
232 // Child approvals and questions are hidden with their sidebar rows. Read their
233 // shell summaries, without subscribing to every child transcript.
234 const childThreadInputsAtomFamily = Atom.family((key: string) => {
235 const ref = parseThreadKey(key);
236 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
237 return Atom.make((get) => {
238 const children = new Map<ThreadId, OrchestrationV2ThreadShell[]>();
239 for (const thread of get(environmentThreadsAtom(ref.environmentId))) {
240 const parent = thread.lineage.parentThreadId;
241 if (parent === null || thread.lineage.relationshipToParent !== "subagent") continue;
242 const siblings = children.get(parent);
243 if (siblings) siblings.push(thread);
244 else children.set(parent, [thread]);
245 }
246 const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));
247 const seen = new Set<ThreadId>([ref.threadId]);
248 const pending = [ref.threadId];
249 const next: EnvironmentThreadShell[] = [];
250 for (const parent of pending) {
251 for (const child of children.get(parent) ?? []) {
252 if (seen.has(child.id)) continue;
253 seen.add(child.id);
254 pending.push(child.id);
255 if (subagentRequest(child) !== null) {
256 next.push(scopedThread(ref.environmentId, child, subagentRequests));
257 }
258 }
259 }
260 // Indicators read only ids, titles and the request kind, so other shell
261 // updates keep the old array.
262 if (
263 previous.length === next.length &&
264 previous.every(
265 (thread, index) =>
266 thread.id === next[index]?.id &&
267 thread.title === next[index]?.title &&
268 thread.hasPendingApprovals === next[index]?.hasPendingApprovals,
269 )
270 ) {
271 return previous;
272 }
273 previous = next;
274 return next;
275 }).pipe(Atom.withLabel(`environment-child-thread-inputs:${key}`));
276 });
277
278 const threadShellsForProjectRefsAtomFamily = Atom.family((key: string) => {
279 const projectRefs = parseProjectRefCollectionKey(key);
280 let previous: ReadonlyArray<EnvironmentThreadShell> = [];
281 return Atom.make((get) => {
282 const next: EnvironmentThreadShell[] = [];
283 const seen = new Set<string>();
284 for (const projectRef of projectRefs) {
285 const refs =
286 get(environmentThreadRefsByProjectAtom(projectRef.environmentId)).get(
287 projectRef.projectId,
288 ) ?? EMPTY_SCOPED_THREAD_REFS;
289 if (refs.length === 0) continue;
290 const threads = get(environmentThreadIndexAtom(projectRef.environmentId));
291 const subagentRequests = get(pendingSubagentRequestsAtom(projectRef.environmentId));
292 for (const ref of refs) {
293 const key = threadKey(ref);
294 if (seen.has(key)) {
295 continue;
296 }
297 seen.add(key);
298 const thread = threads.get(ref.threadId);
299 if (thread !== undefined) {
300 next.push(scopedThread(ref.environmentId, thread, subagentRequests));
301 }
302 }
303 }
304 if (arrayElementsEqual(previous, next)) {
305 return previous;
306 }
307 previous = next;
308 return previous;
309 }).pipe(Atom.withLabel(`environment-thread-shells-for-projects:${key}`));
310 });
311
312 let previousThreadRefs: ReadonlyArray<ScopedThreadRef> = [];
313 const threadRefsAtom = Atom.make((get) => {
314 const refs: ScopedThreadRef[] = [];
315 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
316 refs.push(...get(environmentThreadRefsAtom(environmentId)));
317 }
318 if (threadRefsEqual(previousThreadRefs, refs)) {
319 return previousThreadRefs;
320 }
321 previousThreadRefs = refs;
322 return refs;
323 }).pipe(Atom.withLabel("environment-thread-refs"));
324
325 let previousThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
326 const threadShellsAtom = Atom.make((get) => {
327 const next: EnvironmentThreadShell[] = [];
328 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
329 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
330 for (const thread of get(environmentThreadsAtom(environmentId))) {
331 next.push(scopedThread(environmentId, thread, subagentRequests));
332 }
333 }
334 if (arrayElementsEqual(previousThreadShells, next)) {
335 return previousThreadShells;
336 }
337 previousThreadShells = next;
338 return previousThreadShells;
339 }).pipe(Atom.withLabel("environment-thread-shell-list"));
340
341 let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];
342 const navigationThreadShellsAtom = Atom.make((get) => {
343 const next: EnvironmentThreadShell[] = [];
344 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
345 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
346 for (const thread of get(environmentThreadsAtom(environmentId))) {
347 if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")
348 continue;
349 next.push(scopedThread(environmentId, thread, subagentRequests));
350 }
351 }
352 if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells;
353 previousNavigationShells = next;
354 return next;
355 }).pipe(Atom.withLabel("environment-navigation-thread-shells"));
356
357 return {
358 environmentThreadsAtom,
359 environmentThreadIndexAtom,
360 environmentThreadRefsAtom,
361 environmentThreadRefsByProjectAtom,
362 threadRefsAtom,
363 threadShellsAtom,
364 navigationThreadShellsAtom,
365 threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
366 threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
367 threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
368 childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
369 };
370}