Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type {
3 EnvironmentProject,
4 EnvironmentThread,
5 EnvironmentThreadShell,
6} from "@t3tools/client-runtime/state/shell";
7import {
8 EMPTY_THREAD_HISTORY_META,
9 type EnvironmentThreadStatus,
10 type ThreadHistoryMeta,
11} from "@t3tools/client-runtime/state/threads";
12import {
13 arrayElementsEqual,
14 parseThreadKey,
15 threadKey,
16} from "@t3tools/client-runtime/state/entities";
17import type { ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
18import type {
19 EnvironmentId,
20 OrchestrationV2ProjectedTurnItem,
21 OrchestrationV2ThreadProjection,
22 OrchestrationV2ThreadShell,
23 ThreadId,
24} from "@t3tools/contracts";
25import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
26import { Atom } from "effect/reactivity";
27import { appAtomRegistry } from "../rpc/atomRegistry";
28import { environmentProjects } from "./projects";
29import { environmentPresentations } from "./presentation";
30import { environmentServerConfigsAtom } from "./server";
31import {
32 allEnvironmentProjectSnapshotsReadyAtom,
33 allEnvironmentShellsBootstrappedAtom,
34} from "./shell";
35import { environmentThreadDetails, environmentThreadShells } from "./threads";
36import { waitForAtomValue } from "./waitForAtomValue";
37
38const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
39const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = Object.freeze([]);
40
41const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
42 Atom.withLabel("web-project:empty"),
43);
44const EMPTY_THREAD_REFS_ATOM = Atom.make(EMPTY_THREAD_REFS).pipe(
45 Atom.withLabel("web-thread-refs:empty"),
46);
47const EMPTY_THREAD_SHELLS_ATOM = Atom.make<ReadonlyArray<EnvironmentThreadShell>>(
48 Object.freeze([]),
49).pipe(Atom.withLabel("web-thread-shells:empty"));
50const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
51 Atom.withLabel("web-thread-shell:empty"),
52);
53const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
54 Atom.withLabel("web-thread-projection:empty"),
55);
56const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pipe(
57 Atom.withLabel("web-thread-status:empty"),
58);
59const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
60 Atom.withLabel("web-thread-visible-turn-items:empty"),
61);
62const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>(
63 Object.freeze([]),
64).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty"));
65const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HISTORY_META).pipe(
66 Atom.withLabel("web-thread-history:empty"),
67);
68
69const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
70 Atom.keepAlive,
71 Atom.withLabel("web-active-environment-id"),
72);
73
74export function useActiveEnvironmentId(): EnvironmentId | null {
75 return useAtomValue(activeEnvironmentIdAtom);
76}
77
78export function setActiveEnvironmentId(environmentId: EnvironmentId | null): void {
79 appAtomRegistry.set(activeEnvironmentIdAtom, environmentId);
80}
81
82export function useThreadRefs(): ReadonlyArray<ScopedThreadRef> {
83 return useAtomValue(environmentThreadShells.threadRefsAtom);
84}
85
86export function useEnvironmentThreadRefs(
87 environmentId: EnvironmentId | null,
88): ReadonlyArray<ScopedThreadRef> {
89 return useAtomValue(
90 environmentId === null
91 ? EMPTY_THREAD_REFS_ATOM
92 : environmentThreadShells.environmentThreadRefsAtom(environmentId),
93 );
94}
95
96export function useProjects(): ReadonlyArray<EnvironmentProject> {
97 return useAtomValue(environmentProjects.projectsAtom);
98}
99
100/** Providers are left out; read them with `useEnvironmentProviders()`. */
101export function useServerConfigs() {
102 return useAtomValue(environmentPresentations.serverConfigsAtom);
103}
104
105export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
106 return useAtomValue(
107 enabled ? environmentThreadShells.threadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
108 );
109}
110
111export function useAllEnvironmentShellsBootstrapped(): boolean {
112 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
113}
114
115export function useAllEnvironmentProjectSnapshotsReady(): boolean {
116 return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);
117}
118
119export function useThreadShellsForProjectRefs(
120 refs: ReadonlyArray<ScopedProjectRef>,
121): ReadonlyArray<EnvironmentThreadShell> {
122 return useAtomValue(environmentThreadShells.threadShellsForProjectRefsAtom(refs));
123}
124
125export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
126 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
127}
128
129export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
130 return useAtomValue(
131 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
132 );
133}
134
135/** The shell without its streaming timestamps; see quietThreadShellAtom. */
136export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
137 return useAtomValue(
138 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
139 );
140}
141
142export function useChildThreadInputs(ref: ScopedThreadRef | null) {
143 return useAtomValue(
144 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
145 );
146}
147
148export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
149 return useAtomValue(
150 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
151 );
152}
153
154export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
155 return useAtomValue(
156 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
157 );
158}
159
160export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
161 return useAtomValue(
162 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
163 );
164}
165
166export function resolveThreadDetailRef(
167 ref: ScopedThreadRef | null,
168 options: {
169 shellExists: boolean;
170 waitForShell: boolean;
171 },
172): ScopedThreadRef | null {
173 return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
174}
175
176export function useThreadVisibleTurnItems(
177 ref: ScopedThreadRef | null,
178): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
179 return useAtomValue(
180 ref === null
181 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
182 : environmentThreadDetails.visibleTurnItemsAtom(ref),
183 );
184}
185
186export function useThreadCheckpointSummaries(
187 ref: ScopedThreadRef | null,
188): ReadonlyArray<ThreadCheckpointSummary> {
189 return useAtomValue(
190 ref === null
191 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
192 : environmentThreadDetails.checkpointSummariesAtom(ref),
193 );
194}
195
196export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
197 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
198}
199
200export function readProjects(): ReadonlyArray<EnvironmentProject> {
201 return appAtomRegistry.get(environmentProjects.projectsAtom);
202}
203
204export function waitForProject(
205 ref: ScopedProjectRef,
206 timeoutMs = 10_000,
207): Promise<EnvironmentProject> {
208 const current = readProject(ref);
209 if (current !== null) return Promise.resolve(current);
210
211 return new Promise((resolve, reject) => {
212 let unsubscribe: (() => void) | null = null;
213 const timeout = setTimeout(() => {
214 unsubscribe?.();
215 reject(new Error("The project did not appear in the desktop app."));
216 }, timeoutMs);
217 const finish = (project: EnvironmentProject | null) => {
218 if (project === null) return;
219 clearTimeout(timeout);
220 unsubscribe?.();
221 resolve(project);
222 };
223 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
224 finish(readProject(ref));
225 });
226}
227
228/**
229 * Resolves once a deleted project leaves the live client store. The delete
230 * command returns before the shell stream does, so anything that picks a
231 * project in between (the index route's draft landing) still sees it.
232 */
233export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
234 return waitForAtomValue({
235 registry: appAtomRegistry,
236 atom: environmentProjects.projectAtom(ref),
237 predicate: (project) => project === null,
238 timeoutMs,
239 });
240}
241
242export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
243 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
244}
245
246export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
247 return waitForAtomValue({
248 registry: appAtomRegistry,
249 atom: environmentThreadShells.threadShellAtom(ref),
250 predicate: (thread) => thread !== null,
251 timeoutMs,
252 });
253}
254
255export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
256 const configs = useServerConfigs();
257 return (
258 environmentId !== null &&
259 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
260 );
261}
262
263export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
264 return (
265 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
266 .serverBrowser === true
267 );
268}
269
270export function readEnvironmentSupportsTitleRegeneration(environmentId: EnvironmentId): boolean {
271 return (
272 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
273 .threadTitleRegeneration === true
274 );
275}
276
277export function readEnvironmentSupportsPinning(environmentId: EnvironmentId): boolean {
278 return (
279 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
280 .threadPinning === true
281 );
282}
283
284export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean {
285 return (
286 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
287 .threadPinReorder === true
288 );
289}
290
291export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
292 return (
293 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
294 .threadAutoSettleOptOut === true
295 );
296}
297
298export function readEnvironmentSupportsActiveReorder(environmentId: EnvironmentId): boolean {
299 return (
300 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
301 .threadActiveReorder === true
302 );
303}
304
305export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
306 return (
307 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
308 .threadSettlement === true
309 );
310}
311
312export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
313 return (
314 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
315 .threadSnooze === true
316 );
317}
318
319export function readEnvironmentSupportsVisitedTracking(environmentId: EnvironmentId): boolean {
320 return (
321 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
322 .threadVisitedTracking === true
323 );
324}
325
326export function readEnvironmentThreadRefs(
327 environmentId: EnvironmentId,
328): ReadonlyArray<ScopedThreadRef> {
329 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
330}
331
332export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
333 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
334}
335
336function shellParentThreadId(
337 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
338): ThreadId | null {
339 return thread.forkedFrom?.type === "run"
340 ? thread.forkedFrom.threadId
341 : thread.lineage.parentThreadId;
342}
343
344/**
345 * The live shells the panel's immediate relationships can reach: the thread,
346 * its parent, its children, and the threads its subagents, workflow members and
347 * context transfers name. Keeps its array while those shells are unchanged, so
348 * another thread streaming in the same environment does not re-render the panel.
349 */
350/** Exported for tests. */
351export function selectThreadRelationshipShells(
352 threadId: ThreadId,
353 projection: Pick<
354 OrchestrationV2ThreadProjection,
355 "thread" | "subagents" | "contextTransfers"
356 > | null,
357 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
358): ReadonlyArray<OrchestrationV2ThreadShell> {
359 const named = new Set<string>([threadId]);
360 if (projection !== null) {
361 const parentThreadId = shellParentThreadId(projection.thread);
362 if (parentThreadId !== null) named.add(parentThreadId);
363 for (const subagent of projection.subagents) {
364 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
365 for (const agent of subagent.workflow?.agents ?? []) {
366 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
367 }
368 }
369 for (const transfer of projection.contextTransfers) {
370 named.add(transfer.sourceThreadId);
371 named.add(transfer.targetThreadId);
372 }
373 }
374 const current = threads.find((thread) => thread.id === threadId);
375 const currentParentId = current === undefined ? null : shellParentThreadId(current);
376 if (currentParentId !== null) named.add(currentParentId);
377 return threads.filter(
378 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
379 );
380}
381
382const relationshipShellsAtomFamily = Atom.family((key: string) => {
383 const ref = parseThreadKey(key);
384 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
385 return Atom.make((get) => {
386 const next = selectThreadRelationshipShells(
387 ref.threadId,
388 get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
389 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
390 );
391 if (arrayElementsEqual(previous, next)) return previous;
392 previous = next;
393 return next;
394 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
395});
396
397export function useThreadRelationshipShells(
398 ref: ScopedThreadRef,
399): ReadonlyArray<OrchestrationV2ThreadShell> {
400 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
401}