Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions apps/web/src/components/Sidebar.search.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { createMemoryHistory } from "@tanstack/react-router";
import { MessageId, ORCHESTRATION_V2_WS_METHODS } 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, userEvent } from "vite-plus/test/browser";

import { AppRoot } from "~/AppRoot";
import "~/components/ChatView";
import { __setClientSettingsForTests } from "~/hooks/useSettings";
import appCss from "~/index.css?inline";
import { getRouter } from "~/router";
import {
ENVIRONMENT_ID,
PROJECT_ID,
answerRpc,
installFakeEnvironment,
threadWithHistory,
type FakeDriver,
} from "../../test/fakeEnvironment";
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) => {
const [actual, { fakeDriver }, Layer] = await Promise.all([
importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
import("../../test/fakeEnvironment"),
import("effect/Layer"),
]);
return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
});

vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
...(await original()),
trackRpcRequestSent: () => {},
}));

it("dismisses a previous sidebar message find when the sidebar search changes or clears", async () => {
await page.viewport(1400, 900);
using styles = new DisposableStack();
const style = document.createElement("style");
style.textContent = appCss;
document.head.append(style);
styles.defer(() => style.remove());
const thread = threadWithHistory("sidebar-search", 1);
const messageId = MessageId.make(`${thread.id}-assistant-0`);
using _environment = installFakeEnvironment([thread], {
config: { threadFind: true },
});
using _searchThreads = answerRpc(
ORCHESTRATION_V2_WS_METHODS.searchThreads,
({ query }: { readonly query: string }) =>
Effect.succeed({
matches:
query === "Sidebar.tsx"
? [
{
threadId: thread.id,
projectId: PROJECT_ID,
source: "assistant",
snippet: "checked Sidebar.tsx",
messageId,
messageCreatedAt: null,
},
]
: [],
}),
);
using _searchThread = answerRpc(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 router={router} />, {
// 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");
});
11 changes: 9 additions & 2 deletions apps/web/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,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,
Expand Down Expand Up @@ -1484,6 +1488,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
};

const clearThreadSearch = () => {
closeThreadFind("sidebar");
setThreadSearchQuery("");
setSearchHighlightKey(null);
};
Expand All @@ -1496,7 +1501,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<HTMLInputElement>) => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
Expand Down Expand Up @@ -3181,6 +3187,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
searchInputRef={threadSearchInputRef}
searchQuery={threadSearchQuery}
onSearchQueryChange={(value) => {
closeThreadFind("sidebar");
setThreadSearchQuery(value);
setSearchHighlightKey(null);
}}
Expand Down
26 changes: 26 additions & 0 deletions apps/web/src/components/chat/threadFindStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
Expand Down
14 changes: 12 additions & 2 deletions apps/web/src/components/chat/threadFindStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -34,6 +35,7 @@ export interface ThreadFindState {

export const CLOSED_THREAD_FIND: ThreadFindState = {
threadKey: null,
source: "thread",
query: "",
offset: 0,
start: undefined,
Expand Down Expand Up @@ -91,6 +93,7 @@ export function openThreadFind(threadKey: string): void {
useThreadFindStore.setState({
...current,
threadKey,
source: "thread",
focusRequestId: previous.focusRequestId + 1,
...(query
? {
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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);
}

Expand Down
2 changes: 2 additions & 0 deletions apps/web/test/fakeEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -568,12 +568,14 @@ export function installFakeEnvironment(
/** Commands left unanswered even when accepting, until `rejectPendingCommand`. */
readonly holdCommand?: (command: OrchestrationV2Command) => boolean;
readonly providers?: ReadonlyArray<unknown>;
readonly config?: Partial<ServerConfig>;
},
): Disposable {
threads = fixtures;
baseServerConfig = {
...makeServerConfig(options?.providers ?? [CODEX_PROVIDER]),
keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS,
...options?.config,
};
dispatched = [];
acceptCommands = options?.acceptCommands === true;
Expand Down
Loading