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

browserHistoryStore.test.ts

500 lines20.5 KB

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