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

previewStateStore.test.ts

620 lines19.1 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 type EnvironmentId,
4 type PreviewEvent,
5 type PreviewSessionSnapshot,
6 ThreadId,
7} from "@t3tools/contracts";
8import { beforeEach, describe, expect, it } from "vite-plus/test";
9​
10import {
11 __testing,
12 applyPreviewDesktopState,
13 applyPreviewServerEvent as applyPreviewServerEventImpl,
14 applyPreviewServerSnapshot,
15 beginPreviewSessionClose,
16 cancelPreviewSessionClose,
17 previewStateAtom,
18 readThreadPreviewState,
19 reconcilePreviewServerSessions,
20 rememberPreviewUrl,
21 removePreviewThread,
22 resetPreviewStateForTests,
23 subscribeThreadPreviewState,
24 setActivePreviewTab,
25 updatePreviewServerSnapshot,
26} from "./previewStateStore";
27​
28const environmentId = "env-1" as EnvironmentId;
29const ref = scopeThreadRef(environmentId, ThreadId.make("thread-1"));
30const otherRef = scopeThreadRef(environmentId, ThreadId.make("thread-2"));
31​
32const makeSnapshot = (overrides: Partial<PreviewSessionSnapshot> = {}): PreviewSessionSnapshot => ({
33 threadId: "thread-1",
34 tabId: "tab_a",
35 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
36 canGoBack: false,
37 canGoForward: false,
38 updatedAt: "2026-01-01T00:00:00.000Z",
39 ...overrides,
40});
41​
42type PreviewEventDraft = PreviewEvent extends infer Event
43 ? Event extends { readonly revision: number }
44 ? Omit<Event, "revision" | "serverEpoch">
45 : never
46 : never;
47​
48const serverEpoch = "server-a";
49let nextServerRevision = 0;
50const applyPreviewServerEvent = (eventRef: typeof ref, event: PreviewEventDraft): void => {
51 nextServerRevision += 1;
52 applyPreviewServerEventImpl(eventRef, {
53 ...event,
54 serverEpoch,
55 revision: nextServerRevision,
56 } as PreviewEvent);
57};
58​
59beforeEach(() => {
60 nextServerRevision = 0;
61 resetPreviewStateForTests();
62});
63​
64describe("previewStateStore (single-tab)", () => {
65 it("keeps independent state atoms for each thread", () => {
66 expect(previewStateAtom(scopedThreadKey(ref))).toBe(previewStateAtom(scopedThreadKey(ref)));
67 expect(previewStateAtom(scopedThreadKey(ref))).not.toBe(
68 previewStateAtom(scopedThreadKey(otherRef)),
69 );
70​
71 applyPreviewServerSnapshot(ref, makeSnapshot());
72 expect(readThreadPreviewState(ref).snapshot?.tabId).toBe("tab_a");
73 expect(readThreadPreviewState(otherRef)).toEqual(__testing.EMPTY_THREAD_PREVIEW_STATE);
74 });
75​
76 it("opened event seeds the snapshot and remembers the URL", () => {
77 const snapshot = makeSnapshot();
78 applyPreviewServerEvent(ref, {
79 type: "opened",
80 threadId: "thread-1",
81 tabId: snapshot.tabId,
82 createdAt: snapshot.updatedAt,
83 snapshot,
84 });
85 const state = readThreadPreviewState(ref);
86 expect(state.snapshot?.tabId).toBe(snapshot.tabId);
87 expect(state.recentlySeenUrls).toContain("http://localhost:5173/");
88 });
89​
90 it("a second `opened` for a different tab replaces the rendered snapshot", () => {
91 const a = makeSnapshot({ tabId: "tab_a" });
92 const b = makeSnapshot({ tabId: "tab_b" });
93 applyPreviewServerEvent(ref, {
94 type: "opened",
95 threadId: "thread-1",
96 tabId: a.tabId,
97 createdAt: a.updatedAt,
98 snapshot: a,
99 });
100 applyPreviewServerEvent(ref, {
101 type: "opened",
102 threadId: "thread-1",
103 tabId: b.tabId,
104 createdAt: b.updatedAt,
105 snapshot: b,
106 });
107 const state = readThreadPreviewState(ref);
108 expect(state.snapshot?.tabId).toBe(b.tabId);
109 });
110​
111 it("navigated event updates the snapshot URL", () => {
112 const snapshot = makeSnapshot();
113 applyPreviewServerEvent(ref, {
114 type: "opened",
115 threadId: "thread-1",
116 tabId: snapshot.tabId,
117 createdAt: snapshot.updatedAt,
118 snapshot,
119 });
120 applyPreviewServerEvent(ref, {
121 type: "navigated",
122 threadId: "thread-1",
123 tabId: snapshot.tabId,
124 createdAt: "2026-01-01T00:00:01.000Z",
125 snapshot: {
126 ...snapshot,
127 navStatus: { _tag: "Success", url: "http://localhost:5173/about", title: "About" },
128 },
129 });
130 const state = readThreadPreviewState(ref);
131 expect(state.snapshot?.navStatus._tag).toBe("Success");
132 if (state.snapshot?.navStatus._tag === "Success") {
133 expect(state.snapshot.navStatus.url).toBe("http://localhost:5173/about");
134 }
135 });
136​
137 it("resized event updates tab viewport without changing the active tab", () => {
138 const active = makeSnapshot({ tabId: "tab_a" });
139 const background = makeSnapshot({ tabId: "tab_b" });
140 applyPreviewServerSnapshot(ref, background);
141 applyPreviewServerSnapshot(ref, active);
142​
143 applyPreviewServerEvent(ref, {
144 type: "resized",
145 threadId: "thread-1",
146 tabId: background.tabId,
147 createdAt: "2026-01-01T00:00:01.000Z",
148 snapshot: {
149 ...background,
150 viewport: { _tag: "preset", presetId: "pixel-8", width: 412, height: 915 },
151 updatedAt: "2026-01-01T00:00:01.000Z",
152 },
153 });
154​
155 const state = readThreadPreviewState(ref);
156 expect(state.activeTabId).toBe(active.tabId);
157 expect(state.sessions[background.tabId]?.viewport).toEqual({
158 _tag: "preset",
159 presetId: "pixel-8",
160 width: 412,
161 height: 915,
162 });
163 });
164​
165 it("failed event flips the snapshot to LoadFailed when tabId matches", () => {
166 const snapshot = makeSnapshot();
167 applyPreviewServerEvent(ref, {
168 type: "opened",
169 threadId: "thread-1",
170 tabId: snapshot.tabId,
171 createdAt: snapshot.updatedAt,
172 snapshot,
173 });
174 applyPreviewServerEvent(ref, {
175 type: "failed",
176 threadId: "thread-1",
177 tabId: snapshot.tabId,
178 createdAt: "2026-01-01T00:00:01.000Z",
179 url: "http://localhost:5173/",
180 title: "",
181 code: -105,
182 description: "ERR_NAME_NOT_RESOLVED",
183 });
184 const state = readThreadPreviewState(ref);
185 expect(state.snapshot?.navStatus._tag).toBe("LoadFailed");
186 });
187​
188 it("failed event for a non-active tab is ignored", () => {
189 const snapshot = makeSnapshot({ tabId: "tab_a" });
190 applyPreviewServerEvent(ref, {
191 type: "opened",
192 threadId: "thread-1",
193 tabId: snapshot.tabId,
194 createdAt: snapshot.updatedAt,
195 snapshot,
196 });
197 applyPreviewServerEvent(ref, {
198 type: "failed",
199 threadId: "thread-1",
200 tabId: "tab_b",
201 createdAt: "2026-01-01T00:00:01.000Z",
202 url: "http://localhost:9999/",
203 title: "",
204 code: -105,
205 description: "ERR_NAME_NOT_RESOLVED",
206 });
207 const state = readThreadPreviewState(ref);
208 expect(state.snapshot?.navStatus._tag).toBe("Loading");
209 });
210​
211 it("closed event clears snapshot but retains recently-seen URLs", () => {
212 const snapshot = makeSnapshot();
213 applyPreviewServerEvent(ref, {
214 type: "opened",
215 threadId: "thread-1",
216 tabId: snapshot.tabId,
217 createdAt: snapshot.updatedAt,
218 snapshot,
219 });
220 applyPreviewServerEvent(ref, {
221 type: "closed",
222 threadId: "thread-1",
223 tabId: snapshot.tabId,
224 createdAt: "2026-01-01T00:00:01.000Z",
225 });
226 const state = readThreadPreviewState(ref);
227 expect(state.snapshot).toBeNull();
228 expect(state.recentlySeenUrls).toContain("http://localhost:5173/");
229 });
230​
231 it("optimistically removes a session before the server close event arrives", () => {
232 const first = makeSnapshot({ tabId: "tab_a" });
233 const second = makeSnapshot({
234 tabId: "tab_b",
235 updatedAt: "2026-01-01T00:00:01.000Z",
236 });
237 applyPreviewServerSnapshot(ref, first);
238 applyPreviewServerSnapshot(ref, second);
239​
240 beginPreviewSessionClose(ref, second.tabId);
241​
242 const state = readThreadPreviewState(ref);
243 expect(Object.keys(state.sessions)).toEqual([first.tabId]);
244 expect(state.activeTabId).toBe(first.tabId);
245 expect(state.snapshot?.tabId).toBe(first.tabId);
246 });
247​
248 it("treats a late server close event after optimistic removal as a no-op", () => {
249 const snapshot = makeSnapshot();
250 applyPreviewServerSnapshot(ref, snapshot);
251 beginPreviewSessionClose(ref, snapshot.tabId);
252​
253 applyPreviewServerEvent(ref, {
254 type: "closed",
255 threadId: "thread-1",
256 tabId: snapshot.tabId,
257 createdAt: "2026-01-01T00:00:01.000Z",
258 });
259​
260 const state = readThreadPreviewState(ref);
261 expect(state.sessions).toEqual({});
262 expect(state.snapshot).toBeNull();
263 });
264​
265 it("does not resurrect an intentionally closed tab from a stale list snapshot", () => {
266 const snapshot = makeSnapshot();
267 applyPreviewServerSnapshot(ref, snapshot);
268 beginPreviewSessionClose(ref, snapshot.tabId);
269​
270 applyPreviewServerSnapshot(ref, snapshot);
271​
272 const state = readThreadPreviewState(ref);
273 expect(state.sessions).toEqual({});
274 expect(state.snapshot).toBeNull();
275 });
276​
277 it("can restore a suppressed tab after a failed close", () => {
278 const snapshot = makeSnapshot();
279 applyPreviewServerSnapshot(ref, snapshot);
280 beginPreviewSessionClose(ref, snapshot.tabId);
281​
282 cancelPreviewSessionClose(ref, snapshot, snapshot.tabId);
283​
284 const state = readThreadPreviewState(ref);
285 expect(state.sessions).toEqual({ [snapshot.tabId]: snapshot });
286 expect(state.snapshot).toEqual(snapshot);
287 });
288​
289 it("closed event for a different tab is a no-op", () => {
290 const snapshot = makeSnapshot({ tabId: "tab_a" });
291 applyPreviewServerEvent(ref, {
292 type: "opened",
293 threadId: "thread-1",
294 tabId: snapshot.tabId,
295 createdAt: snapshot.updatedAt,
296 snapshot,
297 });
298 applyPreviewServerEvent(ref, {
299 type: "closed",
300 threadId: "thread-1",
301 tabId: "tab_b",
302 createdAt: "2026-01-01T00:00:01.000Z",
303 });
304 const state = readThreadPreviewState(ref);
305 expect(state.snapshot?.tabId).toBe(snapshot.tabId);
306 });
307​
308 it("desktopOverlay updates independently of snapshot", () => {
309 const snapshot = makeSnapshot();
310 applyPreviewServerEvent(ref, {
311 type: "opened",
312 threadId: "thread-1",
313 tabId: snapshot.tabId,
314 createdAt: snapshot.updatedAt,
315 snapshot,
316 });
317 applyPreviewDesktopState(ref, snapshot.tabId, {
318 hasWebContents: true,
319 canGoBack: true,
320 canGoForward: false,
321 loading: false,
322 zoomFactor: 1,
323 pictureInPicture: false,
324 colorScheme: "system",
325 audioMuted: false,
326 audible: false,
327 controller: "none",
328 favicon: null,
329 });
330 const state = readThreadPreviewState(ref);
331 expect(state.desktopOverlay?.canGoBack).toBe(true);
332 expect(state.snapshot?.canGoBack).toBe(false);
333 });
334​
335 it("does not publish duplicate desktop browser state", () => {
336 const snapshot = makeSnapshot();
337 applyPreviewServerSnapshot(ref, snapshot);
338 const overlay = {
339 hasWebContents: true,
340 canGoBack: true,
341 canGoForward: false,
342 loading: false,
343 zoomFactor: 1,
344 pictureInPicture: false,
345 colorScheme: "system" as const,
346 audioMuted: false,
347 audible: false,
348 controller: "none" as const,
349 favicon: {
350 dataUrl: "data:image/png;base64,AA==",
351 pageUrl: "https://example.com",
352 capturedAt: 1,
353 },
354 };
355 let updateCount = 0;
356 const unsubscribe = subscribeThreadPreviewState(ref, () => {
357 updateCount += 1;
358 });
359​
360 applyPreviewDesktopState(ref, snapshot.tabId, overlay);
361 applyPreviewDesktopState(ref, snapshot.tabId, { ...overlay, favicon: { ...overlay.favicon } });
362 unsubscribe();
363​
364 expect(updateCount).toBe(1);
365 });
366​
367 it("retains multiple tabs and switches active desktop state", () => {
368 const first = makeSnapshot();
369 const second = { ...makeSnapshot(), tabId: "tab_2", updatedAt: "2026-01-02T00:00:00.000Z" };
370 applyPreviewServerSnapshot(ref, first);
371 applyPreviewServerSnapshot(ref, second);
372 applyPreviewDesktopState(ref, first.tabId, {
373 hasWebContents: true,
374 canGoBack: true,
375 canGoForward: false,
376 loading: false,
377 zoomFactor: 1,
378 pictureInPicture: false,
379 colorScheme: "system",
380 audioMuted: false,
381 audible: false,
382 controller: "none",
383 favicon: null,
384 });
385 setActivePreviewTab(ref, first.tabId);
386​
387 const state = readThreadPreviewState(ref);
388 expect(Object.keys(state.sessions)).toEqual([first.tabId, second.tabId]);
389 expect(state.snapshot?.tabId).toBe(first.tabId);
390 expect(state.desktopOverlay?.canGoBack).toBe(true);
391 });
392​
393 it("updates a background snapshot without changing the active tab", () => {
394 const background = makeSnapshot({ tabId: "tab_a" });
395 const active = makeSnapshot({
396 tabId: "tab_b",
397 updatedAt: "2026-01-01T00:00:01.000Z",
398 });
399 applyPreviewServerSnapshot(ref, background);
400 applyPreviewServerSnapshot(ref, active);
401​
402 const resized = {
403 ...background,
404 viewport: { _tag: "freeform" as const, width: 900, height: 700 },
405 updatedAt: "2026-01-01T00:00:02.000Z",
406 };
407 updatePreviewServerSnapshot(ref, resized);
408​
409 const state = readThreadPreviewState(ref);
410 expect(state.activeTabId).toBe(active.tabId);
411 expect(state.snapshot?.tabId).toBe(active.tabId);
412 expect(state.sessions[background.tabId]).toEqual(resized);
413 });
414​
415 it("reconciles an authoritative session list without focusing a background tab", () => {
416 const active = makeSnapshot({ tabId: "tab_a" });
417 const stale = makeSnapshot({
418 tabId: "tab_stale",
419 updatedAt: "2026-01-01T00:00:01.000Z",
420 });
421 applyPreviewServerSnapshot(ref, stale);
422 applyPreviewServerSnapshot(ref, active);
423 applyPreviewDesktopState(ref, stale.tabId, {
424 hasWebContents: true,
425 canGoBack: false,
426 canGoForward: false,
427 loading: false,
428 zoomFactor: 1,
429 pictureInPicture: false,
430 colorScheme: "system",
431 audioMuted: false,
432 audible: false,
433 controller: "none",
434 favicon: null,
435 });
436​
437 reconcilePreviewServerSessions(ref, { sessions: [active], serverEpoch, revision: 1 });
438​
439 const state = readThreadPreviewState(ref);
440 expect(Object.keys(state.sessions)).toEqual([active.tabId]);
441 expect(state.activeTabId).toBe(active.tabId);
442 expect(state.snapshot).toEqual(active);
443 expect(state.desktopByTabId[stale.tabId]).toBeUndefined();
444 });
445​
446 it("clears stale sessions when an authoritative list is empty", () => {
447 applyPreviewServerSnapshot(ref, makeSnapshot());
448​
449 reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 1 });
450​
451 const state = readThreadPreviewState(ref);
452 expect(state.sessions).toEqual({});
453 expect(state.activeTabId).toBeNull();
454 expect(state.snapshot).toBeNull();
455 });
456​
457 it("ignores a list response older than the latest server event", () => {
458 const snapshot = makeSnapshot();
459 applyPreviewServerEvent(ref, {
460 type: "opened",
461 threadId: "thread-1",
462 tabId: snapshot.tabId,
463 createdAt: snapshot.updatedAt,
464 snapshot,
465 });
466​
467 reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 0 });
468​
469 expect(readThreadPreviewState(ref).sessions).toEqual({ [snapshot.tabId]: snapshot });
470 });
471​
472 it("does not resurrect a tab from an event older than its close", () => {
473 const snapshot = makeSnapshot();
474 applyPreviewServerEvent(ref, {
475 type: "opened",
476 threadId: "thread-1",
477 tabId: snapshot.tabId,
478 createdAt: snapshot.updatedAt,
479 snapshot,
480 });
481 applyPreviewServerEvent(ref, {
482 type: "closed",
483 threadId: "thread-1",
484 tabId: snapshot.tabId,
485 createdAt: "2026-01-01T00:00:01.000Z",
486 });
487​
488 applyPreviewServerEventImpl(ref, {
489 type: "opened",
490 threadId: "thread-1",
491 tabId: snapshot.tabId,
492 createdAt: snapshot.updatedAt,
493 serverEpoch,
494 revision: 1,
495 snapshot,
496 });
497​
498 expect(readThreadPreviewState(ref).sessions).toEqual({});
499 });
500​
501 it("accepts a lower revision from a newly restarted server", () => {
502 const snapshot = makeSnapshot();
503 applyPreviewServerEventImpl(ref, {
504 type: "opened",
505 threadId: "thread-1",
506 tabId: snapshot.tabId,
507 createdAt: snapshot.updatedAt,
508 serverEpoch,
509 revision: 12,
510 snapshot,
511 });
512​
513 reconcilePreviewServerSessions(ref, {
514 sessions: [],
515 serverEpoch: "server-b",
516 revision: 0,
517 });
518​
519 const state = readThreadPreviewState(ref);
520 expect(state.sessions).toEqual({});
521 expect(state.serverEpoch).toBe("server-b");
522 expect(state.serverRevision).toBe(0);
523 });
524​
525 it("does not carry raw-tab state across a server restart", () => {
526 const previous = makeSnapshot({
527 navStatus: { _tag: "Success", url: "https://old.example", title: "Old" },
528 updatedAt: "2026-01-01T00:00:02.000Z",
529 });
530 applyPreviewServerEventImpl(ref, {
531 type: "opened",
532 threadId: "thread-1",
533 tabId: previous.tabId,
534 createdAt: previous.updatedAt,
535 serverEpoch,
536 revision: 12,
537 snapshot: previous,
538 });
539 beginPreviewSessionClose(ref, previous.tabId);
540 applyPreviewDesktopState(ref, previous.tabId, {
541 hasWebContents: true,
542 canGoBack: false,
543 canGoForward: false,
544 loading: false,
545 zoomFactor: 1,
546 pictureInPicture: false,
547 colorScheme: "system",
548 audioMuted: false,
549 audible: false,
550 controller: "none",
551 favicon: null,
552 });
553 const restarted = makeSnapshot({
554 navStatus: { _tag: "Success", url: "https://new.example", title: "New" },
555 updatedAt: "2026-01-01T00:00:01.000Z",
556 });
557 reconcilePreviewServerSessions(ref, {
558 sessions: [restarted],
559 serverEpoch: "server-b",
560 revision: 0,
561 });
562​
563 const state = readThreadPreviewState(ref);
564 expect(state.sessions[restarted.tabId]).toEqual(restarted);
565 expect(state.suppressedTabIds).toEqual(new Set());
566 expect(state.desktopByTabId).toEqual({});
567 expect(state.desktopOverlay).toBeNull();
568 });
569​
570 it("applyServerSnapshot null clears snapshot for a thread that had one", () => {
571 const snapshot = makeSnapshot();
572 applyPreviewServerSnapshot(ref, snapshot);
573 applyPreviewServerSnapshot(ref, null);
574 const state = readThreadPreviewState(ref);
575 expect(state.snapshot).toBeNull();
576 });
577​
578 it("does not replace a streamed snapshot with older SWR data", () => {
579 applyPreviewServerSnapshot(
580 ref,
581 makeSnapshot({
582 navStatus: { _tag: "Success", url: "http://localhost:5173/new", title: "New" },
583 updatedAt: "2026-01-01T00:00:02.000Z",
584 }),
585 );
586 applyPreviewServerSnapshot(
587 ref,
588 makeSnapshot({
589 navStatus: { _tag: "Success", url: "http://localhost:5173/old", title: "Old" },
590 updatedAt: "2026-01-01T00:00:01.000Z",
591 }),
592 );
593​
594 const state = readThreadPreviewState(ref);
595 expect(state.snapshot?.navStatus).toEqual({
596 _tag: "Success",
597 url: "http://localhost:5173/new",
598 title: "New",
599 });
600 });
601​
602 it("rememberUrl dedupes and caps at limit", () => {
603 for (let i = 0; i < __testing.RECENT_URL_LIMIT + 5; i += 1) {
604 rememberPreviewUrl(ref, `http://localhost:${5000 + i}/`);
605 }
606 const state = readThreadPreviewState(ref);
607 expect(state.recentlySeenUrls.length).toBeLessThanOrEqual(__testing.RECENT_URL_LIMIT);
608 expect(state.recentlySeenUrls[0]).toBe(
609 `http://localhost:${5000 + __testing.RECENT_URL_LIMIT + 4}/`,
610 );
611 });
612​
613 it("removeThread strips the entry", () => {
614 const snapshot = makeSnapshot();
615 applyPreviewServerSnapshot(ref, snapshot);
616 removePreviewThread(ref);
617 const state = readThreadPreviewState(ref);
618 expect(state).toEqual(__testing.EMPTY_THREAD_PREVIEW_STATE);
619 });
620});