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