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