Open History to see the last commit
1import type * as DateTime from "effect/DateTime";
2import { msg } from "gt-react";
3import { delegatedChildIsWorking } from "@t3tools/client-runtime/state/models";
4import { useAtomValue } from "@effect/atom-react";
5import type {
6 EnvironmentProject,
7 EnvironmentThread,
8 EnvironmentThreadShell,
9 EnvironmentThreadStructure,
10 ThreadStructure,
11 ThreadStructureVisibleTurnItem,
12} from "@t3tools/client-runtime/state/shell";
13import {
14 EMPTY_THREAD_HISTORY_META,
15 type EnvironmentThreadStatus,
16 type ThreadHistoryMeta,
17} from "@t3tools/client-runtime/state/threads";
18import {
19 arrayElementsEqual,
20 parseThreadKey,
21 threadKey,
22} from "@t3tools/client-runtime/state/entities";
23import type { ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
24import type {
25 EnvironmentId,
26 OrchestrationV2ProjectedTurnItem,
27 OrchestrationV2RemoteTaskChild,
28 OrchestrationV2ThreadShell,
29 NodeId,
30 ThreadId,
31 TurnItemId,
32} from "@t3tools/contracts";
33import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
34import { Atom } from "effect/reactivity";
35import { appAtomRegistry } from "../rpc/atomRegistry";
36import { environmentProjects } from "./projects";
37import { environmentPresentations } from "./presentation";
38import { environmentServerConfigsAtom } from "./server";
39import {
40 allEnvironmentProjectSnapshotsReadyAtom,
41 allEnvironmentShellsBootstrappedAtom,
42} from "./shell";
43import { environmentThreadDetails, environmentThreadShells } from "./threads";
44import { waitForAtomValue } from "./waitForAtomValue";
45import { m } from "../i18n/messages";
46
47const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
48const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = Object.freeze([]);
49
50const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
51 Atom.withLabel("web-project:empty"),
52);
53const EMPTY_THREAD_REFS_ATOM = Atom.make(EMPTY_THREAD_REFS).pipe(
54 Atom.withLabel("web-thread-refs:empty"),
55);
56const EMPTY_THREAD_SHELLS_ATOM = Atom.make<ReadonlyArray<EnvironmentThreadShell>>(
57 Object.freeze([]),
58).pipe(Atom.withLabel("web-thread-shells:empty"));
59const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
60 Atom.withLabel("web-thread-shell:empty"),
61);
62const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
63 Atom.withLabel("web-thread-projection:empty"),
64);
65const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pipe(
66 Atom.withLabel("web-thread-status:empty"),
67);
68const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
69 Atom.withLabel("web-thread-visible-turn-items:empty"),
70);
71const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>(
72 Object.freeze([]),
73).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty"));
74const EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM = Atom.make<string | null>(null).pipe(
75 Atom.withLabel("web-assistant-message-text:empty"),
76);
77const EMPTY_LAST_VISITED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
78 Atom.withLabel("web-thread-last-visited:empty"),
79);
80const EMPTY_THREAD_ERROR_ATOM = Atom.make<string | null>(null).pipe(
81 Atom.withLabel("web-thread-error:empty"),
82);
83const EMPTY_UPDATED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
84 Atom.withLabel("web-thread-updated-at:empty"),
85);
86const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HISTORY_META).pipe(
87 Atom.withLabel("web-thread-history:empty"),
88);
89
90export function useThreadRefs(enabled = true): ReadonlyArray<ScopedThreadRef> {
91 return useAtomValue(enabled ? environmentThreadShells.threadRefsAtom : EMPTY_THREAD_REFS_ATOM);
92}
93
94export function useEnvironmentThreadRefs(
95 environmentId: EnvironmentId | null,
96): ReadonlyArray<ScopedThreadRef> {
97 return useAtomValue(
98 environmentId === null
99 ? EMPTY_THREAD_REFS_ATOM
100 : environmentThreadShells.environmentThreadRefsAtom(environmentId),
101 );
102}
103
104export function useProjects(): ReadonlyArray<EnvironmentProject> {
105 return useAtomValue(environmentProjects.projectsAtom);
106}
107
108/** Providers are left out; read them with `useEnvironmentProviders()`. */
109export function useServerConfigs() {
110 return useAtomValue(environmentPresentations.serverConfigsAtom);
111}
112
113export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
114 return useAtomValue(
115 enabled ? environmentThreadShells.threadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
116 );
117}
118
119/** Whether any connected environment is hiding tagged threads right now. */
120export function useAnyEnvironmentHiding(): boolean {
121 return useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
122}
123
124/** Keys of threads the tag filter hides from display, by `threadKey`. */
125export function useHiddenThreadKeys(): ReadonlySet<string> {
126 return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
127}
128
129/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
130export function useVisibleThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
131 return useAtomValue(
132 enabled ? environmentThreadShells.visibleThreadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
133 );
134}
135
136export function useAllEnvironmentShellsBootstrapped(): boolean {
137 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
138}
139
140export function useAllEnvironmentProjectSnapshotsReady(): boolean {
141 return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);
142}
143
144/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */
145export function useDelegatedUnderParent(): ReadonlySet<string> {
146 return useAtomValue(environmentThreadShells.delegatedUnderParentAtom);
147}
148
149export function useThreadShellsForProjectRefs(
150 refs: ReadonlyArray<ScopedProjectRef>,
151): ReadonlyArray<EnvironmentThreadShell> {
152 return useAtomValue(environmentThreadShells.threadShellsForProjectRefsAtom(refs));
153}
154
155export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
156 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
157}
158
159export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
160 return useAtomValue(
161 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
162 );
163}
164
165/** The shell without its streaming timestamps; see quietThreadShellAtom. */
166export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
167 return useAtomValue(
168 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
169 );
170}
171
172/** Every thread shell, held through streaming ticks; see quietThreadShellAtom. */
173export function useQuietThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
174 return useAtomValue(environmentThreadShells.quietThreadShellsAtom);
175}
176
177export function useChildThreadInputs(ref: ScopedThreadRef | null) {
178 return useAtomValue(
179 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
180 );
181}
182
183export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
184 return useAtomValue(
185 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
186 );
187}
188
189/** The thread's structure, held through streamed assistant and reasoning text; see ThreadStructure. */
190export function useQuietThreadProjection(
191 ref: ScopedThreadRef | null,
192): EnvironmentThreadStructure | null {
193 return useAtomValue(
194 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.quietThreadAtom(ref),
195 );
196}
197
198/** The detail's live visit mark, which the thread structure leaves out. */
199export function useThreadLastVisitedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
200 return useAtomValue(
201 ref === null ? EMPTY_LAST_VISITED_AT_ATOM : environmentThreadDetails.lastVisitedAtAtom(ref),
202 );
203}
204
205/** The detail's live `updatedAt`, which the thread structure leaves out. */
206export function useThreadUpdatedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
207 return useAtomValue(
208 ref === null ? EMPTY_UPDATED_AT_ATOM : environmentThreadDetails.updatedAtAtom(ref),
209 );
210}
211
212export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
213 return useAtomValue(
214 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
215 );
216}
217
218export function useThreadError(ref: ScopedThreadRef | null): string | null {
219 return useAtomValue(
220 ref === null ? EMPTY_THREAD_ERROR_ATOM : environmentThreadDetails.errorAtom(ref),
221 );
222}
223
224export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
225 return useAtomValue(
226 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
227 );
228}
229
230export function resolveThreadDetailRef(
231 ref: ScopedThreadRef | null,
232 options: {
233 shellExists: boolean;
234 waitForShell: boolean;
235 },
236): ScopedThreadRef | null {
237 return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
238}
239
240export function useThreadVisibleTurnItems(
241 ref: ScopedThreadRef | null,
242): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
243 return useAtomValue(
244 ref === null
245 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
246 : environmentThreadDetails.visibleTurnItemsAtom(ref),
247 );
248}
249
250/** Visible turn items held through streamed assistant text; see useAssistantMessageText. */
251export function useTimelineVisibleTurnItems(
252 ref: ScopedThreadRef | null,
253): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
254 return useAtomValue(
255 ref === null
256 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
257 : environmentThreadDetails.timelineVisibleTurnItemsAtom(ref),
258 );
259}
260
261/** One assistant message's live text, or null when the thread does not hold the item. */
262export function useAssistantMessageText(
263 ref: ScopedThreadRef | null,
264 itemId: string | undefined,
265): string | null {
266 return useAtomValue(
267 ref === null || itemId === undefined
268 ? EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM
269 : environmentThreadDetails.assistantMessageTextAtom(ref, itemId),
270 );
271}
272
273/** Visible turn items without their streamed text; see ThreadStructure. */
274export function useQuietThreadVisibleTurnItems(
275 ref: ScopedThreadRef | null,
276): ReadonlyArray<ThreadStructureVisibleTurnItem> {
277 return useAtomValue(
278 ref === null
279 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
280 : environmentThreadDetails.quietVisibleTurnItemsAtom(ref),
281 );
282}
283
284export function useThreadCheckpointSummaries(
285 ref: ScopedThreadRef | null,
286): ReadonlyArray<ThreadCheckpointSummary> {
287 return useAtomValue(
288 ref === null
289 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
290 : environmentThreadDetails.checkpointSummariesAtom(ref),
291 );
292}
293
294export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
295 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
296}
297
298export function subscribeProject(
299 ref: ScopedProjectRef,
300 listener: (project: EnvironmentProject | null) => void,
301): () => void {
302 return appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), listener);
303}
304
305export function readProjects(): ReadonlyArray<EnvironmentProject> {
306 return appAtomRegistry.get(environmentProjects.projectsAtom);
307}
308
309export function subscribeProjects(
310 listener: (projects: ReadonlyArray<EnvironmentProject>) => void,
311): () => void {
312 return appAtomRegistry.subscribe(environmentProjects.projectsAtom, listener);
313}
314
315export function waitForProject(
316 ref: ScopedProjectRef,
317 timeoutMs = 10_000,
318): Promise<EnvironmentProject> {
319 const current = readProject(ref);
320 if (current !== null) return Promise.resolve(current);
321
322 return new Promise((resolve, reject) => {
323 let unsubscribe: (() => void) | null = null;
324 const timeout = setTimeout(() => {
325 unsubscribe?.();
326 reject(new Error(m(msg("The project did not appear in the desktop app."))));
327 }, timeoutMs);
328 const finish = (project: EnvironmentProject | null) => {
329 if (project === null) return;
330 clearTimeout(timeout);
331 unsubscribe?.();
332 resolve(project);
333 };
334 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
335 finish(readProject(ref));
336 });
337}
338
339/** Waits for removal from the live store; delete replies arrive before the shell stream. */
340export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
341 return waitForAtomValue({
342 registry: appAtomRegistry,
343 atom: environmentProjects.projectAtom(ref),
344 predicate: (project) => project === null,
345 timeoutMs,
346 });
347}
348
349/** The thread's loaded timeline, for a handler that reads it once instead of subscribing. */
350export function readThreadTurnItems(ref: ScopedThreadRef) {
351 return (
352 appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(ref))?.projection
353 .visibleTurnItems ?? []
354 );
355}
356
357export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
358 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
359}
360
361export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
362 return waitForAtomValue({
363 registry: appAtomRegistry,
364 atom: environmentThreadShells.threadShellAtom(ref),
365 predicate: (thread) => thread !== null,
366 timeoutMs,
367 });
368}
369
370/** Waits for removal from the live store; delete replies arrive before the shell stream. */
371export function waitForThreadShellRemoval(
372 ref: ScopedThreadRef,
373 timeoutMs = 5_000,
374): Promise<boolean> {
375 return waitForAtomValue({
376 registry: appAtomRegistry,
377 atom: environmentThreadShells.threadShellAtom(ref),
378 predicate: (thread) => thread === null,
379 timeoutMs,
380 });
381}
382
383export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
384 const configs = useServerConfigs();
385 return (
386 environmentId !== null &&
387 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
388 );
389}
390
391export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
392 return (
393 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
394 .serverBrowser === true
395 );
396}
397
398export function readEnvironmentServerConfigLoaded(environmentId: EnvironmentId): boolean {
399 return appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId);
400}
401
402export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
403 return (
404 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
405 .threadAutoSettleOptOut === true
406 );
407}
408
409export function readEnvironmentThreadRefs(
410 environmentId: EnvironmentId,
411): ReadonlyArray<ScopedThreadRef> {
412 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
413}
414
415export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
416 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
417}
418
419export function readDelegatedUnderParent(): ReadonlySet<string> {
420 return appAtomRegistry.get(environmentThreadShells.delegatedUnderParentAtom);
421}
422
423function shellParentThreadId(
424 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
425): ThreadId | null {
426 return thread.forkedFrom?.type === "run"
427 ? thread.forkedFrom.threadId
428 : thread.lineage.parentThreadId;
429}
430
431/** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */
432export function selectThreadRelationshipShells(
433 threadId: ThreadId,
434 projection: Pick<ThreadStructure, "thread" | "subagents" | "contextTransfers"> | null,
435 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
436): ReadonlyArray<OrchestrationV2ThreadShell> {
437 const named = new Set<string>([threadId]);
438 if (projection !== null) {
439 const parentThreadId = shellParentThreadId(projection.thread);
440 if (parentThreadId !== null) named.add(parentThreadId);
441 for (const subagent of projection.subagents) {
442 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
443 for (const agent of subagent.workflow?.agents ?? []) {
444 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
445 }
446 }
447 for (const transfer of projection.contextTransfers) {
448 named.add(transfer.sourceThreadId);
449 named.add(transfer.targetThreadId);
450 }
451 }
452 const current = threads.find((thread) => thread.id === threadId);
453 const currentParentId = current === undefined ? null : shellParentThreadId(current);
454 if (currentParentId !== null) named.add(currentParentId);
455 return threads.filter(
456 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
457 );
458}
459
460const relationshipShellsAtomFamily = Atom.family((key: string) => {
461 const ref = parseThreadKey(key);
462 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
463 return Atom.make((get) => {
464 const next = selectThreadRelationshipShells(
465 ref.threadId,
466 get(environmentThreadDetails.quietThreadAtom(ref))?.projection ?? null,
467 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
468 ).map(
469 (thread) =>
470 get(
471 environmentThreadShells.quietThreadShellAtom({
472 environmentId: ref.environmentId,
473 threadId: thread.id,
474 }),
475 )?.source ?? thread,
476 );
477 if (arrayElementsEqual(previous, next)) return previous;
478 previous = next;
479 return next;
480 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
481});
482
483export function useThreadRelationshipShells(
484 ref: ScopedThreadRef,
485): ReadonlyArray<OrchestrationV2ThreadShell> {
486 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
487}
488
489const reopenedRemoteTasksAtomFamily = Atom.family((key: string) => {
490 const ref = parseThreadKey(key);
491 return Atom.make((get) => {
492 const reopened = new Set<NodeId>();
493 const seen = new Set<string>();
494 const tasks = get(environmentThreadDetails.quietThreadAtom(ref))?.projection.subagents ?? [];
495 // Follow-ups share a child thread, so only its newest task shows the live work.
496 for (const task of tasks.toReversed()) {
497 const child = task.remoteChild;
498 if (child === undefined || seen.has(threadKey(child))) continue;
499 seen.add(threadKey(child));
500 const shell = get(environmentThreadShells.quietThreadShellAtom(child));
501 if (
502 task.completedAt !== null &&
503 shell?.connectionPhase === "connected" &&
504 delegatedChildIsWorking(shell.source)
505 ) {
506 reopened.add(task.id);
507 }
508 }
509 return reopened;
510 }).pipe(Atom.withLabel(`web-reopened-remote-tasks:${key}`));
511});
512
513/** Remote tasks that finished but whose thread on a connected environment is at work again. */
514export function useReopenedRemoteTasks(ref: ScopedThreadRef): ReadonlySet<NodeId> {
515 return useAtomValue(reopenedRemoteTasksAtomFamily(threadKey(ref)));
516}
517
518interface SubagentChild {
519 readonly threadId: ThreadId;
520 /** Set when the task ran on a linked environment, which holds its thread. */
521 readonly environmentId?: EnvironmentId;
522 readonly title: string | null | undefined;
523}
524
525/**
526 * The subagents a response reported on, read once on demand so a timeline row does not subscribe
527 * to the thread for it. A result reaches the thread as a message from the subagent's thread or as
528 * a completion notice, at the start of a run or steered into one, so the inputs just before the
529 * response decide it. Turn items are read because older history loads nothing else.
530 */
531export function readResponseSubagents(
532 ref: ScopedThreadRef,
533 itemId: TurnItemId,
534): ReadonlyArray<Omit<SubagentChild, "title"> & { readonly title: string }> {
535 const projection = appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(ref))?.projection;
536 if (!projection) return [];
537 const items = projection.visibleTurnItems;
538 const isInput = (index: number) => {
539 const type = items[index]?.item.type;
540 return type === "user_message" || type === "notification";
541 };
542 let index = items.findIndex((projected) => projected.sourceItemId === itemId) - 1;
543 while (index >= 0 && !isInput(index)) index -= 1;
544
545 const byTask = new Map<NodeId, SubagentChild>();
546 const local = new Map<ThreadId, SubagentChild>();
547 const remember = (
548 taskId: NodeId,
549 childThreadId: ThreadId | null,
550 remote: OrchestrationV2RemoteTaskChild | undefined,
551 title: string | null,
552 ) => {
553 if (childThreadId !== null) {
554 const child = { threadId: childThreadId, title };
555 byTask.set(taskId, child);
556 local.set(childThreadId, child);
557 } else if (remote) {
558 // A task sent to a linked environment has no thread here; its thread lives there.
559 const { threadId, environmentId } = remote;
560 byTask.set(taskId, { threadId, environmentId, title: title ?? remote.title });
561 }
562 };
563 for (const { item } of items) {
564 if (item.type === "subagent") {
565 remember(item.subagentId, item.childThreadId, item.remoteChild, null);
566 }
567 }
568 for (const subagent of projection.subagents) {
569 remember(subagent.id, subagent.childThreadId, subagent.remoteChild, subagent.title);
570 }
571
572 const found = new Map<string, SubagentChild>();
573 const add = (child: SubagentChild | undefined) => {
574 if (child) found.set(`${child.environmentId ?? ""}:${child.threadId}`, child);
575 };
576 for (; index >= 0 && isInput(index); index -= 1) {
577 const item = items[index]!.item;
578 if (item.type === "notification") {
579 // A notice names its child itself, so it counts even when the task is no longer loaded.
580 if ("childThreadId" in item.source && item.source.childThreadId !== undefined) {
581 const threadId = item.source.childThreadId;
582 add(local.get(threadId) ?? { threadId, title: null });
583 }
584 for (const taskId of "taskIds" in item.source ? item.source.taskIds : []) {
585 add(byTask.get(taskId));
586 }
587 } else if (item.type === "user_message") {
588 const message = projection.messages.find(({ id }) => id === item.messageId);
589 for (const taskId of message?.delegatedCompletion?.taskIds ?? []) add(byTask.get(taskId));
590 // A sender counts only as this thread's subagent: a child's first message comes from its parent.
591 if (item.senderThreadId !== undefined) add(local.get(item.senderThreadId));
592 }
593 }
594 return [...found.values()].map(({ title, ...child }) => ({
595 ...child,
596 title:
597 title?.trim() ||
598 appAtomRegistry
599 .get(
600 environmentThreadShells.quietThreadShellAtom({
601 environmentId: child.environmentId ?? ref.environmentId,
602 threadId: child.threadId,
603 }),
604 )
605 ?.title.trim() ||
606 // oxlint-disable-next-line t3code/no-untranslated-copy -- subagent title stored in the reply record sent to the agent
607 "Agent",
608 }));
609}