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 DesktopPreviewColorScheme,
12 type PreviewEvent,
13 type PreviewListResult,
14 type PreviewSessionSnapshot,
15 type ScopedThreadRef,
16} from "@t3tools/contracts";
17import { Atom } from "effect/unstable/reactivity";
18
19import { PREVIEW_RECENT_URL_LIMIT } from "./components/preview/previewConstants";
20import { appAtomRegistry } from "./rpc/atomRegistry";
21
22export interface DesktopPreviewOverlay {
23 hasWebContents: boolean;
24 canGoBack: boolean;
25 canGoForward: boolean;
26 loading: boolean;
27 zoomFactor: number;
28 pictureInPicture: boolean;
29 colorScheme: DesktopPreviewColorScheme;
30 controller: "human" | "agent" | "none";
31}
32
33export interface ThreadPreviewState {
34 snapshot: PreviewSessionSnapshot | null;
35 sessions: Record<string, PreviewSessionSnapshot>;
36 /** Tabs intentionally closed by this client. Stale list snapshots must not resurrect them. */
37 suppressedTabIds: ReadonlySet<string>;
38 activeTabId: string | null;
39 desktopOverlay: DesktopPreviewOverlay | null;
40 desktopByTabId: Record<string, DesktopPreviewOverlay>;
41 recentlySeenUrls: string[];
42 /** Server process currently authoritative for revision ordering. */
43 serverEpoch: string | null;
44 /** Latest ordered server revision applied from a list response or event. */
45 serverRevision: number;
46}
47
48const EMPTY_THREAD_PREVIEW_STATE: ThreadPreviewState = Object.freeze({
49 snapshot: null,
50 sessions: {},
51 suppressedTabIds: new Set<string>(),
52 activeTabId: null,
53 desktopOverlay: null,
54 desktopByTabId: {},
55 recentlySeenUrls: [] as string[],
56 serverEpoch: null,
57 serverRevision: 0,
58});
59
60const emptyPreviewStateAtom = Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
61 Atom.withLabel("preview:empty-thread"),
62);
63
64export const previewStateAtom = Atom.family((threadKey: string) =>
65 Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
66 Atom.keepAlive,
67 Atom.withLabel(`preview:thread:${threadKey}`),
68 ),
69);
70
71// Only the Electron browser host needs a cross-thread view. Keep that index
72// separate so thread-local readers never subscribe to unrelated previews.
73interface ActivePreviewThreadIndex {
74 readonly keys: ReadonlySet<string>;
75}
76
77const activePreviewThreadKeysAtom = Atom.make<ActivePreviewThreadIndex>({
78 keys: new Set<string>(),
79}).pipe(Atom.keepAlive, Atom.withLabel("preview:active-thread-keys"));
80
81const activePreviewSessionsAtom = Atom.make((get) => {
82 const byThreadKey: Record<string, ThreadPreviewState> = {};
83 for (const threadKey of get(activePreviewThreadKeysAtom).keys) {
84 const state = get(previewStateAtom(threadKey));
85 if (Object.keys(state.sessions).length > 0) {
86 byThreadKey[threadKey] = state;
87 }
88 }
89 return byThreadKey;
90}).pipe(Atom.withLabel("preview:active-sessions"));
91
92const changedPreviewThreadKeys = new Set<string>();
93
94function syncActivePreviewThread(threadKey: string, state: ThreadPreviewState): void {
95 const active = Object.keys(state.sessions).length > 0;
96 appAtomRegistry.update(activePreviewThreadKeysAtom, (current) => {
97 if (current.keys.has(threadKey) === active) return current;
98 const next = new Set(current.keys);
99 if (active) next.add(threadKey);
100 else next.delete(threadKey);
101 return { keys: next };
102 });
103}
104
105function updateThreadPreviewState(
106 ref: ScopedThreadRef,
107 update: (current: ThreadPreviewState) => ThreadPreviewState,
108): void {
109 const threadKey = scopedThreadKey(ref);
110 const atom = previewStateAtom(threadKey);
111 let nextState = appAtomRegistry.get(atom);
112 const changed = appAtomRegistry.modify(atom, (current) => {
113 nextState = update(current);
114 return [nextState !== current, nextState];
115 });
116 if (!changed) return;
117 changedPreviewThreadKeys.add(threadKey);
118 syncActivePreviewThread(threadKey, nextState);
119}
120
121const dedupeRecentUrls = (existing: string[], url: string): string[] => {
122 const next = [url, ...existing.filter((entry) => entry !== url)];
123 return next.slice(0, PREVIEW_RECENT_URL_LIMIT);
124};
125
126const rememberSnapshotUrl = (
127 recentlySeenUrls: string[],
128 snapshot: PreviewSessionSnapshot,
129): string[] =>
130 snapshot.navStatus._tag === "Idle"
131 ? recentlySeenUrls
132 : dedupeRecentUrls(recentlySeenUrls, snapshot.navStatus.url);
133
134const latestSnapshot = (
135 sessions: Record<string, PreviewSessionSnapshot>,
136): PreviewSessionSnapshot | null =>
137 Object.values(sessions)
138 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt))
139 .at(-1) ?? null;
140
141const removeSession = (current: ThreadPreviewState, tabId: string): ThreadPreviewState => {
142 if (!current.sessions[tabId]) return current;
143 const { [tabId]: _closed, ...sessions } = current.sessions;
144 const { [tabId]: _desktop, ...desktopByTabId } = current.desktopByTabId;
145 const nextSnapshot = latestSnapshot(sessions);
146 const activeTabId =
147 current.activeTabId === tabId ? (nextSnapshot?.tabId ?? null) : current.activeTabId;
148 const snapshot = activeTabId ? (sessions[activeTabId] ?? nextSnapshot) : nextSnapshot;
149 return {
150 ...current,
151 sessions,
152 desktopByTabId,
153 activeTabId: snapshot?.tabId ?? null,
154 snapshot,
155 desktopOverlay: snapshot ? (desktopByTabId[snapshot.tabId] ?? null) : null,
156 };
157};
158
159export function useThreadPreviewState(ref: ScopedThreadRef | null | undefined): ThreadPreviewState {
160 const atom = ref ? previewStateAtom(scopedThreadKey(ref)) : emptyPreviewStateAtom;
161 return useAtomValue(atom);
162}
163
164export function useActivePreviewSessions(): Record<string, ThreadPreviewState> {
165 return useAtomValue(activePreviewSessionsAtom);
166}
167
168export function readThreadPreviewState(ref: ScopedThreadRef): ThreadPreviewState {
169 return appAtomRegistry.get(previewStateAtom(scopedThreadKey(ref)));
170}
171
172export function subscribeThreadPreviewState(
173 ref: ScopedThreadRef,
174 listener: (state: ThreadPreviewState, previous: ThreadPreviewState) => void,
175): () => void {
176 const atom = previewStateAtom(scopedThreadKey(ref));
177 let previous = appAtomRegistry.get(atom);
178 return appAtomRegistry.subscribe(atom, (state) => {
179 const prior = previous;
180 previous = state;
181 listener(state, prior);
182 });
183}
184
185export function applyPreviewServerEvent(ref: ScopedThreadRef, event: PreviewEvent): void {
186 updateThreadPreviewState(ref, (current) => {
187 if (current.serverEpoch !== null && event.serverEpoch !== current.serverEpoch) return current;
188 if (event.revision < current.serverRevision) return current;
189 const next = (() => {
190 switch (event.type) {
191 case "opened":
192 case "navigated":
193 case "resized": {
194 const snapshot = event.snapshot;
195 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
196 const recentlySeenUrls =
197 snapshot.navStatus._tag === "Idle"
198 ? current.recentlySeenUrls
199 : dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url);
200 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
201 const activeTabId = event.type === "opened" ? snapshot.tabId : current.activeTabId;
202 const activeSnapshot = sessions[activeTabId ?? snapshot.tabId] ?? snapshot;
203 return {
204 ...current,
205 sessions,
206 activeTabId: activeTabId ?? snapshot.tabId,
207 snapshot: activeSnapshot,
208 desktopOverlay: current.desktopByTabId[activeSnapshot.tabId] ?? null,
209 recentlySeenUrls,
210 };
211 }
212 case "failed": {
213 const existing = current.sessions[event.tabId];
214 if (!existing) return current;
215 const failedSnapshot = {
216 ...existing,
217 navStatus: {
218 _tag: "LoadFailed" as const,
219 url: event.url,
220 title: event.title,
221 code: event.code,
222 description: event.description,
223 },
224 updatedAt: event.createdAt,
225 };
226 const sessions = { ...current.sessions, [event.tabId]: failedSnapshot };
227 return {
228 ...current,
229 sessions,
230 snapshot: current.activeTabId === event.tabId ? failedSnapshot : current.snapshot,
231 };
232 }
233 case "closed": {
234 const closed = removeSession(current, event.tabId);
235 if (!closed.suppressedTabIds.has(event.tabId)) return closed;
236 const suppressedTabIds = new Set(closed.suppressedTabIds);
237 suppressedTabIds.delete(event.tabId);
238 return { ...closed, suppressedTabIds };
239 }
240 }
241 })();
242 return next.serverRevision === event.revision && next.serverEpoch === event.serverEpoch
243 ? next
244 : {
245 ...next,
246 serverEpoch: event.serverEpoch,
247 serverRevision: event.revision,
248 };
249 });
250}
251
252export function applyPreviewServerSnapshot(
253 ref: ScopedThreadRef,
254 snapshot: PreviewSessionSnapshot | null,
255): void {
256 updateThreadPreviewState(ref, (current) => {
257 if (!snapshot && current.snapshot === null) return current;
258 if (!snapshot) {
259 return {
260 ...current,
261 snapshot: null,
262 sessions: {},
263 activeTabId: null,
264 desktopOverlay: null,
265 desktopByTabId: {},
266 };
267 }
268 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
269 const existing = current.sessions[snapshot.tabId];
270 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
271 const recentlySeenUrls = rememberSnapshotUrl(current.recentlySeenUrls, snapshot);
272 return {
273 ...current,
274 snapshot,
275 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
276 activeTabId: snapshot.tabId,
277 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
278 recentlySeenUrls,
279 };
280 });
281}
282
283/**
284 * Merge a server mutation without changing which tab the user is viewing.
285 *
286 * Commands such as resize can target background tabs. Their response is
287 * authoritative for that tab, but it is not a request to focus the tab.
288 */
289export function updatePreviewServerSnapshot(
290 ref: ScopedThreadRef,
291 snapshot: PreviewSessionSnapshot,
292): void {
293 updateThreadPreviewState(ref, (current) => {
294 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
295 const existing = current.sessions[snapshot.tabId];
296 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
297 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
298 const activeTabId =
299 current.activeTabId && sessions[current.activeTabId] ? current.activeTabId : snapshot.tabId;
300 const activeSnapshot = sessions[activeTabId] ?? snapshot;
301 return {
302 ...current,
303 sessions,
304 activeTabId,
305 snapshot: activeSnapshot,
306 desktopOverlay: current.desktopByTabId[activeTabId] ?? null,
307 recentlySeenUrls: rememberSnapshotUrl(current.recentlySeenUrls, snapshot),
308 };
309 });
310}
311
312/**
313 * Replace the local session index from an authoritative preview.list result.
314 * Missing tabs are removed while the current active tab is preserved whenever
315 * it still exists in the server result.
316 */
317export function reconcilePreviewServerSessions(
318 ref: ScopedThreadRef,
319 result: PreviewListResult,
320): void {
321 updateThreadPreviewState(ref, (current) => {
322 const sameServer = current.serverEpoch === result.serverEpoch;
323 if (sameServer && result.revision < current.serverRevision) return current;
324 const snapshots = result.sessions;
325 const sessions: Record<string, PreviewSessionSnapshot> = {};
326 const currentSuppressedTabIds = sameServer ? current.suppressedTabIds : new Set<string>();
327 let recentlySeenUrls = current.recentlySeenUrls;
328 for (const snapshot of snapshots) {
329 if (currentSuppressedTabIds.has(snapshot.tabId)) continue;
330 const existing = sameServer ? current.sessions[snapshot.tabId] : undefined;
331 const next = existing && existing.updatedAt > snapshot.updatedAt ? existing : snapshot;
332 sessions[next.tabId] = next;
333 recentlySeenUrls = rememberSnapshotUrl(recentlySeenUrls, next);
334 }
335
336 const fallback = latestSnapshot(sessions);
337 const activeTabId =
338 current.activeTabId && sessions[current.activeTabId]
339 ? current.activeTabId
340 : (fallback?.tabId ?? null);
341 const snapshot = activeTabId ? (sessions[activeTabId] ?? null) : null;
342 const desktopByTabId = sameServer
343 ? Object.fromEntries(
344 Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
345 )
346 : {};
347 const suppressedTabIds = new Set(
348 [...currentSuppressedTabIds].filter((tabId) =>
349 snapshots.some((snapshot) => snapshot.tabId === tabId),
350 ),
351 );
352 return {
353 ...current,
354 sessions,
355 suppressedTabIds,
356 activeTabId,
357 snapshot,
358 desktopByTabId,
359 desktopOverlay: activeTabId ? (desktopByTabId[activeTabId] ?? null) : null,
360 recentlySeenUrls,
361 serverEpoch: result.serverEpoch,
362 serverRevision: result.revision,
363 };
364 });
365}
366
367export function applyPreviewDesktopState(
368 ref: ScopedThreadRef,
369 tabId: string,
370 overlay: DesktopPreviewOverlay | null,
371): void {
372 updateThreadPreviewState(ref, (current) => {
373 const desktopByTabId = { ...current.desktopByTabId };
374 if (overlay) desktopByTabId[tabId] = overlay;
375 else delete desktopByTabId[tabId];
376 return {
377 ...current,
378 desktopByTabId,
379 desktopOverlay: current.activeTabId === tabId ? overlay : current.desktopOverlay,
380 };
381 });
382}
383
384export function beginPreviewSessionClose(ref: ScopedThreadRef, tabId: string): void {
385 updateThreadPreviewState(ref, (current) => {
386 const suppressedTabIds = new Set(current.suppressedTabIds);
387 suppressedTabIds.add(tabId);
388 return {
389 ...removeSession(current, tabId),
390 suppressedTabIds,
391 };
392 });
393}
394
395export function cancelPreviewSessionClose(
396 ref: ScopedThreadRef,
397 snapshot: PreviewSessionSnapshot | null,
398 tabId: string,
399): void {
400 updateThreadPreviewState(ref, (current) => {
401 if (!current.suppressedTabIds.has(tabId)) return current;
402 const suppressedTabIds = new Set(current.suppressedTabIds);
403 suppressedTabIds.delete(tabId);
404 if (!snapshot) {
405 return { ...current, suppressedTabIds };
406 }
407 const recentlySeenUrls =
408 snapshot.navStatus._tag !== "Idle"
409 ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
410 : current.recentlySeenUrls;
411 return {
412 ...current,
413 snapshot,
414 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
415 suppressedTabIds,
416 activeTabId: snapshot.tabId,
417 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
418 recentlySeenUrls,
419 };
420 });
421}
422
423export function setActivePreviewTab(ref: ScopedThreadRef, tabId: string): void {
424 updateThreadPreviewState(ref, (current) => {
425 const snapshot = current.sessions[tabId];
426 if (!snapshot || current.activeTabId === tabId) return current;
427 return {
428 ...current,
429 activeTabId: tabId,
430 snapshot,
431 desktopOverlay: current.desktopByTabId[tabId] ?? null,
432 };
433 });
434}
435
436export function rememberPreviewUrl(ref: ScopedThreadRef, url: string): void {
437 if (url.trim().length === 0) return;
438 updateThreadPreviewState(ref, (current) => ({
439 ...current,
440 recentlySeenUrls: dedupeRecentUrls(current.recentlySeenUrls, url),
441 }));
442}
443
444export function removePreviewThread(ref: ScopedThreadRef): void {
445 const threadKey = scopedThreadKey(ref);
446 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
447 syncActivePreviewThread(threadKey, EMPTY_THREAD_PREVIEW_STATE);
448 changedPreviewThreadKeys.delete(threadKey);
449}
450
451export function isPreviewSupportedInRuntime(): boolean {
452 if (typeof window === "undefined") return false;
453 return Boolean(window.desktopBridge?.preview);
454}
455
456export function resetPreviewStateForTests(): void {
457 for (const threadKey of changedPreviewThreadKeys) {
458 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
459 }
460 changedPreviewThreadKeys.clear();
461 appAtomRegistry.set(activePreviewThreadKeysAtom, { keys: new Set<string>() });
462}
463
464export const __testing = {
465 EMPTY_THREAD_PREVIEW_STATE,
466 RECENT_URL_LIMIT: PREVIEW_RECENT_URL_LIMIT,
467};