Open History to see the last commit
1import {
2 scopedProjectKey,
3 scopedThreadKey,
4 scopeProjectRef,
5} from "@t3tools/client-runtime/environment";
6import {
7 type EnvironmentId,
8 INCOGNITO_BROWSER_PROFILE_ID,
9 type PreviewSessionSnapshot,
10 type ScopedProjectRef,
11 type ScopedThreadRef,
12} from "@t3tools/contracts";
13import { create } from "zustand";
14import { useShallow } from "zustand/react/shallow";
15
16import { normalizePreviewUrl } from "@t3tools/shared/preview";
17import {
18 previewStateAtom,
19 previewThreadRefsAtom,
20 readThreadPreviewState,
21 type ThreadPreviewState,
22} from "~/previewStateStore";
23import { appAtomRegistry } from "~/rpc/atomRegistry";
24import {
25 readProject,
26 readProjects,
27 readThreadShell,
28 useProjects,
29 useQuietThreadShell,
30} from "~/state/entities";
31import { readPrimaryEnvironmentId, usePrimaryEnvironmentId } from "~/state/environments";
32import { readPreparedConnection } from "~/state/session";
33
34import { isLocalLoopbackHost, normalizeHostname } from "./browser/browserTargetResolver";
35import { useComposerDraftStore } from "./composerDraftStore";
36import {
37 ensureClientSettingsHydrated,
38 getClientSettings,
39 isClientSettingsHydrated,
40 useClientSettings,
41} from "./hooks/useSettings";
42import {
43 deriveLogicalProjectKeyFromSettings,
44 derivePhysicalProjectKey,
45 selectProjectGroupingSettings,
46 type ProjectGroupingSettings,
47} from "@t3tools/client-runtime/state/project-grouping";
48import { buildPhysicalToLogicalProjectKeyMap } from "./sidebarProjectGrouping";
49import type { Project } from "./types";
50
51export type BrowserHistoryEntry = { url: string; lastVisitedAt: number; title?: string };
52
53export const BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT = 50;
54export const BROWSER_HISTORY_MAX_PROJECTS = 20;
55const BROWSER_HISTORY_MAX_URL_LENGTH = 2048;
56const BROWSER_HISTORY_MAX_TITLE_LENGTH = 512;
57const MAX_VALID_DATE_MS = 8_640_000_000_000_000;
58
59export function isValidHistoryTimestamp(value: unknown): value is number {
60 return (
61 typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_VALID_DATE_MS
62 );
63}
64
65export function normalizeHistoryUrl(raw: string): string | null {
66 let parsed: URL;
67 try {
68 parsed = new URL(normalizePreviewUrl(raw));
69 } catch {
70 return null;
71 }
72 parsed.username = parsed.password = "";
73 return parsed.href.length > BROWSER_HISTORY_MAX_URL_LENGTH ? null : parsed.href;
74}
75
76function titleLookupKey(normalized: string, environmentHostname?: string | null): string {
77 const parsed = new URL(visitLookupKey(normalized, environmentHostname));
78 if (parsed.pathname !== "/" && parsed.pathname.endsWith("/"))
79 parsed.pathname = parsed.pathname.slice(0, -1);
80 return parsed.href;
81}
82
83function visitLookupKey(normalized: string, environmentHostname?: string | null): string {
84 const parsed = new URL(normalized);
85 const host = normalizeHostname(parsed.hostname);
86 const environmentHost = environmentHostname && normalizeHostname(environmentHostname);
87 if (isLocalLoopbackHost(host) || host === "0.0.0.0" || host === environmentHost)
88 parsed.hostname = "local";
89 return parsed.href;
90}
91
92function isStableLocalUrl(normalized: string): boolean {
93 const host = normalizeHostname(new URL(normalized).hostname);
94 return isLocalLoopbackHost(host) || host === "0.0.0.0";
95}
96
97export function upsertHistoryEntry(
98 entries: ReadonlyArray<BrowserHistoryEntry>,
99 url: string,
100 at: number,
101 options?: { insertOrdered?: boolean; environmentHostname?: string | null },
102): BrowserHistoryEntry[] {
103 const key = visitLookupKey(url, options?.environmentHostname);
104 const existing = entries.find(
105 (candidate) => visitLookupKey(candidate.url, options?.environmentHostname) === key,
106 );
107 const rest = entries.filter(
108 (candidate) => visitLookupKey(candidate.url, options?.environmentHostname) !== key,
109 );
110 const visitedAt =
111 options?.insertOrdered && existing && existing.lastVisitedAt > at ? existing.lastVisitedAt : at;
112 const storedUrl =
113 existing && (isStableLocalUrl(existing.url) || !isStableLocalUrl(url)) ? existing.url : url;
114 const entry: BrowserHistoryEntry = existing
115 ? { ...existing, url: storedUrl, lastVisitedAt: visitedAt }
116 : { url, lastVisitedAt: visitedAt };
117 if (!options?.insertOrdered)
118 return [entry, ...rest].slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
119 const index = rest.findIndex((candidate) => candidate.lastVisitedAt < entry.lastVisitedAt);
120 const next = index === -1 ? [...rest, entry] : rest.toSpliced(index, 0, entry);
121 return next.slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
122}
123
124function evictExcessProjects(
125 byProjectKey: Record<string, BrowserHistoryEntry[]>,
126): Record<string, BrowserHistoryEntry[]> {
127 const keys = Object.keys(byProjectKey);
128 if (keys.length <= BROWSER_HISTORY_MAX_PROJECTS) return byProjectKey;
129 const kept = keys
130 .toSorted(
131 (a, b) =>
132 (byProjectKey[b]?.[0]?.lastVisitedAt ?? 0) - (byProjectKey[a]?.[0]?.lastVisitedAt ?? 0),
133 )
134 .slice(0, BROWSER_HISTORY_MAX_PROJECTS);
135 return Object.fromEntries(kept.map((key) => [key, byProjectKey[key] ?? []]));
136}
137
138export function migratePersistedBrowserHistoryState(persistedState: unknown): {
139 byProjectKey: Record<string, BrowserHistoryEntry[]>;
140} {
141 if (!persistedState || typeof persistedState !== "object") return { byProjectKey: {} };
142 const raw = (persistedState as { byProjectKey?: unknown }).byProjectKey;
143 if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { byProjectKey: {} };
144 const byProjectKey: Record<string, BrowserHistoryEntry[]> = {};
145 for (const [projectKey, value] of Object.entries(raw as Record<string, unknown>)) {
146 if (!Array.isArray(value)) continue;
147 const seenUrls = new Set<string>();
148 const entries = value
149 .flatMap<BrowserHistoryEntry>((candidate) => {
150 if (!candidate || typeof candidate !== "object") return [];
151 const { url, lastVisitedAt, title } = candidate as Record<string, unknown>;
152 if (typeof url !== "string") return [];
153 const normalizedUrl = normalizeHistoryUrl(url);
154 if (!normalizedUrl) return [];
155 if (!isValidHistoryTimestamp(lastVisitedAt)) return [];
156 return [
157 {
158 url: normalizedUrl,
159 lastVisitedAt,
160 ...(typeof title === "string" && title.length > 0
161 ? { title: title.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH) }
162 : {}),
163 },
164 ];
165 })
166 .toSorted((a, b) => b.lastVisitedAt - a.lastVisitedAt)
167 .filter((entry) => {
168 const key = visitLookupKey(entry.url);
169 if (seenUrls.has(key)) return false;
170 seenUrls.add(key);
171 return true;
172 })
173 .slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
174 if (entries.length > 0) byProjectKey[projectKey] = entries;
175 }
176 return { byProjectKey: evictExcessProjects(byProjectKey) };
177}
178
179const BROWSER_HISTORY_STORAGE_KEY = "t3code:browser-history:v1";
180
181const MAX_PERSISTED_THREAD_MAPPINGS = 100;
182const PENDING_MAX_PER_THREAD = 10;
183const PENDING_MAX_THREADS = 20;
184
185type PendingVisit = { url: string; at: number; environmentHostname: string | null };
186
187interface BrowserHistoryStoreState {
188 byProjectKey: Record<string, BrowserHistoryEntry[]>;
189 projectKeyByThreadKey: Record<string, string>;
190 pendingVisitsByThreadKey: Record<string, PendingVisit[]>;
191 recordVisit: (
192 projectKey: string,
193 url: string,
194 at: number,
195 options?: { insertOrdered?: boolean; environmentHostname?: string | null },
196 ) => void;
197 setTitleForUrl: (
198 projectKey: string,
199 url: string,
200 title: string,
201 options?: { environmentHostname?: string | null; onlyIfUntitled?: boolean },
202 ) => void;
203 removeUrl: (projectKey: string, url: string) => void;
204 registerThreadProject: (ref: ScopedThreadRef, projectKey: string) => void;
205}
206
207function addPendingByThread<T>(
208 pendingByThreadKey: Record<string, T[]>,
209 threadKey: string,
210 item: T,
211): Record<string, T[]> {
212 const existing = pendingByThreadKey[threadKey] ?? [];
213 const next = { ...pendingByThreadKey };
214 next[threadKey] = [...existing, item].slice(-PENDING_MAX_PER_THREAD);
215 const keys = Object.keys(next);
216 if (keys.length > PENDING_MAX_THREADS) {
217 const oldestKey = keys[0];
218 if (oldestKey !== undefined && oldestKey !== threadKey) delete next[oldestKey];
219 }
220 return next;
221}
222
223type PersistedBrowserHistory = Pick<
224 BrowserHistoryStoreState,
225 "byProjectKey" | "projectKeyByThreadKey"
226>;
227
228type UpdateHistory = (state: PersistedBrowserHistory) => PersistedBrowserHistory;
229
230function boundThreadMappings(
231 previous: PersistedBrowserHistory,
232 next: PersistedBrowserHistory,
233): PersistedBrowserHistory {
234 return {
235 ...next,
236 projectKeyByThreadKey: Object.fromEntries(
237 Object.entries(next.projectKeyByThreadKey)
238 // Keep new registrations for empty projects, but drop projects that lost their history.
239 .filter(
240 ([, projectKey]) =>
241 !Object.hasOwn(previous.byProjectKey, projectKey) ||
242 Object.hasOwn(next.byProjectKey, projectKey),
243 )
244 .slice(-MAX_PERSISTED_THREAD_MAPPINGS),
245 ),
246 };
247}
248
249const HISTORY_OBJECT_STORE = "history";
250const EMPTY_PERSISTED_HISTORY: PersistedBrowserHistory = {
251 byProjectKey: {},
252 projectKeyByThreadKey: {},
253};
254let historyDatabase: Promise<IDBDatabase> | undefined;
255let historyChannel: BroadcastChannel | undefined;
256
257function readLegacyHistory<Missing = PersistedBrowserHistory>(
258 missing: Missing = EMPTY_PERSISTED_HISTORY as Missing,
259): PersistedBrowserHistory | Missing {
260 try {
261 const value = window.localStorage.getItem(BROWSER_HISTORY_STORAGE_KEY);
262 if (value === null) return missing;
263 const parsed: { state?: unknown } | null = JSON.parse(value);
264 return {
265 ...migratePersistedBrowserHistoryState(parsed?.state),
266 projectKeyByThreadKey: migratePersistedThreadProjectKeys(parsed?.state),
267 };
268 } catch {
269 return EMPTY_PERSISTED_HISTORY;
270 }
271}
272
273function retireLegacyHistory(): void {
274 try {
275 window.localStorage.removeItem(BROWSER_HISTORY_STORAGE_KEY);
276 } catch {
277 // The browser can deny access to localStorage independently of IndexedDB.
278 }
279}
280
281// localStorage can gain visits after migration: from the fallback below, or a tab on an older build.
282function mergeLegacyHistory(
283 saved: PersistedBrowserHistory,
284 legacy: PersistedBrowserHistory,
285): PersistedBrowserHistory {
286 const byProjectKey = { ...saved.byProjectKey };
287 for (const [projectKey, entries] of Object.entries(legacy.byProjectKey))
288 byProjectKey[projectKey] = [...(byProjectKey[projectKey] ?? []), ...entries];
289 return {
290 ...migratePersistedBrowserHistoryState({ byProjectKey }),
291 projectKeyByThreadKey: { ...legacy.projectKeyByThreadKey, ...saved.projectKeyByThreadKey },
292 };
293}
294
295// Without IndexedDB, merge into the freshest localStorage snapshot so a reload keeps new visits.
296function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) {
297 const previous = readLegacyHistory(current);
298 const next = update(previous);
299 if (next === previous) return previous;
300 const history = boundThreadMappings(previous, next);
301 try {
302 window.localStorage.setItem(
303 BROWSER_HISTORY_STORAGE_KEY,
304 JSON.stringify({ state: history, version: 1 }),
305 );
306 } catch {
307 // History stays in memory when the browser denies both storage APIs.
308 }
309 return history;
310}
311
312function invalidateHistoryDatabase(opening: Promise<IDBDatabase>): void {
313 if (historyDatabase === opening) historyDatabase = undefined;
314}
315
316function openHistoryDatabase() {
317 if (historyDatabase) return historyDatabase;
318 const opening = new Promise<IDBDatabase>((resolve, reject) => {
319 const request = indexedDB.open(BROWSER_HISTORY_STORAGE_KEY, 1);
320 request.onupgradeneeded = () => request.result.createObjectStore(HISTORY_OBJECT_STORE);
321 request.onsuccess = () => {
322 const db = request.result;
323 db.onclose = () => invalidateHistoryDatabase(opening);
324 db.onversionchange = () => {
325 invalidateHistoryDatabase(opening);
326 db.close();
327 };
328 resolve(db);
329 };
330 request.onerror = () => reject(request.error);
331 });
332 historyDatabase = opening;
333 void opening.catch(() => invalidateHistoryDatabase(opening));
334 return opening;
335}
336
337async function transactIndexedHistory(update?: UpdateHistory, retry = true) {
338 const opening = openHistoryDatabase();
339 const db = await opening;
340 let transaction: IDBTransaction;
341 try {
342 transaction = db.transaction(HISTORY_OBJECT_STORE, update ? "readwrite" : "readonly");
343 } catch (error) {
344 if (error instanceof DOMException && error.name === "InvalidStateError") {
345 invalidateHistoryDatabase(opening);
346 if (retry) return transactIndexedHistory(update, false);
347 }
348 throw error;
349 }
350
351 return new Promise<{ history: PersistedBrowserHistory; changed: boolean }>((resolve, reject) => {
352 const store = transaction.objectStore(HISTORY_OBJECT_STORE);
353 const request = store.get(BROWSER_HISTORY_STORAGE_KEY);
354 let history: PersistedBrowserHistory;
355 let changed = false;
356 request.onsuccess = () => {
357 const saved = request.result as PersistedBrowserHistory | undefined;
358 const legacy = update ? readLegacyHistory(null) : null;
359 const previous =
360 saved && legacy
361 ? mergeLegacyHistory(saved, legacy)
362 : (saved ?? legacy ?? EMPTY_PERSISTED_HISTORY);
363 const next = update?.(previous) ?? previous;
364 history = next === previous ? previous : boundThreadMappings(previous, next);
365 changed = history !== saved;
366 if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY);
367 };
368 transaction.oncomplete = () => {
369 // Keep the migration source until the IndexedDB snapshot has committed.
370 if (update) retireLegacyHistory();
371 resolve({ history, changed });
372 };
373 transaction.onabort = () => reject(transaction.error);
374 });
375}
376
377export const useBrowserHistoryStore = create<BrowserHistoryStoreState>()((set, get) => {
378 const publish = ({ byProjectKey }: PersistedBrowserHistory) => {
379 if (byProjectKey !== get().byProjectKey) set({ byProjectKey });
380 };
381 const updateHistory = (update: UpdateHistory) => {
382 if (typeof window === "undefined") {
383 publish(update(get()));
384 return;
385 }
386 void transactIndexedHistory(update).then(
387 ({ history, changed }) => {
388 publish(history);
389 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin
390 if (changed) historyChannel?.postMessage(null);
391 },
392 () => {
393 const { byProjectKey, projectKeyByThreadKey } = get();
394 publish(transactLegacyHistory(update, { byProjectKey, projectKeyByThreadKey }));
395 },
396 );
397 };
398
399 return mergeBrowserHistoryState(undefined, {
400 byProjectKey: {},
401 projectKeyByThreadKey: {},
402 pendingVisitsByThreadKey: {},
403 recordVisit: (projectKey, url, at, options) => {
404 const normalized = normalizeHistoryUrl(url);
405 if (!normalized) return;
406 updateHistory((state) => {
407 const entries = state.byProjectKey[projectKey] ?? [];
408 return {
409 ...state,
410 byProjectKey: evictExcessProjects({
411 ...state.byProjectKey,
412 [projectKey]: upsertHistoryEntry(entries, normalized, at, {
413 ...options,
414 insertOrdered: options?.insertOrdered || (entries[0]?.lastVisitedAt ?? at) > at,
415 }),
416 }),
417 };
418 });
419 },
420 setTitleForUrl: (projectKey, url, title, options) => {
421 const normalized = normalizeHistoryUrl(url);
422 const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH);
423 if (!normalized || trimmed.length === 0) return;
424 const key = titleLookupKey(normalized, options?.environmentHostname);
425 updateHistory((state) => {
426 const entries = state.byProjectKey[projectKey];
427 const index =
428 entries?.findIndex(
429 (candidate) => titleLookupKey(candidate.url, options?.environmentHostname) === key,
430 ) ?? -1;
431 const entry = entries?.[index];
432 if (
433 !entries ||
434 !entry ||
435 entry.title === trimmed ||
436 (entry.title && options?.onlyIfUntitled)
437 )
438 return state;
439 return {
440 ...state,
441 byProjectKey: {
442 ...state.byProjectKey,
443 [projectKey]: entries.with(index, { ...entry, title: trimmed }),
444 },
445 };
446 });
447 },
448 removeUrl: (projectKey, url) => {
449 const normalized = normalizeHistoryUrl(url);
450 if (!normalized) return;
451 updateHistory((state) => {
452 const entries = state.byProjectKey[projectKey];
453 if (!entries) return state;
454 const next = entries.filter((candidate) => candidate.url !== normalized);
455 if (next.length === entries.length) return state;
456 const byProjectKey = { ...state.byProjectKey };
457 if (next.length === 0) delete byProjectKey[projectKey];
458 else byProjectKey[projectKey] = next;
459 return { ...state, byProjectKey };
460 });
461 },
462 registerThreadProject: (ref, projectKey) => {
463 const threadKey = scopedThreadKey(ref);
464 const state = get();
465 const pendingVisits = state.pendingVisitsByThreadKey[threadKey];
466 if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return;
467 const nextPendingVisits = { ...state.pendingVisitsByThreadKey };
468 delete nextPendingVisits[threadKey];
469 set({
470 projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey },
471 pendingVisitsByThreadKey: nextPendingVisits,
472 });
473 updateHistory((shared) =>
474 shared.projectKeyByThreadKey[threadKey] === projectKey
475 ? shared
476 : {
477 ...shared,
478 projectKeyByThreadKey: { ...shared.projectKeyByThreadKey, [threadKey]: projectKey },
479 },
480 );
481 for (const visit of pendingVisits ?? [])
482 get().recordVisit(projectKey, visit.url, visit.at, {
483 insertOrdered: true,
484 environmentHostname: visit.environmentHostname,
485 });
486 if (pendingVisits)
487 recordPreviewTitles(ref, readThreadPreviewState(ref), {
488 urls: pendingVisits.map((visit) => visit.url),
489 });
490 },
491 });
492});
493
494if (typeof window !== "undefined") {
495 try {
496 historyChannel = new BroadcastChannel(BROWSER_HISTORY_STORAGE_KEY);
497 } catch {
498 // History still persists when the browser cannot send change notifications.
499 }
500 if (historyChannel) {
501 historyChannel.onmessage = () => {
502 void transactIndexedHistory().then(
503 ({ history }) => useBrowserHistoryStore.setState({ byProjectKey: history.byProjectKey }),
504 () => undefined,
505 );
506 };
507 }
508 const hydrate = (history: PersistedBrowserHistory) => {
509 useBrowserHistoryStore.setState((state) => ({
510 byProjectKey: history.byProjectKey,
511 projectKeyByThreadKey: {
512 ...migratePersistedThreadProjectKeys(history, history.byProjectKey),
513 ...state.projectKeyByThreadKey,
514 },
515 }));
516 };
517 void transactIndexedHistory((history) => history).then(
518 ({ history }) => hydrate(history),
519 () => hydrate(readLegacyHistory()),
520 );
521 import.meta.hot?.dispose(() => {
522 historyChannel?.close();
523 historyChannel = undefined;
524 void historyDatabase?.then(
525 (db) => db.close(),
526 () => undefined,
527 );
528 });
529}
530
531export function mergeBrowserHistoryState(
532 persistedState: unknown,
533 currentState: BrowserHistoryStoreState,
534): BrowserHistoryStoreState {
535 const migrated = migratePersistedBrowserHistoryState(persistedState);
536 return {
537 ...currentState,
538 ...migrated,
539 projectKeyByThreadKey: migratePersistedThreadProjectKeys(persistedState, migrated.byProjectKey),
540 pendingVisitsByThreadKey: {},
541 };
542}
543
544function migratePersistedThreadProjectKeys(
545 persistedState: unknown,
546 byProjectKey?: Record<string, BrowserHistoryEntry[]>,
547): Record<string, string> {
548 if (!persistedState || typeof persistedState !== "object") return {};
549 const raw = (persistedState as { projectKeyByThreadKey?: unknown }).projectKeyByThreadKey;
550 if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
551 const entries = Object.entries(raw as Record<string, unknown>).filter(
552 (entry): entry is [string, string] =>
553 typeof entry[1] === "string" && (!byProjectKey || Object.hasOwn(byProjectKey, entry[1])),
554 );
555 return Object.fromEntries(entries.slice(-MAX_PERSISTED_THREAD_MAPPINGS));
556}
557
558/**
559 * History follows the sidebar's project rows, so a duplicate row shares the
560 * history of the group it is listed under rather than keying by its own path.
561 */
562function deriveHistoryProjectKey(
563 project: Project,
564 projects: ReadonlyArray<Project>,
565 settings: ProjectGroupingSettings,
566 primaryEnvironmentId: EnvironmentId | null,
567): string {
568 return (
569 buildPhysicalToLogicalProjectKeyMap({ projects, settings, primaryEnvironmentId }).get(
570 derivePhysicalProjectKey(project),
571 ) ?? deriveLogicalProjectKeyFromSettings(project, settings)
572 );
573}
574
575/** Server threads name their project in the shell; drafts in the composer draft store. */
576function readThreadProjectRef(ref: ScopedThreadRef): ScopedProjectRef | null {
577 const projectId = readThreadShell(ref)?.projectId;
578 if (projectId) return scopeProjectRef(ref.environmentId, projectId);
579 const draft = useComposerDraftStore.getState().getDraftSessionByRef(ref);
580 return draft ? scopeProjectRef(draft.environmentId, draft.projectId) : null;
581}
582
583/**
584 * Registers the thread under its current project so queued visits and titles
585 * land. Until the project loads, or client settings hydrate (the grouping is
586 * unknown before then), the last registration stands and writes stay queued.
587 */
588function resolveThreadProjectKey(ref: ScopedThreadRef): string | undefined {
589 const state = useBrowserHistoryStore.getState();
590 const registered = state.projectKeyByThreadKey[scopedThreadKey(ref)];
591 if (!isClientSettingsHydrated()) {
592 void ensureClientSettingsHydrated().then(
593 () => resolveThreadProjectKey(ref),
594 () => undefined,
595 );
596 return registered;
597 }
598 const projectRef = readThreadProjectRef(ref);
599 const project = projectRef ? readProject(projectRef) : null;
600 if (!project) return registered;
601 const projectKey = deriveHistoryProjectKey(
602 project,
603 readProjects(),
604 selectProjectGroupingSettings(getClientSettings()),
605 readPrimaryEnvironmentId(),
606 );
607 state.registerThreadProject(ref, projectKey);
608 return projectKey;
609}
610
611export function recordVisitForThread(ref: ScopedThreadRef, url: string, at?: number): void {
612 const threadKey = scopedThreadKey(ref);
613 const projectKey = resolveThreadProjectKey(ref);
614 const state = useBrowserHistoryStore.getState();
615 const visitAt = at ?? Date.now();
616 const connection = readPreparedConnection(ref.environmentId);
617 const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null;
618 if (!projectKey) {
619 useBrowserHistoryStore.setState({
620 pendingVisitsByThreadKey: addPendingByThread(state.pendingVisitsByThreadKey, threadKey, {
621 url,
622 at: visitAt,
623 environmentHostname,
624 }),
625 });
626 return;
627 }
628 state.recordVisit(projectKey, url, visitAt, { environmentHostname });
629 // A page can settle before the address bar records its visit.
630 recordPreviewTitles(ref, readThreadPreviewState(ref), { urls: [url] });
631}
632
633/**
634 * History is shared across a project's threads and settled sessions are retained,
635 * so replaying an old settle would clobber another thread's newer title. Visits
636 * only fill untitled entries; settles apply only pages that loaded or retitled.
637 */
638function recordPreviewTitles(
639 ref: ScopedThreadRef,
640 preview: ThreadPreviewState,
641 only:
642 | { readonly urls: ReadonlyArray<string> }
643 | { readonly changedSince: ThreadPreviewState["sessions"] },
644): void {
645 const state = useBrowserHistoryStore.getState();
646 const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
647 if (!projectKey) return;
648 const connection = readPreparedConnection(ref.environmentId);
649 const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null;
650 const titleKey = (url: string) => {
651 const normalized = normalizeHistoryUrl(url);
652 return normalized ? titleLookupKey(normalized, environmentHostname) : null;
653 };
654 const visitKeys = "urls" in only ? new Set(only.urls.map(titleKey)) : null;
655 // Resizes and list reconciles replace a session without loading a new page.
656 const settledAgain = (session: PreviewSessionSnapshot, previous?: PreviewSessionSnapshot) =>
657 previous?.navStatus._tag === "Success" &&
658 session.navStatus._tag === "Success" &&
659 previous.navStatus.url === session.navStatus.url &&
660 previous.navStatus.title === session.navStatus.title;
661 const include = (session: PreviewSessionSnapshot, url: string) =>
662 "changedSince" in only
663 ? !settledAgain(session, only.changedSince[session.tabId])
664 : (visitKeys?.has(titleKey(url)) ?? false);
665 // A fill uses the newest eligible title first because it only sets an untitled entry.
666 const sessions = Object.values(preview.sessions).toSorted((a, b) =>
667 "urls" in only
668 ? b.updatedAt.localeCompare(a.updatedAt)
669 : a.updatedAt.localeCompare(b.updatedAt),
670 );
671 for (const session of sessions) {
672 const status = session.navStatus;
673 if (session.profileId === INCOGNITO_BROWSER_PROFILE_ID) continue;
674 if (status._tag !== "Success" || !status.title || !include(session, status.url)) continue;
675 state.setTitleForUrl(projectKey, status.url, status.title, {
676 environmentHostname,
677 onlyIfUntitled: "urls" in only,
678 });
679 }
680}
681
682/** Records settled page titles for every thread with previews, for the life of the page. */
683export function startPreviewTitleRecording(): () => void {
684 const followed = new Map<string, () => void>();
685 const followNewThreads = (refs: ReadonlyMap<string, ScopedThreadRef>) => {
686 for (const [threadKey, threadRef] of refs) {
687 if (followed.has(threadKey)) continue;
688 const atom = previewStateAtom(threadKey);
689 let previousSessions = appAtomRegistry.get(atom).sessions;
690 followed.set(
691 threadKey,
692 appAtomRegistry.subscribe(atom, (next) => {
693 if (next.sessions === previousSessions) return;
694 const changedSince = previousSessions;
695 previousSessions = next.sessions;
696 recordPreviewTitles(threadRef, next, { changedSince });
697 }),
698 );
699 }
700 };
701 const stopIndex = appAtomRegistry.subscribe(previewThreadRefsAtom, followNewThreads, {
702 immediate: true,
703 });
704 return () => {
705 stopIndex();
706 for (const stop of followed.values()) stop();
707 };
708}
709
710export function removeUrlForThread(ref: ScopedThreadRef, url: string): void {
711 const projectKey = resolveThreadProjectKey(ref);
712 if (!projectKey) return;
713 useBrowserHistoryStore.getState().removeUrl(projectKey, url);
714}
715
716const EMPTY_HISTORY: ReadonlyArray<BrowserHistoryEntry> = [];
717
718function useThreadHistoryProjectKey(ref: ScopedThreadRef): string | null {
719 const threadKey = scopedThreadKey(ref);
720 const shellProjectId = useQuietThreadShell(ref)?.projectId ?? null;
721 const draftProjectKey = useComposerDraftStore((state) => {
722 const draft = state.getDraftSessionByRef(ref);
723 return draft ? scopedProjectKey(scopeProjectRef(draft.environmentId, draft.projectId)) : null;
724 });
725 const projectKey = shellProjectId
726 ? scopedProjectKey(scopeProjectRef(ref.environmentId, shellProjectId))
727 : draftProjectKey;
728 const projects = useProjects();
729 const settings = useClientSettings(selectProjectGroupingSettings);
730 const primaryEnvironmentId = usePrimaryEnvironmentId();
731 const registered = useBrowserHistoryStore(
732 (state) => state.projectKeyByThreadKey[threadKey] ?? null,
733 );
734 const project = projects.find(
735 (candidate) =>
736 scopedProjectKey(scopeProjectRef(candidate.environmentId, candidate.id)) === projectKey,
737 );
738 return project
739 ? deriveHistoryProjectKey(project, projects, settings, primaryEnvironmentId)
740 : registered;
741}
742
743export function useThreadRecentHistory(
744 ref: ScopedThreadRef,
745 limit: number,
746): ReadonlyArray<BrowserHistoryEntry> {
747 const projectKey = useThreadHistoryProjectKey(ref);
748 return useBrowserHistoryStore(
749 useShallow((state) => {
750 const entries = projectKey ? state.byProjectKey[projectKey] : undefined;
751 return entries && entries.length > 0 ? entries.slice(0, limit) : EMPTY_HISTORY;
752 }),
753 );
754}
755
756export function resetBrowserHistoryForTests(): void {
757 useBrowserHistoryStore.setState({
758 byProjectKey: {},
759 projectKeyByThreadKey: {},
760 pendingVisitsByThreadKey: {},
761 });
762}