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

entities.ts

612 lines22.4 KB

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