From b8f9a9f0274284225ffde886ed10d5de992a57f6 Mon Sep 17 00:00:00 2001 From: Upsidedly Date: Sat, 31 Oct 2026 19:21:22 -0500 Subject: [PATCH] fix(web): clear stale sidebar search highlights --- .../src/components/ChatView.browser.test.tsx | 102 +++++++++++++++++- apps/web/src/components/Sidebar.tsx | 11 +- .../components/chat/threadFindStore.test.ts | 26 +++++ .../src/components/chat/threadFindStore.ts | 14 ++- apps/web/test/fakeEnvironment.ts | 28 ++++- 5 files changed, 170 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 8fe98b78da113..61e900b46c665 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -1,10 +1,13 @@ import { createMemoryHistory } from "@tanstack/react-router"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; -import { ThreadId } from "@t3tools/contracts"; +import { MessageId, ORCHESTRATION_V2_WS_METHODS, ThreadId } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import type * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; import { AppRoot } from "~/AppRoot"; import { DraftId, useComposerDraftStore } from "~/composerDraftStore"; @@ -14,9 +17,11 @@ import { ENVIRONMENT_ID, PROJECT_ID, installFakeEnvironment, + threadWithHistory, type FakeDriver, } from "../../test/fakeEnvironment"; -import { render } from "../../test/render"; +import { act, render } from "../../test/render"; +import { closeThreadFind, openThreadFindOnQuery, useThreadFindStore } from "./chat/threadFindStore"; // The socket is the only fake layer; see test/appScenarios.renders.tsx. vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { @@ -33,6 +38,97 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ trackRpcRequestSent: () => {}, })); +it("dismisses a previous sidebar message find when the sidebar search changes or clears", async () => { + await page.viewport(1400, 900); + const thread = threadWithHistory("sidebar-search", 1); + const messageId = MessageId.make(`${thread.id}-assistant-0`); + using _environment = installFakeEnvironment([thread], { + config: { threadFind: true }, + rpc: { + [ORCHESTRATION_V2_WS_METHODS.searchThreads]: ({ query }) => + Effect.succeed({ + matches: + query === "Sidebar.tsx" + ? [ + { + threadId: thread.id, + projectId: PROJECT_ID, + source: "assistant", + snippet: "checked Sidebar.tsx", + messageId, + messageCreatedAt: null, + }, + ] + : [], + }), + [ORCHESTRATION_V2_WS_METHODS.searchThread]: () => + Effect.succeed({ + snapshotSequence: 1, + totalMatches: 1, + activeIndex: 0, + match: { entryId: messageId, runId: thread.runs[0]!.id, occurrence: 0 }, + }), + }, + }); + closeThreadFind(); + using _find = { [Symbol.dispose]: closeThreadFind }; + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using screen = await render(, { + // AppRoot brings its own router. + router: false, + }); + const search = screen.getByRole("combobox", { name: "Search threads" }); + await expect.element(search).toBeVisible(); + const find = screen.getByRole("searchbox", { name: "Find in thread" }); + const assertFindClosed = async () => { + await expect.element(find).not.toBeInTheDocument(); + expect(CSS.highlights.has("t3-thread-find")).toBe(false); + expect(CSS.highlights.has("t3-thread-find-active")).toBe(false); + }; + const selectMessageResult = async () => { + await userEvent.fill(search, "Sidebar.tsx"); + await userEvent.click(screen.getByRole("option", { name: new RegExp(thread.title) })); + await expect.element(find).toHaveValue("Sidebar.tsx"); + await vi.waitFor(() => expect(CSS.highlights.get("t3-thread-find-active")?.size).toBe(1)); + }; + const openMessageFind = () => + act(() => + openThreadFindOnQuery(`${ENVIRONMENT_ID}:${thread.id}`, { query: "Sidebar.tsx" }, "sidebar"), + ); + + await selectMessageResult(); + await userEvent.fill(search, thread.title); + await assertFindClosed(); + + await openMessageFind(); + await userEvent.click(screen.getByRole("button", { name: "Clear thread search" })); + await expect.element(search).toHaveValue(""); + await assertFindClosed(); + + await userEvent.fill(search, thread.title); + await openMessageFind(); + await userEvent.click(search); + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await assertFindClosed(); + + await userEvent.fill(search, thread.title); + await openMessageFind(); + await userEvent.clear(search); + await expect.element(search).toHaveValue(""); + await assertFindClosed(); + + await selectMessageResult(); + expect(useThreadFindStore.getState().query).toBe("Sidebar.tsx"); +}); + it("a new draft does not load its reserved thread before the server lists it", async () => { using _environment = installFakeEnvironment([]); using fetchSpy = vi.spyOn(globalThis, "fetch"); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e6f23149dfedb..16bf428539944 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -41,7 +41,11 @@ import { type ShownOrder, } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankMessageMatches } from "@t3tools/shared/paletteSearch"; -import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore"; +import { + closeThreadFind, + findForMessageMatch, + openThreadFindOnQuery, +} from "./chat/threadFindStore"; import { threadRuntimeCanArchive, type EnvironmentThreadShell, @@ -1467,6 +1471,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; const clearThreadSearch = () => { + closeThreadFind("sidebar"); setThreadSearchQuery(""); setSearchHighlightKey(null); }; @@ -1479,7 +1484,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const query = threadSearch.query; clearThreadSearch(); navigateToThread(ref); - if (match) openThreadFindOnQuery(scopedThreadKey(ref), findForMessageMatch(match, query)); + if (match) + openThreadFindOnQuery(scopedThreadKey(ref), findForMessageMatch(match, query), "sidebar"); }; const handleThreadSearchKeyDown = (event: ReactKeyboardEvent) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; @@ -3153,6 +3159,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve searchInputRef={threadSearchInputRef} searchQuery={threadSearchQuery} onSearchQueryChange={(value) => { + closeThreadFind("sidebar"); setThreadSearchQuery(value); setSearchHighlightKey(null); }} diff --git a/apps/web/src/components/chat/threadFindStore.test.ts b/apps/web/src/components/chat/threadFindStore.test.ts index 3819d8a4110f7..380aa6e9be553 100644 --- a/apps/web/src/components/chat/threadFindStore.test.ts +++ b/apps/web/src/components/chat/threadFindStore.test.ts @@ -64,6 +64,32 @@ describe("thread find store", () => { detach(); }); + it("dismisses sidebar finds without closing a find the user opened or edited", () => { + setup(); + openThreadFindOnQuery(threadKey, { query: "manual" }); + closeThreadFind("sidebar"); + expect(useThreadFindStore.getState().query).toBe("manual"); + + openThreadFindOnQuery(threadKey, { query: "result" }, "sidebar"); + closeThreadFind("sidebar"); + expect(useThreadFindStore.getState().threadKey).toBeNull(); + + openThreadFindOnQuery(threadKey, { query: "result" }, "sidebar"); + openThreadFind(threadKey); + closeThreadFind("sidebar"); + expect(useThreadFindStore.getState().query).toBe("result"); + + openThreadFindOnQuery(threadKey, { query: "result" }, "sidebar"); + setThreadFindQuery(threadKey, "edited"); + closeThreadFind("sidebar"); + expect(useThreadFindStore.getState().query).toBe("edited"); + + openThreadFindOnQuery(threadKey, { query: "result" }, "sidebar"); + openThreadFindOnQuery(threadKey, { query: "palette" }); + closeThreadFind("sidebar"); + expect(useThreadFindStore.getState().query).toBe("palette"); + }); + it("keeps find over Settings and Usage, and closes it on any other route", () => { setup(); openThreadFindOnQuery(threadKey, { query: "x" }); diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.ts index ea52de6c2747e..8386e176b4c13 100644 --- a/apps/web/src/components/chat/threadFindStore.ts +++ b/apps/web/src/components/chat/threadFindStore.ts @@ -23,6 +23,7 @@ export interface ThreadFindLocalSelection { /** Find is open in at most one thread: the one the chat view shows. */ export interface ThreadFindState { readonly threadKey: string | null; + readonly source: "thread" | "sidebar"; readonly query: string; readonly offset: number; readonly start: ThreadFindStart | undefined; @@ -34,6 +35,7 @@ export interface ThreadFindState { export const CLOSED_THREAD_FIND: ThreadFindState = { threadKey: null, + source: "thread", query: "", offset: 0, start: undefined, @@ -91,6 +93,7 @@ export function openThreadFind(threadKey: string): void { useThreadFindStore.setState({ ...current, threadKey, + source: "thread", focusRequestId: previous.focusRequestId + 1, ...(query ? { @@ -114,12 +117,17 @@ export interface PendingThreadFind { * Opens find on `query` in the thread, such as at the message a search result * came from. The thread's view shows it once it is on screen. */ -export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind): void { +export function openThreadFindOnQuery( + threadKey: string, + find: PendingThreadFind, + source: ThreadFindState["source"] = "thread", +): void { const previous = useThreadFindStore.getState(); announceOpening(previous, threadKey); useThreadFindStore.setState({ ...(previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND), threadKey, + source, query: find.query, offset: 0, start: find.start, @@ -133,6 +141,7 @@ export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind export function setThreadFindQuery(threadKey: string, query: string): void { const start = readThreadFindPosition(threadKey, query.trim()); useThreadFindStore.setState((previous) => ({ + source: "thread", query, offset: 0, start, @@ -142,7 +151,8 @@ export function setThreadFindQuery(threadKey: string, query: string): void { })); } -export function closeThreadFind(): void { +export function closeThreadFind(source?: ThreadFindState["source"]): void { + if (source !== undefined && useThreadFindStore.getState().source !== source) return; useThreadFindStore.setState(CLOSED_THREAD_FIND); } diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index c586ad51c2c5f..3931643581ca0 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -45,6 +45,11 @@ import { RpcSchema } from "effect/rpc"; export const ENVIRONMENT_ID = EnvironmentId.make("environment-render"); export const PROJECT_ID = ProjectId.make("project-render"); +type FakeRpcHandlers = { + readonly [Method in keyof WsRpcProtocolClient]?: ( + input: Parameters[0], + ) => ReturnType; +}; const CODEX = ProviderInstanceId.make("codex"); const MODEL = { instanceId: CODEX, model: "gpt-5.4" }; const AT = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z"); @@ -100,6 +105,8 @@ const serverConfig: ServerConfig = { }), keybindings: DEFAULT_RESOLVED_KEYBINDINGS, }; +let activeConfig = serverConfig; +let rpcOverrides: FakeRpcHandlers = {}; const project: OrchestrationProjectShell = { id: PROJECT_ID, @@ -357,12 +364,13 @@ const handlers: Record unknown> = { ); }, [WS_METHODS.subscribeServerConfig]: () => - subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]), + subscribe([{ version: 1 as const, type: "snapshot" as const, config: activeConfig }]), }; // Unanswered calls stay pending, like a server that has not replied yet. const client = new Proxy(handlers, { get: (target, method: string) => + rpcOverrides[method as keyof WsRpcProtocolClient] ?? target[method] ?? (() => { const rpc = WsRpcGroup.requests.get(method); @@ -372,9 +380,9 @@ const client = new Proxy(handlers, { const session: EnvironmentConnectionLease["session"] = { client: client as unknown as WsRpcProtocolClient, - initialConfig: Effect.succeed(serverConfig), + initialConfig: Effect.sync(() => activeConfig), subscribeServerConfig: () => - subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]), + subscribe([{ version: 1 as const, type: "snapshot" as const, config: activeConfig }]), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), @@ -408,7 +416,17 @@ const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)( ); /** Serves the environment's HTTP API and these threads until disposed. */ -export function installFakeEnvironment(fixtures: ReadonlyArray): Disposable { +export function installFakeEnvironment( + fixtures: ReadonlyArray, + options: { + readonly config?: Partial; + readonly rpc?: FakeRpcHandlers; + } = {}, +): Disposable { + const previousConfig = activeConfig; + const previousRpc = rpcOverrides; + activeConfig = { ...serverConfig, ...options.config }; + rpcOverrides = options.rpc ?? {}; threads = fixtures; globalThis.fetch = async (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), window.location.href); @@ -429,6 +447,8 @@ export function installFakeEnvironment(fixtures: ReadonlyArray): Dis }; return { [Symbol.dispose]: () => { + activeConfig = previousConfig; + rpcOverrides = previousRpc; globalThis.fetch = realFetch; threads = []; },