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