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

entities.ts

419 lines14.9 KB

1import type * as DateTime from "effect/DateTime";
2import { useAtomValue } from "@effect/atom-react";
3import type {
4 EnvironmentProject,
5 EnvironmentThread,
6 EnvironmentThreadShell,
7 EnvironmentThreadStructure,
8 ThreadStructureVisibleTurnItem,
9} from "@t3tools/client-runtime/state/shell";
10import {
11 EMPTY_THREAD_HISTORY_META,
12 type EnvironmentThreadStatus,
13 type ThreadHistoryMeta,
14} from "@t3tools/client-runtime/state/threads";
15import {
16 arrayElementsEqual,
17 parseThreadKey,
18 threadKey,
19} from "@t3tools/client-runtime/state/entities";
20import type { ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
21import type {
22 EnvironmentId,
23 OrchestrationV2ProjectedTurnItem,
24 OrchestrationV2ThreadProjection,
25 OrchestrationV2ThreadShell,
26 ThreadId,
27} from "@t3tools/contracts";
28import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
29import { Atom } from "effect/reactivity";
30import { appAtomRegistry } from "../rpc/atomRegistry";
31import { environmentProjects } from "./projects";
32import { environmentPresentations } from "./presentation";
33import { environmentServerConfigsAtom } from "./server";
34import {
35 allEnvironmentProjectSnapshotsReadyAtom,
36 allEnvironmentShellsBootstrappedAtom,
37} from "./shell";
38import { environmentThreadDetails, environmentThreadShells } from "./threads";
39import { waitForAtomValue } from "./waitForAtomValue";
40​
41const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
42const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = Object.freeze([]);
43​
44const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
45 Atom.withLabel("web-project:empty"),
46);
47const EMPTY_THREAD_REFS_ATOM = Atom.make(EMPTY_THREAD_REFS).pipe(
48 Atom.withLabel("web-thread-refs:empty"),
49);
50const EMPTY_THREAD_SHELLS_ATOM = Atom.make<ReadonlyArray<EnvironmentThreadShell>>(
51 Object.freeze([]),
52).pipe(Atom.withLabel("web-thread-shells:empty"));
53const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
54 Atom.withLabel("web-thread-shell:empty"),
55);
56const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
57 Atom.withLabel("web-thread-projection:empty"),
58);
59const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pipe(
60 Atom.withLabel("web-thread-status:empty"),
61);
62const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
63 Atom.withLabel("web-thread-visible-turn-items:empty"),
64);
65const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>(
66 Object.freeze([]),
67).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty"));
68const EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM = Atom.make<string | null>(null).pipe(
69 Atom.withLabel("web-assistant-message-text:empty"),
70);
71const EMPTY_LAST_VISITED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
72 Atom.withLabel("web-thread-last-visited:empty"),
73);
74const EMPTY_UPDATED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
75 Atom.withLabel("web-thread-updated-at:empty"),
76);
77const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HISTORY_META).pipe(
78 Atom.withLabel("web-thread-history:empty"),
79);
80​
81export function useThreadRefs(enabled = true): ReadonlyArray<ScopedThreadRef> {
82 return useAtomValue(enabled ? environmentThreadShells.threadRefsAtom : EMPTY_THREAD_REFS_ATOM);
84​
85export function useEnvironmentThreadRefs(
86 environmentId: EnvironmentId | null,
87): ReadonlyArray<ScopedThreadRef> {
88 return useAtomValue(
89 environmentId === null
90 ? EMPTY_THREAD_REFS_ATOM
91 : environmentThreadShells.environmentThreadRefsAtom(environmentId),
92 );
94​
95export function useProjects(): ReadonlyArray<EnvironmentProject> {
96 return useAtomValue(environmentProjects.projectsAtom);
98​
99/** Providers are left out; read them with `useEnvironmentProviders()`. */
100export function useServerConfigs() {
101 return useAtomValue(environmentPresentations.serverConfigsAtom);
103​
104export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
105 return useAtomValue(
106 enabled ? environmentThreadShells.threadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
107 );
109​
110export function useAllEnvironmentShellsBootstrapped(): boolean {
111 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
113​
114export function useAllEnvironmentProjectSnapshotsReady(): boolean {
115 return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);
117​
118/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */
119export function useDelegatedUnderParent(): ReadonlySet<string> {
120 return useAtomValue(environmentThreadShells.delegatedUnderParentAtom);
122​
123export function useThreadShellsForProjectRefs(
124 refs: ReadonlyArray<ScopedProjectRef>,
125): ReadonlyArray<EnvironmentThreadShell> {
126 return useAtomValue(environmentThreadShells.threadShellsForProjectRefsAtom(refs));
128​
129export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
130 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
132​
133export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
134 return useAtomValue(
135 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
136 );
138​
139/** The shell without its streaming timestamps; see quietThreadShellAtom. */
140export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
141 return useAtomValue(
142 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
143 );
145​
146/** Every thread shell, held through streaming ticks; see quietThreadShellAtom. */
147export function useQuietThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
148 return useAtomValue(environmentThreadShells.quietThreadShellsAtom);
150​
151export function useChildThreadInputs(ref: ScopedThreadRef | null) {
152 return useAtomValue(
153 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
154 );
156​
157export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
158 return useAtomValue(
159 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
160 );
162​
163/** The thread's structure, held through streamed assistant and reasoning text; see ThreadStructure. */
164export function useQuietThreadProjection(
165 ref: ScopedThreadRef | null,
166): EnvironmentThreadStructure | null {
167 return useAtomValue(
168 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.quietThreadAtom(ref),
169 );
171​
172/** The detail's live visit mark, which the thread structure leaves out. */
173export function useThreadLastVisitedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
174 return useAtomValue(
175 ref === null ? EMPTY_LAST_VISITED_AT_ATOM : environmentThreadDetails.lastVisitedAtAtom(ref),
176 );
178​
179/** The detail's live `updatedAt`, which the thread structure leaves out. */
180export function useThreadUpdatedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
181 return useAtomValue(
182 ref === null ? EMPTY_UPDATED_AT_ATOM : environmentThreadDetails.updatedAtAtom(ref),
183 );
185​
186export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
187 return useAtomValue(
188 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
189 );
191​
192export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
193 return useAtomValue(
194 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
195 );
197​
198export function resolveThreadDetailRef(
199 ref: ScopedThreadRef | null,
200 options: {
201 shellExists: boolean;
202 waitForShell: boolean;
203 },
204): ScopedThreadRef | null {
205 return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
207​
208export function useThreadVisibleTurnItems(
209 ref: ScopedThreadRef | null,
210): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
211 return useAtomValue(
212 ref === null
213 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
214 : environmentThreadDetails.visibleTurnItemsAtom(ref),
215 );
217​
218/** Visible turn items held through streamed assistant text; see useAssistantMessageText. */
219export function useTimelineVisibleTurnItems(
220 ref: ScopedThreadRef | null,
221): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
222 return useAtomValue(
223 ref === null
224 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
225 : environmentThreadDetails.timelineVisibleTurnItemsAtom(ref),
226 );
228​
229/** One assistant message's live text, or null when the thread does not hold the item. */
230export function useAssistantMessageText(
231 ref: ScopedThreadRef | null,
232 itemId: string | undefined,
233): string | null {
234 return useAtomValue(
235 ref === null || itemId === undefined
236 ? EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM
237 : environmentThreadDetails.assistantMessageTextAtom(ref, itemId),
238 );
240​
241/** Visible turn items without their streamed text; see ThreadStructure. */
242export function useQuietThreadVisibleTurnItems(
243 ref: ScopedThreadRef | null,
244): ReadonlyArray<ThreadStructureVisibleTurnItem> {
245 return useAtomValue(
246 ref === null
247 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
248 : environmentThreadDetails.quietVisibleTurnItemsAtom(ref),
249 );
251​
252export function useThreadCheckpointSummaries(
253 ref: ScopedThreadRef | null,
254): ReadonlyArray<ThreadCheckpointSummary> {
255 return useAtomValue(
256 ref === null
257 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
258 : environmentThreadDetails.checkpointSummariesAtom(ref),
259 );
261​
262export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
263 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
265​
266export function subscribeProject(
267 ref: ScopedProjectRef,
268 listener: (project: EnvironmentProject | null) => void,
269): () => void {
270 return appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), listener);
272​
273export function readProjects(): ReadonlyArray<EnvironmentProject> {
274 return appAtomRegistry.get(environmentProjects.projectsAtom);
276​
277export function waitForProject(
278 ref: ScopedProjectRef,
279 timeoutMs = 10_000,
280): Promise<EnvironmentProject> {
281 const current = readProject(ref);
282 if (current !== null) return Promise.resolve(current);
283​
284 return new Promise((resolve, reject) => {
285 let unsubscribe: (() => void) | null = null;
286 const timeout = setTimeout(() => {
287 unsubscribe?.();
288 reject(new Error("The project did not appear in the desktop app."));
289 }, timeoutMs);
290 const finish = (project: EnvironmentProject | null) => {
291 if (project === null) return;
292 clearTimeout(timeout);
293 unsubscribe?.();
294 resolve(project);
295 };
296 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
297 finish(readProject(ref));
298 });
300​
301/** Waits for removal from the live store; delete replies arrive before the shell stream. */
302export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
303 return waitForAtomValue({
304 registry: appAtomRegistry,
305 atom: environmentProjects.projectAtom(ref),
306 predicate: (project) => project === null,
307 timeoutMs,
308 });
310​
311export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
312 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
314​
315export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
316 return waitForAtomValue({
317 registry: appAtomRegistry,
318 atom: environmentThreadShells.threadShellAtom(ref),
319 predicate: (thread) => thread !== null,
320 timeoutMs,
321 });
323​
324export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
325 const configs = useServerConfigs();
326 return (
327 environmentId !== null &&
328 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
329 );
331​
332export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
333 return (
334 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
335 .serverBrowser === true
336 );
338​
339export function readEnvironmentServerConfigLoaded(environmentId: EnvironmentId): boolean {
340 return appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId);
342​
343export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
344 return (
345 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
346 .threadAutoSettleOptOut === true
347 );
349​
350export function readEnvironmentThreadRefs(
351 environmentId: EnvironmentId,
352): ReadonlyArray<ScopedThreadRef> {
353 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
355​
356export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
357 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
359​
360function shellParentThreadId(
361 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
362): ThreadId | null {
363 return thread.forkedFrom?.type === "run"
364 ? thread.forkedFrom.threadId
365 : thread.lineage.parentThreadId;
367​
368/** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */
369export function selectThreadRelationshipShells(
370 threadId: ThreadId,
371 projection: Pick<
372 OrchestrationV2ThreadProjection,
373 "thread" | "subagents" | "contextTransfers"
374 > | null,
375 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
376): ReadonlyArray<OrchestrationV2ThreadShell> {
377 const named = new Set<string>([threadId]);
378 if (projection !== null) {
379 const parentThreadId = shellParentThreadId(projection.thread);
380 if (parentThreadId !== null) named.add(parentThreadId);
381 for (const subagent of projection.subagents) {
382 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
383 for (const agent of subagent.workflow?.agents ?? []) {
384 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
385 }
386 }
387 for (const transfer of projection.contextTransfers) {
388 named.add(transfer.sourceThreadId);
389 named.add(transfer.targetThreadId);
390 }
391 }
392 const current = threads.find((thread) => thread.id === threadId);
393 const currentParentId = current === undefined ? null : shellParentThreadId(current);
394 if (currentParentId !== null) named.add(currentParentId);
395 return threads.filter(
396 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
397 );
399​
400const relationshipShellsAtomFamily = Atom.family((key: string) => {
401 const ref = parseThreadKey(key);
402 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
403 return Atom.make((get) => {
404 const next = selectThreadRelationshipShells(
405 ref.threadId,
406 get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
407 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
408 );
409 if (arrayElementsEqual(previous, next)) return previous;
410 previous = next;
411 return next;
412 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
413});
414​
415export function useThreadRelationshipShells(
416 ref: ScopedThreadRef,
417): ReadonlyArray<OrchestrationV2ThreadShell> {
418 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));