diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c1dad92..fb66ee5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -233,6 +233,11 @@ state (`/sessions`) and the WS snapshot — so no web code calls them. | 19 子代理状态线并入 telemetry | `telemetry.tsx`(`.telemetry--sub`,标题只留身份) | | 20 移动端顶栏胶囊 + 页面 sheet、删除底栏 | `components/shared/{page-pill,page-sheet}.tsx`、`app.css`;`.tabbar` 与 `--tabbar-h` 已删除 | +`WorkspaceSwitch`(CHG-02)的排序与搜索契约落在 `features/chat/workspace-order.ts`:行按 +**最近使用**排序(浏览器本地 `pi2-workspace-recency` 时间戳优先,其次 daemon 的 `lastActiveAt`, +再按名称 / id);顶部搜索框按名称、别名、cwd、目录名、id 过滤(空格分词,全部命中); +行是 `role=option` + `aria-selected`,Enter 取首个匹配,Esc 关闭并把焦点还给触发器。 + ### 9.1 与原型的有意偏差(数据模型所致) | 原型 | pi2d 现实 | 我们的处理 | diff --git a/scripts/e2e/ui-e2e.mjs b/scripts/e2e/ui-e2e.mjs index 03e2b4e..7c941c0 100644 --- a/scripts/e2e/ui-e2e.mjs +++ b/scripts/e2e/ui-e2e.mjs @@ -1405,7 +1405,7 @@ scenario("B5", "Chat tree: workspace picker, New session → /chat/, rename await page.goto(`${BASE}/chat?workspace=${encodeURIComponent(state.ws1)}`, { waitUntil: "domcontentloaded" }); await page.locator(".tree-pane .pane-head").waitFor({ state: "visible", timeout: 20000 }); - // v0.1.1: the workspace picker is a button + `menuitemradio` menu (no ). const wsSwitch = page.locator('[data-testid="ws-switch"]'); const wsMenu = page.locator('[data-testid="ws-menu"]'); ctx.check("workspace switch is present", (await wsSwitch.count()) === 1, { observed: await wsSwitch.count() }); @@ -1415,13 +1415,40 @@ scenario("B5", "Chat tree: workspace picker, New session → /chat/, rename .locator("[data-workspace-id]") .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); const checkedWorkspaces = await wsMenu - .locator('[data-workspace-id][aria-checked="true"]') + .locator('[data-workspace-id][aria-selected="true"]') .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); ctx.checkValue("the workspace menu marks W1 as current", checkedWorkspaces, [state.ws1]); ctx.check("workspace menu lists every workspace", options.length >= 2 && options.includes(state.ws2), { expected: [state.ws1, state.ws2], observed: options, }); + + // The picker is searchable: one row per match, and a blank query restores all. + const search = page.locator('[data-testid="ws-menu-search"]'); + await search.fill("ws2"); + const filtered = await wsMenu + .locator("[data-workspace-id]") + .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); + ctx.checkValue("the workspace search filters to W2", filtered, [state.ws2]); + await search.fill("no-such-workspace-xyz"); + const noMatch = await waitFor( + async () => ((await wsMenu.locator("[data-testid='ws-menu-empty']").count()) > 0 ? true : null), + 6000, + ); + ctx.check("the workspace search reports an empty result", Boolean(noMatch), { + observed: await wsMenu.locator("[data-workspace-id]").count(), + }); + await page.locator('[data-testid="ws-menu"] .ws-menu__input').fill(""); + const restored = await waitFor( + async () => + (await wsMenu.locator("[data-workspace-id]").count()) === options.length ? true : null, + 6000, + ); + ctx.check("clearing the search restores every workspace", Boolean(restored), { + expected: options.length, + observed: await wsMenu.locator("[data-workspace-id]").count(), + }); + await wsSwitch.click(); const menuClosed = await waitFor(async () => ((await wsMenu.isVisible()) ? null : true), 6000); ctx.check("the workspace menu closes on a second click", Boolean(menuClosed), { observed: await wsMenu.isVisible() }); diff --git a/web/src/features/chat/workspace-order.ts b/web/src/features/chat/workspace-order.ts new file mode 100644 index 0000000..a8725cb --- /dev/null +++ b/web/src/features/chat/workspace-order.ts @@ -0,0 +1,134 @@ +/** + * Workspace picker ordering and search (chat sidebar, `.ws-menu`). + * + * The picker answers "which workspace was I in last?", so it lists rows by + * **recent use**, in this precedence order: + * + * 1. a browser-local "last opened here" stamp (`pi2-workspace-recency`), written + * whenever a workspace becomes the active one in the console; + * 2. the daemon's `lastActiveAt` (mtime of the workspace's newest session file), + * which carries across devices and survives a cleared browser profile; + * 3. alphabetical, then by id — a deterministic order for never-touched rows. + * + * Ordering is intentionally *not* pinned-first: the picker is a recency control, + * the `/workspaces` page is the curated list. + */ + +import type { WorkspaceInfo } from "@/lib/protocol"; + +/** `localStorage` key holding `{ [workspaceId]: epoch ms }`. */ +export const WORKSPACE_RECENCY_KEY = "pi2-workspace-recency"; + +/** Upper bound on persisted rows; a picker never needs more history than this. */ +const RECENCY_LIMIT = 60; + +export type WorkspaceRecency = Record; + +/** Display label: name → directory basename → id. */ +export function workspaceLabel(workspace: WorkspaceInfo): string { + const name = workspace.name?.trim(); + if (name) return name; + const cwd = workspace.cwd?.replace(/\/+$/, ""); + if (cwd) { + const segments = cwd.split("/"); + const base = segments[segments.length - 1]; + if (base) return base; + } + return workspace.workspaceId; +} + +/** `localStorage` read; any failure (private mode, corrupt JSON) means "no history". */ +export function readWorkspaceRecency(): WorkspaceRecency { + try { + const raw = localStorage.getItem(WORKSPACE_RECENCY_KEY); + if (!raw) return {}; + const parsed: unknown = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; + const out: WorkspaceRecency = {}; + for (const [id, value] of Object.entries(parsed as Record)) { + if (typeof value === "number" && Number.isFinite(value)) out[id] = value; + } + return out; + } catch { + return {}; + } +} + +/** Stamp `workspaceId` as used now and persist; returns the updated map. */ +export function markWorkspaceUsed(workspaceId: string, at: number = Date.now()): WorkspaceRecency { + if (!workspaceId) return readWorkspaceRecency(); + const next: WorkspaceRecency = { ...readWorkspaceRecency(), [workspaceId]: at }; + const trimmed = Object.entries(next) + .sort((a, b) => b[1] - a[1]) + .slice(0, RECENCY_LIMIT); + const out = Object.fromEntries(trimmed); + try { + localStorage.setItem(WORKSPACE_RECENCY_KEY, JSON.stringify(out)); + } catch { + // private mode / quota: ordering still works for this render + } + return out; +} + +/** Recency score of one row: the later of local use and daemon activity. */ +export function workspaceRecency(workspace: WorkspaceInfo, recency: WorkspaceRecency = {}): number { + const local = recency[workspace.workspaceId] ?? 0; + const remote = workspace.lastActiveAt ?? 0; + return Math.max(local, remote); +} + +/** Most-recently-used first, with a stable alphabetical fallback. */ +export function compareByRecentUse( + a: WorkspaceInfo, + b: WorkspaceInfo, + recency: WorkspaceRecency = {}, +): number { + const delta = workspaceRecency(b, recency) - workspaceRecency(a, recency); + if (delta !== 0) return delta; + const byName = workspaceLabel(a).localeCompare(workspaceLabel(b), undefined, { sensitivity: "base" }); + if (byName !== 0) return byName; + return a.workspaceId.localeCompare(b.workspaceId); +} + +/** Sort a copy; the caller's array is never mutated. */ +export function sortByRecentUse( + workspaces: readonly WorkspaceInfo[], + recency: WorkspaceRecency = {}, +): WorkspaceInfo[] { + return workspaces.slice().sort((a, b) => compareByRecentUse(a, b, recency)); +} + +/** Split a raw query into lower-cased terms (empty when nothing was typed). */ +export function searchTerms(query: string): string[] { + return query + .toLowerCase() + .split(/\s+/) + .filter((term) => term.length > 0); +} + +/** Fields a workspace is searchable by, lower-cased and deduped. */ +function haystack(workspace: WorkspaceInfo): string[] { + const cwd = workspace.cwd ?? ""; + const base = workspaceLabel(workspace); + const fields = [base, workspace.name ?? "", workspace.alias ?? "", cwd, workspace.workspaceId]; + const tail = cwd.replace(/\/+$/, "").split("/").pop(); + if (tail) fields.push(tail); + return [...new Set(fields.map((field) => field.toLowerCase()).filter((field) => field.length > 0))]; +} + +/** Every term must hit some field (name, alias, cwd, basename or id). */ +export function workspaceMatches(workspace: WorkspaceInfo, terms: readonly string[]): boolean { + if (!terms.length) return true; + const fields = haystack(workspace); + return terms.every((term) => fields.some((field) => field.includes(term))); +} + +/** Filter a (already sorted) list; ordering is preserved. */ +export function searchWorkspaces( + workspaces: readonly WorkspaceInfo[], + query: string, +): WorkspaceInfo[] { + const terms = searchTerms(query); + if (!terms.length) return workspaces.slice(); + return workspaces.filter((workspace) => workspaceMatches(workspace, terms)); +} diff --git a/web/src/features/chat/workspace-switch.tsx b/web/src/features/chat/workspace-switch.tsx index b6a7e50..24586a6 100644 --- a/web/src/features/chat/workspace-switch.tsx +++ b/web/src/features/chat/workspace-switch.tsx @@ -1,9 +1,10 @@ import type { WorkspaceInfo } from "@protocol/types"; -import { useEffect, useRef } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Icon } from "@/components/icons"; import { cn } from "@/lib/utils"; +import { readWorkspaceRecency, searchWorkspaces, sortByRecentUse, workspaceLabel } from "./workspace-order"; export interface WorkspaceSwitchProps { /** Every workspace the daemon knows about (the menu lists all of them). */ @@ -18,17 +19,16 @@ export interface WorkspaceSwitchProps { className?: string; } -function workspaceLabel(workspace: WorkspaceInfo): string { - return workspace.name?.trim() || workspace.cwd || workspace.workspaceId; -} - /** * `.ws-switch` + `.ws-menu` (v0.1.1 Chat IA v3). * * The tree pane carries exactly ONE workspace, so the workspace picker is a - * button with a menu instead of a native ``: it shows the name, the + * session count and a chevron that rotates while open. + * + * The menu is a filterable listbox: rows are ordered by **recent use** (see + * `./workspace-order`), the search field at the top filters by name, alias, path + * or id, and each row is an `option` with the current workspace selected. */ export function WorkspaceSwitch({ workspaces, @@ -43,10 +43,21 @@ export function WorkspaceSwitch({ const rootRef = useRef(null); const buttonRef = useRef(null); const menuRef = useRef(null); + const listRef = useRef(null); + const inputRef = useRef(null); + + const [query, setQuery] = useState(""); + // Snapshot of "which workspace did I open last" taken when the menu opens, + // so a fresh pick is reflected the next time the user looks. + const [recency, setRecency] = useState(() => readWorkspaceRecency()); const active = workspaces.find((workspace) => workspace.workspaceId === activeWorkspaceId); const label = active ? workspaceLabel(active) : t("chat.noWorkspace"); + const ordered = useMemo(() => sortByRecentUse(workspaces, recency), [workspaces, recency]); + const rows = useMemo(() => searchWorkspaces(ordered, query), [ordered, query]); + const filtering = query.trim().length > 0; + // Click outside closes the menu. `composedPath()` (not `contains`) because a // menu item selection re-renders and detaches the clicked node first. useEffect(() => { @@ -60,37 +71,54 @@ export function WorkspaceSwitch({ return () => document.removeEventListener("pointerdown", onPointerDown, true); }, [open, onOpenChange]); - // Opening moves focus into the menu (the checked row), like a real picker. + // Opening: refresh the recency snapshot, clear the last query, focus the + // search field (there is always something to type in a searchable picker). useEffect(() => { - if (!open) return; + if (!open) { + setQuery(""); + return; + } + setRecency(readWorkspaceRecency()); const frame = requestAnimationFrame(() => { - const target = - menuRef.current?.querySelector('[aria-checked="true"]') ?? - menuRef.current?.querySelector("[data-workspace-id]"); - target?.focus({ preventScroll: true }); + inputRef.current?.focus({ preventScroll: true }); }); return () => cancelAnimationFrame(frame); }, [open]); - function moveFocus(delta: 1 | -1 | "home" | "end") { - const items = Array.from(menuRef.current?.querySelectorAll("[data-workspace-id]") ?? []); + function close(refocus = true) { + onOpenChange(false); + if (!refocus) return; + requestAnimationFrame(() => buttonRef.current?.focus({ preventScroll: true })); + } + + function options(): HTMLElement[] { + return Array.from(listRef.current?.querySelectorAll("[data-workspace-id]") ?? []); + } + + function moveFocus(move: 1 | -1 | "home" | "end") { + const items = options(); if (!items.length) return; const current = items.indexOf(document.activeElement as HTMLElement); let next = current; - if (delta === "home") next = 0; - else if (delta === "end") next = items.length - 1; - else if (delta === 1) next = current < 0 ? 0 : (current + 1) % items.length; + if (move === "home") next = 0; + else if (move === "end") next = items.length - 1; + else if (move === 1) next = current < 0 ? 0 : (current + 1) % items.length; else next = current < 0 ? items.length - 1 : (current - 1 + items.length) % items.length; items[next]?.focus({ preventScroll: true }); } + function choose(workspaceId: string) { + onOpenChange(false); + onSelect(workspaceId); + } + return (
- ); - })} + ) : null} +
+
+ {rows.map((workspace) => { + const checked = workspace.workspaceId === activeWorkspaceId; + const count = checked ? sessionCount : workspace.sessionCount; + return ( + + ); + })} + {rows.length ? null : ( +
+ {filtering + ? t("chat.workspaceSearchNoMatch", { query: query.trim() }) + : t("chat.noWorkspace")} +
+ )} +
); diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 43bc742..b0becb3 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -393,6 +393,10 @@ "chat.web.sources.other": "{n} sources", "chat.workspace": "Workspace", "chat.workspaceCrumb": "Workspace", + "chat.workspaceSearch": "Search workspaces", + "chat.workspaceSearchAria": "Search workspaces by name or path", + "chat.workspaceSearchClear": "Clear search", + "chat.workspaceSearchNoMatch": "No workspace matches “{query}”", "chat.workspaceSwitch": "Switch workspace", "chat.workspaceSwitchAria": "Workspace: {name}. Click to switch", "chat.you": "You", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index 4247ca1..9caba6f 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -393,6 +393,10 @@ "chat.web.sources.other": "{n} 个来源", "chat.workspace": "工作空间", "chat.workspaceCrumb": "工作空间", + "chat.workspaceSearch": "搜索工作空间", + "chat.workspaceSearchAria": "按名称或路径搜索工作空间", + "chat.workspaceSearchClear": "清除搜索", + "chat.workspaceSearchNoMatch": "没有匹配“{query}”的工作空间", "chat.workspaceSwitch": "切换工作空间", "chat.workspaceSwitchAria": "工作空间:{name},点击切换", "chat.you": "你", diff --git a/web/src/pages/chat.tsx b/web/src/pages/chat.tsx index f15d33a..0440073 100644 --- a/web/src/pages/chat.tsx +++ b/web/src/pages/chat.tsx @@ -51,6 +51,7 @@ import { SessionTree } from "@/features/chat/session-tree"; import { SubagentView } from "@/features/chat/subagent-view"; import { useChatStore, type TrayTab } from "@/features/chat/store"; import { Telemetry } from "@/features/chat/telemetry"; +import { markWorkspaceUsed } from "@/features/chat/workspace-order"; import "@/styles/pages/chat.css"; @@ -106,6 +107,11 @@ function ChatExperience({ sessionId }: { sessionId?: string }) { workspaces[0]?.workspaceId; const sessionsQuery = useChatSessions(workspaceId, paired); + // "Recently used" for the workspace picker: whichever workspace is active + // (deep link, picker pick, default choice) gets a browser-local stamp. + useEffect(() => { + if (workspaceId) markWorkspaceUsed(workspaceId); + }, [workspaceId]); const sessions = sessionsQuery.sessions; const sessionIds = useMemo(() => sessions.map((session) => session.sessionId), [sessions]); useChatSocket(workspaceId, sessionIds, paired); diff --git a/web/src/styles/pages/chat.css b/web/src/styles/pages/chat.css index ca9c427..2661759 100644 --- a/web/src/styles/pages/chat.css +++ b/web/src/styles/pages/chat.css @@ -158,26 +158,82 @@ right: 8px; top: 42px; z-index: 12; - padding: 4px; + display: flex; + flex-direction: column; background: var(--popover); color: var(--popover-foreground); border: 1px solid var(--border); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); max-height: min(50vh, 22rem); - overflow-y: auto; + overflow: hidden; } .ws-menu[hidden] { display: none; } -.ws-menu__label { - padding: 6px 8px 4px; - font-size: var(--fs-2xs); - font-weight: 650; - letter-spacing: 0.08em; - text-transform: uppercase; +/* 搜索框固定在顶部,只有下面的列表滚动 */ +.ws-menu__search { + display: flex; + flex: none; + align-items: center; + gap: 6px; + padding: 0 8px; + border-bottom: 1px solid var(--border-subtle); +} +.ws-menu__search svg { + flex: none; + width: 14px; + height: 14px; color: var(--faint); } +.ws-menu__input { + flex: 1; + min-width: 0; + height: 34px; + min-height: 34px; + padding: 0; + border: 0; + background: transparent; + color: var(--foreground); + font-size: var(--fs-sm); + appearance: none; + outline: none; +} +.ws-menu__input::-webkit-search-cancel-button { + appearance: none; +} +.ws-menu__input::placeholder { + color: var(--faint); +} +.ws-menu__clear { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: var(--radius-sm); + color: var(--faint); +} +.ws-menu__clear:hover { + background: var(--surface-2); + color: var(--foreground); +} +.ws-menu__clear svg { + width: 12px; + height: 12px; +} +.ws-menu__list { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 4px; +} +.ws-menu__empty { + padding: 10px 8px; + color: var(--faint); + font-size: var(--fs-sm); +} .ws-menu__item { display: flex; align-items: center; @@ -191,7 +247,8 @@ color: var(--secondary-foreground); } .ws-menu__item:hover, -.ws-menu__item:focus-visible { +.ws-menu__item:focus-visible, +.ws-menu__item:focus { background: var(--surface-2); color: var(--foreground); outline: none; diff --git a/web/tests/workspace-order.test.ts b/web/tests/workspace-order.test.ts new file mode 100644 index 0000000..dfe411e --- /dev/null +++ b/web/tests/workspace-order.test.ts @@ -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 & Pick, +): 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 }); + }); +}); diff --git a/web/tests/workspace-switch.test.tsx b/web/tests/workspace-switch.test.tsx new file mode 100644 index 0000000..d3dfc2e --- /dev/null +++ b/web/tests/workspace-switch.test.tsx @@ -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 & Pick, +): 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 ( + + ); +} + +function rowIds(): string[] { + return screen + .getAllByRole("option") + .map((element) => element.getAttribute("data-workspace-id") ?? ""); +} + +describe("WorkspaceSwitch", () => { + it("lists workspaces most-recently-used first", () => { + render(); + 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(); + expect(rowIds()).toEqual(["WA", "WB", "WC"]); + }); + + it("filters as the user types and reports no match", () => { + render(); + 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(); + 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(); + 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(); + + 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(); + const trigger = screen.getByTestId("ws-switch"); + expect(trigger).toBeDisabled(); + expect(trigger).toHaveTextContent("No workspaces yet"); + }); +});