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