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

entities.ts

560 lines20.5 KB

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);
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 );
102​
103export function useProjects(): ReadonlyArray<EnvironmentProject> {
104 return useAtomValue(environmentProjects.projectsAtom);
106​
107/** Providers are left out; read them with `useEnvironmentProviders()`. */
108export function useServerConfigs() {
109 return useAtomValue(environmentPresentations.serverConfigsAtom);
111​
112export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
113 return useAtomValue(
114 enabled ? environmentThreadShells.threadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
115 );
117​
118/** Whether any connected environment is hiding tagged threads right now. */
119export function useAnyEnvironmentHiding(): boolean {
120 return useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
122​
123/** Keys of threads the tag filter hides from display, by `threadKey`. */
124export function useHiddenThreadKeys(): ReadonlySet<string> {
125 return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
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 );
134​
135export function useAllEnvironmentShellsBootstrapped(): boolean {
136 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
138​
139export function useAllEnvironmentProjectSnapshotsReady(): boolean {
140 return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);
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);
147​
148export function useThreadShellsForProjectRefs(
149 refs: ReadonlyArray<ScopedProjectRef>,
150): ReadonlyArray<EnvironmentThreadShell> {
151 return useAtomValue(environmentThreadShells.threadShellsForProjectRefsAtom(refs));
153​
154export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
155 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
157​
158export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
159 return useAtomValue(
160 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
161 );
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 );
170​
171/** Every thread shell, held through streaming ticks; see quietThreadShellAtom. */
172export function useQuietThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
173 return useAtomValue(environmentThreadShells.quietThreadShellsAtom);
175​
176export function useChildThreadInputs(ref: ScopedThreadRef | null) {
177 return useAtomValue(
178 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
179 );
181​
182export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
183 return useAtomValue(
184 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
185 );
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 );
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 );
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 );
210​
211export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
212 return useAtomValue(
213 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
214 );
216​
217export function useThreadError(ref: ScopedThreadRef | null): string | null {
218 return useAtomValue(
219 ref === null ? EMPTY_THREAD_ERROR_ATOM : environmentThreadDetails.errorAtom(ref),
220 );
222​
223export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
224 return useAtomValue(
225 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
226 );
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;
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 );
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 );
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 );
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 );
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 );
292​
293export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
294 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
296​
297export function subscribeProject(
298 ref: ScopedProjectRef,
299 listener: (project: EnvironmentProject | null) => void,
300): () => void {
301 return appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), listener);
303​
304export function readProjects(): ReadonlyArray<EnvironmentProject> {
305 return appAtomRegistry.get(environmentProjects.projectsAtom);
307​
308export function waitForProject(
309 ref: ScopedProjectRef,
310 timeoutMs = 10_000,
311): Promise<EnvironmentProject> {
312 const current = readProject(ref);
313 if (current !== null) return Promise.resolve(current);
314​
315 return new Promise((resolve, reject) => {
316 let unsubscribe: (() => void) | null = null;
317 const timeout = setTimeout(() => {
318 unsubscribe?.();
319 reject(new Error(m(msg("The project did not appear in the desktop app."))));
320 }, timeoutMs);
321 const finish = (project: EnvironmentProject | null) => {
322 if (project === null) return;
323 clearTimeout(timeout);
324 unsubscribe?.();
325 resolve(project);
326 };
327 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
328 finish(readProject(ref));
329 });
331​
332/** Waits for removal from the live store; delete replies arrive before the shell stream. */
333export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
334 return waitForAtomValue({
335 registry: appAtomRegistry,
336 atom: environmentProjects.projectAtom(ref),
337 predicate: (project) => project === null,
338 timeoutMs,
339 });
341​
342/** The thread's loaded timeline, for a handler that reads it once instead of subscribing. */
343export function readThreadTurnItems(ref: ScopedThreadRef) {
344 return (
345 appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(ref))?.projection
346 .visibleTurnItems ?? []
347 );
349​
350export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
351 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
353​
354export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
355 return waitForAtomValue({
356 registry: appAtomRegistry,
357 atom: environmentThreadShells.threadShellAtom(ref),
358 predicate: (thread) => thread !== null,
359 timeoutMs,
360 });
362​
363export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
364 const configs = useServerConfigs();
365 return (
366 environmentId !== null &&
367 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
368 );
370​
371export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
372 return (
373 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
374 .serverBrowser === true
375 );
377​
378export function readEnvironmentServerConfigLoaded(environmentId: EnvironmentId): boolean {
379 return appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId);
381​
382export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
383 return (
384 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
385 .threadAutoSettleOptOut === true
386 );
388​
389export function readEnvironmentThreadRefs(
390 environmentId: EnvironmentId,
391): ReadonlyArray<ScopedThreadRef> {
392 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
394​
395export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
396 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
398​
399export function readDelegatedUnderParent(): ReadonlySet<string> {
400 return appAtomRegistry.get(environmentThreadShells.delegatedUnderParentAtom);
402​
403function shellParentThreadId(
404 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
405): ThreadId | null {
406 return thread.forkedFrom?.type === "run"
407 ? thread.forkedFrom.threadId
408 : thread.lineage.parentThreadId;
410​
411/** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */
412export function selectThreadRelationshipShells(
413 threadId: ThreadId,
414 projection: Pick<ThreadStructure, "thread" | "subagents" | "contextTransfers"> | null,
415 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
416): ReadonlyArray<OrchestrationV2ThreadShell> {
417 const named = new Set<string>([threadId]);
418 if (projection !== null) {
419 const parentThreadId = shellParentThreadId(projection.thread);
420 if (parentThreadId !== null) named.add(parentThreadId);
421 for (const subagent of projection.subagents) {
422 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
423 for (const agent of subagent.workflow?.agents ?? []) {
424 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
425 }
426 }
427 for (const transfer of projection.contextTransfers) {
428 named.add(transfer.sourceThreadId);
429 named.add(transfer.targetThreadId);
430 }
431 }
432 const current = threads.find((thread) => thread.id === threadId);
433 const currentParentId = current === undefined ? null : shellParentThreadId(current);
434 if (currentParentId !== null) named.add(currentParentId);
435 return threads.filter(
436 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
437 );
439​
440const relationshipShellsAtomFamily = Atom.family((key: string) => {
441 const ref = parseThreadKey(key);
442 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
443 return Atom.make((get) => {
444 const next = selectThreadRelationshipShells(
445 ref.threadId,
446 get(environmentThreadDetails.quietThreadAtom(ref))?.projection ?? null,
447 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
448 ).map(
449 (thread) =>
450 get(
451 environmentThreadShells.quietThreadShellAtom({
452 environmentId: ref.environmentId,
453 threadId: thread.id,
454 }),
455 )?.source ?? thread,
456 );
457 if (arrayElementsEqual(previous, next)) return previous;
458 previous = next;
459 return next;
460 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
461});
462​
463export function useThreadRelationshipShells(
464 ref: ScopedThreadRef,
465): ReadonlyArray<OrchestrationV2ThreadShell> {
466 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
468​
469interface SubagentChild {
470 readonly threadId: ThreadId;
471 /** Set when the task ran on a linked environment, which holds its thread. */
472 readonly environmentId?: EnvironmentId;
473 readonly title: string | null | undefined;
475​
476/**
477 * The subagents a response reported on, read once on demand so a timeline row does not subscribe
478 * to the thread for it. A result reaches the thread as a message from the subagent's thread or as
479 * a completion notice, at the start of a run or steered into one, so the inputs just before the
480 * response decide it. Turn items are read because older history loads nothing else.
481 */
482export function readResponseSubagents(
483 ref: ScopedThreadRef,
484 itemId: TurnItemId,
485): ReadonlyArray<Omit<SubagentChild, "title"> & { readonly title: string }> {
486 const projection = appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(ref))?.projection;
487 if (!projection) return [];
488 const items = projection.visibleTurnItems;
489 const isInput = (index: number) => {
490 const type = items[index]?.item.type;
491 return type === "user_message" || type === "notification";
492 };
493 let index = items.findIndex((projected) => projected.sourceItemId === itemId) - 1;
494 while (index >= 0 && !isInput(index)) index -= 1;
495​
496 const byTask = new Map<NodeId, SubagentChild>();
497 const local = new Map<ThreadId, SubagentChild>();
498 const remember = (
499 taskId: NodeId,
500 childThreadId: ThreadId | null,
501 remote: OrchestrationV2RemoteTaskChild | undefined,
502 title: string | null,
503 ) => {
504 if (childThreadId !== null) {
505 const child = { threadId: childThreadId, title };
506 byTask.set(taskId, child);
507 local.set(childThreadId, child);
508 } else if (remote) {
509 // A task sent to a linked environment has no thread here; its thread lives there.
510 const { threadId, environmentId } = remote;
511 byTask.set(taskId, { threadId, environmentId, title: title ?? remote.title });
512 }
513 };
514 for (const { item } of items) {
515 if (item.type === "subagent") {
516 remember(item.subagentId, item.childThreadId, item.remoteChild, null);
517 }
518 }
519 for (const subagent of projection.subagents) {
520 remember(subagent.id, subagent.childThreadId, subagent.remoteChild, subagent.title);
521 }
522​
523 const found = new Map<string, SubagentChild>();
524 const add = (child: SubagentChild | undefined) => {
525 if (child) found.set(`${child.environmentId ?? ""}:${child.threadId}`, child);
526 };
527 for (; index >= 0 && isInput(index); index -= 1) {
528 const item = items[index]!.item;
529 if (item.type === "notification") {
530 // A notice names its child itself, so it counts even when the task is no longer loaded.
531 if ("childThreadId" in item.source && item.source.childThreadId !== undefined) {
532 const threadId = item.source.childThreadId;
533 add(local.get(threadId) ?? { threadId, title: null });
534 }
535 for (const taskId of "taskIds" in item.source ? item.source.taskIds : []) {
536 add(byTask.get(taskId));
537 }
538 } else if (item.type === "user_message") {
539 const message = projection.messages.find(({ id }) => id === item.messageId);
540 for (const taskId of message?.delegatedCompletion?.taskIds ?? []) add(byTask.get(taskId));
541 // A sender counts only as this thread's subagent: a child's first message comes from its parent.
542 if (item.senderThreadId !== undefined) add(local.get(item.senderThreadId));
543 }
544 }
545 return [...found.values()].map(({ title, ...child }) => ({
546 ...child,
547 title:
548 title?.trim() ||
549 appAtomRegistry
550 .get(
551 environmentThreadShells.quietThreadShellAtom({
552 environmentId: child.environmentId ?? ref.environmentId,
553 threadId: child.threadId,
554 }),
555 )
556 ?.title.trim() ||
557 // oxlint-disable-next-line t3code/no-untranslated-copy -- subagent title stored in the reply record sent to the agent
558 "Agent",
559 }));