Open History to see the last commit
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_LAST_VISITED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
69 Atom.withLabel("web-thread-last-visited:empty"),
70);
71const EMPTY_UPDATED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
72 Atom.withLabel("web-thread-updated-at:empty"),
73);
74const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HISTORY_META).pipe(
75 Atom.withLabel("web-thread-history:empty"),
76);
77
78const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
79 Atom.keepAlive,
80 Atom.withLabel("web-active-environment-id"),
81);
82
83export function useActiveEnvironmentId(): EnvironmentId | null {
84 return useAtomValue(activeEnvironmentIdAtom);
85}
86
87export function setActiveEnvironmentId(environmentId: EnvironmentId | null): void {
88 appAtomRegistry.set(activeEnvironmentIdAtom, environmentId);
89}
90
91export function useThreadRefs(enabled = true): ReadonlyArray<ScopedThreadRef> {
92 return useAtomValue(enabled ? environmentThreadShells.threadRefsAtom : EMPTY_THREAD_REFS_ATOM);
93}
94
95export function useEnvironmentThreadRefs(
96 environmentId: EnvironmentId | null,
97): ReadonlyArray<ScopedThreadRef> {
98 return useAtomValue(
99 environmentId === null
100 ? EMPTY_THREAD_REFS_ATOM
101 : environmentThreadShells.environmentThreadRefsAtom(environmentId),
102 );
103}
104
105export function useProjects(): ReadonlyArray<EnvironmentProject> {
106 return useAtomValue(environmentProjects.projectsAtom);
107}
108
109/** Providers are left out; read them with `useEnvironmentProviders()`. */
110export function useServerConfigs() {
111 return useAtomValue(environmentPresentations.serverConfigsAtom);
112}
113
114export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
115 return useAtomValue(
116 enabled ? environmentThreadShells.threadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
117 );
118}
119
120export function useAllEnvironmentShellsBootstrapped(): boolean {
121 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
122}
123
124export function useAllEnvironmentProjectSnapshotsReady(): boolean {
125 return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);
126}
127
128export function useThreadShellsForProjectRefs(
129 refs: ReadonlyArray<ScopedProjectRef>,
130): ReadonlyArray<EnvironmentThreadShell> {
131 return useAtomValue(environmentThreadShells.threadShellsForProjectRefsAtom(refs));
132}
133
134export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
135 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
136}
137
138export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
139 return useAtomValue(
140 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
141 );
142}
143
144/** The shell without its streaming timestamps; see quietThreadShellAtom. */
145export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
146 return useAtomValue(
147 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
148 );
149}
150
151/** Every thread shell, held through streaming ticks; see quietThreadShellAtom. */
152export function useQuietThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
153 return useAtomValue(environmentThreadShells.quietThreadShellsAtom);
154}
155
156export function useChildThreadInputs(ref: ScopedThreadRef | null) {
157 return useAtomValue(
158 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
159 );
160}
161
162export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
163 return useAtomValue(
164 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
165 );
166}
167
168/** The thread's structure, held through streamed assistant and reasoning text; see ThreadStructure. */
169export function useQuietThreadProjection(
170 ref: ScopedThreadRef | null,
171): EnvironmentThreadStructure | null {
172 return useAtomValue(
173 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.quietThreadAtom(ref),
174 );
175}
176
177/** The detail's live visit mark, which the thread structure leaves out. */
178export function useThreadLastVisitedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
179 return useAtomValue(
180 ref === null ? EMPTY_LAST_VISITED_AT_ATOM : environmentThreadDetails.lastVisitedAtAtom(ref),
181 );
182}
183
184/** The detail's live `updatedAt`, which the thread structure leaves out. */
185export function useThreadUpdatedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
186 return useAtomValue(
187 ref === null ? EMPTY_UPDATED_AT_ATOM : environmentThreadDetails.updatedAtAtom(ref),
188 );
189}
190
191export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
192 return useAtomValue(
193 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
194 );
195}
196
197export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
198 return useAtomValue(
199 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
200 );
201}
202
203export function resolveThreadDetailRef(
204 ref: ScopedThreadRef | null,
205 options: {
206 shellExists: boolean;
207 waitForShell: boolean;
208 },
209): ScopedThreadRef | null {
210 return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
211}
212
213export function useThreadVisibleTurnItems(
214 ref: ScopedThreadRef | null,
215): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
216 return useAtomValue(
217 ref === null
218 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
219 : environmentThreadDetails.visibleTurnItemsAtom(ref),
220 );
221}
222
223/** Visible turn items without their streamed text; see ThreadStructure. */
224export function useQuietThreadVisibleTurnItems(
225 ref: ScopedThreadRef | null,
226): ReadonlyArray<ThreadStructureVisibleTurnItem> {
227 return useAtomValue(
228 ref === null
229 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
230 : environmentThreadDetails.quietVisibleTurnItemsAtom(ref),
231 );
232}
233
234export function useThreadCheckpointSummaries(
235 ref: ScopedThreadRef | null,
236): ReadonlyArray<ThreadCheckpointSummary> {
237 return useAtomValue(
238 ref === null
239 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
240 : environmentThreadDetails.checkpointSummariesAtom(ref),
241 );
242}
243
244export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
245 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
246}
247
248export function readProjects(): ReadonlyArray<EnvironmentProject> {
249 return appAtomRegistry.get(environmentProjects.projectsAtom);
250}
251
252export function waitForProject(
253 ref: ScopedProjectRef,
254 timeoutMs = 10_000,
255): Promise<EnvironmentProject> {
256 const current = readProject(ref);
257 if (current !== null) return Promise.resolve(current);
258
259 return new Promise((resolve, reject) => {
260 let unsubscribe: (() => void) | null = null;
261 const timeout = setTimeout(() => {
262 unsubscribe?.();
263 reject(new Error("The project did not appear in the desktop app."));
264 }, timeoutMs);
265 const finish = (project: EnvironmentProject | null) => {
266 if (project === null) return;
267 clearTimeout(timeout);
268 unsubscribe?.();
269 resolve(project);
270 };
271 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
272 finish(readProject(ref));
273 });
274}
275
276/** Waits for removal from the live store; delete replies arrive before the shell stream. */
277export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
278 return waitForAtomValue({
279 registry: appAtomRegistry,
280 atom: environmentProjects.projectAtom(ref),
281 predicate: (project) => project === null,
282 timeoutMs,
283 });
284}
285
286export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
287 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
288}
289
290export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
291 return waitForAtomValue({
292 registry: appAtomRegistry,
293 atom: environmentThreadShells.threadShellAtom(ref),
294 predicate: (thread) => thread !== null,
295 timeoutMs,
296 });
297}
298
299export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
300 const configs = useServerConfigs();
301 return (
302 environmentId !== null &&
303 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
304 );
305}
306
307export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
308 return (
309 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
310 .serverBrowser === true
311 );
312}
313
314export function readEnvironmentSupportsTitleRegeneration(environmentId: EnvironmentId): boolean {
315 return (
316 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
317 .threadTitleRegeneration === true
318 );
319}
320
321export function readEnvironmentSupportsPinning(environmentId: EnvironmentId): boolean {
322 return (
323 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
324 .threadPinning === true
325 );
326}
327
328export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean {
329 return (
330 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
331 .threadPinReorder === true
332 );
333}
334
335export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
336 return (
337 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
338 .threadAutoSettleOptOut === true
339 );
340}
341
342export function readEnvironmentSupportsActiveReorder(environmentId: EnvironmentId): boolean {
343 return (
344 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
345 .threadActiveReorder === true
346 );
347}
348
349export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
350 return (
351 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
352 .threadSettlement === true
353 );
354}
355
356export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
357 return (
358 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
359 .threadSnooze === true
360 );
361}
362
363export function readEnvironmentSupportsVisitedTracking(environmentId: EnvironmentId): boolean {
364 return (
365 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
366 .threadVisitedTracking === true
367 );
368}
369
370export function readEnvironmentThreadRefs(
371 environmentId: EnvironmentId,
372): ReadonlyArray<ScopedThreadRef> {
373 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
374}
375
376export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
377 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
378}
379
380function shellParentThreadId(
381 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
382): ThreadId | null {
383 return thread.forkedFrom?.type === "run"
384 ? thread.forkedFrom.threadId
385 : thread.lineage.parentThreadId;
386}
387
388/** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */
389export function selectThreadRelationshipShells(
390 threadId: ThreadId,
391 projection: Pick<
392 OrchestrationV2ThreadProjection,
393 "thread" | "subagents" | "contextTransfers"
394 > | null,
395 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
396): ReadonlyArray<OrchestrationV2ThreadShell> {
397 const named = new Set<string>([threadId]);
398 if (projection !== null) {
399 const parentThreadId = shellParentThreadId(projection.thread);
400 if (parentThreadId !== null) named.add(parentThreadId);
401 for (const subagent of projection.subagents) {
402 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
403 for (const agent of subagent.workflow?.agents ?? []) {
404 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
405 }
406 }
407 for (const transfer of projection.contextTransfers) {
408 named.add(transfer.sourceThreadId);
409 named.add(transfer.targetThreadId);
410 }
411 }
412 const current = threads.find((thread) => thread.id === threadId);
413 const currentParentId = current === undefined ? null : shellParentThreadId(current);
414 if (currentParentId !== null) named.add(currentParentId);
415 return threads.filter(
416 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
417 );
418}
419
420const relationshipShellsAtomFamily = Atom.family((key: string) => {
421 const ref = parseThreadKey(key);
422 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
423 return Atom.make((get) => {
424 const next = selectThreadRelationshipShells(
425 ref.threadId,
426 get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
427 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
428 );
429 if (arrayElementsEqual(previous, next)) return previous;
430 previous = next;
431 return next;
432 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
433});
434
435export function useThreadRelationshipShells(
436 ref: ScopedThreadRef,
437): ReadonlyArray<OrchestrationV2ThreadShell> {
438 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
439}