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