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

previewStateStore.ts

561 lines19.5 KB

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