Open History to see the last commit
1/**
2 * Per-thread preview UI state.
3 *
4 * Each thread owns an independent atom. Most consumers read exactly one
5 * thread; the desktop browser host uses the aggregate session atom because it
6 * is the one place that must enumerate every live preview tab.
7 */
8import { useAtomValue } from "@effect/atom-react";
9import { scopedThreadKey } from "@t3tools/client-runtime/environment";
10import {
11 type PreviewEvent,
12 type PreviewSessionSnapshot,
13 type ScopedThreadRef,
14} from "@t3tools/contracts";
15import { Atom } from "effect/unstable/reactivity";
16
17import { PREVIEW_RECENT_URL_LIMIT } from "./components/preview/previewConstants";
18import { appAtomRegistry } from "./rpc/atomRegistry";
19
20export interface DesktopPreviewOverlay {
21 canGoBack: boolean;
22 canGoForward: boolean;
23 loading: boolean;
24 zoomFactor: number;
25 controller: "human" | "agent" | "none";
26}
27
28export interface ThreadPreviewState {
29 snapshot: PreviewSessionSnapshot | null;
30 sessions: Record<string, PreviewSessionSnapshot>;
31 /** Tabs intentionally closed by this client. Stale list snapshots must not resurrect them. */
32 suppressedTabIds: ReadonlySet<string>;
33 activeTabId: string | null;
34 desktopOverlay: DesktopPreviewOverlay | null;
35 desktopByTabId: Record<string, DesktopPreviewOverlay>;
36 recentlySeenUrls: string[];
37}
38
39const EMPTY_THREAD_PREVIEW_STATE: ThreadPreviewState = Object.freeze({
40 snapshot: null,
41 sessions: {},
42 suppressedTabIds: new Set<string>(),
43 activeTabId: null,
44 desktopOverlay: null,
45 desktopByTabId: {},
46 recentlySeenUrls: [] as string[],
47});
48
49const emptyPreviewStateAtom = Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
50 Atom.withLabel("preview:empty-thread"),
51);
52
53export const previewStateAtom = Atom.family((threadKey: string) =>
54 Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
55 Atom.keepAlive,
56 Atom.withLabel(`preview:thread:${threadKey}`),
57 ),
58);
59
60// Only the Electron browser host needs a cross-thread view. Keep that index
61// separate so thread-local readers never subscribe to unrelated previews.
62interface ActivePreviewThreadIndex {
63 readonly keys: ReadonlySet<string>;
64}
65
66const activePreviewThreadKeysAtom = Atom.make<ActivePreviewThreadIndex>({
67 keys: new Set<string>(),
68}).pipe(Atom.keepAlive, Atom.withLabel("preview:active-thread-keys"));
69
70const activePreviewSessionsAtom = Atom.make((get) => {
71 const byThreadKey: Record<string, ThreadPreviewState> = {};
72 for (const threadKey of get(activePreviewThreadKeysAtom).keys) {
73 const state = get(previewStateAtom(threadKey));
74 if (Object.keys(state.sessions).length > 0) {
75 byThreadKey[threadKey] = state;
76 }
77 }
78 return byThreadKey;
79}).pipe(Atom.withLabel("preview:active-sessions"));
80
81const changedPreviewThreadKeys = new Set<string>();
82
83function syncActivePreviewThread(threadKey: string, state: ThreadPreviewState): void {
84 const active = Object.keys(state.sessions).length > 0;
85 appAtomRegistry.update(activePreviewThreadKeysAtom, (current) => {
86 if (current.keys.has(threadKey) === active) return current;
87 const next = new Set(current.keys);
88 if (active) next.add(threadKey);
89 else next.delete(threadKey);
90 return { keys: next };
91 });
92}
93
94function updateThreadPreviewState(
95 ref: ScopedThreadRef,
96 update: (current: ThreadPreviewState) => ThreadPreviewState,
97): void {
98 const threadKey = scopedThreadKey(ref);
99 const atom = previewStateAtom(threadKey);
100 let nextState = appAtomRegistry.get(atom);
101 const changed = appAtomRegistry.modify(atom, (current) => {
102 nextState = update(current);
103 return [nextState !== current, nextState];
104 });
105 if (!changed) return;
106 changedPreviewThreadKeys.add(threadKey);
107 syncActivePreviewThread(threadKey, nextState);
108}
109
110const dedupeRecentUrls = (existing: string[], url: string): string[] => {
111 const next = [url, ...existing.filter((entry) => entry !== url)];
112 return next.slice(0, PREVIEW_RECENT_URL_LIMIT);
113};
114
115const removeSession = (current: ThreadPreviewState, tabId: string): ThreadPreviewState => {
116 if (!current.sessions[tabId]) return current;
117 const { [tabId]: _closed, ...sessions } = current.sessions;
118 const { [tabId]: _desktop, ...desktopByTabId } = current.desktopByTabId;
119 const nextSnapshot =
120 Object.values(sessions)
121 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt))
122 .at(-1) ?? null;
123 const activeTabId =
124 current.activeTabId === tabId ? (nextSnapshot?.tabId ?? null) : current.activeTabId;
125 const snapshot = activeTabId ? (sessions[activeTabId] ?? nextSnapshot) : nextSnapshot;
126 return {
127 ...current,
128 sessions,
129 desktopByTabId,
130 activeTabId: snapshot?.tabId ?? null,
131 snapshot,
132 desktopOverlay: snapshot ? (desktopByTabId[snapshot.tabId] ?? null) : null,
133 };
134};
135
136export function useThreadPreviewState(ref: ScopedThreadRef | null | undefined): ThreadPreviewState {
137 const atom = ref ? previewStateAtom(scopedThreadKey(ref)) : emptyPreviewStateAtom;
138 return useAtomValue(atom);
139}
140
141export function useActivePreviewSessions(): Record<string, ThreadPreviewState> {
142 return useAtomValue(activePreviewSessionsAtom);
143}
144
145export function readThreadPreviewState(ref: ScopedThreadRef): ThreadPreviewState {
146 return appAtomRegistry.get(previewStateAtom(scopedThreadKey(ref)));
147}
148
149export function subscribeThreadPreviewState(
150 ref: ScopedThreadRef,
151 listener: (state: ThreadPreviewState, previous: ThreadPreviewState) => void,
152): () => void {
153 const atom = previewStateAtom(scopedThreadKey(ref));
154 let previous = appAtomRegistry.get(atom);
155 return appAtomRegistry.subscribe(atom, (state) => {
156 const prior = previous;
157 previous = state;
158 listener(state, prior);
159 });
160}
161
162export function applyPreviewServerEvent(ref: ScopedThreadRef, event: PreviewEvent): void {
163 updateThreadPreviewState(ref, (current) => {
164 switch (event.type) {
165 case "opened":
166 case "navigated": {
167 const snapshot = event.snapshot;
168 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
169 const recentlySeenUrls =
170 snapshot.navStatus._tag === "Idle"
171 ? current.recentlySeenUrls
172 : dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url);
173 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
174 const activeTabId = event.type === "opened" ? snapshot.tabId : current.activeTabId;
175 const activeSnapshot = sessions[activeTabId ?? snapshot.tabId] ?? snapshot;
176 return {
177 ...current,
178 sessions,
179 activeTabId: activeTabId ?? snapshot.tabId,
180 snapshot: activeSnapshot,
181 desktopOverlay: current.desktopByTabId[activeSnapshot.tabId] ?? null,
182 recentlySeenUrls,
183 };
184 }
185 case "failed": {
186 const existing = current.sessions[event.tabId];
187 if (!existing) return current;
188 const failedSnapshot = {
189 ...existing,
190 navStatus: {
191 _tag: "LoadFailed" as const,
192 url: event.url,
193 title: event.title,
194 code: event.code,
195 description: event.description,
196 },
197 updatedAt: event.createdAt,
198 };
199 const sessions = { ...current.sessions, [event.tabId]: failedSnapshot };
200 return {
201 ...current,
202 sessions,
203 snapshot: current.activeTabId === event.tabId ? failedSnapshot : current.snapshot,
204 };
205 }
206 case "closed":
207 return removeSession(current, event.tabId);
208 }
209 });
210}
211
212export function applyPreviewServerSnapshot(
213 ref: ScopedThreadRef,
214 snapshot: PreviewSessionSnapshot | null,
215): void {
216 updateThreadPreviewState(ref, (current) => {
217 if (!snapshot && current.snapshot === null) return current;
218 if (!snapshot) {
219 return {
220 ...current,
221 snapshot: null,
222 sessions: {},
223 activeTabId: null,
224 desktopOverlay: null,
225 desktopByTabId: {},
226 };
227 }
228 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
229 const existing = current.sessions[snapshot.tabId];
230 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
231 const recentlySeenUrls =
232 snapshot.navStatus._tag !== "Idle"
233 ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
234 : current.recentlySeenUrls;
235 return {
236 ...current,
237 snapshot,
238 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
239 activeTabId: snapshot.tabId,
240 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
241 recentlySeenUrls,
242 };
243 });
244}
245
246export function applyPreviewDesktopState(
247 ref: ScopedThreadRef,
248 tabId: string,
249 overlay: DesktopPreviewOverlay | null,
250): void {
251 updateThreadPreviewState(ref, (current) => {
252 const desktopByTabId = { ...current.desktopByTabId };
253 if (overlay) desktopByTabId[tabId] = overlay;
254 else delete desktopByTabId[tabId];
255 return {
256 ...current,
257 desktopByTabId,
258 desktopOverlay: current.activeTabId === tabId ? overlay : current.desktopOverlay,
259 };
260 });
261}
262
263export function beginPreviewSessionClose(ref: ScopedThreadRef, tabId: string): void {
264 updateThreadPreviewState(ref, (current) => {
265 const suppressedTabIds = new Set(current.suppressedTabIds);
266 suppressedTabIds.add(tabId);
267 return {
268 ...removeSession(current, tabId),
269 suppressedTabIds,
270 };
271 });
272}
273
274export function cancelPreviewSessionClose(
275 ref: ScopedThreadRef,
276 snapshot: PreviewSessionSnapshot | null,
277 tabId: string,
278): void {
279 updateThreadPreviewState(ref, (current) => {
280 if (!current.suppressedTabIds.has(tabId)) return current;
281 const suppressedTabIds = new Set(current.suppressedTabIds);
282 suppressedTabIds.delete(tabId);
283 if (!snapshot) {
284 return { ...current, suppressedTabIds };
285 }
286 const recentlySeenUrls =
287 snapshot.navStatus._tag !== "Idle"
288 ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
289 : current.recentlySeenUrls;
290 return {
291 ...current,
292 snapshot,
293 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
294 suppressedTabIds,
295 activeTabId: snapshot.tabId,
296 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
297 recentlySeenUrls,
298 };
299 });
300}
301
302export function setActivePreviewTab(ref: ScopedThreadRef, tabId: string): void {
303 updateThreadPreviewState(ref, (current) => {
304 const snapshot = current.sessions[tabId];
305 if (!snapshot || current.activeTabId === tabId) return current;
306 return {
307 ...current,
308 activeTabId: tabId,
309 snapshot,
310 desktopOverlay: current.desktopByTabId[tabId] ?? null,
311 };
312 });
313}
314
315export function rememberPreviewUrl(ref: ScopedThreadRef, url: string): void {
316 if (url.trim().length === 0) return;
317 updateThreadPreviewState(ref, (current) => ({
318 ...current,
319 recentlySeenUrls: dedupeRecentUrls(current.recentlySeenUrls, url),
320 }));
321}
322
323export function removePreviewThread(ref: ScopedThreadRef): void {
324 const threadKey = scopedThreadKey(ref);
325 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
326 syncActivePreviewThread(threadKey, EMPTY_THREAD_PREVIEW_STATE);
327 changedPreviewThreadKeys.delete(threadKey);
328}
329
330export function isPreviewSupportedInRuntime(): boolean {
331 if (typeof window === "undefined") return false;
332 return Boolean(window.desktopBridge?.preview);
333}
334
335export function resetPreviewStateForTests(): void {
336 for (const threadKey of changedPreviewThreadKeys) {
337 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
338 }
339 changedPreviewThreadKeys.clear();
340 appAtomRegistry.set(activePreviewThreadKeysAtom, { keys: new Set<string>() });
341}
342
343export const __testing = {
344 EMPTY_THREAD_PREVIEW_STATE,
345 RECENT_URL_LIMIT: PREVIEW_RECENT_URL_LIMIT,
346};