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