TypeScript
fix(web): preview favicons resolve their project without ChatView syncing it (#25068)
Julius Marmingef9956434fa2f
diff --git a/apps/web/src/browserFaviconStore.test.ts b/apps/web/src/browserFaviconStore.test.tsindex cfdedef0016..b0f9b5b7b97 100644--- a/apps/web/src/browserFaviconStore.test.ts+++ b/apps/web/src/browserFaviconStore.test.ts@@ -1,13 +1,26 @@-import { scopeProjectRef } from "@t3tools/client-runtime/environment";+import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/environment";import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";-vi.mock("~/state/entities", () => ({ useQuietThreadShell: () => null }));-vi.mock("~/state/session", () => ({ usePreparedConnection: () => ({ _tag: "None" }) }));+const metadata = vi.hoisted(() => ({+ projectId: null as string | null,+ httpBaseUrl: null as string | null,+}));+vi.mock("~/state/entities", () => ({+ useQuietThreadShell: () => null,+ readThreadShell: () => (metadata.projectId ? { projectId: metadata.projectId } : null),+}));+vi.mock("~/state/session", () => ({+ usePreparedConnection: () => ({ _tag: "None" }),+ readPreparedConnection: () =>+ metadata.httpBaseUrl ? { httpBaseUrl: metadata.httpBaseUrl } : null,+}));++import { useComposerDraftStore, type DraftThreadState } from "./composerDraftStore";import {- flushPendingFaviconsForThread,lookupFavicon,+ lookupFaviconForThread,recordFaviconForProject,recordFaviconForThread,resetBrowserFaviconsForTests,@@ -26,7 +39,12 @@ const favicon = (pageUrl: string, capturedAt: number, dataUrl = PNG) => ({});describe("browser favicon store", () => {- beforeEach(resetBrowserFaviconsForTests);+ beforeEach(() => {+ resetBrowserFaviconsForTests();+ metadata.projectId = null;+ metadata.httpBaseUrl = null;+ useComposerDraftStore.setState({ draftThreadsByThreadKey: {} });+ });afterEach(() => {vi.unstubAllGlobals();vi.restoreAllMocks();@@ -67,18 +85,16 @@ describe("browser favicon store", () => {).toBeNull();});- it("retains multiple origins until project and connection metadata hydrate", () => {- expect(- recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1), null, undefined),- ).toBe(false);- expect(- recordFaviconForThread(threadRef, favicon("http://localhost:5173/", 2), null, undefined),- ).toBe(false);+ it("retains origins until the thread's project is known, then lands them with the next capture", () => {+ expect(recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1))).toBe(false);+ expect(recordFaviconForThread(threadRef, favicon("http://localhost:5173/", 2))).toBe(false);expect(Object.keys(Object.values(useBrowserFaviconStore.getState().pendingByThreadKey)[0] ?? {}),).toHaveLength(2);- expect(flushPendingFaviconsForThread(threadRef, projectRef, "192.168.64.2")).toBe(true);+ metadata.projectId = "project-1";+ metadata.httpBaseUrl = "http://192.168.64.2:3773";+ expect(recordFaviconForThread(threadRef, favicon("http://localhost:5173/", 3))).toBe(true);expect(Object.keys(useBrowserFaviconStore.getState().byKey).toSorted()).toEqual(["env-1:project-1 http://localhost:3000","env-1:project-1 http://localhost:5173",@@ -86,29 +102,53 @@ describe("browser favicon store", () => {expect(useBrowserFaviconStore.getState().pendingByThreadKey).toEqual({});});+ 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,+ },+ });+ 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 },+ });+ });+it("persists unambiguous loopback captures while the environment is offline", () => {- expect(- recordFaviconForThread(- threadRef,- favicon("http://localhost:3000/", 1),- projectRef,- undefined,- ),- ).toBe(true);+ metadata.projectId = "project-1";+ 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 },});- recordFaviconForThread(- threadRef,- favicon("http://192.168.64.2:5173/", 2),- projectRef,- undefined,- );- expect(flushPendingFaviconsForThread(threadRef, projectRef, undefined)).toBe(false);+ expect(recordFaviconForThread(threadRef, favicon("http://192.168.64.2:5173/", 2))).toBe(false);expect(Object.values(useBrowserFaviconStore.getState().pendingByThreadKey)[0]).toBeDefined();});+ it("shows a newer pending capture over the stored favicon for the same origin", () => {+ const NEWER = "data:image/png;base64,BBBB";+ metadata.projectId = "project-1";+ metadata.httpBaseUrl = "http://192.168.64.2:3773";+ expect(recordFaviconForThread(threadRef, favicon("http://192.168.64.2:5173/", 1))).toBe(true);++ metadata.httpBaseUrl = null;+ expect(recordFaviconForThread(threadRef, favicon("http://192.168.64.2:5173/", 2, NEWER))).toBe(+ false,+ );+ expect(+ lookupFaviconForThread(+ useBrowserFaviconStore.getState(),+ scopedThreadKey(threadRef),+ projectRef,+ "http://192.168.64.2:5173/",+ "192.168.64.2",+ ),+ ).toBe(NEWER);+ });+it("keeps the memory shadow authoritative after an asymmetric primary write failure", () => {vi.stubGlobal("window", {localStorage: {diff --git a/apps/web/src/browserFaviconStore.ts b/apps/web/src/browserFaviconStore.tsindex c8d6fd521d2..c11de1425d4 100644--- a/apps/web/src/browserFaviconStore.ts+++ b/apps/web/src/browserFaviconStore.ts@@ -1,4 +1,5 @@import {+ parseScopedProjectKey,scopedProjectKey,scopedThreadKey,scopeProjectRef,@@ -9,8 +10,8 @@ import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";import { normalizeHostname } from "~/browser/browserTargetResolver";-import { useQuietThreadShell } from "~/state/entities";-import { usePreparedConnection } from "~/state/session";+import { readThreadShell, useQuietThreadShell } from "~/state/entities";+import { readPreparedConnection, usePreparedConnection } from "~/state/session";import {BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,@@ -23,12 +24,12 @@ import {isValidFaviconCapturedAt,migratePersistedBrowserFaviconState,} from "./browserFaviconLogic";+import { useComposerDraftStore } from "./composerDraftStore";import { createMemoryStorage, type StateStorage } from "./lib/storage";const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";const MAX_PENDING_ORIGINS_PER_THREAD = 10;const MAX_PENDING_THREADS = 20;-const MAX_REGISTERED_THREADS = 100;type PendingFavicon = DesktopPreviewFavicon;type PendingFaviconsByOrigin = Record<string, PendingFavicon>;@@ -36,7 +37,6 @@ type PendingFaviconsByOrigin = Record<string, PendingFavicon>;export interface BrowserFaviconStoreState {byKey: Record<string, BrowserFaviconEntry>;pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;- projectRefByThreadKey: Record<string, ScopedProjectRef>;recordFavicon: (key: string,dataUrl: string,@@ -121,7 +121,6 @@ export const useBrowserFaviconStore = create<BrowserFaviconStoreState>()((set) => ({byKey: {},pendingByThreadKey: {},- projectRefByThreadKey: {},recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>set((state) => {if (!isStorableFaviconDataUrl(dataUrl)) return state;@@ -172,38 +171,23 @@ function mergeBrowserFaviconState(};}-export function registerFaviconProjectForThread(- threadRef: ScopedThreadRef,- projectRef: ScopedProjectRef,-): void {- const threadKey = scopedThreadKey(threadRef);- const state = useBrowserFaviconStore.getState();- const current = state.projectRefByThreadKey[threadKey];- if (- current?.environmentId === projectRef.environmentId &&- current.projectId === projectRef.projectId- ) {- return;- }- useBrowserFaviconStore.setState({- projectRefByThreadKey: Object.fromEntries(- [- ...Object.entries(state.projectRefByThreadKey).filter(([key]) => key !== threadKey),- [threadKey, projectRef],- ].slice(-MAX_REGISTERED_THREADS),- ),+/** Server threads name their project in the shell; drafts in the composer draft store. */+function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {+ const shell = useQuietThreadShell(threadRef);+ const draftProjectRef = useComposerDraftStore((state) => {+ const draft = state.draftThreadsByThreadKey[scopedThreadKey(threadRef)];+ return draft ? scopedProjectKey(scopeProjectRef(draft.environmentId, draft.projectId)) : null;});+ if (shell?.projectId) return scopeProjectRef(threadRef.environmentId, shell.projectId);+ return draftProjectRef === null ? null : parseScopedProjectKey(draftProjectRef);}-export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {- const shell = useQuietThreadShell(threadRef);- const shellProjectId = shell?.projectId ?? null;- const environmentId = threadRef.environmentId;- const shellProjectRef = shellProjectId ? scopeProjectRef(environmentId, shellProjectId) : null;- const registered = useBrowserFaviconStore(- (state) => state.projectRefByThreadKey[scopedThreadKey(threadRef)] ?? null,- );- return shellProjectRef ?? registered;+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)];+ return draft ? scopeProjectRef(draft.environmentId, draft.projectId) : null;}export function recordFaviconForProject(@@ -232,11 +216,14 @@ export function recordFaviconForProject(return true;}+/**+ * The thread's project and environment host may not be known yet when a capture+ * arrives; such captures wait per thread and land with the next capture that can+ * resolve them.+ */export function recordFaviconForThread(threadRef: ScopedThreadRef,favicon: DesktopPreviewFavicon,- projectRef: ScopedProjectRef | null,- environmentHostname: string | undefined,): boolean {if (!isStorableFaviconDataUrl(favicon.dataUrl) ||@@ -244,6 +231,10 @@ export function recordFaviconForThread(!pendingOriginKey(favicon.pageUrl))return false;+ const projectRef = readThreadProjectRef(threadRef);+ const connection = readPreparedConnection(threadRef.environmentId);+ const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : undefined;+ if (projectRef) flushPendingFaviconsForThread(threadRef, projectRef, environmentHostname);const hostname =environmentHostname !== undefined? environmentHostname@@ -266,7 +257,7 @@ export function recordFaviconForThread(return false;}-export function flushPendingFaviconsForThread(+function flushPendingFaviconsForThread(threadRef: ScopedThreadRef,projectRef: ScopedProjectRef,environmentHostname: string | undefined,@@ -300,28 +291,56 @@ export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string):const environmentHostname = Option.isSome(preparedConnection)? new URL(preparedConnection.value.httpBaseUrl).hostname: null;+ const threadKey = scopedThreadKey(threadRef);return useBrowserFaviconStore((state) =>- lookupFavicon(state.byKey, projectRef, url, environmentHostname),+ lookupFaviconForThread(state, threadKey, projectRef, url, environmentHostname),);}+/**+ * A capture waiting for its thread's project still shows on that thread, and wins+ * over an older stored capture for the same origin.+ */+export function lookupFaviconForThread(+ state: Pick<BrowserFaviconStoreState, "byKey" | "pendingByThreadKey">,+ threadKey: string,+ projectRef: ScopedProjectRef | null,+ url: string,+ environmentHostname: string | null,+): string | null {+ const stored = lookupFaviconEntry(state.byKey, projectRef, url, environmentHostname);+ const originKey = pendingOriginKey(url);+ const pending = originKey ? state.pendingByThreadKey[threadKey]?.[originKey] : undefined;+ if (pending && (!stored || pending.capturedAt > stored.capturedAt)) return pending.dataUrl;+ return stored?.dataUrl ?? null;+}+export function lookupFavicon(byKey: Record<string, BrowserFaviconEntry>,projectRef: ScopedProjectRef | null,url: string,environmentHostname: string | null,): string | null {+ return lookupFaviconEntry(byKey, projectRef, url, environmentHostname)?.dataUrl ?? null;+}++function lookupFaviconEntry(+ byKey: Record<string, BrowserFaviconEntry>,+ projectRef: ScopedProjectRef | null,+ url: string,+ environmentHostname: string | null,+): BrowserFaviconEntry | null {const key = projectRef? faviconKey(scopedProjectKey(projectRef), url, environmentHostname): null;if (!key) return null;const direct = byKey[key];- if (direct) return direct.dataUrl;+ if (direct) return direct;try {const requestedHost = normalizeHostname(new URL(url).hostname);const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);const localEntry = localKey ? byKey[localKey] : null;- return localEntry?.aliases?.includes(requestedHost) ? localEntry.dataUrl : null;+ return localEntry?.aliases?.includes(requestedHost) ? localEntry : null;} catch {return null;}@@ -331,7 +350,6 @@ export function resetBrowserFaviconsForTests(): void {useBrowserFaviconStore.setState({byKey: {},pendingByThreadKey: {},- projectRefByThreadKey: {},});useBrowserFaviconStore.persist.clearStorage();}diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 7e81eb6124a..c9b32bffd07 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -178,7 +178,6 @@ import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";import { stackedThreadToast, toastManager } from "./ui/toast";import { projectScriptIdFromCommand } from "~/projectScripts";import { newMessageId } from "~/lib/utils";-import { registerFaviconProjectForThread } from "~/browserFaviconStore";import {applyProviderInstanceSettings,deriveProviderInstanceEntries,@@ -1110,10 +1109,6 @@ export default function ChatView(props: ChatViewProps) {}, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]);const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;- useEffect(() => {- if (!activeThreadRef || !activeProjectRef) return;- registerFaviconProjectForThread(activeThreadRef, activeProjectRef);- }, [activeProjectRef, activeThreadRef]);const activeEnvironment =activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null);const activeEnvironmentUnavailable =diff --git a/apps/web/src/components/preview/usePreviewBridge.ts b/apps/web/src/components/preview/usePreviewBridge.tsindex e98cca0c67c..a58382d4f83 100644--- a/apps/web/src/components/preview/usePreviewBridge.ts+++ b/apps/web/src/components/preview/usePreviewBridge.ts@@ -4,18 +4,12 @@ import type {ScopedThreadRef,ThreadId,} from "@t3tools/contracts";-import * as Option from "effect/Option";import { useEffect, useEffectEvent, useRef } from "react";-import {- flushPendingFaviconsForThread,- recordFaviconForThread,- useFaviconProjectRefForThread,-} from "~/browserFaviconStore";+import { recordFaviconForThread } from "~/browserFaviconStore";import { useBrowserPointerStore } from "~/browser/browserPointerStore";import { applyPreviewDesktopState, type DesktopPreviewOverlay } from "~/previewStateStore";import { previewEnvironment } from "~/state/preview";-import { usePreparedConnection } from "~/state/session";import { useAtomCommand } from "~/state/use-atom-command";import { previewBridge } from "./previewBridge";@@ -40,11 +34,6 @@ export function usePreviewBridge(input: {const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");const { environmentId, threadId } = threadRef;const stableThreadRef: ScopedThreadRef = { environmentId, threadId };- const projectRef = useFaviconProjectRefForThread(stableThreadRef);- const preparedConnection = usePreparedConnection(stableThreadRef.environmentId);- const environmentHostname = Option.isSome(preparedConnection)- ? new URL(preparedConnection.value.httpBaseUrl).hostname- : undefined;const lastReportedUrl = useRef<string | null>(null);const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);@@ -58,7 +47,7 @@ export function usePreviewBridge(input: {lastDesktopNavStatus.current = state.navStatus;applyPreviewDesktopState(stableThreadRef, tabId, projectDesktopState(state));if (state.favicon) {- recordFaviconForThread(stableThreadRef, state.favicon, projectRef, environmentHostname);+ recordFaviconForThread(stableThreadRef, state.favicon);}const reported = buildReportInput({threadId: stableThreadRef.threadId,@@ -88,10 +77,6 @@ export function usePreviewBridge(input: {stableThreadRef,tabId,]);- useEffect(() => {- if (!projectRef) return;- flushPendingFaviconsForThread(stableThreadRef, projectRef, environmentHostname);- }, [environmentHostname, projectRef, stableThreadRef]);}function shouldClearBrowserPointer(