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