fix(agents): keep context menus from switching conversations (#4804)

Right-clicking another task in Agents selected it through the same callback that opens conversations, replacing the current chat or file. Tree now marks context-menu selections (right-click, and Control-click on macOS) so the Agents view updates the menu target without navigating; ordinary clicks, keyboard activation and multi-selection are unchanged.

Co-authored-by: YannABC <9603157+YannABC@users.noreply.github.com>
This commit is contained in:
Yann
2026-11-20 20:02:25 +08:00
committed by GitHub
parent dd6d83fd2c
commit 608b292510
6 changed files with 205 additions and 30 deletions
+85
View File
@@ -0,0 +1,85 @@
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const first: AgentTask = {
id: "context-first",
title: "First conversation",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const second: AgentTask = { ...first, id: "context-second", title: "Second conversation" };
for (const active of ["conversation", "file"] as const) {
test(`an agent context menu keeps the current ${active} open`, async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toBeVisible();
await page.evaluate(
async ({ first, second }) => {
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const store = await import(storePath);
const { commands } = await import(ipcPath);
const { toolWindowService } = await import(contributionsPath);
commands.agentChanges = async () => ({ status: "ok", data: [] });
const entries: AgentEntry[] = [{ type: "agent", text: "The active conversation stays here." }];
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([
[first.id, first],
[second.id, second],
]),
entries: new Map([
[first.id, entries],
[second.id, []],
]),
composers: new Map([[first.id, { text: "Keep this unsent draft", files: [], images: [] }]]),
unread: new Set(),
docked: null,
homeOpen: false,
sessionLocation: "editor",
});
toolWindowService().show("agents", true);
store.openTask(first.id);
},
{ first, second },
);
const firstTab = page.getByRole("tab", { name: first.title, exact: true });
const fileTab = page.getByRole("tab", { name: "README.md", exact: true });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
if (active === "file") await fileTab.click();
const current = active === "file" ? fileTab : firstTab;
const target = page.getByRole("tree", { name: "Agent tasks" }).getByText(second.title, { exact: true });
await target.click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Rename…", exact: true })).toBeVisible();
await expect(current).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(current).toHaveAttribute("aria-selected", "true");
await expect
.poll(() =>
page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
return (await import(storePath)).composerDraft(id).text;
}, first.id),
)
.toBe("Keep this unsent draft");
await target.click();
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveAttribute("aria-selected", "true");
});
}
+55 -8
View File
@@ -9,6 +9,7 @@ import { promptInput } from "@/workbench/inputDialogs";
import { ContextMenuHost, dragSession, hideContextMenu } from "@/ui";
import { AgentsHeaderActions, AgentsView } from "./AgentsView";
import { SESSION_KIND, TASK_DRAG } from "./model";
import { usePlatform } from "@/platform/platformInfo";
import { archiveTask, unarchiveTask, deleteTask, dockTask, openTask, useAgents } from "./store";
import { taskActions, taskMenu, useAgentsHeaderMenu } from "./taskActions";
import styles from "./Agents.module.css";
@@ -140,6 +141,42 @@ function setup() {
}
describe("Agents selection", () => {
it.each([SESSION_KIND, "file"])("right-clicking a task keeps the current %s view open", (kind) => {
editor.active = { kind, key: "current", data: { task: "one" } };
setup();
context("two");
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
expect(selectedTasks()).toEqual(["two"]);
expect(openTask).not.toHaveBeenCalled();
fireEvent.keyDown(document, { key: "Escape" });
expect(openTask).not.toHaveBeenCalled();
});
it("preserves a multi-selection when opening its context menu without activating a task", () => {
setup();
select("one");
select("three", { shiftKey: true });
vi.mocked(openTask).mockClear();
context("two");
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
});
it("treats macOS Control-click as a context menu without opening the task", () => {
const os = usePlatform.getState().os;
usePlatform.setState({ os: "macos" });
try {
setup();
fireEvent.mouseDown(row("two"), { button: 0, ctrlKey: true });
fireEvent.contextMenu(row("two"), { button: 0, ctrlKey: true });
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
} finally {
usePlatform.setState({ os });
}
});
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
setup();
select("one");
@@ -164,14 +201,24 @@ describe("Agents selection", () => {
expect(openTask).not.toHaveBeenCalled();
});
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
it.each([
{ os: "macos", modifier: "metaKey" },
{ os: "windows", modifier: "ctrlKey" },
{ os: "linux", modifier: "ctrlKey" },
])("toggles individual tasks with $modifier on $os", ({ os, modifier }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
try {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
} finally {
usePlatform.setState({ os: previousOs });
}
});
});
+3 -2
View File
@@ -322,9 +322,10 @@ export function AgentsView() {
})
}
selected={selected}
onSelectionChange={(sel, lead) => {
onSelectionChange={(sel, lead, reason) => {
setSelected(sel);
if (!inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) showTask(lead.task.id);
if (reason !== "contextMenu" && !inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id))
showTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
onContextMenu={(n, sel, e) => {
+24 -13
View File
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { usePlatform } from "@/platform/platformInfo";
import { ToolWindowShownProvider, useServiceProviders, type ServiceTreeItem } from "@/workbench/contributions";
import { ServicesTreeView } from "./ServicesTree";
import { useServicesTree } from "./tree";
@@ -54,19 +55,29 @@ function setup() {
}
describe("Services selection → actions", () => {
it.each(["ctrlKey", "metaKey"])("%s toggles rows and Run applies to the selection", (modifier) => {
const { row, selected, toolbar } = setup();
fireEvent.mouseDown(row("one"));
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual(["one", "two"]);
expect(screen.getByTestId("detail")).toHaveTextContent("two");
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
expect(run.mock.calls).toEqual([["one"], ["two"]]);
fireEvent.mouseDown(row("one"), { [modifier]: true });
expect(selected()).toEqual(["two"]);
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual([]);
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
it.each([
{ os: "macos", modifier: "metaKey" },
{ os: "windows", modifier: "ctrlKey" },
{ os: "linux", modifier: "ctrlKey" },
])("$modifier on $os toggles rows and Run applies to the selection", ({ os, modifier }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
try {
const { row, selected, toolbar } = setup();
fireEvent.mouseDown(row("one"));
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual(["one", "two"]);
expect(screen.getByTestId("detail")).toHaveTextContent("two");
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
expect(run.mock.calls).toEqual([["one"], ["two"]]);
fireEvent.mouseDown(row("one"), { [modifier]: true });
expect(selected()).toEqual(["two"]);
fireEvent.mouseDown(row("two"), { [modifier]: true });
expect(selected()).toEqual([]);
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
} finally {
usePlatform.setState({ os: previousOs });
}
});
it("tells the provider which node became the lead selection", () => {
+29
View File
@@ -49,6 +49,35 @@ const labels = (tree: HTMLElement) =>
.queryAllByRole("treeitem")
.map((el) => el.textContent);
describe("Tree context-menu selection", () => {
it.each([
{ os: "windows", gesture: { button: 2 } },
{ os: "macos", gesture: { button: 0, ctrlKey: true } },
])("marks $os context-menu selection without changing ordinary activation", ({ os, gesture }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
try {
const selection = vi.fn();
const menu = vi.fn();
const { tree, key, onActivate } = setup({ onSelectionChange: selection, onContextMenu: menu });
const readme = within(tree).getByRole("treeitem", { name: "README.md" });
fireEvent.mouseDown(readme, gesture);
fireEvent.contextMenu(readme, gesture);
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1], "contextMenu");
expect(menu).toHaveBeenCalledWith(data[1], new Set(["README.md"]), expect.anything());
expect(onActivate).not.toHaveBeenCalled();
key("Home");
expect(selection).toHaveBeenLastCalledWith(new Set(["src"]), data[0]);
fireEvent.mouseDown(readme, { button: 0 });
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1]);
key("Enter");
expect(onActivate).toHaveBeenCalledWith(data[1], expect.anything());
} finally {
usePlatform.setState({ os: previousOs });
}
});
});
describe("Tree directory context", () => {
it("does not contribute virtual document URIs as filesystem directories", () => {
const { key } = setup({ getDirectory: () => "jdt://contents/library.jar/package" });
+9 -7
View File
@@ -104,7 +104,8 @@ export interface TreeProps<T> {
selected?: ReadonlySet<string>;
defaultSelected?: Iterable<string>;
onSelectionChange?: (selected: Set<string>, lead: T | null) => void;
/** Context-menu selection can update the action target without navigating to it. */
onSelectionChange?: (selected: Set<string>, lead: T | null, reason?: "contextMenu") => void;
multiSelect?: boolean;
/** Enter / double-click on a leaf (or on nodes `activateExpandable` accepts). */
@@ -426,22 +427,23 @@ export function Tree<T>(props: TreeProps<T>) {
};
const commitSelection = useCallback(
(next: Set<string>, leadKey: string | null) => {
(next: Set<string>, leadKey: string | null, reason?: "contextMenu") => {
if (!selectedControlled) setSelectedInner(next);
setLead(leadKey);
const leadRow = leadKey != null ? rows[indexOfKey.get(leadKey) ?? -1] : undefined;
props.onSelectionChange?.(next, leadRow?.node ?? null);
if (reason) props.onSelectionChange?.(next, leadRow?.node ?? null, reason);
else props.onSelectionChange?.(next, leadRow?.node ?? null);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[rows, indexOfKey, selectedControlled, props.onSelectionChange],
);
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single") => {
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single", reason?: "contextMenu") => {
const row = rows[i];
if (!row || row.loading) return;
if (mode === "single" || !multiSelect) {
setAnchor(row.key);
commitSelection(new Set([row.key]), row.key);
commitSelection(new Set([row.key]), row.key, reason);
} else if (mode === "toggle") {
const next = new Set(selected);
if (next.has(row.key)) next.delete(row.key);
@@ -649,8 +651,8 @@ export function Tree<T>(props: TreeProps<T>) {
};
const onRowMouseDown = (e: MouseEvent, i: number) => {
if (e.button === 2) {
if (!selected.has(rows[i]!.key)) selectIndex(i);
if (e.button === 2 || (e.button === 0 && e.ctrlKey && isMacHost())) {
if (!selected.has(rows[i]!.key)) selectIndex(i, "single", "contextMenu");
return;
}
if (e.button !== 0) return;