Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8490: feat(agents): bring back list search as a header icon (#9821)

Bohan Jiang84a15b5fd073
diff --git a/e2e/agents-search-narrow.spec.ts b/e2e/agents-search-narrow.spec.ts
new file mode 100644
index 0000000000..1d1c291e4f
--- /dev/null
+++ b/e2e/agents-search-narrow.spec.ts
@@ -0,0 +1,137 @@
+import { expect, test, type Locator, type Page } from "@playwright/test";
+import { loginAsDefault } from "./helpers";
+
+/**
+ * MUL-8490: on a phone, the open agents search used to overflow its slot and
+ * cover Reset (390px) and Display settings too (375px), so a tap on Reset
+ * landed on the field. Every header control must keep its own box.
+ *
+ * The agent list is mocked at the network boundary: the header layout does
+ * not depend on real agents, and the spec leaves nothing behind.
+ */
+
+// Scope "all" lists every agent, so the owner only has to be well-formed.
+const OWNER_ID = "44444444-4444-4444-8444-444444444444";
+
+const AGENTS = [
+ { id: "a1a1a1a1-1111-4111-8111-111111111111", name: "PR Reviewer", description: "Reviews pull requests" },
+ { id: "b2b2b2b2-2222-4222-8222-222222222222", name: "Docs Bot", description: "Keeps docs in sync" },
+];
+
+async function mockAgents(page: Page) {
+ await page.route("**/api/agents**", (route) => {
+ const req = route.request();
+ const url = new URL(req.url());
+ if (req.method() !== "GET" || !url.pathname.endsWith("/api/agents")) {
+ return route.fallback();
+ }
+ return route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(
+ AGENTS.map((agent) => ({
+ ...agent,
+ workspace_id: url.searchParams.get("workspace_id") ?? "ws-mock",
+ runtime_id: "33333333-3333-4333-8333-333333333333",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "workspace",
+ permission_mode: "private",
+ invocation_targets: [],
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "claude-opus-4",
+ owner_id: OWNER_ID,
+ skills: [],
+ created_at: "2026-06-30T00:00:00Z",
+ updated_at: "2026-06-30T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+ })),
+ ),
+ });
+ });
+}
+
+/** Open the list with one filter already on, the case that widens the header most. */
+async function openFilteredList(page: Page, width: number) {
+ await page.setViewportSize({ width, height: 760 });
+ const slug = await loginAsDefault(page);
+ await mockAgents(page);
+ await page.evaluate((key) => {
+ localStorage.setItem(
+ key,
+ JSON.stringify({
+ state: {
+ scope: "all",
+ filters: { availability: [], runtimes: [], owners: [], models: ["claude-opus-4"], access: [] },
+ },
+ version: 2,
+ }),
+ );
+ }, `multica_agents_view:${slug}`);
+ await page.goto(`/${slug}/agents`, { waitUntil: "domcontentloaded" });
+ await expect(page.getByRole("button", { name: "1 filter" })).toBeVisible({ timeout: 20000 });
+}
+
+async function box(locator: Locator) {
+ const b = await locator.boundingBox();
+ if (!b) throw new Error("Could not measure a header control");
+ return b;
+}
+
+function overlaps(a: { x: number; width: number }, b: { x: number; width: number }) {
+ return a.x < b.x + b.width && b.x < a.x + a.width;
+}
+
+for (const width of [375, 390]) {
+ test(`keeps search, Reset and Display settings apart at ${width}px`, async ({ page }) => {
+ await openFilteredList(page, width);
+
+ await page.getByRole("button", { name: "Search agents" }).click();
+ const field = page.getByRole("textbox", { name: "Search agents" });
+ await field.fill("review");
+
+ const reset = page.getByRole("button", { name: "Reset" });
+ const display = page.getByRole("button", { name: "Display settings" });
+ const create = page.getByRole("button", { name: "New agent" });
+ const filter = page.getByRole("button", { name: "1 filter" });
+ const fieldBox = await box(page.getByRole("group").filter({ has: field }));
+ // The field keeps room to read a query.
+ expect(fieldBox.width).toBeGreaterThanOrEqual(96);
+ for (const other of [filter, reset, display, create]) {
+ expect(overlaps(fieldBox, await box(other))).toBe(false);
+ }
+ expect(overlaps(await box(reset), await box(display))).toBe(false);
+ const createBox = await box(create);
+ expect(createBox.x + createBox.width).toBeLessThanOrEqual(width);
+
+ // Display settings takes its own click.
+ await display.click({ timeout: 3000 });
+ await expect(page.getByRole("dialog")).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+
+ // Reset takes its own click and clears both the search and the filter.
+ await reset.click({ timeout: 3000 });
+ await expect(field).toHaveCount(0);
+ await expect(page.getByRole("button", { name: "Filter", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { level: 1, name: /All agents/ })).toBeVisible();
+ });
+}
+
+test("keeps the title beside an open search on a wide window", async ({ page }) => {
+ await openFilteredList(page, 1280);
+
+ await page.getByRole("button", { name: "Search agents" }).click();
+ await page.getByRole("textbox", { name: "Search agents" }).fill("review");
+
+ await expect(page.getByRole("heading", { level: 1, name: /All agents/ })).toBeVisible();
+ const fieldBox = await box(
+ page.getByRole("group").filter({ has: page.getByRole("textbox", { name: "Search agents" }) }),
+ );
+ expect(fieldBox.width).toBe(240);
+});
diff --git a/packages/core/agents/stores/view-store.test.ts b/packages/core/agents/stores/view-store.test.ts
index eaebe78de2..d5650902f5 100644
--- a/packages/core/agents/stores/view-store.test.ts
+++ b/packages/core/agents/stores/view-store.test.ts
@@ -26,7 +26,7 @@ beforeAll(() => {
beforeEach(() => {
localStorage.clear();
- useAgentsViewStore.setState({ scope: "mine" });
+ useAgentsViewStore.setState({ scope: "mine", search: "" });
setCurrentWorkspace(null, null);
});
@@ -257,4 +257,42 @@ describe("useAgentsViewStore", () => {
expect(useAgentsViewStore.getState().hiddenColumns).toEqual(["created", "runs"]);
});
});
+
+ describe("search (session-only)", () => {
+ it("keeps the query in the store but never persists it", async () => {
+ setCurrentWorkspace("acme", "ws_a");
+ await flush();
+ useAgentsViewStore.getState().setSearch("reviewer");
+ await flush();
+
+ expect(useAgentsViewStore.getState().search).toBe("reviewer");
+ const raw = localStorage.getItem("multica_agents_view:acme");
+ expect(raw).not.toBeNull();
+ expect(JSON.parse(raw as string).state).not.toHaveProperty("search");
+ });
+
+ it("clears the query on workspace switch", async () => {
+ localStorage.setItem(
+ "multica_agents_view:beta",
+ JSON.stringify({ state: { scope: "all" }, version: 2 }),
+ );
+ setCurrentWorkspace("acme", "ws_a");
+ await flush();
+ await flush();
+ useAgentsViewStore.getState().setSearch("reviewer");
+
+ // A workspace with saved preferences.
+ setCurrentWorkspace("beta", "ws_b");
+ await flush();
+ await flush();
+ expect(useAgentsViewStore.getState().search).toBe("");
+
+ // A workspace with nothing saved.
+ useAgentsViewStore.getState().setSearch("reviewer");
+ setCurrentWorkspace("gamma", "ws_c");
+ await flush();
+ await flush();
+ expect(useAgentsViewStore.getState().search).toBe("");
+ });
+ });
});
diff --git a/packages/core/collections/view-store.ts b/packages/core/collections/view-store.ts
index 1f5a1e2fb5..f0f6eebda0 100644
--- a/packages/core/collections/view-store.ts
+++ b/packages/core/collections/view-store.ts
@@ -11,6 +11,10 @@ import { defaultStorage } from "../platform/storage";
// Shared view preferences for the collection list pages (agents, skills,
// autopilots, projects, squads): sort, column visibility and multi-select
// filters, persisted per workspace. Row selection stays session-local.
+//
+// The list search lives here too but is never persisted: it has to survive
+// opening a row and coming back to the list, yet a query restored days later
+// would read as "my rows vanished".
export type CollectionSortDirection = "asc" | "desc";
@@ -25,6 +29,10 @@ export interface CollectionViewCore<
sortDirection: CollectionSortDirection;
hiddenColumns: Column[];
filters: Filters;
+ /** Free-text list search. Session-only: excluded from persistence and
+ * cleared on workspace switch. */
+ search: string;
+ setSearch: (search: string) => void;
/** Header click: toggles direction on the active field, otherwise switches
* to the field with its default direction. */
toggleSort: (field: Sort) => void;
@@ -100,6 +108,7 @@ export function createCollectionViewStore<
sortDirection: options.sortDefaultDirection[options.defaultSortField],
hiddenColumns: options.defaultHiddenColumns,
filters: options.emptyFilters,
+ search: "",
...extraState,
};
const extraKeys = Object.keys(extraState) as (keyof ExtraState)[];
@@ -109,6 +118,7 @@ export function createCollectionViewStore<
(set, get) =>
({
...defaults,
+ setSearch: (search: string) => set({ search } as Partial<State>),
toggleSort: (field: Sort) =>
set((state) =>
state.sortField === field
@@ -183,7 +193,9 @@ export function createCollectionViewStore<
// A workspace with nothing persisted resets to the defaults instead
// of keeping the previous workspace's in-memory state. Filters are
// deep-merged so a payload saved before a filter dimension existed
- // still gets that key's empty default.
+ // still gets that key's empty default. Every rehydrate is a workspace
+ // switch, and the search must not follow the user into another
+ // workspace.
merge: (persisted, current) => {
if (!persisted) return { ...current, ...defaults };
const p = persisted as Partial<State>;
@@ -191,6 +203,7 @@ export function createCollectionViewStore<
...current,
...p,
filters: { ...options.emptyFilters, ...(p.filters ?? {}) },
+ search: "",
};
},
},
diff --git a/packages/views/agents/components/agents-page-filter-predicate.test.ts b/packages/views/agents/components/agents-page-filter-predicate.test.ts
index f492414057..87ddab0a01 100644
--- a/packages/views/agents/components/agents-page-filter-predicate.test.ts
+++ b/packages/views/agents/components/agents-page-filter-predicate.test.ts
@@ -7,7 +7,11 @@ import {
EMPTY_AGENT_FILTERS,
type AgentListFilters,
} from "@multica/core/agents/stores";
-import { rowMatchesFilters, type AgentListRow } from "./agents-page";
+import {
+ matchesAgentSearch,
+ rowMatchesFilters,
+ type AgentListRow,
+} from "./agents-page";
function makeRow(
overrides: Partial<AgentListRow["agent"]> = {},
@@ -221,3 +225,35 @@ describe("rowMatchesFilters — access dimension", () => {
}
});
});
+
+describe("matchesAgentSearch", () => {
+ const reviewer = makeRow({
+ name: "PR Reviewer",
+ description: "Reviews pull requests before merge",
+ });
+ const chinese = makeRow({ name: "审核助手", description: "代码审查" });
+ const noDescription = makeRow({ name: "Docs Bot", description: "" });
+
+ it("matches every row while the query is empty or whitespace", () => {
+ expect(matchesAgentSearch(reviewer, "")).toBe(true);
+ expect(matchesAgentSearch(reviewer, " ")).toBe(true);
+ });
+
+ it("matches the name, ignoring case and surrounding spaces", () => {
+ expect(matchesAgentSearch(reviewer, " reviewer ")).toBe(true);
+ expect(matchesAgentSearch(reviewer, "PR REV")).toBe(true);
+ expect(matchesAgentSearch(reviewer, "deploy")).toBe(false);
+ });
+
+ it("matches the description", () => {
+ expect(matchesAgentSearch(reviewer, "pull requests")).toBe(true);
+ expect(matchesAgentSearch(noDescription, "pull")).toBe(false);
+ });
+
+ it("matches Chinese names and descriptions by pinyin", () => {
+ expect(matchesAgentSearch(chinese, "shenhe")).toBe(true);
+ expect(matchesAgentSearch(chinese, "shzs")).toBe(true);
+ expect(matchesAgentSearch(chinese, "daima")).toBe(true);
+ expect(matchesAgentSearch(chinese, "fabu")).toBe(false);
+ });
+});
diff --git a/packages/views/agents/components/agents-page.test.tsx b/packages/views/agents/components/agents-page.test.tsx
index d353539280..8d5fc9c312 100644
--- a/packages/views/agents/components/agents-page.test.tsx
+++ b/packages/views/agents/components/agents-page.test.tsx
@@ -42,6 +42,8 @@ const mocks = vi.hoisted(() => ({
models: [] as string[],
access: [] as string[],
},
+ search: "",
+ setSearch: vi.fn(),
setScope: vi.fn(),
toggleSort: vi.fn(),
setSortField: vi.fn(),
@@ -254,6 +256,7 @@ beforeEach(() => {
mocks.viewState.sortField = "lastActive";
mocks.viewState.sortDirection = "desc";
mocks.viewState.hiddenColumns = ["created"];
+ mocks.viewState.search = "";
mocks.viewState.filters = {
availability: [],
runtimes: [],
@@ -388,14 +391,6 @@ describe("AgentsPage header", () => {
).toHaveTextContent("Agents archivés");
});
- it("has no search in the header", () => {
- renderPage();
- expect(
- within(screen.getByRole("banner")).queryByRole("textbox"),
- ).not.toBeInTheDocument();
- expect(screen.queryByRole("button", { name: /search/i })).not.toBeInTheDocument();
- });
-
it("offers Reset only while a filter narrows the list", () => {
renderPage();
expect(screen.queryByRole("button", { name: "Reset" })).not.toBeInTheDocument();
@@ -421,6 +416,50 @@ describe("AgentsPage header", () => {
});
});
+describe("AgentsPage search (MUL-8490)", () => {
+ it("opens the search from an icon beside the filter and writes the query to the store", () => {
+ renderPage();
+ const header = screen.getByRole("banner");
+ expect(within(header).queryByRole("textbox")).not.toBeInTheDocument();
+
+ fireEvent.click(within(header).getByRole("button", { name: "Search agents" }));
+ const field = within(header).getByRole("textbox", { name: "Search agents" });
+ expect(field).toHaveFocus();
+
+ fireEvent.change(field, { target: { value: "beta" } });
+ expect(mocks.viewState.setSearch).toHaveBeenCalledWith("beta");
+ });
+
+ it("narrows the list by the store's query, so it is still applied on return", () => {
+ mocks.viewState.sortField = "name";
+ mocks.viewState.search = "beta";
+
+ renderPage();
+
+ expect(screen.getByRole("textbox", { name: "Search agents" })).toHaveValue("beta");
+ expect(screen.getByText("Beta Agent")).toBeInTheDocument();
+ expect(screen.queryByText("Alpha Agent")).not.toBeInTheDocument();
+ });
+
+ it("names the query when nothing matches", () => {
+ mocks.viewState.sortField = "name";
+ mocks.viewState.search = "zeta";
+
+ renderPage();
+
+ expect(screen.getByText('No agents match "zeta".')).toBeInTheDocument();
+ });
+
+ it("clears the search together with the filters on Reset", () => {
+ mocks.viewState.search = "beta";
+ renderPage();
+
+ fireEvent.click(screen.getByRole("button", { name: "Reset" }));
+ expect(mocks.viewState.clearFilters).toHaveBeenCalled();
+ expect(mocks.viewState.setSearch).toHaveBeenCalledWith("");
+ });
+});
+
describe("AgentsPage model column (GitHub #9500)", () => {
it("renders the model column by default", () => {
mocks.viewState.sortField = "name";
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index 552a5e8961..7680f35694 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -55,6 +55,7 @@ import {
CollectionPageState,
CollectionResetButton,
CollectionScopeItems,
+ CollectionSearch,
} from "../../layout/collection-page";
import {
CollectionDisplayMenu,
@@ -72,6 +73,7 @@ import {
countActiveFilterDimensions,
} from "./agent-list-toolbar";
import { useLocale, useT } from "../../i18n";
+import { matchesPinyin } from "../../editor/extensions/pinyin-match";
export interface AgentListRow {
agent: Agent;
@@ -98,6 +100,23 @@ function lastActiveDaysAgo(activity: AgentActivity | null): number | null {
return null;
}
+/**
+ * List search: the query, trimmed and case-folded, matches the name or the
+ * description, directly or by pinyin. An empty query matches every row.
+ */
+export function matchesAgentSearch(row: AgentListRow, search: string): boolean {
+ const query = search.trim().toLowerCase();
+ if (!query) return true;
+ const { name, description } = row.agent;
+ return (
+ name.toLowerCase().includes(query) ||
+ matchesPinyin(name, query) ||
+ (!!description &&
+ (description.toLowerCase().includes(query) ||
+ matchesPinyin(description, query)))
+ );
+}
+
/**
* Pure row-filter predicate: returns true if the row matches all active
* filter dimensions. Empty filter arrays are inactive (the row passes). The
@@ -409,6 +428,9 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
const toggleColumn = useAgentsViewStore((s) => s.toggleColumn);
const toggleFilter = useAgentsViewStore((s) => s.toggleFilter);
const clearFilters = useAgentsViewStore((s) => s.clearFilters);
+ // Session-only, so the query survives opening an agent and coming back.
+ const search = useAgentsViewStore((s) => s.search);
+ const setSearch = useAgentsViewStore((s) => s.setSearch);
const runtimesById = useMemo(() => {
const m = new Map<string, AgentRuntime>();
@@ -490,9 +512,11 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
isWorkspaceAdmin,
]);
- // Visible rows: filters, then sort.
+ // Visible rows: search and filters, then sort.
const rows = useMemo<AgentListRow[]>(() => {
- const filtered = scopeRows.filter((row) => rowMatchesFilters(row, filters));
+ const filtered = scopeRows.filter(
+ (row) => matchesAgentSearch(row, search) && rowMatchesFilters(row, filters),
+ );
const dir = sortDirection === "asc" ? 1 : -1;
filtered.sort((a, b) => {
@@ -521,15 +545,25 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
);
});
return filtered;
- }, [scopeRows, filters, sortField, sortDirection]);
+ }, [scopeRows, search, filters, sortField, sortDirection]);
const noMatchText = useMemo(() => {
+ const query = search.trim();
+ if (query) {
+ if (scope === "archived") {
+ return t(($) => $.no_matches.search_archived, { query });
+ }
+ if (countActiveFilterDimensions(filters) > 0) {
+ return t(($) => $.no_matches.search_active_filtered, { query });
+ }
+ return t(($) => $.no_matches.search_active, { query });
+ }
if (scope === "archived") return t(($) => $.no_matches.no_archived);
if (countActiveFilterDimensions(filters) > 0) {
return t(($) => $.no_matches.no_filter_match);
}
return t(($) => $.no_matches.title);
- }, [filters, scope, t]);
+ }, [filters, scope, search, t]);
// Straight to the manual form: a duplicate already has every field decided,
// so the method chooser would be a step with nothing to choose.
@@ -633,7 +667,12 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
};
const showEmpty = !listError && !isLoading && agents.length === 0;
- const hasNarrowing = countActiveFilterDimensions(filters) > 0;
+ const hasNarrowing =
+ countActiveFilterDimensions(filters) > 0 || search.trim() !== "";
+ const resetNarrowing = () => {
+ clearFilters();
+ setSearch("");
+ };
const scopeTitles: Record<AgentsScope, string> = {
mine: t(($) => $.page.scope_title.mine),
all: t(($) => $.page.scope_title.all),
@@ -688,7 +727,12 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
allRows={scopeRows}
members={members}
/>
- {hasNarrowing ? <CollectionResetButton onClick={clearFilters} /> : null}
+ <CollectionSearch
+ value={search}
+ onChange={setSearch}
+ label={t(($) => $.page.search)}
+ />
+ {hasNarrowing ? <CollectionResetButton onClick={resetNarrowing} /> : null}
</>
}
actions={
diff --git a/packages/views/layout/collection-page.test.tsx b/packages/views/layout/collection-page.test.tsx
index e41e1884f4..0651e86ae5 100644
--- a/packages/views/layout/collection-page.test.tsx
+++ b/packages/views/layout/collection-page.test.tsx
@@ -1,7 +1,8 @@
+import { useState } from "react";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Users } from "@multica/ui/icons";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { renderWithI18n } from "../test/i18n";
import {
CollectionCreateButton,
@@ -9,6 +10,7 @@ import {
CollectionPageHeader,
CollectionPageState,
CollectionScopeItems,
+ CollectionSearch,
} from "./collection-page";
describe("CollectionPageHeader", () => {
@@ -82,3 +84,116 @@ describe("CollectionPageState", () => {
expect(screen.getByText("Try again.").tagName).toBe("P");
});
});
+
+function SearchHarness({ initial = "" }: { initial?: string }) {
+ const [value, setValue] = useState(initial);
+ return (
+ <>
+ <CollectionSearch value={value} onChange={setValue} label="Search teams" />
+ <input aria-label="Other field" />
+ <button type="button">Elsewhere</button>
+ </>
+ );
+}
+
+/** jsdom lays nothing out; pretend the header is on screen. */
+function showPage() {
+ vi.spyOn(HTMLElement.prototype, "getClientRects").mockReturnValue(
+ [{}] as unknown as DOMRectList,
+ );
+}
+
+describe("CollectionSearch", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("starts as an icon and opens a focused field on click", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<SearchHarness />);
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Search teams" }));
+
+ const field = screen.getByRole("textbox", { name: "Search teams" });
+ expect(field).toHaveFocus();
+ expect(field).toHaveAttribute("placeholder", "Search teams");
+ });
+
+ it("closes an empty field when focus leaves and keeps a field with a query open", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<SearchHarness />);
+
+ await user.click(screen.getByRole("button", { name: "Search teams" }));
+ await user.click(screen.getByRole("button", { name: "Elsewhere" }));
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Search teams" }));
+ await user.keyboard("ops");
+ await user.click(screen.getByRole("button", { name: "Elsewhere" }));
+ expect(screen.getByRole("textbox", { name: "Search teams" })).toHaveValue("ops");
+ });
+
+ it("empties and closes on Escape", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<SearchHarness />);
+
+ await user.click(screen.getByRole("button", { name: "Search teams" }));
+ await user.keyboard("ops{Escape}");
+
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Search teams" }));
+ expect(screen.getByRole("textbox", { name: "Search teams" })).toHaveValue("");
+ });
+
+ it("empties and closes from the clear button, handing focus back to the icon", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<SearchHarness />);
+
+ await user.click(screen.getByRole("button", { name: "Search teams" }));
+ await user.keyboard("ops");
+ await user.click(screen.getByRole("button", { name: "Clear search" }));
+
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Search teams" })).toHaveFocus();
+ });
+
+ it("shows a query restored from the store without taking focus", () => {
+ renderWithI18n(<SearchHarness initial="ops" />);
+
+ const field = screen.getByRole("textbox", { name: "Search teams" });
+ expect(field).toHaveValue("ops");
+ expect(field).not.toHaveFocus();
+ });
+
+ it("opens from \"/\" on the page without typing the slash", async () => {
+ showPage();
+ const user = userEvent.setup();
+ renderWithI18n(<SearchHarness />);
+
+ await user.keyboard("/");
+
+ const field = screen.getByRole("textbox", { name: "Search teams" });
+ expect(field).toHaveFocus();
+ expect(field).toHaveValue("");
+ });
+
+ it("leaves \"/\" alone in another field, with a modifier, or on a hidden page", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<SearchHarness />);
+
+ // Hidden page: nothing laid out.
+ await user.keyboard("/");
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+
+ showPage();
+ await user.keyboard("{Control>}/{/Control}");
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+
+ const other = screen.getByRole("textbox", { name: "Other field" });
+ await user.click(other);
+ await user.keyboard("/");
+ expect(other).toHaveValue("/");
+ expect(screen.queryByRole("textbox", { name: "Search teams" })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/layout/collection-page.tsx b/packages/views/layout/collection-page.tsx
index ef7e5c44fe..4847b4e98b 100644
--- a/packages/views/layout/collection-page.tsx
+++ b/packages/views/layout/collection-page.tsx
@@ -1,11 +1,13 @@
"use client";
-import type { ComponentProps, ReactNode } from "react";
+import { useEffect, useRef, useState, type ComponentProps, type ReactNode } from "react";
import {
ChevronDown,
Filter,
Plus,
+ Search,
SlidersHorizontal,
+ X,
type IconComponent,
} from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
@@ -25,7 +27,20 @@ import {
EmptyMedia,
EmptyTitle,
} from "@multica/ui/components/ui/empty";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@multica/ui/components/ui/input-group";
import { cn } from "@multica/ui/lib/utils";
+import { useModalStore } from "@multica/core/modals";
+import {
+ createShortcutChord,
+ isEditableShortcutTarget,
+ isPortalLayerShortcutTarget,
+} from "@multica/core/shortcuts";
+import { isImeComposing } from "@multica/core/utils";
+import { ShortcutKeycaps } from "../common/shortcut-keycaps";
import { useT } from "../i18n";
import { PageHeader } from "./page-header";
@@ -45,6 +60,16 @@ interface CollectionPageHeaderProps {
className?: string;
}
+/**
+ * Below this width of the header's left group, an open search cannot share
+ * the row with the title: title, filter, field and Reset only fit together
+ * from here up. Narrower, as on a phone, the title steps aside while the
+ * search is open so every control keeps its own box (MUL-8490). The scope
+ * stays one tap away in the nav.
+ */
+const TITLE_YIELDS_TO_SEARCH =
+ "@max-[22rem]/collection-tools:group-has-[[data-collection-search=open]]/collection-tools:hidden";
+
/**
* The one header row of a list page, laid out like the issues header: the
* title names the scope and opens the scope menu, filter and search follow
@@ -67,10 +92,10 @@ export function CollectionPageHeader({
);
return (
<PageHeader className={className}>
- <div className="flex min-w-0 flex-1 items-center gap-1">
+ <div className="group/collection-tools @container/collection-tools flex min-w-0 flex-1 items-center gap-1">
{menu ? (
<DropdownMenu>
- <h1 className="flex min-w-20">
+ <h1 className={cn("flex min-w-20", TITLE_YIELDS_TO_SEARCH)}>
<DropdownMenuTrigger
render={
<Button
@@ -89,7 +114,12 @@ export function CollectionPageHeader({
</DropdownMenuContent>
</DropdownMenu>
) : (
- <h1 className="flex min-w-0 items-center gap-2 px-2 text-body font-medium">
+ <h1
+ className={cn(
+ "flex min-w-0 items-center gap-2 px-2 text-body font-medium",
+ TITLE_YIELDS_TO_SEARCH,
+ )}
+ >
{label}
</h1>
)}
@@ -192,6 +222,154 @@ export function CollectionResetButton({ onClick }: { onClick: () => void }) {
);
}
+const SEARCH_SHORTCUT = createShortcutChord("/");
+
+interface CollectionSearchProps {
+ value: string;
+ onChange: (value: string) => void;
+ /**
+ * Names the search, e.g. "Search agents": the icon's tooltip, the field's
+ * accessible name and its placeholder.
+ */
+ label: string;
+}
+
+/**
+ * List search for the header's tools: an icon until it is used, then a field.
+ * "/" opens it from anywhere on the page. Esc or the clear button empties and
+ * closes it; while it holds a query it stays open, so a query kept in the view
+ * store is still visible after coming back to the list. In a narrow
+ * `CollectionPageHeader` the title steps aside while it is open.
+ */
+export function CollectionSearch({
+ value,
+ onChange,
+ label,
+}: CollectionSearchProps) {
+ const { t } = useT("layout");
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const focusTriggerOnCloseRef = useRef(false);
+ const expanded = open || value !== "";
+
+ // Only opening focuses the field: a query restored on return must not take
+ // focus from the list, whose j/k keys need it on the page.
+ useEffect(() => {
+ if (open) inputRef.current?.focus();
+ }, [open]);
+
+ // Clearing with the button removes it; hand focus to the icon that replaces
+ // the field instead of dropping it on the body.
+ useEffect(() => {
+ if (expanded || !focusTriggerOnCloseRef.current) return;
+ focusTriggerOnCloseRef.current = false;
+ rootRef.current?.querySelector("button")?.focus();
+ }, [expanded]);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "/" || event.defaultPrevented || event.repeat) return;
+ if (event.metaKey || event.ctrlKey || event.altKey || isImeComposing(event)) return;
+ if (isEditableShortcutTarget(event.target)) return;
+ if (isPortalLayerShortcutTarget(event.target)) return;
+ if (useModalStore.getState().modal) return;
+ // A page kept mounted in a hidden tab must not take the key.
+ const root = rootRef.current;
+ if (!root || root.getClientRects().length === 0) return;
+ event.preventDefault();
+ setOpen(true);
+ inputRef.current?.focus();
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, []);
+
+ const close = () => {
+ onChange("");
+ setOpen(false);
+ };
+
+ return (
+ <div
+ ref={rootRef}
+ data-collection-search={expanded ? "open" : "closed"}
+ className={cn(
+ "flex items-center",
+ // The open field takes the room left after the title, up to 240px.
+ // Its size limits live on this flex item, never on a child: a child
+ // wider than its slot spills over Reset and the actions instead of
+ // making the title shrink (MUL-8490).
+ expanded
+ ? "min-w-0 max-w-60 flex-1 @min-[22rem]/collection-tools:min-w-32"
+ : "shrink-0",
+ )}
+ >
+ {expanded ? (
+ <InputGroup
+ className="h-7 w-full"
+ onFocus={() => setOpen(true)}
+ onBlur={(event) => {
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
+ // Switching windows blurs too but keeps the element active; the
+ // field should still be open on return.
+ if (document.activeElement === event.target) return;
+ setOpen(false);
+ }}
+ >
+ <InputGroupAddon>
+ <Search aria-hidden="true" className="size-3.5" />
+ </InputGroupAddon>
+ <InputGroupInput
+ ref={inputRef}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Escape" || isImeComposing(event)) return;
+ event.preventDefault();
+ close();
+ event.currentTarget.blur();
+ }}
+ aria-label={label}
+ aria-keyshortcuts="/"
+ placeholder={label}
+ autoComplete="off"
+ spellCheck={false}
+ className="h-full"
+ />
+ {value ? (
+ <InputGroupAddon align="inline-end">
+ <IconButton
+ size="icon-xs"
+ tooltipSide="bottom"
+ label={t(($) => $.collection.clear_search)}
+ className="text-muted-foreground"
+ onClick={() => {
+ focusTriggerOnCloseRef.current = true;
+ close();
+ }}
+ >
+ <X />
+ </IconButton>
+ </InputGroupAddon>
+ ) : null}
+ </InputGroup>
+ ) : (
+ <IconButton
+ label={label}
+ shortcut={<ShortcutKeycaps shortcut={SEARCH_SHORTCUT} decorative />}
+ tooltipSide="bottom"
+ aria-keyshortcuts="/"
+ className="shrink-0 text-muted-foreground"
+ onClick={() => setOpen(true)}
+ >
+ <Search />
+ </IconButton>
+ )}
+ </div>
+ );
+}
+
/**
* Display settings (sort, columns, layout). Pass it as the `render` of the
* popover that holds them; `icon` shows the current layout when there is one.
diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.ts
index 318fc0eb09..e203f9fa29 100644
--- a/packages/views/layout/index.ts
+++ b/packages/views/layout/index.ts
@@ -11,6 +11,7 @@ export {
CollectionPageState,
CollectionResetButton,
CollectionScopeItems,
+ CollectionSearch,
type CollectionScopeOption,
} from "./collection-page";
export {
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 0e577ac231..56faa0fc08 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -2,6 +2,7 @@
"page": {
"title": "Agents",
"new_agent": "New agent",
+ "search": "Search agents",
"show_archived": "Show archived ({{count}}) →",
"of_total": "{{visible}} of {{total}}",
"list_load_failed": "Couldn't load agents",
@@ -50,7 +51,10 @@
},
"no_matches": {
"title": "No matches",
+ "search_active": "No agents match \"{{query}}\".",
+ "search_active_filtered": "No agents match \"{{query}}\" in this filter.",
"no_archived": "No archived agents yet.",
+ "search_archived": "No archived agents match \"{{query}}\".",
"no_filter_match": "No agents match this filter.",
"search_runtime_filtered": "No agents on \"{{machine}}\" match \"{{query}}\".",
"runtime_filtered": "No agents on \"{{machine}}\"."
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index e5c3921ee2..7e4998fe37 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -164,6 +164,7 @@
"filter_count_one": "{{count}} filter",
"filter_count_other": "{{count}} filters",
"reset": "Reset",
+ "clear_search": "Clear search",
"display": "Display settings",
"selected_one": "{{count}} selected",
"selected_other": "{{count}} selected",
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index ef9bdd996e..69fdb8e12c 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -2,6 +2,7 @@
"page": {
"title": "Agents",
"new_agent": "Nouvel agent",
+ "search": "Rechercher des agents",
"show_archived": "Afficher les archivés ({{count}}) →",
"of_total": "{{visible}} sur {{total}}",
"list_load_failed": "Impossible de charger les agents",
@@ -50,7 +51,10 @@
},
"no_matches": {
"title": "Aucune correspondance",
+ "search_active": "Aucun agent ne correspond à « {{query}} ».",
+ "search_active_filtered": "Aucun agent ne correspond à « {{query}} » dans ce filtre.",
"no_archived": "Aucun agent archivé pour l'instant.",
+ "search_archived": "Aucun agent archivé ne correspond à « {{query}} ».",
"no_filter_match": "Aucun agent ne correspond à ce filtre.",
"search_runtime_filtered": "Aucun agent sur « {{machine}} » ne correspond à « {{query}} ».",
"runtime_filtered": "Aucun agent sur « {{machine}} »."
diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.json
index a7bb85896a..5ef5dda1d1 100644
--- a/packages/views/locales/fr/layout.json
+++ b/packages/views/locales/fr/layout.json
@@ -164,6 +164,7 @@
"filter_count_one": "{{count}} filtre",
"filter_count_other": "{{count}} filtres",
"reset": "Réinitialiser",
+ "clear_search": "Effacer la recherche",
"display": "Affichage",
"selected_one": "{{count}} sélectionné",
"selected_other": "{{count}} sélectionnés",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 28992f7b8b..9d908ef3d8 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -2,6 +2,7 @@
"page": {
"title": "エージェント",
"new_agent": "新規エージェント",
+ "search": "エージェントを検索",
"show_archived": "アーカイブ済みを表示 ({{count}}) →",
"of_total": "{{total}} 件中 {{visible}} 件",
"list_load_failed": "エージェントを読み込めませんでした",
@@ -49,7 +50,10 @@
},
"no_matches": {
"title": "一致する結果なし",
+ "search_active": "\"{{query}}\" に一致するエージェントがありません。",
+ "search_active_filtered": "このフィルターで \"{{query}}\" に一致するエージェントがありません。",
"no_archived": "まだアーカイブ済みのエージェントはありません。",
+ "search_archived": "\"{{query}}\" に一致するアーカイブ済みエージェントがありません。",
"no_filter_match": "このフィルターに一致するエージェントがありません。",
"search_runtime_filtered": "\"{{machine}}\" 上に \"{{query}}\" に一致するエージェントがありません。",
"runtime_filtered": "\"{{machine}}\" 上にエージェントがありません。"
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index 9480311225..7f5aa2d66a 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -158,6 +158,7 @@
"filter": "フィルター",
"filter_count_other": "{{count}} 件のフィルター",
"reset": "リセット",
+ "clear_search": "検索をクリア",
"display": "表示設定",
"selected_other": "{{count}} 件選択中",
"clear_selection": "選択を解除",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 91efbb3acb..2c9078374f 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -2,6 +2,7 @@
"page": {
"title": "에이전트",
"new_agent": "새 에이전트",
+ "search": "에이전트 검색",
"show_archived": "보관된 에이전트 보기 ({{count}}) →",
"of_total": "{{total}}개 중 {{visible}}개",
"list_load_failed": "에이전트 목록을 불러오지 못했습니다",
@@ -49,7 +50,10 @@
},
"no_matches": {
"title": "일치하는 결과 없음",
+ "search_active": "\"{{query}}\"와 일치하는 에이전트가 없습니다.",
+ "search_active_filtered": "이 필터에서 \"{{query}}\"와 일치하는 에이전트가 없습니다.",
"no_archived": "아직 보관된 에이전트가 없습니다.",
+ "search_archived": "\"{{query}}\"와 일치하는 보관된 에이전트가 없습니다.",
"no_filter_match": "이 필터와 일치하는 에이전트가 없습니다.",
"search_runtime_filtered": "\"{{machine}}\"에서 \"{{query}}\"와 일치하는 에이전트가 없습니다.",
"runtime_filtered": "\"{{machine}}\"에 에이전트가 없습니다."
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index ea1dd8b3fa..03e0b7078e 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -158,6 +158,7 @@
"filter": "필터",
"filter_count_other": "필터 {{count}}개",
"reset": "초기화",
+ "clear_search": "검색 지우기",
"display": "표시 설정",
"selected_other": "{{count}}개 선택됨",
"clear_selection": "선택 해제",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 96a86f0759..6191234887 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -2,6 +2,7 @@
"page": {
"title": "智能体",
"new_agent": "新建智能体",
+ "search": "搜索智能体",
"show_archived": "显示已归档({{count}})→",
"of_total": "{{visible}} / {{total}}",
"list_load_failed": "无法加载智能体列表",
@@ -49,7 +50,10 @@
},
"no_matches": {
"title": "无匹配项",
+ "search_active": "没有智能体匹配\"{{query}}\"。",
+ "search_active_filtered": "在该筛选下没有智能体匹配\"{{query}}\"。",
"no_archived": "还没有已归档智能体。",
+ "search_archived": "没有已归档智能体匹配\"{{query}}\"。",
"no_filter_match": "该筛选下没有匹配的智能体。",
"search_runtime_filtered": "\"{{machine}}\"上没有匹配\"{{query}}\"的智能体。",
"runtime_filtered": "\"{{machine}}\"上还没有智能体。"
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index 3305d39068..d0b74e344f 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -158,6 +158,7 @@
"filter": "筛选",
"filter_count_other": "{{count}} 个筛选",
"reset": "重置",
+ "clear_search": "清除搜索",
"display": "显示设置",
"selected_other": "已选 {{count}} 项",
"clear_selection": "清除选择",
diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.json
index 63094f4def..708d62b0ea 100644
--- a/packages/views/locales/zh-Hant/agents.json
+++ b/packages/views/locales/zh-Hant/agents.json
@@ -2,6 +2,7 @@
"page": {
"title": "AI 代理",
"new_agent": "新建 AI 代理",
+ "search": "搜尋 AI 代理",
"show_archived": "顯示已歸檔({{count}})→",
"of_total": "{{visible}} / {{total}}",
"list_load_failed": "無法載入 AI 代理列表",
@@ -49,7 +50,10 @@
},
"no_matches": {
"title": "無匹配項",
+ "search_active": "沒有 AI 代理匹配\"{{query}}\"。",
+ "search_active_filtered": "在該篩選下沒有 AI 代理匹配\"{{query}}\"。",
"no_archived": "還沒有已歸檔 AI 代理。",
+ "search_archived": "沒有已歸檔 AI 代理匹配\"{{query}}\"。",
"no_filter_match": "該篩選下沒有匹配的 AI 代理。",
"search_runtime_filtered": "\"{{machine}}\"上沒有匹配\"{{query}}\"的 AI 代理。",
"runtime_filtered": "\"{{machine}}\"上還沒有 AI 代理。"
diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.json
index 96a12a22d6..df2bc3502c 100644
--- a/packages/views/locales/zh-Hant/layout.json
+++ b/packages/views/locales/zh-Hant/layout.json
@@ -158,6 +158,7 @@
"filter": "篩選",
"filter_count_other": "{{count}} 個篩選",
"reset": "重設",
+ "clear_search": "清除搜尋",
"display": "顯示設定",
"selected_other": "已選 {{count}} 項",
"clear_selection": "清除選擇",