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