Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usePreviewSession.ts

133 lines4.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 parseScopedThreadKey,
4 scopeThreadRef,
5 scopedThreadKey,
6} from "@t3tools/client-runtime/environment";
7import { type EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
8import * as Schema from "effect/Schema";
9import { AsyncResult, Atom } from "effect/reactivity";
10​
11import {
12 applyPreviewServerEvent,
13 readThreadPreviewState,
14 reconcilePreviewServerSessions,
15} from "~/previewStateStore";
16import { isElectron } from "~/env";
17import { previewEnvironment } from "~/state/preview";
18​
19class PreviewSessionThreadKeyParseError extends Schema.TaggedError<PreviewSessionThreadKeyParseError>()(
20 "PreviewSessionThreadKeyParseError",
21 { threadKey: Schema.String },
22) {
23 override get message(): string {
24 return `Invalid scoped preview thread key: ${this.threadKey}`;
25 }
27​
28const previewSessionSyncAtom = Atom.family((threadKey: string) => {
29 const threadRef = parseScopedThreadKey(threadKey);
30 if (threadRef === null) {
31 throw new PreviewSessionThreadKeyParseError({ threadKey });
32 }
33​
34 const sessionsAtom = previewEnvironment.list({
35 environmentId: threadRef.environmentId,
36 input: { threadId: threadRef.threadId },
37 });
38 const eventsAtom = previewEnvironment.events({
39 environmentId: threadRef.environmentId,
40 input: {},
41 });
42​
43 return Atom.make((get) => {
44 let disposed = false;
45 let eventsVersion = 0;
46​
47 const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
48 if (result.waiting || !AsyncResult.isSuccess(result)) return;
49 reconcilePreviewServerSessions(threadRef, result.value);
50 if (!readThreadPreviewState(threadRef).listLoaded) {
51 // An event overtook the first list. Retry the authoritative baseline;
52 // do not declare a partial event-only index ready for surface cleanup.
53 queueMicrotask(() => {
54 if (!disposed) get.refresh(sessionsAtom);
55 });
56 }
57 };
58​
59 const applyLatestEvent = (result: Atom.Type<typeof eventsAtom>) => {
60 if (!AsyncResult.isSuccess(result) || result.value.threadId !== threadRef.threadId) return;
61 const currentEpoch = readThreadPreviewState(threadRef).serverEpoch;
62 if (currentEpoch !== null && currentEpoch !== result.value.serverEpoch) {
63 get.refresh(sessionsAtom);
64 return;
65 }
66 applyPreviewServerEvent(threadRef, result.value);
67 };
68​
69 get.addFinalizer(() => {
70 disposed = true;
71 });
72 const initialEvent = get.once(eventsAtom);
73 // Subscribing alone does not evaluate a lazy list. Start it now, but
74 // reconcile only subsequent responses: a completed cache may be stale.
75 get.once(sessionsAtom);
76 get.subscribe(sessionsAtom, (result) => {
77 reconcileSessions(result);
78 });
79 get.subscribe(eventsAtom, (result) => {
80 eventsVersion += 1;
81 applyLatestEvent(result);
82 });
83 get.mount(sessionsAtom);
84 get.mount(eventsAtom);
85 queueMicrotask(() => {
86 if (disposed) return;
87 // The cached list can predate an automation-created tab. Keep the local
88 // snapshot visible until an authoritative refresh arrives instead of
89 // reconciling against a stale empty result when the panel first mounts.
90 const current = get.once(sessionsAtom);
91 if (!AsyncResult.isInitial(current) && !current.waiting) get.refresh(sessionsAtom);
92 if (eventsVersion === 0) applyLatestEvent(initialEvent);
93 });
94 }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));
95});
96​
97export function usePreviewSession(threadRef: ScopedThreadRef): void {
98 useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef)));
100​
101const inactiveAtom = Atom.make(() => undefined);
102​
103// Discover background tabs without listing every thread at startup. Retain each
104// sync for the host's lifetime so later events still arrive while chat is absent.
105const desktopHostedPreviewSyncAtom = Atom.family((environmentId: EnvironmentId) => {
106 const eventsAtom = previewEnvironment.events({ environmentId, input: {} });
107 return Atom.make((get) => {
108 const syncedThreadIds = new Set<string>();
109 get.subscribe(
110 eventsAtom,
111 (result) => {
112 if (!AsyncResult.isSuccess(result) || result.value.type === "closed") return;
113 const threadId = result.value.threadId;
114 if (syncedThreadIds.has(threadId)) return;
115 syncedThreadIds.add(threadId);
116 get.mount(
117 previewSessionSyncAtom(
118 scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(threadId))),
119 ),
120 );
121 },
122 { immediate: true },
123 );
124 }).pipe(Atom.withLabel(`preview:desktop-hosted-sync:${environmentId}`));
125});
126​
127export function useDesktopHostedPreviewSessions(environmentId: EnvironmentId | null): void {
128 useAtomValue(
129 isElectron && environmentId !== null
130 ? desktopHostedPreviewSyncAtom(environmentId)
131 : inactiveAtom,
132 );