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