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

previewStateStore.ts

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