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

previewStateStore.ts

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