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(enabled = true): ReadonlyArray<ScopedThreadRef> {
83 return useAtomValue(enabled ? environmentThreadShells.threadRefsAtom : EMPTY_THREAD_REFS_ATOM);
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
142/** Every thread shell, held through streaming ticks; see quietThreadShellAtom. */
143export function useQuietThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
144 return useAtomValue(environmentThreadShells.quietThreadShellsAtom);
145}
146
147export function useChildThreadInputs(ref: ScopedThreadRef | null) {
148 return useAtomValue(
149 ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
150 );
151}
152
153export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThread | null {
154 return useAtomValue(
155 ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref),
156 );
157}
158
159export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
160 return useAtomValue(
161 ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
162 );
163}
164
165export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta {
166 return useAtomValue(
167 ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref),
168 );
169}
170
171export function resolveThreadDetailRef(
172 ref: ScopedThreadRef | null,
173 options: {
174 shellExists: boolean;
175 waitForShell: boolean;
176 },
177): ScopedThreadRef | null {
178 return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null;
179}
180
181export function useThreadVisibleTurnItems(
182 ref: ScopedThreadRef | null,
183): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {
184 return useAtomValue(
185 ref === null
186 ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
187 : environmentThreadDetails.visibleTurnItemsAtom(ref),
188 );
189}
190
191export function useThreadCheckpointSummaries(
192 ref: ScopedThreadRef | null,
193): ReadonlyArray<ThreadCheckpointSummary> {
194 return useAtomValue(
195 ref === null
196 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
197 : environmentThreadDetails.checkpointSummariesAtom(ref),
198 );
199}
200
201export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {
202 return appAtomRegistry.get(environmentProjects.projectAtom(ref));
203}
204
205export function readProjects(): ReadonlyArray<EnvironmentProject> {
206 return appAtomRegistry.get(environmentProjects.projectsAtom);
207}
208
209export function waitForProject(
210 ref: ScopedProjectRef,
211 timeoutMs = 10_000,
212): Promise<EnvironmentProject> {
213 const current = readProject(ref);
214 if (current !== null) return Promise.resolve(current);
215
216 return new Promise((resolve, reject) => {
217 let unsubscribe: (() => void) | null = null;
218 const timeout = setTimeout(() => {
219 unsubscribe?.();
220 reject(new Error("The project did not appear in the desktop app."));
221 }, timeoutMs);
222 const finish = (project: EnvironmentProject | null) => {
223 if (project === null) return;
224 clearTimeout(timeout);
225 unsubscribe?.();
226 resolve(project);
227 };
228 unsubscribe = appAtomRegistry.subscribe(environmentProjects.projectAtom(ref), finish);
229 finish(readProject(ref));
230 });
231}
232
233/**
234 * Resolves once a deleted project leaves the live client store. The delete
235 * command returns before the shell stream does, so anything that picks a
236 * project in between (the index route's draft landing) still sees it.
237 */
238export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
239 return waitForAtomValue({
240 registry: appAtomRegistry,
241 atom: environmentProjects.projectAtom(ref),
242 predicate: (project) => project === null,
243 timeoutMs,
244 });
245}
246
247export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
248 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
249}
250
251export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
252 return waitForAtomValue({
253 registry: appAtomRegistry,
254 atom: environmentThreadShells.threadShellAtom(ref),
255 predicate: (thread) => thread !== null,
256 timeoutMs,
257 });
258}
259
260export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
261 const configs = useServerConfigs();
262 return (
263 environmentId !== null &&
264 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
265 );
266}
267
268export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
269 return (
270 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
271 .serverBrowser === true
272 );
273}
274
275export function readEnvironmentSupportsTitleRegeneration(environmentId: EnvironmentId): boolean {
276 return (
277 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
278 .threadTitleRegeneration === true
279 );
280}
281
282export function readEnvironmentSupportsPinning(environmentId: EnvironmentId): boolean {
283 return (
284 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
285 .threadPinning === true
286 );
287}
288
289export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean {
290 return (
291 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
292 .threadPinReorder === true
293 );
294}
295
296export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
297 return (
298 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
299 .threadAutoSettleOptOut === true
300 );
301}
302
303export function readEnvironmentSupportsActiveReorder(environmentId: EnvironmentId): boolean {
304 return (
305 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
306 .threadActiveReorder === true
307 );
308}
309
310export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
311 return (
312 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
313 .threadSettlement === true
314 );
315}
316
317export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
318 return (
319 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
320 .threadSnooze === true
321 );
322}
323
324export function readEnvironmentSupportsVisitedTracking(environmentId: EnvironmentId): boolean {
325 return (
326 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
327 .threadVisitedTracking === true
328 );
329}
330
331export function readEnvironmentThreadRefs(
332 environmentId: EnvironmentId,
333): ReadonlyArray<ScopedThreadRef> {
334 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
335}
336
337export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
338 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
339}
340
341function shellParentThreadId(
342 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
343): ThreadId | null {
344 return thread.forkedFrom?.type === "run"
345 ? thread.forkedFrom.threadId
346 : thread.lineage.parentThreadId;
347}
348
349/**
350 * The live shells the panel's immediate relationships can reach: the thread,
351 * its parent, its children, and the threads its subagents, workflow members and
352 * context transfers name. Keeps its array while those shells are unchanged, so
353 * another thread streaming in the same environment does not re-render the panel.
354 */
355/** Exported for tests. */
356export function selectThreadRelationshipShells(
357 threadId: ThreadId,
358 projection: Pick<
359 OrchestrationV2ThreadProjection,
360 "thread" | "subagents" | "contextTransfers"
361 > | null,
362 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
363): ReadonlyArray<OrchestrationV2ThreadShell> {
364 const named = new Set<string>([threadId]);
365 if (projection !== null) {
366 const parentThreadId = shellParentThreadId(projection.thread);
367 if (parentThreadId !== null) named.add(parentThreadId);
368 for (const subagent of projection.subagents) {
369 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
370 for (const agent of subagent.workflow?.agents ?? []) {
371 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
372 }
373 }
374 for (const transfer of projection.contextTransfers) {
375 named.add(transfer.sourceThreadId);
376 named.add(transfer.targetThreadId);
377 }
378 }
379 const current = threads.find((thread) => thread.id === threadId);
380 const currentParentId = current === undefined ? null : shellParentThreadId(current);
381 if (currentParentId !== null) named.add(currentParentId);
382 return threads.filter(
383 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
384 );
385}
386
387const relationshipShellsAtomFamily = Atom.family((key: string) => {
388 const ref = parseThreadKey(key);
389 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
390 return Atom.make((get) => {
391 const next = selectThreadRelationshipShells(
392 ref.threadId,
393 get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
394 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
395 );
396 if (arrayElementsEqual(previous, next)) return previous;
397 previous = next;
398 return next;
399 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
400});
401
402export function useThreadRelationshipShells(
403 ref: ScopedThreadRef,
404): ReadonlyArray<OrchestrationV2ThreadShell> {
405 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
406}