Skip to content
TypeScript

fix(web): browser history and titles show up again (#25491)

Julius Marminge7c6e85cfdaad
diff --git a/apps/web/src/browserFaviconStore.test.ts b/apps/web/src/browserFaviconStore.test.ts
index b0f9b5b7b97..f15d25af473 100644
--- a/apps/web/src/browserFaviconStore.test.ts
+++ b/apps/web/src/browserFaviconStore.test.ts
@@ -17,7 +17,7 @@ vi.mock("~/state/session", () => ({
metadata.httpBaseUrl ? { httpBaseUrl: metadata.httpBaseUrl } : null,
}));
-import { useComposerDraftStore, type DraftThreadState } from "./composerDraftStore";
+import { DraftId, useComposerDraftStore } from "./composerDraftStore";
import {
lookupFavicon,
lookupFaviconForThread,
@@ -103,14 +103,11 @@ describe("browser favicon store", () => {
});
it("files a draft thread's capture under the draft's project with no view registering it", () => {
- useComposerDraftStore.setState({
- draftThreadsByThreadKey: {
- [scopedThreadKey(threadRef)]: {
- environmentId,
- projectId: ProjectId.make("project-1"),
- } as DraftThreadState,
- },
- });
+ useComposerDraftStore
+ .getState()
+ .setLogicalProjectDraftThreadId("env-1:project-1", projectRef, DraftId.make("draft-1"), {
+ threadId: threadRef.threadId,
+ });
expect(recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1))).toBe(true);
expect(useBrowserFaviconStore.getState().byKey).toEqual({
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 1 },
diff --git a/apps/web/src/browserFaviconStore.ts b/apps/web/src/browserFaviconStore.ts
index c11de1425d4..8bafa69304f 100644
--- a/apps/web/src/browserFaviconStore.ts
+++ b/apps/web/src/browserFaviconStore.ts
@@ -175,7 +175,7 @@ function mergeBrowserFaviconState(
function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
const shell = useQuietThreadShell(threadRef);
const draftProjectRef = useComposerDraftStore((state) => {
- const draft = state.draftThreadsByThreadKey[scopedThreadKey(threadRef)];
+ const draft = state.getDraftSessionByRef(threadRef);
return draft ? scopedProjectKey(scopeProjectRef(draft.environmentId, draft.projectId)) : null;
});
if (shell?.projectId) return scopeProjectRef(threadRef.environmentId, shell.projectId);
@@ -185,8 +185,7 @@ function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjec
function readThreadProjectRef(threadRef: ScopedThreadRef): ScopedProjectRef | null {
const projectId = readThreadShell(threadRef)?.projectId;
if (projectId) return scopeProjectRef(threadRef.environmentId, projectId);
- const draft =
- useComposerDraftStore.getState().draftThreadsByThreadKey[scopedThreadKey(threadRef)];
+ const draft = useComposerDraftStore.getState().getDraftSessionByRef(threadRef);
return draft ? scopeProjectRef(draft.environmentId, draft.projectId) : null;
}
diff --git a/apps/web/src/browserHistoryStore.test.ts b/apps/web/src/browserHistoryStore.test.ts
index 554faf086d5..fa8df253264 100644
--- a/apps/web/src/browserHistoryStore.test.ts
+++ b/apps/web/src/browserHistoryStore.test.ts
@@ -1,13 +1,52 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-import { EnvironmentId, type PreviewSessionSnapshot, ThreadId } from "@t3tools/contracts";
+import { scopeProjectRef } from "@t3tools/client-runtime/environment";
+import {
+ EnvironmentId,
+ type PreviewSessionSnapshot,
+ ProjectId,
+ ThreadId,
+} from "@t3tools/contracts";
-const { readPreparedConnection } = vi.hoisted(() => ({
+const { readPreparedConnection, entities, settingsHydration } = vi.hoisted(() => ({
readPreparedConnection: vi.fn<() => { httpBaseUrl: string } | null>(() => null),
+ entities: {
+ projects: [] as Array<Record<string, unknown>>,
+ shellProjectId: null as string | null,
+ },
+ settingsHydration: {
+ hydrated: true,
+ finish: () => {},
+ promise: Promise.resolve(),
+ },
}));
vi.mock("~/state/session", () => ({ readPreparedConnection }));
+vi.mock("~/state/entities", () => ({
+ readThreadShell: () => (entities.shellProjectId ? { projectId: entities.shellProjectId } : null),
+ readProject: (ref: { environmentId: string; projectId: string }) =>
+ entities.projects.find(
+ (project) => project.environmentId === ref.environmentId && project.id === ref.projectId,
+ ) ?? null,
+ readProjects: () => entities.projects,
+ useProjects: () => entities.projects,
+ useQuietThreadShell: () => null,
+}));
+vi.mock("./hooks/useSettings", async () => {
+ const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings");
+ return {
+ getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
+ useClientSettings: () => DEFAULT_CLIENT_SETTINGS,
+ isClientSettingsHydrated: () => settingsHydration.hydrated,
+ ensureClientSettingsHydrated: () => settingsHydration.promise,
+ };
+});
+vi.mock("~/state/environments", () => ({
+ readPrimaryEnvironmentId: () => null,
+ usePrimaryEnvironmentId: () => null,
+}));
+import { DraftId, useComposerDraftStore } from "./composerDraftStore";
import {
BROWSER_HISTORY_MAX_PROJECTS,
type BrowserHistoryEntry,
@@ -26,7 +65,14 @@ function entry(overrides: Partial<BrowserHistoryEntry> = {}): BrowserHistoryEntr
return { url: "http://localhost:3000/", lastVisitedAt: 1000, ...overrides };
}
-beforeEach(() => readPreparedConnection.mockReturnValue(null));
+beforeEach(() => {
+ readPreparedConnection.mockReturnValue(null);
+ entities.projects = [];
+ entities.shellProjectId = null;
+ settingsHydration.hydrated = true;
+ settingsHydration.promise = Promise.resolve();
+ useComposerDraftStore.setState({ draftThreadsByThreadKey: {} });
+});
afterEach(() => vi.restoreAllMocks());
describe("normalizeHistoryUrl", () => {
@@ -251,6 +297,81 @@ describe("useBrowserHistoryStore", () => {
});
});
+const repoProject = {
+ environmentId: EnvironmentId.make("env-1"),
+ id: ProjectId.make("project-1"),
+ workspaceRoot: "/repo",
+ repositoryIdentity: null,
+ isScratch: false,
+};
+
+describe("thread project resolution", () => {
+ beforeEach(resetStores);
+
+ it("files a browser tab's visits and titles under the thread's project with no view registering it", () => {
+ entities.projects = [repoProject];
+ entities.shellProjectId = "project-1";
+
+ recordVisitForThread(threadRef, "http://localhost:5173/", 1);
+ settle("http://localhost:5173/", "Dev App");
+
+ expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({
+ "env-1:/repo": [{ url: "http://localhost:5173/", lastVisitedAt: 1, title: "Dev App" }],
+ });
+ expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
+ });
+
+ it("files a draft thread's visits under the draft's project", () => {
+ entities.projects = [repoProject];
+ const projectRef = scopeProjectRef(EnvironmentId.make("env-1"), ProjectId.make("project-1"));
+ useComposerDraftStore
+ .getState()
+ .setLogicalProjectDraftThreadId("env-1:/repo", projectRef, DraftId.make("draft-1"), {
+ threadId: threadRef.threadId,
+ });
+
+ recordVisitForThread(threadRef, "http://localhost:5173/", 1);
+
+ expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({
+ "env-1:/repo": [{ url: "http://localhost:5173/", lastVisitedAt: 1 }],
+ });
+ expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
+ });
+
+ it("waits for client settings before filing a thread under its project", async () => {
+ entities.projects = [repoProject];
+ entities.shellProjectId = "project-1";
+ settingsHydration.hydrated = false;
+ settingsHydration.promise = new Promise<void>((resolve) => {
+ settingsHydration.finish = () => {
+ settingsHydration.hydrated = true;
+ resolve();
+ };
+ });
+
+ recordVisitForThread(threadRef, "http://localhost:5173/", 1);
+ expect(useBrowserHistoryStore.getState().projectKeyByThreadKey).toEqual({});
+
+ settingsHydration.finish();
+ await settingsHydration.promise;
+ expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({
+ "env-1:/repo": [{ url: "http://localhost:5173/", lastVisitedAt: 1 }],
+ });
+ expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
+ });
+
+ it("lands visits queued before the thread's project loaded with the next visit", () => {
+ recordVisitForThread(threadRef, "http://a.test/", 1);
+ entities.projects = [repoProject];
+ entities.shellProjectId = "project-1";
+ recordVisitForThread(threadRef, "http://b.test/", 2);
+
+ expect(
+ useBrowserHistoryStore.getState().byProjectKey["env-1:/repo"]?.map((entry) => entry.url),
+ ).toEqual(["http://b.test/", "http://a.test/"]);
+ });
+});
+
describe("pendingVisitsByThreadKey", () => {
beforeEach(resetStores);
diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts
index 33a9b0dc523..780f06b5c91 100644
--- a/apps/web/src/browserHistoryStore.ts
+++ b/apps/web/src/browserHistoryStore.ts
@@ -1,5 +1,14 @@
-import { scopedThreadKey } from "@t3tools/client-runtime/environment";
-import type { PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
+import {
+ scopedProjectKey,
+ scopedThreadKey,
+ scopeProjectRef,
+} from "@t3tools/client-runtime/environment";
+import type {
+ EnvironmentId,
+ PreviewSessionSnapshot,
+ ScopedProjectRef,
+ ScopedThreadRef,
+} from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { useShallow } from "zustand/react/shallow";
@@ -12,10 +21,33 @@ import {
type ThreadPreviewState,
} from "~/previewStateStore";
import { appAtomRegistry } from "~/rpc/atomRegistry";
+import {
+ readProject,
+ readProjects,
+ readThreadShell,
+ useProjects,
+ useQuietThreadShell,
+} from "~/state/entities";
+import { readPrimaryEnvironmentId, usePrimaryEnvironmentId } from "~/state/environments";
import { readPreparedConnection } from "~/state/session";
import { isLocalLoopbackHost, normalizeHostname } from "./browser/browserTargetResolver";
+import { useComposerDraftStore } from "./composerDraftStore";
+import {
+ ensureClientSettingsHydrated,
+ getClientSettings,
+ isClientSettingsHydrated,
+ useClientSettings,
+} from "./hooks/useSettings";
import { resolveStorage } from "./lib/storage";
+import {
+ deriveLogicalProjectKeyFromSettings,
+ derivePhysicalProjectKey,
+ selectProjectGroupingSettings,
+ type ProjectGroupingSettings,
+} from "./logicalProject";
+import { buildPhysicalToLogicalProjectKeyMap } from "./sidebarProjectGrouping";
+import type { Project } from "./types";
export type BrowserHistoryEntry = { url: string; lastVisitedAt: number; title?: string };
@@ -313,10 +345,63 @@ function migratePersistedThreadProjectKeys(
);
}
+/**
+ * History follows the sidebar's project rows, so a duplicate row shares the
+ * history of the group it is listed under rather than keying by its own path.
+ */
+function deriveHistoryProjectKey(
+ project: Project,
+ projects: ReadonlyArray<Project>,
+ settings: ProjectGroupingSettings,
+ primaryEnvironmentId: EnvironmentId | null,
+): string {
+ return (
+ buildPhysicalToLogicalProjectKeyMap({ projects, settings, primaryEnvironmentId }).get(
+ derivePhysicalProjectKey(project),
+ ) ?? deriveLogicalProjectKeyFromSettings(project, settings)
+ );
+}
+
+/** Server threads name their project in the shell; drafts in the composer draft store. */
+function readThreadProjectRef(ref: ScopedThreadRef): ScopedProjectRef | null {
+ const projectId = readThreadShell(ref)?.projectId;
+ if (projectId) return scopeProjectRef(ref.environmentId, projectId);
+ const draft = useComposerDraftStore.getState().getDraftSessionByRef(ref);
+ return draft ? scopeProjectRef(draft.environmentId, draft.projectId) : null;
+}
+
+/**
+ * Registers the thread under its current project so queued visits and titles
+ * land. Until the project loads, or client settings hydrate (the grouping is
+ * unknown before then), the last registration stands and writes stay queued.
+ */
+function resolveThreadProjectKey(ref: ScopedThreadRef): string | undefined {
+ const state = useBrowserHistoryStore.getState();
+ const registered = state.projectKeyByThreadKey[scopedThreadKey(ref)];
+ if (!isClientSettingsHydrated()) {
+ void ensureClientSettingsHydrated().then(
+ () => resolveThreadProjectKey(ref),
+ () => undefined,
+ );
+ return registered;
+ }
+ const projectRef = readThreadProjectRef(ref);
+ const project = projectRef ? readProject(projectRef) : null;
+ if (!project) return registered;
+ const projectKey = deriveHistoryProjectKey(
+ project,
+ readProjects(),
+ selectProjectGroupingSettings(getClientSettings()),
+ readPrimaryEnvironmentId(),
+ );
+ state.registerThreadProject(ref, projectKey);
+ return projectKey;
+}
+
export function recordVisitForThread(ref: ScopedThreadRef, url: string, at?: number): void {
const threadKey = scopedThreadKey(ref);
+ const projectKey = resolveThreadProjectKey(ref);
const state = useBrowserHistoryStore.getState();
- const projectKey = state.projectKeyByThreadKey[threadKey];
const visitAt = at ?? Date.now();
const connection = readPreparedConnection(ref.environmentId);
const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null;
@@ -412,21 +497,45 @@ export function startPreviewTitleRecording(): () => void {
}
export function removeUrlForThread(ref: ScopedThreadRef, url: string): void {
- const state = useBrowserHistoryStore.getState();
- const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
+ const projectKey = resolveThreadProjectKey(ref);
if (!projectKey) return;
- state.removeUrl(projectKey, url);
+ useBrowserHistoryStore.getState().removeUrl(projectKey, url);
}
const EMPTY_HISTORY: ReadonlyArray<BrowserHistoryEntry> = [];
+function useThreadHistoryProjectKey(ref: ScopedThreadRef): string | null {
+ const threadKey = scopedThreadKey(ref);
+ const shellProjectId = useQuietThreadShell(ref)?.projectId ?? null;
+ const draftProjectKey = useComposerDraftStore((state) => {
+ const draft = state.getDraftSessionByRef(ref);
+ return draft ? scopedProjectKey(scopeProjectRef(draft.environmentId, draft.projectId)) : null;
+ });
+ const projectKey = shellProjectId
+ ? scopedProjectKey(scopeProjectRef(ref.environmentId, shellProjectId))
+ : draftProjectKey;
+ const projects = useProjects();
+ const settings = useClientSettings(selectProjectGroupingSettings);
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const registered = useBrowserHistoryStore(
+ (state) => state.projectKeyByThreadKey[threadKey] ?? null,
+ );
+ const project = projects.find(
+ (candidate) =>
+ scopedProjectKey(scopeProjectRef(candidate.environmentId, candidate.id)) === projectKey,
+ );
+ return project
+ ? deriveHistoryProjectKey(project, projects, settings, primaryEnvironmentId)
+ : registered;
+}
+
export function useThreadRecentHistory(
ref: ScopedThreadRef,
limit: number,
): ReadonlyArray<BrowserHistoryEntry> {
+ const projectKey = useThreadHistoryProjectKey(ref);
return useBrowserHistoryStore(
useShallow((state) => {
- const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
const entries = projectKey ? state.byProjectKey[projectKey] : undefined;
return entries && entries.length > 0 ? entries.slice(0, limit) : EMPTY_HISTORY;
}),
diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts
index b65ab6c189d..9da33c507c7 100644
--- a/apps/web/src/hooks/useSettings.ts
+++ b/apps/web/src/hooks/useSettings.ts
@@ -265,6 +265,10 @@ export function getClientSettings(): ClientSettings {
return getClientSettingsSnapshot();
}
+export function isClientSettingsHydrated(): boolean {
+ return getClientSettingsHydratedSnapshot();
+}
+
/** Failed reads reject and remain retryable so defaults cannot overwrite saved preferences. */
export function ensureClientSettingsHydrated(): Promise<void> {
return hydrateClientSettings();
diff --git a/apps/web/src/state/environments.ts b/apps/web/src/state/environments.ts
index 72f5afcf989..e399c201c34 100644
--- a/apps/web/src/state/environments.ts
+++ b/apps/web/src/state/environments.ts
@@ -9,6 +9,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { environmentCatalog } from "../connection/catalog";
+import { appAtomRegistry } from "../rpc/atomRegistry";
import {
environmentPresentations,
environmentSummaries,
@@ -64,6 +65,10 @@ export function usePrimaryEnvironmentId(): EnvironmentId | null {
return useAtomValue(primaryEnvironmentIdAtom);
}
+export function readPrimaryEnvironmentId(): EnvironmentId | null {
+ return appAtomRegistry.get(primaryEnvironmentIdAtom);
+}
+
export function useEnvironment(
environmentId: EnvironmentId | null,
): EnvironmentPresentation | null {