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 });
326 const state = readThreadPreviewState(ref);
327 expect(state.desktopOverlay?.canGoBack).toBe(true);
328 expect(state.snapshot?.canGoBack).toBe(false);
329 });
330
331 it("retains multiple tabs and switches active desktop state", () => {
332 const first = makeSnapshot();
333 const second = { ...makeSnapshot(), tabId: "tab_2", updatedAt: "2026-01-02T00:00:00.000Z" };
334 applyPreviewServerSnapshot(ref, first);
335 applyPreviewServerSnapshot(ref, second);
336 applyPreviewDesktopState(ref, first.tabId, {
337 hasWebContents: true,
338 canGoBack: true,
339 canGoForward: false,
340 loading: false,
341 zoomFactor: 1,
342 pictureInPicture: false,
343 colorScheme: "system",
344 controller: "none",
345 });
346 setActivePreviewTab(ref, first.tabId);
347
348 const state = readThreadPreviewState(ref);
349 expect(Object.keys(state.sessions)).toEqual([first.tabId, second.tabId]);
350 expect(state.snapshot?.tabId).toBe(first.tabId);
351 expect(state.desktopOverlay?.canGoBack).toBe(true);
352 });
353
354 it("updates a background snapshot without changing the active tab", () => {
355 const background = makeSnapshot({ tabId: "tab_a" });
356 const active = makeSnapshot({
357 tabId: "tab_b",
358 updatedAt: "2026-01-01T00:00:01.000Z",
359 });
360 applyPreviewServerSnapshot(ref, background);
361 applyPreviewServerSnapshot(ref, active);
362
363 const resized = {
364 ...background,
365 viewport: { _tag: "freeform" as const, width: 900, height: 700 },
366 updatedAt: "2026-01-01T00:00:02.000Z",
367 };
368 updatePreviewServerSnapshot(ref, resized);
369
370 const state = readThreadPreviewState(ref);
371 expect(state.activeTabId).toBe(active.tabId);
372 expect(state.snapshot?.tabId).toBe(active.tabId);
373 expect(state.sessions[background.tabId]).toEqual(resized);
374 });
375
376 it("reconciles an authoritative session list without focusing a background tab", () => {
377 const active = makeSnapshot({ tabId: "tab_a" });
378 const stale = makeSnapshot({
379 tabId: "tab_stale",
380 updatedAt: "2026-01-01T00:00:01.000Z",
381 });
382 applyPreviewServerSnapshot(ref, stale);
383 applyPreviewServerSnapshot(ref, active);
384 applyPreviewDesktopState(ref, stale.tabId, {
385 hasWebContents: true,
386 canGoBack: false,
387 canGoForward: false,
388 loading: false,
389 zoomFactor: 1,
390 pictureInPicture: false,
391 colorScheme: "system",
392 controller: "none",
393 });
394
395 reconcilePreviewServerSessions(ref, { sessions: [active], serverEpoch, revision: 1 });
396
397 const state = readThreadPreviewState(ref);
398 expect(Object.keys(state.sessions)).toEqual([active.tabId]);
399 expect(state.activeTabId).toBe(active.tabId);
400 expect(state.snapshot).toEqual(active);
401 expect(state.desktopByTabId[stale.tabId]).toBeUndefined();
402 });
403
404 it("clears stale sessions when an authoritative list is empty", () => {
405 applyPreviewServerSnapshot(ref, makeSnapshot());
406
407 reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 1 });
408
409 const state = readThreadPreviewState(ref);
410 expect(state.sessions).toEqual({});
411 expect(state.activeTabId).toBeNull();
412 expect(state.snapshot).toBeNull();
413 });
414
415 it("ignores a list response older than the latest server event", () => {
416 const snapshot = makeSnapshot();
417 applyPreviewServerEvent(ref, {
418 type: "opened",
419 threadId: "thread-1",
420 tabId: snapshot.tabId,
421 createdAt: snapshot.updatedAt,
422 snapshot,
423 });
424
425 reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 0 });
426
427 expect(readThreadPreviewState(ref).sessions).toEqual({ [snapshot.tabId]: snapshot });
428 });
429
430 it("does not resurrect a tab from an event older than its close", () => {
431 const snapshot = makeSnapshot();
432 applyPreviewServerEvent(ref, {
433 type: "opened",
434 threadId: "thread-1",
435 tabId: snapshot.tabId,
436 createdAt: snapshot.updatedAt,
437 snapshot,
438 });
439 applyPreviewServerEvent(ref, {
440 type: "closed",
441 threadId: "thread-1",
442 tabId: snapshot.tabId,
443 createdAt: "2026-01-01T00:00:01.000Z",
444 });
445
446 applyPreviewServerEventImpl(ref, {
447 type: "opened",
448 threadId: "thread-1",
449 tabId: snapshot.tabId,
450 createdAt: snapshot.updatedAt,
451 serverEpoch,
452 revision: 1,
453 snapshot,
454 });
455
456 expect(readThreadPreviewState(ref).sessions).toEqual({});
457 });
458
459 it("accepts a lower revision from a newly restarted server", () => {
460 const snapshot = makeSnapshot();
461 applyPreviewServerEventImpl(ref, {
462 type: "opened",
463 threadId: "thread-1",
464 tabId: snapshot.tabId,
465 createdAt: snapshot.updatedAt,
466 serverEpoch,
467 revision: 12,
468 snapshot,
469 });
470
471 reconcilePreviewServerSessions(ref, {
472 sessions: [],
473 serverEpoch: "server-b",
474 revision: 0,
475 });
476
477 const state = readThreadPreviewState(ref);
478 expect(state.sessions).toEqual({});
479 expect(state.serverEpoch).toBe("server-b");
480 expect(state.serverRevision).toBe(0);
481 });
482
483 it("does not carry raw-tab state across a server restart", () => {
484 const previous = makeSnapshot({
485 navStatus: { _tag: "Success", url: "https://old.example", title: "Old" },
486 updatedAt: "2026-01-01T00:00:02.000Z",
487 });
488 applyPreviewServerEventImpl(ref, {
489 type: "opened",
490 threadId: "thread-1",
491 tabId: previous.tabId,
492 createdAt: previous.updatedAt,
493 serverEpoch,
494 revision: 12,
495 snapshot: previous,
496 });
497 beginPreviewSessionClose(ref, previous.tabId);
498 applyPreviewDesktopState(ref, previous.tabId, {
499 hasWebContents: true,
500 canGoBack: false,
501 canGoForward: false,
502 loading: false,
503 zoomFactor: 1,
504 pictureInPicture: false,
505 colorScheme: "system",
506 controller: "none",
507 });
508 const restarted = makeSnapshot({
509 navStatus: { _tag: "Success", url: "https://new.example", title: "New" },
510 updatedAt: "2026-01-01T00:00:01.000Z",
511 });
512 reconcilePreviewServerSessions(ref, {
513 sessions: [restarted],
514 serverEpoch: "server-b",
515 revision: 0,
516 });
517
518 const state = readThreadPreviewState(ref);
519 expect(state.sessions[restarted.tabId]).toEqual(restarted);
520 expect(state.suppressedTabIds).toEqual(new Set());
521 expect(state.desktopByTabId).toEqual({});
522 expect(state.desktopOverlay).toBeNull();
523 });
524
525 it("applyServerSnapshot null clears snapshot for a thread that had one", () => {
526 const snapshot = makeSnapshot();
527 applyPreviewServerSnapshot(ref, snapshot);
528 applyPreviewServerSnapshot(ref, null);
529 const state = readThreadPreviewState(ref);
530 expect(state.snapshot).toBeNull();
531 });
532
533 it("does not replace a streamed snapshot with older SWR data", () => {
534 applyPreviewServerSnapshot(
535 ref,
536 makeSnapshot({
537 navStatus: { _tag: "Success", url: "http://localhost:5173/new", title: "New" },
538 updatedAt: "2026-01-01T00:00:02.000Z",
539 }),
540 );
541 applyPreviewServerSnapshot(
542 ref,
543 makeSnapshot({
544 navStatus: { _tag: "Success", url: "http://localhost:5173/old", title: "Old" },
545 updatedAt: "2026-01-01T00:00:01.000Z",
546 }),
547 );
548
549 const state = readThreadPreviewState(ref);
550 expect(state.snapshot?.navStatus).toEqual({
551 _tag: "Success",
552 url: "http://localhost:5173/new",
553 title: "New",
554 });
555 });
556
557 it("rememberUrl dedupes and caps at limit", () => {
558 for (let i = 0; i < __testing.RECENT_URL_LIMIT + 5; i += 1) {
559 rememberPreviewUrl(ref, `http://localhost:${5000 + i}/`);
560 }
561 const state = readThreadPreviewState(ref);
562 expect(state.recentlySeenUrls.length).toBeLessThanOrEqual(__testing.RECENT_URL_LIMIT);
563 expect(state.recentlySeenUrls[0]).toBe(
564 `http://localhost:${5000 + __testing.RECENT_URL_LIMIT + 4}/`,
565 );
566 });
567
568 it("removeThread strips the entry", () => {
569 const snapshot = makeSnapshot();
570 applyPreviewServerSnapshot(ref, snapshot);
571 removePreviewThread(ref);
572 const state = readThreadPreviewState(ref);
573 expect(state).toEqual(__testing.EMPTY_THREAD_PREVIEW_STATE);
574 });
575});