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

browserHistoryStore.test.ts

469 lines19.2 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import { scopeProjectRef } from "@t3tools/client-runtime/environment";
4import {
5 EnvironmentId,
6 type PreviewSessionSnapshot,
7 ProjectId,
8 ThreadId,
9} from "@t3tools/contracts";
10​
11const { readPreparedConnection, entities, settingsHydration } = vi.hoisted(() => ({
12 readPreparedConnection: vi.fn<() => { httpBaseUrl: string } | null>(() => null),
13 entities: {
14 projects: [] as Array<Record<string, unknown>>,
15 shellProjectId: null as string | null,
16 },
17 settingsHydration: {
18 hydrated: true,
19 finish: () => {},
20 promise: Promise.resolve(),
21 },
22}));
23​
24vi.mock("~/state/session", () => ({ readPreparedConnection }));
25vi.mock("~/state/entities", () => ({
26 readThreadShell: () => (entities.shellProjectId ? { projectId: entities.shellProjectId } : null),
27 readProject: (ref: { environmentId: string; projectId: string }) =>
28 entities.projects.find(
29 (project) => project.environmentId === ref.environmentId && project.id === ref.projectId,
30 ) ?? null,
31 readProjects: () => entities.projects,
32 useProjects: () => entities.projects,
33 useQuietThreadShell: () => null,
34}));
35vi.mock("./hooks/useSettings", async () => {
36 const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings");
37 return {
38 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
39 useClientSettings: () => DEFAULT_CLIENT_SETTINGS,
40 isClientSettingsHydrated: () => settingsHydration.hydrated,
41 ensureClientSettingsHydrated: () => settingsHydration.promise,
42 };
43});
44vi.mock("~/state/environments", () => ({
45 readPrimaryEnvironmentId: () => null,
46 usePrimaryEnvironmentId: () => null,
47}));
48​
49import { DraftId, useComposerDraftStore } from "./composerDraftStore";
50import {
51 BROWSER_HISTORY_MAX_PROJECTS,
52 type BrowserHistoryEntry,
53 mergeBrowserHistoryState,
54 migratePersistedBrowserHistoryState,
55 normalizeHistoryUrl,
56 recordVisitForThread,
57 resetBrowserHistoryForTests,
58 startPreviewTitleRecording,
59 upsertHistoryEntry,
60 useBrowserHistoryStore,
61} from "./browserHistoryStore";
62import { applyPreviewServerSnapshot, resetPreviewStateForTests } from "./previewStateStore";
63​
64function entry(overrides: Partial<BrowserHistoryEntry> = {}): BrowserHistoryEntry {
65 return { url: "http://localhost:3000/", lastVisitedAt: 1000, ...overrides };
67​
68beforeEach(() => {
69 readPreparedConnection.mockReturnValue(null);
70 entities.projects = [];
71 entities.shellProjectId = null;
72 settingsHydration.hydrated = true;
73 settingsHydration.promise = Promise.resolve();
74 useComposerDraftStore.setState({ draftThreadsByThreadKey: {} });
75});
76afterEach(() => vi.restoreAllMocks());
77​
78describe("normalizeHistoryUrl", () => {
79 it("normalizes bare loopback hosts to http and keeps path/query", () => {
80 expect(normalizeHistoryUrl("localhost:3000/admin?tab=1")).toBe(
81 "http://localhost:3000/admin?tab=1",
82 );
83 });
84​
85 it("preserves hash routes and strips credentials", () => {
86 expect(normalizeHistoryUrl("http://localhost:3000/app#/route")).toBe(
87 "http://localhost:3000/app#/route",
88 );
89 expect(normalizeHistoryUrl("https://user:secret@example.com/")).toBe("https://example.com/");
90 });
91​
92 it("rejects non-http(s), unparseable, and oversized urls", () => {
93 expect(normalizeHistoryUrl("ftp://example.com")).toBeNull();
94 expect(normalizeHistoryUrl("")).toBeNull();
95 expect(normalizeHistoryUrl(`http://localhost/${"a".repeat(2048)}`)).toBeNull();
96 });
97});
98​
99describe("upsertHistoryEntry", () => {
100 it("with insertOrdered, replaying an older visit for an existing entry keeps its newer timestamp", () => {
101 const existing = [entry({ url: "http://a.test/", lastVisitedAt: 2000 })];
102 const next = upsertHistoryEntry(existing, "http://a.test/", 1000, { insertOrdered: true });
103 expect(next).toEqual([{ url: "http://a.test/", lastVisitedAt: 2000 }]);
104 });
105});
106​
107describe("migratePersistedBrowserHistoryState", () => {
108 it("drops malformed state and invalid entries", () => {
109 expect(migratePersistedBrowserHistoryState(null)).toEqual({ byProjectKey: {} });
110 expect(migratePersistedBrowserHistoryState({ byProjectKey: 42 })).toEqual({ byProjectKey: {} });
111 const migrated = migratePersistedBrowserHistoryState({
112 byProjectKey: {
113 good: [
114 { url: "http://a.test/", lastVisitedAt: 100, title: "A" },
115 { url: "", lastVisitedAt: 100 },
116 { url: "ftp://ghost.test/", lastVisitedAt: 100 },
117 { url: "http://b.test/", lastVisitedAt: Number.NaN },
118 "junk",
119 ],
120 bad: "junk",
121 },
122 });
123 expect(migrated.byProjectKey["good"]).toEqual([
124 { url: "http://a.test/", lastVisitedAt: 100, title: "A" },
125 ]);
126 expect(migrated.byProjectKey["bad"]).toBeUndefined();
127 });
128​
129 it("restores MRU ordering, deduplicates normalized urls, and enforces project bounds", () => {
130 const byProjectKey = Object.fromEntries(
131 Array.from({ length: BROWSER_HISTORY_MAX_PROJECTS + 1 }, (_, index) => [
132 `project-${index}`,
133 [{ url: `http://project-${index}.test/`, lastVisitedAt: index }],
134 ]),
135 );
136 byProjectKey["project-1"] = [
137 { url: "a.test/", lastVisitedAt: 1 },
138 { url: "http://newer.test/", lastVisitedAt: 3 },
139 { url: "https://a.test/", lastVisitedAt: 2 },
140 ];
141​
142 const migrated = migratePersistedBrowserHistoryState({ byProjectKey });
143​
144 expect(Object.keys(migrated.byProjectKey)).toHaveLength(BROWSER_HISTORY_MAX_PROJECTS);
145 expect(migrated.byProjectKey["project-0"]).toBeUndefined();
146 expect(migrated.byProjectKey["project-1"]).toEqual([
147 { url: "http://newer.test/", lastVisitedAt: 3 },
148 { url: "https://a.test/", lastVisitedAt: 2 },
149 ]);
150 });
151});
152​
153const threadRef = {
154 environmentId: EnvironmentId.make("env-1"),
155 threadId: ThreadId.make("thread-1"),
156};
157​
158let settledAt = 0;
159​
160function settle(url: string, title: string, tabId = "tab_a", ref = threadRef): void {
161 settledAt += 1;
162 const snapshot: PreviewSessionSnapshot = {
163 threadId: ref.threadId,
164 tabId,
165 navStatus: { _tag: "Success", url, title },
166 canGoBack: false,
167 canGoForward: false,
168 updatedAt: new Date(settledAt).toISOString(),
169 };
170 applyPreviewServerSnapshot(ref, snapshot);
172​
173function resetStores(): () => void {
174 resetBrowserHistoryForTests();
175 resetPreviewStateForTests();
176 return startPreviewTitleRecording();
178​
179describe("useBrowserHistoryStore", () => {
180 beforeEach(resetStores);
181​
182 it("titles only pages already in history when they settle", () => {
183 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
184 settle("http://a.test/", "Should not create");
185 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
186 recordVisitForThread(threadRef, "http://a.test/#/settings", 1);
187 settle("http://a.test/#/settings", "My App");
188 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("My App");
189 });
190​
191 it("titles a visit recorded after its page already settled", () => {
192 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
193 recordVisitForThread(threadRef, "http://other.test/", 1);
194 settle("http://a.test/", "My App");
195 recordVisitForThread(threadRef, "http://a.test/", 2);
196 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
197 url: "http://a.test/",
198 title: "My App",
199 });
200 });
201​
202 it("keeps the newest title when another tab shows the same url", () => {
203 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
204 recordVisitForThread(threadRef, "http://a.test/", 1);
205 settle("http://a.test/", "Old", "tab_a");
206 settle("http://a.test/", "Old", "tab_b");
207 settle("http://a.test/", "New", "tab_a");
208 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("New");
209 });
210​
211 it("keeps another thread's newer title when an unrelated tab settles", () => {
212 const otherThreadRef = { ...threadRef, threadId: ThreadId.make("thread-2") };
213 const store = useBrowserHistoryStore.getState();
214 store.registerThreadProject(threadRef, "proj-a");
215 store.registerThreadProject(otherThreadRef, "proj-a");
216 recordVisitForThread(threadRef, "http://a.test/", 1);
217 settle("http://a.test/", "Old", "tab_a", threadRef);
218 settle("http://a.test/", "New", "tab_a", otherThreadRef);
219 settle("http://b.test/", "Unrelated", "tab_b", threadRef);
220 expect(
221 useBrowserHistoryStore
222 .getState()
223 .byProjectKey["proj-a"]?.find((e) => e.url === "http://a.test/")?.title,
224 ).toBe("New");
225 });
226​
227 it("keeps another thread's newer title when this thread records a different visit", () => {
228 const otherThreadRef = { ...threadRef, threadId: ThreadId.make("thread-2") };
229 const store = useBrowserHistoryStore.getState();
230 store.registerThreadProject(threadRef, "proj-a");
231 store.registerThreadProject(otherThreadRef, "proj-a");
232 recordVisitForThread(threadRef, "http://a.test/", 1);
233 settle("http://a.test/", "Old", "tab_a", threadRef);
234 settle("http://a.test/", "New", "tab_a", otherThreadRef);
235 recordVisitForThread(threadRef, "http://b.test/", 2);
236 expect(
237 useBrowserHistoryStore
238 .getState()
239 .byProjectKey["proj-a"]?.find((e) => e.url === "http://a.test/")?.title,
240 ).toBe("New");
241 });
242​
243 it("keeps another thread's newer title when this thread's unchanged tab is re-sent", () => {
244 const otherThreadRef = { ...threadRef, threadId: ThreadId.make("thread-2") };
245 const store = useBrowserHistoryStore.getState();
246 store.registerThreadProject(threadRef, "proj-a");
247 store.registerThreadProject(otherThreadRef, "proj-a");
248 recordVisitForThread(threadRef, "http://a.test/", 1);
249 settle("http://a.test/", "Old", "tab_a", threadRef);
250 settle("http://a.test/", "New", "tab_a", otherThreadRef);
251 // A resize or a list reconcile replaces the session without a new page load.
252 settle("http://a.test/", "Old", "tab_a", threadRef);
253 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("New");
254 });
255​
256 it("keeps another thread's newer title when this thread revisits the same url", () => {
257 const otherThreadRef = { ...threadRef, threadId: ThreadId.make("thread-2") };
258 const store = useBrowserHistoryStore.getState();
259 store.registerThreadProject(threadRef, "proj-a");
260 store.registerThreadProject(otherThreadRef, "proj-a");
261 recordVisitForThread(threadRef, "http://a.test/", 1);
262 settle("http://a.test/", "Old", "tab_a", threadRef);
263 settle("http://a.test/", "New", "tab_a", otherThreadRef);
264 recordVisitForThread(threadRef, "http://a.test/", 2);
265 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("New");
266 });
267​
268 it("sets a title against a settled url that differs from the stored one only by a trailing slash", () => {
269 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
270 recordVisitForThread(threadRef, "http://a.test/community", 1);
271 settle("http://a.test/community/", "Community");
272 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
273 url: "http://a.test/community",
274 title: "Community",
275 });
276​
277 useBrowserHistoryStore.setState({ byProjectKey: {} });
278 recordVisitForThread(threadRef, "http://a.test/community/", 1);
279 settle("http://a.test/community", "Community");
280 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
281 url: "http://a.test/community/",
282 title: "Community",
283 });
284 });
285​
286 it("matches a requested localhost URL to the resolved environment host", () => {
287 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
288 recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
289 readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.64.2:3773" });
290 settle("http://192.168.64.2:5173/app", "Local App");
291 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("Local App");
292 });
293​
294 it("deduplicates loopback aliases and the resolved environment host", () => {
295 readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.64.2:3773" });
296 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
297 recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
298 recordVisitForThread(threadRef, "http://127.0.0.1:5173/app", 2);
299 recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 3);
300 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
301 { url: "http://localhost:5173/app", lastVisitedAt: 3 },
302 ]);
303​
304 useBrowserHistoryStore.setState({ byProjectKey: {} });
305 recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 4);
306 recordVisitForThread(threadRef, "http://localhost:5173/app", 5);
307 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
308 { url: "http://localhost:5173/app", lastVisitedAt: 5 },
309 ]);
310 });
311});
312​
313const repoProject = {
314 environmentId: EnvironmentId.make("env-1"),
315 id: ProjectId.make("project-1"),
316 workspaceRoot: "/repo",
317 repositoryIdentity: null,
318 isScratch: false,
319};
320​
321describe("thread project resolution", () => {
322 beforeEach(resetStores);
323​
324 it("files a browser tab's visits and titles under the thread's project with no view registering it", () => {
325 entities.projects = [repoProject];
326 entities.shellProjectId = "project-1";
327​
328 recordVisitForThread(threadRef, "http://localhost:5173/", 1);
329 settle("http://localhost:5173/", "Dev App");
330​
331 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({
332 "env-1:/repo": [{ url: "http://localhost:5173/", lastVisitedAt: 1, title: "Dev App" }],
333 });
334 expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
335 });
336​
337 it("files a draft thread's visits under the draft's project", () => {
338 entities.projects = [repoProject];
339 const projectRef = scopeProjectRef(EnvironmentId.make("env-1"), ProjectId.make("project-1"));
340 useComposerDraftStore
341 .getState()
342 .setLogicalProjectDraftThreadId("env-1:/repo", projectRef, DraftId.make("draft-1"), {
343 threadId: threadRef.threadId,
344 });
345​
346 recordVisitForThread(threadRef, "http://localhost:5173/", 1);
347​
348 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({
349 "env-1:/repo": [{ url: "http://localhost:5173/", lastVisitedAt: 1 }],
350 });
351 expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
352 });
353​
354 it("waits for client settings before filing a thread under its project", async () => {
355 entities.projects = [repoProject];
356 entities.shellProjectId = "project-1";
357 settingsHydration.hydrated = false;
358 settingsHydration.promise = new Promise<void>((resolve) => {
359 settingsHydration.finish = () => {
360 settingsHydration.hydrated = true;
361 resolve();
362 };
363 });
364​
365 recordVisitForThread(threadRef, "http://localhost:5173/", 1);
366 expect(useBrowserHistoryStore.getState().projectKeyByThreadKey).toEqual({});
367​
368 settingsHydration.finish();
369 await settingsHydration.promise;
370 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({
371 "env-1:/repo": [{ url: "http://localhost:5173/", lastVisitedAt: 1 }],
372 });
373 expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
374 });
375​
376 it("lands visits queued before the thread's project loaded with the next visit", () => {
377 recordVisitForThread(threadRef, "http://a.test/", 1);
378 entities.projects = [repoProject];
379 entities.shellProjectId = "project-1";
380 recordVisitForThread(threadRef, "http://b.test/", 2);
381​
382 expect(
383 useBrowserHistoryStore.getState().byProjectKey["env-1:/repo"]?.map((entry) => entry.url),
384 ).toEqual(["http://b.test/", "http://a.test/"]);
385 });
386});
387​
388describe("pendingVisitsByThreadKey", () => {
389 beforeEach(resetStores);
390​
391 it("queues a visit recorded before registration and drains it in order on registration", () => {
392 recordVisitForThread(threadRef, "http://a.test/", 1);
393 recordVisitForThread(threadRef, "http://b.test/", 2);
394 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
395 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
396 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url)).toEqual([
397 "http://b.test/",
398 "http://a.test/",
399 ]);
400 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.lastVisitedAt).toBe(2);
401 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[1]?.lastVisitedAt).toBe(1);
402 expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
403 });
404​
405 it("slots a replayed visit by timestamp instead of hoisting it above a newer live visit", () => {
406 const otherThreadRef = {
407 environmentId: EnvironmentId.make("env-1"),
408 threadId: ThreadId.make("thread-2"),
409 };
410 useBrowserHistoryStore.getState().registerThreadProject(otherThreadRef, "proj-a");
411 recordVisitForThread(otherThreadRef, "http://newer.test/", 2000);
412 recordVisitForThread(threadRef, "http://older.test/", 1000);
413 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
414​
415 const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
416 expect(entries?.map((e) => e.url)).toEqual(["http://newer.test/", "http://older.test/"]);
417 expect(entries?.[0]?.lastVisitedAt).toBe(2000);
418 });
419});
420​
421describe("titles before registration", () => {
422 beforeEach(resetStores);
423​
424 it("applies a settled page's title once the matching visit drains", () => {
425 recordVisitForThread(threadRef, "http://a.test/", 1);
426 settle("http://a.test/", "My App");
427 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
428​
429 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
430​
431 const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
432 expect(entries?.[0]).toMatchObject({ url: "http://a.test/", title: "My App" });
433 });
434​
435 it("keeps another thread's title when a queued visit to the same url drains", () => {
436 const otherThreadRef = { ...threadRef, threadId: ThreadId.make("thread-2") };
437 recordVisitForThread(threadRef, "http://a.test/", 1);
438 settle("http://a.test/", "Old", "tab_a", threadRef);
439 useBrowserHistoryStore.getState().registerThreadProject(otherThreadRef, "proj-a");
440 recordVisitForThread(otherThreadRef, "http://a.test/", 2);
441 settle("http://a.test/", "New", "tab_a", otherThreadRef);
442​
443 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
444​
445 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("New");
446 });
447});
448​
449describe("mergeBrowserHistoryState", () => {
450 it("sanitizes same-version corrupt persisted data and preserves actions", () => {
451 const current = useBrowserHistoryStore.getState();
452 const merged = mergeBrowserHistoryState(
453 {
454 byProjectKey: {
455 a: [{ url: "ftp://bad.test/", lastVisitedAt: 1 }],
456 b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
457 },
458 projectKeyByThreadKey: { good: "b", stale: "a", malformed: 42 },
459 },
460 current,
461 );
462 expect(merged.byProjectKey).toEqual({
463 b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
464 });
465 expect(typeof merged.recordVisit).toBe("function");
466 expect(merged.projectKeyByThreadKey).toEqual({ good: "b" });
467 expect(merged.pendingVisitsByThreadKey).toEqual({});
468 });
469});