feat(web): sort the workspace picker by recent use and make it searchable

The chat sidebar's workspace picker listed rows in daemon order, which says
nothing about where the user was last. It now orders by recent use and filters
as you type.

- new `features/chat/workspace-order.ts`: recency = browser-local stamp
  (`pi2-workspace-recency`, written whenever a workspace becomes active) >
  daemon `lastActiveAt` > name/id, so the order is deterministic and stable;
  search matches name, alias, cwd, directory name and id, whitespace-split
  terms all required
- `WorkspaceSwitch` becomes a filterable listbox: fixed search field on top
  (focused on open, cleared on close), scrolling row list, empty state,
  arrow/Home/End focus, Enter takes the first match, Esc returns focus to the
  trigger; rows are `role=option` + `aria-selected`
- pages/chat.tsx stamps whichever workspace is active (deep link, picker,
  default), styles and en/zh strings for the search field
- tests for ordering, matching, persistence and the keyboard/selection paths;
  the B5 UI e2e scenario follows the ARIA change and asserts the filter
This commit is contained in:
yuez committed 2026-10-30 16:41:42 +08:00
1 parent 00c81a56f4
commit 3a797ac3f7
10 files changed
+651 -54

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceInfo } from "@/lib/protocol";
import {
markWorkspaceUsed,
readWorkspaceRecency,
searchWorkspaces,
sortByRecentUse,
workspaceLabel,
WORKSPACE_RECENCY_KEY,
workspaceRecency,
} from "@/features/chat/workspace-order";
function workspace(
overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">,
): WorkspaceInfo {
return {
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: 0,
instance: null,
...overrides,
};
}
const alpha = workspace({ workspaceId: "WA", cwd: "/work/alpha", name: "Alpha", lastActiveAt: 100 });
const bravo = workspace({ workspaceId: "WB", cwd: "/srv/bravo", name: "Bravo", lastActiveAt: 300 });
const charlie = workspace({ workspaceId: "WC", cwd: "/work/charlie", name: "Charlie", lastActiveAt: 200 });
describe("workspaceLabel", () => {
it("prefers the name, falls back to the cwd basename, then the id", () => {
expect(workspaceLabel(alpha)).toBe("Alpha");
expect(workspaceLabel(workspace({ workspaceId: "W", cwd: "/deep/path/proj/", name: " " }))).toBe("proj");
expect(workspaceLabel(workspace({ workspaceId: "W9", cwd: "/", name: "" }))).toBe("W9");
});
});
describe("sortByRecentUse", () => {
it("orders by the daemon's lastActiveAt", () => {
expect(sortByRecentUse([alpha, bravo, charlie]).map((w) => w.workspaceId)).toEqual(["WB", "WC", "WA"]);
});
it("lets a browser-local stamp beat lastActiveAt", () => {
const recency = { WA: 900 };
expect(sortByRecentUse([bravo, charlie, alpha], recency).map((w) => w.workspaceId)).toEqual([
"WA",
"WB",
"WC",
]);
});
it("falls back to the name, then the id, for never-touched rows", () => {
const newer = workspace({ workspaceId: "WZ", cwd: "/work/newer", name: "Newer", lastActiveAt: 0 });
const sameNameB = workspace({ workspaceId: "W2", cwd: "/a/beta", name: "beta", lastActiveAt: 0 });
const sameNameA = workspace({ workspaceId: "W1", cwd: "/a/alpha", name: "alpha", lastActiveAt: 0 });
expect(sortByRecentUse([sameNameB, newer, sameNameA]).map((w) => w.workspaceId)).toEqual([
"W1",
"W2",
"WZ",
]);
});
it("never mutates the caller's array", () => {
const list = [alpha, bravo];
sortByRecentUse(list);
expect(list.map((w) => w.workspaceId)).toEqual(["WA", "WB"]);
});
});
describe("workspaceRecency", () => {
it("takes the later of the local stamp and the daemon activity", () => {
expect(workspaceRecency(charlie, { WC: 50 })).toBe(200);
expect(workspaceRecency(charlie, { WC: 500 })).toBe(500);
expect(workspaceRecency(workspace({ workspaceId: "WN", cwd: "/n", name: "N" }))).toBe(0);
});
});
describe("searchWorkspaces", () => {
const sorted = sortByRecentUse([alpha, bravo, charlie]);
it("returns everything in the given order when the query is blank", () => {
expect(searchWorkspaces(sorted, "").map((w) => w.workspaceId)).toEqual(["WB", "WC", "WA"]);
expect(searchWorkspaces(sorted, " ").map((w) => w.workspaceId)).toEqual(["WB", "WC", "WA"]);
});
it("matches the name case-insensitively", () => {
expect(searchWorkspaces(sorted, "CHAR").map((w) => w.workspaceId)).toEqual(["WC"]);
});
it("matches the cwd, the basename and the id", () => {
expect(searchWorkspaces(sorted, "/srv").map((w) => w.workspaceId)).toEqual(["WB"]);
expect(searchWorkspaces(sorted, "alpha").map((w) => w.workspaceId)).toEqual(["WA"]);
expect(searchWorkspaces(sorted, "wc").map((w) => w.workspaceId)).toEqual(["WC"]);
});
it("matches an alias", () => {
const aliased = workspace({ workspaceId: "WD", cwd: "/x/y", name: "Delta", alias: "delta-nvim" });
expect(searchWorkspaces([aliased], "nvim").map((w) => w.workspaceId)).toEqual(["WD"]);
});
it("requires every whitespace-separated term to hit some field", () => {
expect(searchWorkspaces(sorted, "work char").map((w) => w.workspaceId)).toEqual(["WC"]);
expect(searchWorkspaces(sorted, "work charlie extra")).toEqual([]);
});
});
describe("recency persistence", () => {
it("round-trips through localStorage and keeps the newest stamps", () => {
markWorkspaceUsed("WA", 1000);
markWorkspaceUsed("WB", 2000);
expect(readWorkspaceRecency()).toEqual({ WA: 1000, WB: 2000 });
markWorkspaceUsed("WA", 3000);
expect(readWorkspaceRecency()).toEqual({ WA: 3000, WB: 2000 });
expect(sortByRecentUse([bravo, alpha], readWorkspaceRecency()).map((w) => w.workspaceId)).toEqual([
"WA",
"WB",
]);
});
it("survives a corrupt payload", () => {
localStorage.setItem(WORKSPACE_RECENCY_KEY, "{not json");
expect(readWorkspaceRecency()).toEqual({});
localStorage.setItem(WORKSPACE_RECENCY_KEY, '{"WA": "nope", "WB": 5}');
expect(readWorkspaceRecency()).toEqual({ WB: 5 });
});
});
+148
View File
@@ -0,0 +1,148 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import type { WorkspaceInfo } from "@/lib/protocol";
import { setLanguage } from "@/lib/i18n";
import { WorkspaceSwitch } from "@/features/chat/workspace-switch";
import { WORKSPACE_RECENCY_KEY } from "@/features/chat/workspace-order";
beforeAll(async () => {
await setLanguage("en");
});
function workspace(
overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">,
): WorkspaceInfo {
return {
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: 0,
instance: null,
...overrides,
};
}
const alpha = workspace({ workspaceId: "WA", cwd: "/work/alpha", name: "Alpha", lastActiveAt: 100, sessionCount: 4 });
const bravo = workspace({ workspaceId: "WB", cwd: "/srv/bravo", name: "Bravo", lastActiveAt: 300, sessionCount: 2 });
const charlie = workspace({ workspaceId: "WC", cwd: "/work/charlie", name: "Charlie", lastActiveAt: 200 });
/** The picker with live open state, so open/close paths are exercised. */
function Harness({
workspaces = [alpha, bravo, charlie],
activeWorkspaceId = "WC",
initiallyOpen = true,
onSelect = vi.fn(),
}: {
workspaces?: WorkspaceInfo[];
activeWorkspaceId?: string | null;
initiallyOpen?: boolean;
onSelect?: (workspaceId: string) => void;
}) {
const [open, setOpen] = useState(initiallyOpen);
return (
<WorkspaceSwitch
workspaces={workspaces}
activeWorkspaceId={activeWorkspaceId}
sessionCount={7}
open={open}
onOpenChange={setOpen}
onSelect={onSelect}
/>
);
}
function rowIds(): string[] {
return screen
.getAllByRole("option")
.map((element) => element.getAttribute("data-workspace-id") ?? "");
}
describe("WorkspaceSwitch", () => {
it("lists workspaces most-recently-used first", () => {
render(<Harness />);
expect(rowIds()).toEqual(["WB", "WC", "WA"]);
// The active row is selected, and the trigger shows the live count.
expect(screen.getByRole("option", { selected: true })).toHaveAttribute("data-workspace-id", "WC");
expect(screen.getByTestId("ws-switch")).toHaveTextContent("Charlie");
expect(screen.getByTestId("ws-switch")).toHaveTextContent("7");
});
it("puts a browser-locally used workspace on top", () => {
localStorage.setItem(WORKSPACE_RECENCY_KEY, JSON.stringify({ WA: 5_000 }));
render(<Harness />);
expect(rowIds()).toEqual(["WA", "WB", "WC"]);
});
it("filters as the user types and reports no match", () => {
render(<Harness />);
const search = screen.getByTestId("ws-menu-search");
fireEvent.change(search, { target: { value: "char" } });
expect(rowIds()).toEqual(["WC"]);
fireEvent.change(search, { target: { value: "zzz" } });
expect(screen.queryAllByRole("option")).toEqual([]);
expect(screen.getByTestId("ws-menu-empty")).toHaveTextContent("zzz");
// The clear button empties the field and keeps focus in the picker.
fireEvent.click(screen.getByRole("button", { name: "Clear search" }));
expect(rowIds()).toEqual(["WB", "WC", "WA"]);
expect(search).toHaveValue("");
});
it("selects the first match with Enter from the search field", () => {
const onSelect = vi.fn();
render(<Harness onSelect={onSelect} />);
const search = screen.getByTestId("ws-menu-search");
fireEvent.change(search, { target: { value: "bravo" } });
fireEvent.keyDown(search, { key: "Enter" });
expect(onSelect).toHaveBeenCalledWith("WB");
expect(screen.queryAllByRole("option")).toEqual([]);
});
it("moves focus with the arrow keys and closes on Escape", async () => {
render(<Harness />);
const search = screen.getByTestId("ws-menu-search");
await waitFor(() => expect(search).toHaveFocus());
fireEvent.keyDown(search, { key: "ArrowDown" });
expect(screen.getByRole("option", { name: /Bravo/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "ArrowDown" });
expect(screen.getByRole("option", { name: /Charlie/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "ArrowUp" });
expect(screen.getByRole("option", { name: /Bravo/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "End" });
expect(screen.getByRole("option", { name: /Alpha/ })).toHaveFocus();
fireEvent.keyDown(search, { key: "Escape" });
expect(screen.queryAllByRole("option")).toEqual([]);
await waitFor(() => expect(screen.getByTestId("ws-switch")).toHaveFocus());
});
it("selects a clicked row and closes; clicking the active row only closes", () => {
const onSelect = vi.fn();
render(<Harness onSelect={onSelect} />);
fireEvent.click(screen.getByRole("option", { name: /Alpha/ }));
expect(onSelect).toHaveBeenCalledWith("WA");
expect(screen.queryAllByRole("option")).toEqual([]);
fireEvent.click(screen.getByTestId("ws-switch"));
fireEvent.click(screen.getByRole("option", { selected: true }));
expect(onSelect).toHaveBeenCalledTimes(1);
expect(screen.queryAllByRole("option")).toEqual([]);
});
it("disables the trigger when the daemon reports no workspaces", () => {
render(<Harness workspaces={[]} activeWorkspaceId={null} initiallyOpen={false} />);
const trigger = screen.getByTestId("ws-switch");
expect(trigger).toBeDisabled();
expect(trigger).toHaveTextContent("No workspaces yet");
});
});