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

entities.ts

436 lines15.6 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​
110/** Whether any connected environment is hiding tagged threads right now. */
111export function useAnyEnvironmentHiding(): boolean {
112 return useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
114​
115/** Keys of threads the tag filter hides from display, by `threadKey`. */
116export function useHiddenThreadKeys(): ReadonlySet<string> {
117 return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
119​
120/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
121export function useVisibleThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
122 return useAtomValue(
123 enabled ? environmentThreadShells.visibleThreadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
124 );
126​
127export function useAllEnvironmentShellsBootstrapped(): boolean {
128 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
130​
131export function useAllEnvironmentProjectSnapshotsReady(): boolean {
132 return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);
134​
135/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */
136export function useDelegatedUnderParent(): ReadonlySet<string> {
137 return useAtomValue(environmentThreadShells.delegatedUnderParentAtom);
139​
140export function useThreadShellsForProjectRefs(
141 refs: ReadonlyArray<ScopedProjectRef>,
142): ReadonlyArray<EnvironmentThreadShell> {
143 return useAtomValue(environmentThreadShells.threadShellsForProjectRefsAtom(refs));
145​
146export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
147 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
149​
150export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
151 return useAtomValue(
152 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
153 );
155​
156/** The shell without its streaming timestamps; see quietThreadShellAtom. */
157export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
158 return useAtomValue(
159 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
160 );
162​
163/** Every thread shell, held through streaming ticks; see quietThreadShellAtom. */
164export function useQuietThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
165 return useAtomValue(environmentThreadShells.quietThreadShellsAtom);
167​
168export function useChildThreadInputs(ref: ScopedThreadRef | null) {
169 return useAtomValue(
170 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
171 );
173​
174export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
175 return useAtomValue(
176 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
177 );
179​
180/** The thread's structure, held through streamed assistant and reasoning text; see ThreadStructure. */
181export function useQuietThreadProjection(
182 ref: ScopedThreadRef | null,
183): EnvironmentThreadStructure | null {
184 return useAtomValue(
185 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.quietThreadAtom(ref),
186 );
188​
189/** The detail's live visit mark, which the thread structure leaves out. */
190export function useThreadLastVisitedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
191 return useAtomValue(
192 ref === null ? EMPTY_LAST_VISITED_AT_ATOM : environmentThreadDetails.lastVisitedAtAtom(ref),
193 );
195​
196/** The detail's live `updatedAt`, which the thread structure leaves out. */
197export function useThreadUpdatedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
198 return useAtomValue(
199 ref === null ? EMPTY_UPDATED_AT_ATOM : environmentThreadDetails.updatedAtAtom(ref),
200 );
202​
203export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
204 return useAtomValue(
205 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
206 );
208​
209export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
210 return useAtomValue(
211 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
212 );
214​
215export function resolveThreadDetailRef(
216 ref: ScopedThreadRef | null,
217 options: {
218 shellExists: boolean;
219 waitForShell: boolean;
220 },
221): ScopedThreadRef | null {
222 return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
224​
225export function useThreadVisibleTurnItems(
226 ref: ScopedThreadRef | null,
227): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
228 return useAtomValue(
229 ref === null
230 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
231 : environmentThreadDetails.visibleTurnItemsAtom(ref),
232 );
234​
235/** Visible turn items held through streamed assistant text; see useAssistantMessageText. */
236export function useTimelineVisibleTurnItems(
237 ref: ScopedThreadRef | null,
238): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
239 return useAtomValue(
240 ref === null
241 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
242 : environmentThreadDetails.timelineVisibleTurnItemsAtom(ref),
243 );
245​
246/** One assistant message's live text, or null when the thread does not hold the item. */
247export function useAssistantMessageText(
248 ref: ScopedThreadRef | null,
249 itemId: string | undefined,
250): string | null {
251 return useAtomValue(
252 ref === null || itemId === undefined
253 ? EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM
254 : environmentThreadDetails.assistantMessageTextAtom(ref, itemId),
255 );
257​
258/** Visible turn items without their streamed text; see ThreadStructure. */
259export function useQuietThreadVisibleTurnItems(
260 ref: ScopedThreadRef | null,
261): ReadonlyArray<ThreadStructureVisibleTurnItem> {
262 return useAtomValue(
263 ref === null
264 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
265 : environmentThreadDetails.quietVisibleTurnItemsAtom(ref),
266 );
268​
269export function useThreadCheckpointSummaries(
270 ref: ScopedThreadRef | null,
271): ReadonlyArray<ThreadCheckpointSummary> {
272 return useAtomValue(
273 ref === null
274 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
275 : environmentThreadDetails.checkpointSummariesAtom(ref),
276 );
278​
279export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
280 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
282​
283export function subscribeProject(
284 ref: ScopedProjectRef,
285 listener: (project: EnvironmentProject | null) => void,
286): () => void {
287 return appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), listener);
289​
290export function readProjects(): ReadonlyArray<EnvironmentProject> {
291 return appAtomRegistry.get(environmentProjects.projectsAtom);
293​
294export function waitForProject(
295 ref: ScopedProjectRef,
296 timeoutMs = 10_000,
297): Promise<EnvironmentProject> {
298 const current = readProject(ref);
299 if (current !== null) return Promise.resolve(current);
300​
301 return new Promise((resolve, reject) => {
302 let unsubscribe: (() => void) | null = null;
303 const timeout = setTimeout(() => {
304 unsubscribe?.();
305 reject(new Error("The project did not appear in the desktop app."));
306 }, timeoutMs);
307 const finish = (project: EnvironmentProject | null) => {
308 if (project === null) return;
309 clearTimeout(timeout);
310 unsubscribe?.();
311 resolve(project);
312 };
313 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
314 finish(readProject(ref));
315 });
317​
318/** Waits for removal from the live store; delete replies arrive before the shell stream. */
319export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
320 return waitForAtomValue({
321 registry: appAtomRegistry,
322 atom: environmentProjects.projectAtom(ref),
323 predicate: (project) => project === null,
324 timeoutMs,
325 });
327​
328export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
329 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
331​
332export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
333 return waitForAtomValue({
334 registry: appAtomRegistry,
335 atom: environmentThreadShells.threadShellAtom(ref),
336 predicate: (thread) => thread !== null,
337 timeoutMs,
338 });
340​
341export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
342 const configs = useServerConfigs();
343 return (
344 environmentId !== null &&
345 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
346 );
348​
349export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
350 return (
351 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
352 .serverBrowser === true
353 );
355​
356export function readEnvironmentServerConfigLoaded(environmentId: EnvironmentId): boolean {
357 return appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId);
359​
360export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
361 return (
362 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
363 .threadAutoSettleOptOut === true
364 );
366​
367export function readEnvironmentThreadRefs(
368 environmentId: EnvironmentId,
369): ReadonlyArray<ScopedThreadRef> {
370 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
372​
373export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
374 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
376​
377function shellParentThreadId(
378 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
379): ThreadId | null {
380 return thread.forkedFrom?.type === "run"
381 ? thread.forkedFrom.threadId
382 : thread.lineage.parentThreadId;
384​
385/** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */
386export function selectThreadRelationshipShells(
387 threadId: ThreadId,
388 projection: Pick<
389 OrchestrationV2ThreadProjection,
390 "thread" | "subagents" | "contextTransfers"
391 > | null,
392 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
393): ReadonlyArray<OrchestrationV2ThreadShell> {
394 const named = new Set<string>([threadId]);
395 if (projection !== null) {
396 const parentThreadId = shellParentThreadId(projection.thread);
397 if (parentThreadId !== null) named.add(parentThreadId);
398 for (const subagent of projection.subagents) {
399 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
400 for (const agent of subagent.workflow?.agents ?? []) {
401 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
402 }
403 }
404 for (const transfer of projection.contextTransfers) {
405 named.add(transfer.sourceThreadId);
406 named.add(transfer.targetThreadId);
407 }
408 }
409 const current = threads.find((thread) => thread.id === threadId);
410 const currentParentId = current === undefined ? null : shellParentThreadId(current);
411 if (currentParentId !== null) named.add(currentParentId);
412 return threads.filter(
413 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
414 );
416​
417const relationshipShellsAtomFamily = Atom.family((key: string) => {
418 const ref = parseThreadKey(key);
419 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
420 return Atom.make((get) => {
421 const next = selectThreadRelationshipShells(
422 ref.threadId,
423 get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
424 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
425 );
426 if (arrayElementsEqual(previous, next)) return previous;
427 previous = next;
428 return next;
429 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
430});
431​
432export function useThreadRelationshipShells(
433 ref: ScopedThreadRef,
434): ReadonlyArray<OrchestrationV2ThreadShell> {
435 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));