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