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

previewStateStore.ts

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