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 subscribeThreadPreviewState(
177 ref: ScopedThreadRef,
178 listener: (state: ThreadPreviewState, previous: ThreadPreviewState) => void,
179): () => void {
180 const atom = previewStateAtom(scopedThreadKey(ref));
181 let previous = appAtomRegistry.get(atom);
182 return appAtomRegistry.subscribe(atom, (state) => {
183 const prior = previous;
184 previous = state;
185 listener(state, prior);
186 });
187}
188
189export function applyPreviewServerEvent(ref: ScopedThreadRef, event: PreviewEvent): void {
190 updateThreadPreviewState(ref, (current) => {
191 if (current.serverEpoch !== null && event.serverEpoch !== current.serverEpoch) return current;
192 if (event.revision < current.serverRevision) return current;
193 const next = (() => {
194 switch (event.type) {
195 case "opened":
196 case "navigated":
197 case "resized": {
198 const snapshot = event.snapshot;
199 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
200 const recentlySeenUrls =
201 snapshot.navStatus._tag === "Idle"
202 ? current.recentlySeenUrls
203 : dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url);
204 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
205 const activeTabId = event.type === "opened" ? snapshot.tabId : current.activeTabId;
206 const activeSnapshot = sessions[activeTabId ?? snapshot.tabId] ?? snapshot;
207 return {
208 ...current,
209 sessions,
210 activeTabId: activeTabId ?? snapshot.tabId,
211 snapshot: activeSnapshot,
212 desktopOverlay: current.desktopByTabId[activeSnapshot.tabId] ?? null,
213 recentlySeenUrls,
214 };
215 }
216 case "failed": {
217 const existing = current.sessions[event.tabId];
218 if (!existing) return current;
219 const failedSnapshot = {
220 ...existing,
221 navStatus: {
222 _tag: "LoadFailed" as const,
223 url: event.url,
224 title: event.title,
225 code: event.code,
226 description: event.description,
227 },
228 updatedAt: event.createdAt,
229 };
230 const sessions = { ...current.sessions, [event.tabId]: failedSnapshot };
231 return {
232 ...current,
233 sessions,
234 snapshot: current.activeTabId === event.tabId ? failedSnapshot : current.snapshot,
235 };
236 }
237 case "closed": {
238 const closed = removeSession(current, event.tabId);
239 if (!closed.suppressedTabIds.has(event.tabId)) return closed;
240 const suppressedTabIds = new Set(closed.suppressedTabIds);
241 suppressedTabIds.delete(event.tabId);
242 return { ...closed, suppressedTabIds };
243 }
244 }
245 })();
246 return next.serverRevision === event.revision && next.serverEpoch === event.serverEpoch
247 ? next
248 : {
249 ...next,
250 serverEpoch: event.serverEpoch,
251 serverRevision: event.revision,
252 };
253 });
254}
255
256export function applyPreviewServerSnapshot(
257 ref: ScopedThreadRef,
258 snapshot: PreviewSessionSnapshot | null,
259): void {
260 updateThreadPreviewState(ref, (current) => {
261 if (!snapshot && current.snapshot === null) return current;
262 if (!snapshot) {
263 return {
264 ...current,
265 snapshot: null,
266 sessions: {},
267 activeTabId: null,
268 desktopOverlay: null,
269 desktopByTabId: {},
270 };
271 }
272 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
273 const existing = current.sessions[snapshot.tabId];
274 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
275 const recentlySeenUrls = rememberSnapshotUrl(current.recentlySeenUrls, snapshot);
276 return {
277 ...current,
278 snapshot,
279 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
280 activeTabId: snapshot.tabId,
281 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
282 recentlySeenUrls,
283 };
284 });
285}
286
287/**
288 * Merge a server mutation without changing which tab the user is viewing.
289 *
290 * Commands such as resize can target background tabs. Their response is
291 * authoritative for that tab, but it is not a request to focus the tab.
292 */
293export function updatePreviewServerSnapshot(
294 ref: ScopedThreadRef,
295 snapshot: PreviewSessionSnapshot,
296): void {
297 updateThreadPreviewState(ref, (current) => {
298 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
299 const existing = current.sessions[snapshot.tabId];
300 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
301 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
302 const activeTabId =
303 current.activeTabId && sessions[current.activeTabId] ? current.activeTabId : snapshot.tabId;
304 const activeSnapshot = sessions[activeTabId] ?? snapshot;
305 return {
306 ...current,
307 sessions,
308 activeTabId,
309 snapshot: activeSnapshot,
310 desktopOverlay: current.desktopByTabId[activeTabId] ?? null,
311 recentlySeenUrls: rememberSnapshotUrl(current.recentlySeenUrls, snapshot),
312 };
313 });
314}
315
316/**
317 * Replace the local session index from an authoritative preview.list result.
318 * Missing tabs are removed while the current active tab is preserved whenever
319 * it still exists in the server result.
320 */
321export function reconcilePreviewServerSessions(
322 ref: ScopedThreadRef,
323 result: PreviewListResult,
324): void {
325 updateThreadPreviewState(ref, (current) => {
326 const sameServer = current.serverEpoch === result.serverEpoch;
327 if (sameServer && result.revision < current.serverRevision) return current;
328 const snapshots = result.sessions;
329 const sessions: Record<string, PreviewSessionSnapshot> = {};
330 const currentSuppressedTabIds = sameServer ? current.suppressedTabIds : new Set<string>();
331 let recentlySeenUrls = current.recentlySeenUrls;
332 for (const snapshot of snapshots) {
333 if (currentSuppressedTabIds.has(snapshot.tabId)) continue;
334 const existing = sameServer ? current.sessions[snapshot.tabId] : undefined;
335 const next = existing && existing.updatedAt > snapshot.updatedAt ? existing : snapshot;
336 sessions[next.tabId] = next;
337 recentlySeenUrls = rememberSnapshotUrl(recentlySeenUrls, next);
338 }
339
340 const fallback = latestSnapshot(sessions);
341 const activeTabId =
342 current.activeTabId && sessions[current.activeTabId]
343 ? current.activeTabId
344 : (fallback?.tabId ?? null);
345 const snapshot = activeTabId ? (sessions[activeTabId] ?? null) : null;
346 const desktopByTabId = sameServer
347 ? Object.fromEntries(
348 Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
349 )
350 : {};
351 const suppressedTabIds = new Set(
352 [...currentSuppressedTabIds].filter((tabId) =>
353 snapshots.some((snapshot) => snapshot.tabId === tabId),
354 ),
355 );
356 return {
357 ...current,
358 sessions,
359 suppressedTabIds,
360 activeTabId,
361 snapshot,
362 desktopByTabId,
363 desktopOverlay: activeTabId ? (desktopByTabId[activeTabId] ?? null) : null,
364 recentlySeenUrls,
365 serverEpoch: result.serverEpoch,
366 serverRevision: result.revision,
367 };
368 });
369}
370
371export function applyPreviewDesktopState(
372 ref: ScopedThreadRef,
373 tabId: string,
374 overlay: DesktopPreviewOverlay | null,
375): void {
376 updateThreadPreviewState(ref, (current) => {
377 const desktopByTabId = { ...current.desktopByTabId };
378 if (overlay) desktopByTabId[tabId] = overlay;
379 else delete desktopByTabId[tabId];
380 return {
381 ...current,
382 desktopByTabId,
383 desktopOverlay: current.activeTabId === tabId ? overlay : current.desktopOverlay,
384 };
385 });
386}
387
388export function beginPreviewSessionClose(ref: ScopedThreadRef, tabId: string): void {
389 updateThreadPreviewState(ref, (current) => {
390 const suppressedTabIds = new Set(current.suppressedTabIds);
391 suppressedTabIds.add(tabId);
392 return {
393 ...removeSession(current, tabId),
394 suppressedTabIds,
395 };
396 });
397}
398
399export function cancelPreviewSessionClose(
400 ref: ScopedThreadRef,
401 snapshot: PreviewSessionSnapshot | null,
402 tabId: string,
403): void {
404 updateThreadPreviewState(ref, (current) => {
405 if (!current.suppressedTabIds.has(tabId)) return current;
406 const suppressedTabIds = new Set(current.suppressedTabIds);
407 suppressedTabIds.delete(tabId);
408 if (!snapshot) {
409 return { ...current, suppressedTabIds };
410 }
411 const recentlySeenUrls =
412 snapshot.navStatus._tag !== "Idle"
413 ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
414 : current.recentlySeenUrls;
415 return {
416 ...current,
417 snapshot,
418 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
419 suppressedTabIds,
420 activeTabId: snapshot.tabId,
421 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
422 recentlySeenUrls,
423 };
424 });
425}
426
427export function setActivePreviewTab(ref: ScopedThreadRef, tabId: string): void {
428 updateThreadPreviewState(ref, (current) => {
429 const snapshot = current.sessions[tabId];
430 if (!snapshot || current.activeTabId === tabId) return current;
431 return {
432 ...current,
433 activeTabId: tabId,
434 snapshot,
435 desktopOverlay: current.desktopByTabId[tabId] ?? null,
436 };
437 });
438}
439
440export function rememberPreviewUrl(ref: ScopedThreadRef, url: string): void {
441 if (url.trim().length === 0) return;
442 updateThreadPreviewState(ref, (current) => ({
443 ...current,
444 recentlySeenUrls: dedupeRecentUrls(current.recentlySeenUrls, url),
445 }));
446}
447
448export function removePreviewThread(ref: ScopedThreadRef): void {
449 const threadKey = scopedThreadKey(ref);
450 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
451 syncActivePreviewThread(threadKey, EMPTY_THREAD_PREVIEW_STATE);
452 changedPreviewThreadKeys.delete(threadKey);
453}
454
455export function isPreviewSupportedInRuntime(): boolean {
456 if (typeof window === "undefined") return false;
457 return Boolean(window.desktopBridge?.preview);
458}
459
460export function resetPreviewStateForTests(): void {
461 for (const threadKey of changedPreviewThreadKeys) {
462 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
463 }
464 changedPreviewThreadKeys.clear();
465 appAtomRegistry.set(activePreviewThreadKeysAtom, { keys: new Set<string>() });
466}
467
468export const __testing = {
469 EMPTY_THREAD_PREVIEW_STATE,
470 RECENT_URL_LIMIT: PREVIEW_RECENT_URL_LIMIT,
471};