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

usePreviewSession.ts

135 lines4.8 KB

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