Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

previewStateStore.ts

484 lines16.7 KB

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;
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;
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>;
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 });
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);
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);
170​
171export function useActivePreviewSessions(): Record<string, ThreadPreviewState> {
172 return useAtomValue(activePreviewSessionsAtom);
174​
175export function readThreadPreviewState(ref: ScopedThreadRef): ThreadPreviewState {
176 return appAtomRegistry.get(previewStateAtom(scopedThreadKey(ref)));
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 },
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 });
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 });
276​
277/**
278 * Merge a server mutation without changing which tab the user is viewing.
279 *
280 * Commands such as resize can target background tabs. Their response is
281 * authoritative for that tab, but it is not a request to focus the tab.
282 */
283export function updatePreviewServerSnapshot(
284 ref: ScopedThreadRef,
285 snapshot: PreviewSessionSnapshot,
286): void {
287 updateThreadPreviewState(ref, (current) => {
288 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
289 const existing = current.sessions[snapshot.tabId];
290 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
291 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
292 const activeTabId =
293 current.activeTabId && sessions[current.activeTabId] ? current.activeTabId : snapshot.tabId;
294 const activeSnapshot = sessions[activeTabId] ?? snapshot;
295 return {
296 ...current,
297 sessions,
298 activeTabId,
299 snapshot: activeSnapshot,
300 desktopOverlay: current.desktopByTabId[activeTabId] ?? null,
301 recentlySeenUrls: rememberSnapshotUrl(current.recentlySeenUrls, snapshot),
302 };
303 });
305​
306/**
307 * Replace the local session index from an authoritative preview.list result.
308 * Missing tabs are removed while the current active tab is preserved whenever
309 * it still exists in the server result.
310 */
311export function reconcilePreviewServerSessions(
312 ref: ScopedThreadRef,
313 result: PreviewListResult,
314): void {
315 updateThreadPreviewState(ref, (current) => {
316 const sameServer = current.serverEpoch === result.serverEpoch;
317 if (sameServer && result.revision < current.serverRevision) {
318 return current;
319 }
320 const snapshots = result.sessions;
321 const sessions: Record<string, PreviewSessionSnapshot> = {};
322 const currentSuppressedTabIds = sameServer ? current.suppressedTabIds : new Set<string>();
323 let recentlySeenUrls = current.recentlySeenUrls;
324 for (const snapshot of snapshots) {
325 if (currentSuppressedTabIds.has(snapshot.tabId)) continue;
326 const existing = sameServer ? current.sessions[snapshot.tabId] : undefined;
327 const next = existing && existing.updatedAt > snapshot.updatedAt ? existing : snapshot;
328 sessions[next.tabId] = next;
329 recentlySeenUrls = rememberSnapshotUrl(recentlySeenUrls, next);
330 }
331​
332 const fallback = latestSnapshot(sessions);
333 const activeTabId =
334 current.activeTabId && sessions[current.activeTabId]
335 ? current.activeTabId
336 : (fallback?.tabId ?? null);
337 const snapshot = activeTabId ? (sessions[activeTabId] ?? null) : null;
338 const desktopByTabId = sameServer
339 ? Object.fromEntries(
340 Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
341 )
342 : {};
343 const suppressedTabIds = new Set(
344 [...currentSuppressedTabIds].filter((tabId) =>
345 snapshots.some((snapshot) => snapshot.tabId === tabId),
346 ),
347 );
348 return {
349 ...current,
350 sessions,
351 suppressedTabIds,
352 activeTabId,
353 snapshot,
354 desktopByTabId,
355 desktopOverlay: activeTabId ? (desktopByTabId[activeTabId] ?? null) : null,
356 recentlySeenUrls,
357 listLoaded: true,
358 serverEpoch: result.serverEpoch,
359 serverRevision: result.revision,
360 };
361 });
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 );
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 });
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 });
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 });
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 });
459​
460export function rememberPreviewUrl(ref: ScopedThreadRef, url: string): void {
461 if (url.trim().length === 0) return;
462 updateThreadPreviewState(ref, (current) => ({
463 ...current,
464 recentlySeenUrls: dedupeRecentUrls(current.recentlySeenUrls, url),
465 }));
467​
468export function isPreviewSupportedInRuntime(): boolean {
469 if (typeof window === "undefined") return false;
470 return Boolean(window.desktopBridge?.preview);
472​
473export function resetPreviewStateForTests(): void {
474 for (const threadKey of changedPreviewThreadKeys) {
475 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
476 }
477 changedPreviewThreadKeys.clear();
478 appAtomRegistry.set(activePreviewThreadKeysAtom, { keys: new Set<string>() });
480​
481export const __testing = {
482 EMPTY_THREAD_PREVIEW_STATE,
483 RECENT_URL_LIMIT: PREVIEW_RECENT_URL_LIMIT,
484};