feat(webui): add a host directory picker and refine composer controls

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-08 20:33:15 +08:00
1 parent 3865bde3fe
commit 66c8d41f66
32 files changed
+1974 -464

No files matched your search

+6 -6
View File
@@ -1088,7 +1088,7 @@ describe("App layout", () => {
expect(window.location.hash).toBe("#/new");
// Let queued browser navigation events settle before sending the first message.
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); });
expect(await screen.findByRole("button", { name: "Choose project" })).toHaveTextContent("selected-project");
expect(await screen.findByRole("button", { name: "Switch working directory" })).toHaveTextContent("selected-project");
fireEvent.change(screen.getByLabelText("Message input"), {
target: { value: "project topic" },
});
@@ -1113,7 +1113,7 @@ describe("App layout", () => {
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
expect(await screen.findByRole("button", { name: "Choose project" })).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Switch working directory" })).toBeInTheDocument();
act(() => {
sessionUpdateHandlers.forEach((handler) => handler("selected-chat", "metadata", {
project_path: "/tmp/selected-project",
@@ -1124,7 +1124,7 @@ describe("App layout", () => {
});
fireEvent.click(screen.getByRole("button", { name: "Temporary chat" }));
expect(screen.queryByRole("button", { name: "Choose project" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Switch working directory" })).not.toBeInTheDocument();
expect(screen.queryByText("Full Access")).not.toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Message input"), {
target: { value: "temporary project check" },
@@ -1161,11 +1161,11 @@ describe("App layout", () => {
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
fireEvent.click(await screen.findByRole("button", { name: "Choose project" }));
fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" }));
fireEvent.change(await screen.findByLabelText("Paste path"), {
target: { value: "C:\\missing-project" },
});
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
fireEvent.click(screen.getByRole("button", { name: "Select" }));
const message = screen.getByLabelText("Message input");
fireEvent.change(message, { target: { value: "keep this first message" } });
@@ -1173,7 +1173,7 @@ describe("App layout", () => {
await waitFor(() => expect(createChatSpy).toHaveBeenCalledTimes(1));
expect(message).toHaveValue("keep this first message");
const projectButton = screen.getByRole("button", { name: "Choose project" });
const projectButton = screen.getByRole("button", { name: "Switch working directory" });
await waitFor(() => expect(projectButton).toHaveFocus());
expect(screen.getByRole("alert")).toHaveTextContent(
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
+103 -53
View File
@@ -866,6 +866,34 @@ describe("ThreadComposer", () => {
expect(onPresetChange).toHaveBeenCalledWith("dflash");
});
it("switches the same primary button between voice and send as the draft changes", () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} onTranscribeAudio={vi.fn(async () => "voice")} />);
const input = screen.getByRole("textbox");
const action = screen.getByRole("button", { name: "Voice input" });
expect(screen.queryByRole("button", { name: "Send message" })).not.toBeInTheDocument();
fireEvent.change(input, { target: { value: " " } });
expect(screen.getByRole("button", { name: "Voice input" })).toBe(action);
fireEvent.change(input, { target: { value: "send this" } });
expect(screen.getByRole("button", { name: "Send message" })).toBe(action);
expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument();
fireEvent.click(action);
expect(onSend).toHaveBeenCalledWith("send this", undefined, undefined);
expect(screen.getByRole("button", { name: "Voice input" })).toBe(action);
});
it("uses send for an attachment-only draft and restores voice after removal", async () => {
mockBlobUrls();
const { container } = render(<ThreadComposer onSend={vi.fn()} onTranscribeAudio={vi.fn(async () => "voice")} />);
fireEvent.change(container.querySelector('input[type="file"]')!, {
target: { files: [new File(["image"], "photo.png", { type: "image/png" })] },
});
await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled());
expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Remove attachment" }));
expect(screen.getByRole("button", { name: "Voice input" })).toBeInTheDocument();
});
it("transcribes voice input into the composer without sending", async () => {
mockVoiceRecorder();
const onSend = vi.fn();
@@ -1106,10 +1134,11 @@ describe("ThreadComposer", () => {
it("ignores the delayed click emitted after a long-press voice recording", async () => {
const { getUserMedia } = mockVoiceRecorder();
const onSend = vi.fn();
const onTranscribeAudio = vi.fn(async () => "held once");
render(
<ThreadComposer
onSend={vi.fn()}
onSend={onSend}
onTranscribeAudio={onTranscribeAudio}
placeholder="Type your message..."
/>,
@@ -1131,8 +1160,9 @@ describe("ThreadComposer", () => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
});
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).not.toHaveBeenCalled();
expect(getUserMedia).toHaveBeenCalledTimes(1);
expect(onTranscribeAudio).toHaveBeenCalledTimes(1);
});
@@ -1153,7 +1183,8 @@ describe("ThreadComposer", () => {
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "draft" } });
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
fireEvent.keyDown(window, { key: "D", code: "KeyD", ctrlKey: true, shiftKey: true });
expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument();
await waitForVoiceCapture();
fireEvent.click(await screen.findByRole("button", { name: "Stop recording" }));
@@ -1342,6 +1373,19 @@ describe("ThreadComposer", () => {
expect(screen.getByRole("progressbar", { name: "Context 50%" })).toBeVisible();
});
it.each([
["restricted", "Default Permission", "File access and command execution are restricted to the current working directory."],
["full", "Full Access", "Allows file access and command execution outside the current working directory."],
] as const)("explains %s workspace access on hover", async (mode, label, explanation) => {
const user = userEvent.setup();
render(<ThreadComposer onSend={vi.fn()} workspaceScope={{ project_path: "/tmp/project", project_name: "project", access_mode: mode, restrict_to_workspace: mode === "restricted" }} onWorkspaceScopeChange={vi.fn()} />);
const access = screen.getByRole("button", { name: `Workspace access mode: ${label}` });
expect(access).not.toHaveAttribute("title");
await user.hover(access);
expect(await screen.findByRole("tooltip")).toHaveTextContent(explanation);
expect(access).toHaveAttribute("aria-describedby");
});
it("toggles workspace access directly by click and keyboard", async () => {
const user = userEvent.setup();
const onWorkspaceScopeChange = vi.fn();
@@ -1403,7 +1447,7 @@ describe("ThreadComposer", () => {
expect(shortLabel).toHaveClass("hidden");
});
it("keeps project selection as a compact composer dropdown", async () => {
it("opens project selection in a searchable dialog", async () => {
const user = userEvent.setup();
const onWorkspaceScopeChange = vi.fn();
const defaultScope = {
@@ -1428,22 +1472,18 @@ describe("ThreadComposer", () => {
/>,
);
await user.click(screen.getByRole("button", { name: "Choose project" }));
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(await screen.findByRole("button", { name: /Default workspace/ })).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
expect(screen.getByRole("dialog")).toBeInTheDocument();
const input = screen.getByLabelText("Paste path");
fireEvent.change(input, { target: { value: "relative/project" } });
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
expect(screen.getByRole("alert")).toHaveTextContent(
"Enter an absolute folder path on this machine.",
);
expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument();
expect(onWorkspaceScopeChange).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } });
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
fireEvent.click(screen.getByRole("option", { name: "/Users/test/project-alpha" }));
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/Users/test/project-alpha",
@@ -1452,10 +1492,10 @@ describe("ThreadComposer", () => {
restrict_to_workspace: false,
}));
await user.click(screen.getByRole("button", { name: "Choose project" }));
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const reopenedInput = await screen.findByLabelText("Paste path");
fireEvent.change(reopenedInput, { target: { value: "~/Pictures/Photos" } });
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
fireEvent.click(screen.getByRole("option", { name: "~/Pictures/Photos" }));
expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({
project_path: "~/Pictures/Photos",
@@ -1467,10 +1507,12 @@ describe("ThreadComposer", () => {
it.each([
["Windows", "D:\\Users\\test\\.nanobot\\workspace", "D:\\path\\to\\project"],
["Windows UNC", "\\\\server\\share\\workspace", "\\\\server\\share\\project"],
["macOS", "/Users/test/.nanobot/workspace", "/Users/name/project"],
["Linux", "/home/test/.nanobot/workspace", "/home/name/project"],
])("uses a %s path example for the project picker", async (_, projectPath, placeholder) => {
])("accepts a %s project path", async (_, projectPath, selectedPath) => {
const user = userEvent.setup();
const onWorkspaceScopeChange = vi.fn();
const defaultScope = {
project_path: projectPath,
project_name: "workspace",
@@ -1486,16 +1528,18 @@ describe("ThreadComposer", () => {
workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope}
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={vi.fn()}
onWorkspaceScopeChange={onWorkspaceScopeChange}
/>,
);
await user.click(screen.getByRole("button", { name: "Choose project" }));
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(await screen.findByLabelText("Paste path")).toHaveAttribute("placeholder", placeholder);
fireEvent.change(await screen.findByLabelText("Paste path"), { target: { value: selectedPath } });
fireEvent.keyDown(screen.getByLabelText("Paste path"), { key: "Enter" });
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath }));
});
it("slides project controls closed without offering a compact replacement", () => {
it("groups the directory and access beside attachments and hides them with workspace controls", () => {
const defaultScope = {
project_path: "/Users/test/.nanobot/workspace",
project_name: "workspace",
@@ -1515,36 +1559,38 @@ describe("ThreadComposer", () => {
/>
);
const { container, rerender } = render(composer(false));
const drawer = container.querySelector("[data-composer-workspace-drawer]");
expect(drawer).toHaveClass("inline-disclosure");
expect(drawer?.firstElementChild).toHaveClass("inline-disclosure-clip");
expect(drawer?.firstElementChild?.firstElementChild).toHaveClass("inline-disclosure-content");
expect(drawer).toHaveAttribute("data-state", "open");
expect(drawer).not.toHaveAttribute("aria-hidden");
expect(container.querySelector("[data-composer-workspace-compact]")).not.toBeInTheDocument();
const trigger = screen.getByRole("button", { name: "Switch working directory" });
expect(trigger).toHaveTextContent("workspace");
expect(trigger.closest(".thread-composer-footer-primary")).not.toBeNull();
expect(trigger.closest(".thread-composer-workspace-group")).toContainElement(screen.getByRole("button", { name: "Workspace access mode: Full Access" }));
expect(container.querySelector("[data-composer-workspace-drawer]")).not.toBeInTheDocument();
rerender(composer(true));
expect(container.querySelector("[data-composer-workspace-drawer]")).toBe(drawer);
expect(drawer).toHaveAttribute("data-state", "closed");
expect(drawer).toHaveAttribute("aria-hidden", "true");
expect(within(drawer as HTMLElement).getByRole("button", {
hidden: true,
name: "Choose project",
})).toBeDisabled();
expect(screen.queryByRole("button", { name: "Choose project" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", {
name: "Workspace access mode: Full Access",
})).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Switch working directory" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Workspace access mode: Full Access" })).not.toBeInTheDocument();
rerender(composer(false));
expect(screen.getByRole("button", { name: "Switch working directory" })).toBeEnabled();
});
expect(container.querySelector("[data-composer-workspace-drawer]")).toBe(drawer);
expect(drawer).toHaveAttribute("data-state", "open");
expect(within(drawer as HTMLElement).getByRole("button", {
name: "Choose project",
})).toBeEnabled();
it("places the directory left and access right on narrow composers, moving them into the toolbar on desktop", () => {
let width = 390;
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));
const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope} workspaceControls={{ can_change_project: true }} onWorkspaceScopeChange={vi.fn()} />);
const input = screen.getByRole("textbox");
const row = container.querySelector(".thread-composer-workspace-row")!;
const trigger = screen.getByRole("button", { name: "Switch working directory" });
expect(row).toContainElement(trigger);
expect(trigger.closest(".ml-auto")).toBeNull();
const access = screen.getByRole("button", { name: "Workspace access mode: Full Access" });
expect(row).toContainElement(access);
expect(access.closest(".ml-auto")).not.toBeNull();
width = 800;
fireEvent(window, new Event("resize"));
expect(screen.getByRole("button", { name: "Switch working directory" }).closest(".thread-composer-footer-primary")).not.toBeNull();
expect(container.querySelector("[data-composer-workspace-drawer]")).not.toBeInTheDocument();
expect(screen.getByRole("textbox")).toBe(input);
expect(screen.getAllByRole("button", { name: "Switch working directory" })).toHaveLength(1);
});
it("uses the native folder picker for project selection on native host", async () => {
@@ -1583,10 +1629,12 @@ describe("ThreadComposer", () => {
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Choose project" }));
fireEvent.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(screen.getByRole("dialog", { name: "Choose project" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Use system folder picker…" }));
await waitFor(() => expect(pickFolder).toHaveBeenCalled());
expect(screen.queryByRole("button", { name: /Default workspace/ })).not.toBeInTheDocument();
expect(screen.queryByRole("dialog", { name: "Choose project" })).not.toBeInTheDocument();
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/Users/test/native-project",
project_name: "native-project",
@@ -1628,7 +1676,7 @@ describe("ThreadComposer", () => {
/>,
);
await user.click(screen.getByRole("button", { name: "Choose project" }));
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(await screen.findByLabelText("Paste path")).toBeInTheDocument();
expect(pickFolder).not.toHaveBeenCalled();
@@ -1637,7 +1685,7 @@ describe("ThreadComposer", () => {
fireEvent.change(screen.getByLabelText("Paste path"), {
target: { value: "/srv/nas-project" },
});
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
fireEvent.click(screen.getByRole("option", { name: "/srv/nas-project" }));
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/srv/nas-project",
@@ -1673,8 +1721,10 @@ describe("ThreadComposer", () => {
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Choose project" }));
fireEvent.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(screen.getByRole("dialog", { name: "Choose project" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Use system folder picker…" }));
await waitFor(() => expect(pickFolder).toHaveBeenCalled());
expect(screen.queryByLabelText("Paste path")).not.toBeInTheDocument();
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
@@ -1706,9 +1756,9 @@ describe("ThreadComposer", () => {
/>,
);
await user.click(screen.getByRole("button", { name: "Choose project" }));
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(await screen.findByRole("button", { name: /Default workspace/ })).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
expect(screen.getByLabelText("Paste path")).toBeInTheDocument();
});
+5 -4
View File
@@ -1775,7 +1775,7 @@ describe("ThreadShell", () => {
await waitFor(() => {
expect(screen.queryByText("delete me cleanly")).not.toBeInTheDocument();
});
expect(screen.getByPlaceholderText("Ask anything...")).toBeInTheDocument();
expect(screen.getByRole("textbox")).toBeInTheDocument();
});
it("creates a chat only when the blank landing sends a first message", async () => {
@@ -2131,7 +2131,7 @@ describe("ThreadShell", () => {
const greeting = screen.getByRole("heading", { level: 1, name: HERO_GREETING_PATTERN });
expect(greeting).toHaveAttribute("data-testid", "hero-greeting");
expect(greeting).toHaveClass("select-none", "whitespace-nowrap");
expect(screen.getByPlaceholderText("Ask anything...")).toBeInTheDocument();
expect(screen.getByRole("textbox")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Write code" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Create a project plan" })).not.toBeInTheDocument();
});
@@ -2191,9 +2191,10 @@ describe("ThreadShell", () => {
expect(screen.queryByText("old answer")).not.toBeInTheDocument();
await waitFor(() =>
expect(screen.getByPlaceholderText("Ask anything...")).toBeInTheDocument(),
expect(screen.getByRole("textbox")).toBeInTheDocument(),
);
const input = screen.getByPlaceholderText("Ask anything...");
const input = screen.getByRole("textbox");
expect(input).toHaveAttribute("placeholder", "Describe what you’d like to do");
expect(input.className).toContain("min-h-[78px]");
expect(screen.queryByText("old answer")).not.toBeInTheDocument();
});
@@ -0,0 +1,55 @@
import { describe, expect, it, vi } from "vitest";
import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache";
import type { WorkspaceDirectoriesPayload } from "@/lib/types";
const directory: WorkspaceDirectoriesPayload = {
path: "/srv/workspace", parent: "/srv", entries: [], truncated: false,
host: "dev-server", platform: "Linux",
};
describe("workspace directory cache", () => {
it("reuses revisited directories while separating filters and hidden-folder modes", async () => {
const browse = vi.fn().mockResolvedValue(directory);
const cache = createWorkspaceDirectoryCache(browse);
await cache.load("/srv/workspace/", "", false, true);
expect(cache.peek("/srv/workspace", "", false, true)).toBe(directory);
await cache.load("/srv/workspace", "", false, true);
expect(browse).toHaveBeenCalledTimes(1);
await cache.load("/srv/workspace", "alpha", false, true);
await cache.load("/srv/workspace", "", true, true);
await cache.load("/srv/workspace", "", false, false);
expect(browse).toHaveBeenCalledTimes(4);
});
it("evicts least recently used results and refreshes expired directory listings", async () => {
const clock = vi.spyOn(Date, "now").mockReturnValue(1000);
try {
const browse = vi.fn().mockResolvedValue(directory);
const cache = createWorkspaceDirectoryCache(browse);
for (let i = 0; i < 64; i++) await cache.load(`/srv/${i}`, "", false);
expect(cache.peek("/srv/0", "", false)).toBe(directory);
await cache.load("/srv/64", "", false);
expect(cache.peek("/srv/1", "", false)).toBeUndefined();
expect(cache.peek("/srv/0", "", false)).toBe(directory);
clock.mockReturnValue(31_001);
expect(cache.peek("/srv/0", "", false)).toBeUndefined();
await cache.load("/srv/0", "", false);
expect(browse).toHaveBeenCalledTimes(66);
} finally { clock.mockRestore(); }
});
it("shares simultaneous requests and lets failed requests be retried", async () => {
let reject!: (reason: Error) => void;
const browse = vi.fn().mockImplementationOnce(() => new Promise<WorkspaceDirectoriesPayload>((_resolve, fail) => { reject = fail; }))
.mockResolvedValue(directory);
const cache = createWorkspaceDirectoryCache(browse);
const first = cache.load("/srv/workspace", "", false);
expect(cache.load("/srv/workspace", "", false)).toBe(first);
const failed = expect(first).rejects.toThrow("permission denied");
reject(new Error("permission denied"));
await failed;
expect(cache.peek("/srv/workspace", "", false)).toBeUndefined();
await expect(cache.load("/srv/workspace", "", false)).resolves.toBe(directory);
expect(browse).toHaveBeenCalledTimes(2);
});
});
+318
View File
@@ -0,0 +1,318 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
import type { WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
const scope = { project_path: "/srv/workspace", access_mode: "restricted" as const };
const catalog: WorkspacesPayload = {
schema_version: 1,
default_access_mode: "default",
default_scope: scope,
recent_projects: [{ name: "alpha", path: "/srv/alpha" }, { name: "beta", path: "/srv/beta" }],
host: { name: "dev-server", platform: "Linux" },
controls: { can_change_project: true, can_use_full_access: false, can_browse_directories: true },
};
const directory: WorkspaceDirectoriesPayload = {
path: "/srv/workspace", parent: "/srv", entries: [{ name: "alpha", path: "/srv/workspace/alpha" }],
truncated: false, host: "dev-server", platform: "Linux",
};
describe("Workspace project picker", () => {
it("keeps saved locations separate from directory filtering", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn().mockResolvedValue(directory);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const shortcut = await screen.findByRole("button", { name: "/srv/beta" });
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "al");
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "al", false, true));
expect(shortcut).toBeInTheDocument();
expect(screen.getAllByRole("listbox")).toHaveLength(1);
onBrowse.mockResolvedValue({ ...directory, path: "/srv/beta", entries: [] });
await user.click(shortcut);
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
expect(screen.getAllByRole("listbox")).toHaveLength(1);
expect(screen.getByRole("combobox")).toHaveValue("/srv/beta/");
expect(onChange).not.toHaveBeenCalled();
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "oth");
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/beta", "oth", false, true));
expect(shortcut).toBeInTheDocument();
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/beta", access_mode: "restricted" }));
});
it("shows cached directories without loading again when revisiting or reopening", async () => {
const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
expect(onBrowse).toHaveBeenCalledTimes(2);
await user.click(screen.getByRole("button", { name: "/srv/workspace" }));
expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toBeInTheDocument();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(onBrowse).toHaveBeenCalledTimes(2);
await user.keyboard("{Escape}");
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toBeInTheDocument();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(onBrowse).toHaveBeenCalledTimes(2);
});
it("scrolls deep directory columns horizontally with Shift and preserves ordinary wheel events", async () => {
const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
const viewport = screen.getAllByRole("listbox")[0].closest("[data-workspace-columns]") as HTMLElement;
Object.defineProperties(viewport, { clientWidth: { value: 300 }, scrollWidth: { value: 600 } });
viewport.scrollLeft = 0;
const wheel = (options: WheelEventInit) => fireEvent(viewport, Object.assign(
new Event("wheel", { bubbles: true, cancelable: true }),
{ deltaX: 0, deltaY: 0, deltaMode: 0, shiftKey: false, ctrlKey: false, metaKey: false, ...options },
));
expect(wheel({ deltaY: 120, shiftKey: true })).toBe(false);
expect(viewport.scrollLeft).toBe(120);
expect(wheel({ deltaY: -2, deltaMode: 1, shiftKey: true })).toBe(false);
expect(viewport.scrollLeft).toBe(88);
wheel({ deltaY: 120 });
expect(viewport.scrollLeft).toBe(88);
wheel({ deltaY: 120, shiftKey: true, ctrlKey: true });
expect(viewport.scrollLeft).toBe(88);
});
it("browses folders immediately, toggles hidden entries, and selects the resolved directory", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn().mockResolvedValue(directory);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", false, true);
await user.click(screen.getByRole("switch", { name: "Show hidden folders" }));
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", true, true));
onBrowse.mockResolvedValue({ ...directory, path: "/srv/workspace/alpha", entries: [] });
await user.click(screen.getByRole("option", { name: "/srv/workspace/alpha" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/workspace/alpha" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Switch working directory" })).not.toHaveFocus());
});
it("keeps invalid paths editable and validates the project before closing", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onResolve = vi.fn().mockRejectedValueOnce(new Error("project_path must be an existing directory"))
.mockResolvedValueOnce({ name: "alpha", path: "/srv/alpha" });
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ ...catalog.controls, can_resolve_project: true }} onResolveProject={onResolve} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/missing");
await user.keyboard("{Enter}");
expect(await screen.findByRole("alert")).toHaveTextContent("existing directory");
expect(screen.getByRole("combobox")).toHaveValue("/srv/missing");
await waitFor(() => expect(screen.getByRole("combobox")).toHaveFocus());
expect(onChange).not.toHaveBeenCalled();
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/alpha");
await user.keyboard("{Enter}");
await waitFor(() => expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" })));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("uses manual paths without new requests on a host missing optional capabilities", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn();
const onResolve = vi.fn();
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ can_change_project: true, can_use_full_access: false }} onBrowseDirectories={onBrowse} onResolveProject={onResolve} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(screen.queryByRole("option", { name: "Browse folders…" })).not.toBeInTheDocument();
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/alpha");
await user.keyboard("{Enter}");
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" }));
expect(onBrowse).not.toHaveBeenCalled();
expect(onResolve).not.toHaveBeenCalled();
});
it("does not apply a directory response after closing the dialog", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
let finish!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn(() => new Promise<WorkspaceDirectoriesPayload>((resolve) => { finish = resolve; }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await waitFor(() => expect(onBrowse).toHaveBeenCalled());
await user.keyboard("{Escape}");
finish(directory);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(onChange).not.toHaveBeenCalled();
});
it("pins folders without selecting and keeps favorites ahead of recent projects", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const favorites = [{ name: "beta", path: "/srv/beta" }];
const onFavorite = vi.fn().mockResolvedValueOnce(favorites).mockRejectedValueOnce(new Error("disk full")).mockResolvedValueOnce([]);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })} onFavoriteProject={onFavorite} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
async function openFavoriteMenu(name: string) {
fireEvent.contextMenu(await screen.findByRole("button", { name: "/srv/beta" }), { clientX: 100, clientY: 100 });
return screen.findByRole("menuitem", { name });
}
await user.click(await openFavoriteMenu("Pin beta"));
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", true);
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(screen.getByRole("navigation")).toHaveTextContent("Favorites/srv/betaRecent projects");
expect(screen.getByRole("combobox")).toHaveFocus();
expect(onChange).not.toHaveBeenCalled();
await user.click(await openFavoriteMenu("Unpin beta"));
expect(await screen.findByRole("alert")).toHaveTextContent("disk full");
await user.click(await openFavoriteMenu("Unpin beta"));
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(await openFavoriteMenu("Pin beta")).toBeInTheDocument();
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", false);
expect(onChange).not.toHaveBeenCalled();
});
it.each([
["/srv/al", "/srv/alpha", "/srv/alpha/"],
["C:\\Projects\\al", "C:\\Projects\\alpha", "C:\\Projects\\alpha\\"],
["\\\\server\\share\\al", "\\\\server\\share\\alpha", "\\\\server\\share\\alpha\\"],
])("completes paths in the same input: %s", async (draft, completed, expected) => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: completed, partial: path === draft, entries: path === draft ? [{ name: "alpha", path: completed }] : [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
await user.type(input, draft);
await screen.findByRole("option", { name: completed });
await user.keyboard("{Tab}");
expect(input).toHaveValue(expected);
expect(input).toHaveFocus();
expect(screen.getByRole("combobox")).toBe(input);
expect(onChange).not.toHaveBeenCalled();
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
expect(fireEvent.keyDown(input, { key: "Tab", shiftKey: true })).toBe(true);
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: completed }));
});
it("uses one list for partial paths and keyboard completion", async () => {
const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path === "/srv/al" ? "/srv" : path, parent: "/srv", partial: path === "/srv/al", entries: path === "/srv/al" ? [{ name: "alpha", path: "/srv/alpha" }, { name: "alpine", path: "/srv/alpine" }] : [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
await user.type(input, "/srv/al");
await screen.findByRole("option", { name: "/srv/alpine" });
expect(screen.getByRole("button", { name: "Select" })).toBeDisabled();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
await user.keyboard("{ArrowDown}{Tab}");
expect(input).toHaveValue("/srv/alpine/");
expect(screen.getAllByRole("combobox")).toHaveLength(1);
expect(screen.getAllByRole("listbox")).toHaveLength(2);
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
expect(input).toHaveFocus();
});
it("ignores a Tab completion after the user changes the path", async () => {
const user = userEvent.setup();
let finish!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn((_path: string, query: string) => query ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
await user.type(input, "/srv/al");
await user.keyboard("{Tab}");
await user.type(input, "ternative");
finish({ ...directory, entries: [{ name: "alpha", path: "/srv/alpha" }] });
await waitFor(() => expect(input).toHaveValue("/srv/alternative"));
expect(input).toHaveFocus();
});
it("updates folders while typing and ignores results from older paths", async () => {
const user = userEvent.setup();
let finishOld!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn((path: string) => path === "/srv/old/" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finishOld = resolve; }) : Promise.resolve({ ...directory, path, entries: [{ name: path === "/srv/new/" ? "new-child" : "initial-child", path: `${path.replace(/\/$/, "")}/child` }] }));
const onChange = vi.fn();
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/child" });
const input = screen.getByRole("combobox");
await user.clear(input);
await user.type(input, "/srv/old/");
expect(screen.queryByRole("option", { name: "/srv/workspace/child" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Select" })).toBeDisabled();
await waitFor(() => expect(onBrowse).toHaveBeenCalledWith("/srv/old/", "", false, true));
await user.clear(input);
await user.type(input, "/srv/new/");
await screen.findByRole("option", { name: "/srv/new/child" });
finishOld({ ...directory, path: "/srv/old/", entries: [{ name: "stale-child", path: "/srv/old/child" }] });
await waitFor(() => expect(screen.queryByRole("option", { name: "/srv/old/child" })).not.toBeInTheDocument());
expect(screen.getByRole("combobox")).toBe(input);
expect(input).toHaveFocus();
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/new/" }));
});
it("filters the current directory by name without a second browser view", async () => {
const user = userEvent.setup();
const onBrowse = vi.fn().mockResolvedValue(directory);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
const input = screen.getByRole("combobox");
await user.clear(input);
await user.type(input, "alp");
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "alp", false, true));
expect(screen.getAllByRole("combobox")).toHaveLength(1);
expect(screen.queryByText("Browse folders…")).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText("Filter folders…")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Close" })).not.toBeInTheDocument();
});
it("keeps ancestor columns and replaces descendants when another folder is opened", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn((rawPath: string, _query: string, showHidden: boolean) => {
const path = rawPath.replace(/\/$/, "");
const names = path === scope.project_path ? ["alpha", "beta"] : path.endsWith("/alpha") ? ["child"] : path.endsWith("/beta") ? ["other"] : [];
if (showHidden) names.push(".hidden");
return Promise.resolve({ ...directory, path, entries: names.map(name => ({ name, path: `${path}/${name}` })) });
});
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" }));
expect(screen.getAllByRole("listbox")).toHaveLength(3);
expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toHaveAttribute("aria-selected", "true");
expect(onChange).not.toHaveBeenCalled();
expect(onBrowse.mock.calls.filter(call => call[0].replace(/\/$/, "") === scope.project_path)).toHaveLength(1);
await user.click(screen.getByRole("switch", { name: "Show hidden folders" }));
await screen.findByRole("option", { name: "/srv/workspace/.hidden" });
await screen.findByRole("option", { name: "/srv/workspace/alpha/.hidden" });
await screen.findByRole("option", { name: "/srv/workspace/alpha/child/.hidden" });
await user.click(screen.getByRole("option", { name: "/srv/workspace/beta" }));
await screen.findByRole("option", { name: "/srv/workspace/beta/other" });
expect(screen.getAllByRole("listbox")).toHaveLength(2);
expect(screen.queryByRole("option", { name: "/srv/workspace/alpha/child" })).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/workspace/beta" }));
});
});