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/**
277 * Resolves once a deleted project leaves the live client store. The delete
278 * command returns before the shell stream does, so anything that picks a
279 * project in between (the index route's draft landing) still sees it.
280 */
281export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): Promise<boolean> {
282 return waitForAtomValue({
283 registry: appAtomRegistry,
284 atom: environmentProjects.projectAtom(ref),
285 predicate: (project) => project === null,
286 timeoutMs,
287 });
288}
289
290export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
291 return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
292}
293
294export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise<boolean> {
295 return waitForAtomValue({
296 registry: appAtomRegistry,
297 atom: environmentThreadShells.threadShellAtom(ref),
298 predicate: (thread) => thread !== null,
299 timeoutMs,
300 });
301}
302
303export function useEnvironmentSupportsServerBrowser(environmentId: EnvironmentId | null): boolean {
304 const configs = useServerConfigs();
305 return (
306 environmentId !== null &&
307 configs.get(environmentId)?.environment.capabilities.serverBrowser === true
308 );
309}
310
311export function readEnvironmentSupportsServerBrowser(environmentId: EnvironmentId): boolean {
312 return (
313 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
314 .serverBrowser === true
315 );
316}
317
318export function readEnvironmentSupportsTitleRegeneration(environmentId: EnvironmentId): boolean {
319 return (
320 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
321 .threadTitleRegeneration === true
322 );
323}
324
325export function readEnvironmentSupportsPinning(environmentId: EnvironmentId): boolean {
326 return (
327 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
328 .threadPinning === true
329 );
330}
331
332export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean {
333 return (
334 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
335 .threadPinReorder === true
336 );
337}
338
339export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean {
340 return (
341 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
342 .threadAutoSettleOptOut === true
343 );
344}
345
346export function readEnvironmentSupportsActiveReorder(environmentId: EnvironmentId): boolean {
347 return (
348 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
349 .threadActiveReorder === true
350 );
351}
352
353export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
354 return (
355 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
356 .threadSettlement === true
357 );
358}
359
360export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
361 return (
362 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
363 .threadSnooze === true
364 );
365}
366
367export function readEnvironmentSupportsVisitedTracking(environmentId: EnvironmentId): boolean {
368 return (
369 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
370 .threadVisitedTracking === true
371 );
372}
373
374export function readEnvironmentThreadRefs(
375 environmentId: EnvironmentId,
376): ReadonlyArray<ScopedThreadRef> {
377 return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));
378}
379
380export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
381 return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
382}
383
384function shellParentThreadId(
385 thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
386): ThreadId | null {
387 return thread.forkedFrom?.type === "run"
388 ? thread.forkedFrom.threadId
389 : thread.lineage.parentThreadId;
390}
391
392/**
393 * The live shells the panel's immediate relationships can reach: the thread,
394 * its parent, its children, and the threads its subagents, workflow members and
395 * context transfers name. Keeps its array while those shells are unchanged, so
396 * another thread streaming in the same environment does not re-render the panel.
397 */
398/** Exported for tests. */
399export function selectThreadRelationshipShells(
400 threadId: ThreadId,
401 projection: Pick<
402 OrchestrationV2ThreadProjection,
403 "thread" | "subagents" | "contextTransfers"
404 > | null,
405 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
406): ReadonlyArray<OrchestrationV2ThreadShell> {
407 const named = new Set<string>([threadId]);
408 if (projection !== null) {
409 const parentThreadId = shellParentThreadId(projection.thread);
410 if (parentThreadId !== null) named.add(parentThreadId);
411 for (const subagent of projection.subagents) {
412 if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
413 for (const agent of subagent.workflow?.agents ?? []) {
414 if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
415 }
416 }
417 for (const transfer of projection.contextTransfers) {
418 named.add(transfer.sourceThreadId);
419 named.add(transfer.targetThreadId);
420 }
421 }
422 const current = threads.find((thread) => thread.id === threadId);
423 const currentParentId = current === undefined ? null : shellParentThreadId(current);
424 if (currentParentId !== null) named.add(currentParentId);
425 return threads.filter(
426 (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
427 );
428}
429
430const relationshipShellsAtomFamily = Atom.family((key: string) => {
431 const ref = parseThreadKey(key);
432 let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
433 return Atom.make((get) => {
434 const next = selectThreadRelationshipShells(
435 ref.threadId,
436 get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
437 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
438 );
439 if (arrayElementsEqual(previous, next)) return previous;
440 previous = next;
441 return next;
442 }).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
443});
444
445export function useThreadRelationshipShells(
446 ref: ScopedThreadRef,
447): ReadonlyArray<OrchestrationV2ThreadShell> {
448 return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
449}