diff --git a/components/McpConfig.test.mjs b/components/McpConfig.test.mjs index 7c48c7857..80d1b3741 100644 --- a/components/McpConfig.test.mjs +++ b/components/McpConfig.test.mjs @@ -40,3 +40,43 @@ test("MCP management cannot mutate configuration without a selected session", as assert.equal((await screen.findByRole("switch", { name: "Enable demo" })).disabled, true); assert.equal(screen.getByRole("button", { name: "Reload MCP" }).disabled, true); }); + +function mcpServers(cwd) { + if (cwd === "/proj-a") return [{ name: "alpha", config: { type: "stdio", command: "alpha-cmd", args: [] } }]; + if (cwd === "/proj-b") return [{ name: "beta", config: { type: "stdio", command: "beta-cmd", args: [] } }]; + return []; +} + +test("MCP editor must not keep project A's server after switching to project B", async (t) => { + t.mock.method(globalThis, "fetch", async (url) => { + const cwd = new URL(String(url), "http://x").searchParams.get("cwd"); + return Response.json({ servers: mcpServers(cwd), path: cwd ? `${cwd}/.omp/mcp.json` : null }); + }); + const view = render(createElement(McpConfig, { cwd: "/proj-a" })); + await screen.findByText("alpha"); + await userEvent.setup().click(screen.getByText("alpha")); + assert.equal(screen.getByDisplayValue("alpha").tagName, "INPUT"); + view.rerender(createElement(McpConfig, { cwd: "/proj-b" })); + await screen.findByText("beta"); + // No server is selected in project B, so the editor must be blank; the + // stale name/JSON from project A must not survive the workspace switch + // (saving it would create project A's server verbatim in project B). + const nameInput = document.querySelector("input.mcp-config-input"); + assert.equal(nameInput.value, ""); + assert.equal(document.querySelector("textarea.mcp-config-input").value.includes("alpha-cmd"), false); +}); + +test("MCP editor blanks when the selected server disappears from the same workspace", async (t) => { + let servers = mcpServers("/proj-a"); + t.mock.method(globalThis, "fetch", async () => Response.json({ servers, path: "/proj-a/.omp/mcp.json" })); + render(createElement(McpConfig, { cwd: "/proj-a" })); + await screen.findByText("alpha"); + await userEvent.setup().click(screen.getByText("alpha")); + assert.equal(screen.getByDisplayValue("alpha").tagName, "INPUT"); + // The server was deleted elsewhere; a refresh must not leave its editor + // behind to be saved back into the project. + servers = []; + await userEvent.setup().click(screen.getByRole("button", { name: "Refresh live MCP status" })); + await waitFor(() => assert.equal(document.querySelector("input.mcp-config-input").value, "")); + assert.equal(document.querySelector("textarea.mcp-config-input").value.includes("alpha-cmd"), false); +}); diff --git a/components/McpConfig.tsx b/components/McpConfig.tsx index 325fa263d..b4c5cf89f 100644 --- a/components/McpConfig.tsx +++ b/components/McpConfig.tsx @@ -46,6 +46,11 @@ export function McpConfig({ cwd, sessionId, liveOnly = false }: { cwd: string | const [liveError, setLiveError] = useState(null); const [path, setPath] = useState(null); const [selected, setSelected] = useState(null); + // Mirror of `selected` for load(): the editor must be blanked when the + // selected server disappears (workspace switch or external delete), but a + // fresh "add server" draft (selected === null) survives a plain refresh. + const selectedRef = useRef(null); + const loadedCwdRef = useRef(undefined); const [name, setName] = useState(""); const [source, setSource] = useState(newServer); const [loading, setLoading] = useState(true); @@ -95,7 +100,20 @@ export function McpConfig({ cwd, sessionId, liveOnly = false }: { cwd: string | setInventory(Array.isArray(data.inventory) ? data.inventory : null); setLiveError(data.liveError ?? null); setPath(data.path ?? null); - setSelected((current) => current && data.servers?.some((server) => server.name === current) ? current : null); + // A workspace switch always blanks the editor: a name/source typed for + // the old project must never be saved into the new one. Otherwise, + // only a dropped selection blanks it — a server deleted elsewhere + // while it was selected leaves the same stale editor behind. + const workspaceChanged = loadedCwdRef.current !== undefined && loadedCwdRef.current !== cwd; + loadedCwdRef.current = cwd; + const kept = workspaceChanged ? null : (selectedRef.current && data.servers?.some((server) => server.name === selectedRef.current) ? selectedRef.current : null); + const dropped = selectedRef.current !== null && kept === null; + selectedRef.current = kept; + setSelected(kept); + if (workspaceChanged || dropped) { + setName(""); + setSource(newServer()); + } // Live status can start or reuse an OMP child and wait for /mcp list. // Keep it off the initial paint path; the static inventory is already @@ -136,6 +154,7 @@ export function McpConfig({ cwd, sessionId, liveOnly = false }: { cwd: string | }; const choose = (server: McpServer) => { + selectedRef.current = server.name; setSelected(server.name); setName(server.name); setSource(JSON.stringify(server.config, null, 2)); @@ -143,6 +162,7 @@ export function McpConfig({ cwd, sessionId, liveOnly = false }: { cwd: string | }; const add = () => { + selectedRef.current = null; setSelected(null); setName(""); setSource(newServer()); @@ -185,6 +205,7 @@ export function McpConfig({ cwd, sessionId, liveOnly = false }: { cwd: string | const response = await fetch("/api/mcp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cwd, name, previousName: selected ?? undefined, server }) }); const data = await response.json() as { error?: string }; if (!response.ok || data.error) throw new Error(data.error || `HTTP ${response.status}`); + selectedRef.current = name; setSelected(name); toast.success(t("mcpConfig.serverSaved", { name })); await load(); diff --git a/components/NotificationList.test.mjs b/components/NotificationList.test.mjs index af035848f..656aeef44 100644 --- a/components/NotificationList.test.mjs +++ b/components/NotificationList.test.mjs @@ -144,9 +144,14 @@ test("pressing Space on a row opens its session, like Enter", () => { window.addEventListener(OPEN_SESSION_EVENT, onOpen); try { const { row } = mount(); - act(() => { row().dispatchEvent(new window.KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true })); }); + const space = (target) => act(() => { target.dispatchEvent(new window.KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true })); }); + space(row()); assert.deepEqual(opened, ["n1-session"]); assert.equal(notificationHistory.get()[0].read, true); + // Space on the expandable description or the dismiss button must not open the session. + space(row().querySelector("[aria-expanded]")); + space(row().querySelector("button")); + assert.equal(opened.length, 1); } finally { window.removeEventListener(OPEN_SESSION_EVENT, onOpen); } diff --git a/components/SettingsConfig.toggles.test.mjs b/components/SettingsConfig.toggles.test.mjs new file mode 100644 index 000000000..0e2aec590 --- /dev/null +++ b/components/SettingsConfig.toggles.test.mjs @@ -0,0 +1,72 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { act, createElement } from "react"; +const { cleanup, fireEvent, render, within } = await import("@testing-library/react/pure.js"); +const { SettingsConfig } = await import("./SettingsConfig"); + +const noop = () => {}; +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20))); + +const settingsProps = { + activeTab: "system", + toolCallsDefaultCollapsed: false, onToolCallsDefaultCollapsedChange: noop, + hideToolActivity: false, onHideToolActivityChange: noop, + expandThinkingByDefault: false, onExpandThinkingByDefaultChange: noop, onHideThinkingBlockChange: noop, + providerUsageVisible: false, onProviderUsageVisibleChange: noop, + scopeNativeSelectAll: false, onScopeNativeSelectAllChange: noop, + openUrlAutomatically: false, onOpenUrlAutomaticallyChange: noop, + cwd: null, remoteHost: false, sessionId: null, + onModelsSaved: noop, onPluginsReloaded: noop, + appUpdate: null, onRefreshAppUpdate: async () => null, + onRequestAppUpdate: noop, onSelectTab: noop, onClose: noop, +}; + +/** `get` answers the settings load; each PUT waits until the test releases it. */ +function fakeSettings(t, get) { + const puts = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url, init) => { + if (String(url) !== "/api/web-settings") return Response.json({}); + if (init?.method === "PUT") { + const { promise, resolve } = Promise.withResolvers(); + puts.push({ body: init.body, release: () => resolve(Response.json({})) }); + return promise; + } + return get(); + }; + t.after(() => { + cleanup(); + globalThis.fetch = originalFetch; + }); + return puts; +} + +// Two overlapping PUTs can resolve out of order and leave the UI showing the +// opposite of the server value — for the agent-tools toggle, a security +// boundary. Each switch must take no second change until its save lands. +for (const [label, body] of [ + ["Resume running sessions after a restart", '{"autoResumeSessions":true}'], + ["Agent tools (cross-session)", '{"agentToolsEnabled":true}'], +]) { + test(`${label}: the switch takes no second change until its save lands`, async (t) => { + const puts = fakeSettings(t, () => Response.json({ autoResumeSessions: false, agentToolsEnabled: false })); + const { container } = render(createElement(SettingsConfig, settingsProps)); + await settle(); + const toggle = within(container).getByRole("switch", { name: label }); + assert.equal(toggle.disabled, false); + + fireEvent.click(toggle); + await settle(); + assert.deepEqual(puts.map((p) => p.body), [body]); + assert.equal(toggle.disabled, true, "an off click now could reach the server before the on"); + fireEvent.click(toggle); + await settle(); + assert.equal(puts.length, 1); + + puts[0].release(); + await settle(); + assert.equal(toggle.disabled, false); + assert.equal(toggle.getAttribute("aria-checked"), "true"); + }); +} diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 04af234fa..4cb3143a1 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -280,6 +280,10 @@ function SearchResultsList({ results, query, onSelect }: { results: SearchResult function AutoResumeSessionsSetting() { const { t } = useI18n(); const [enabled, setEnabled] = useState(null); + // While a save is in flight the toggle is disabled, like the notification + // toggles below: two overlapping PUTs can resolve out of order and leave + // the UI showing the opposite of the server value. + const [saving, setSaving] = useState(false); useEffect(() => { let alive = true; fetch("/api/web-settings") @@ -289,8 +293,10 @@ function AutoResumeSessionsSetting() { return () => { alive = false; }; }, []); const change = async (next: boolean) => { + if (saving) return; const previous = enabled; setEnabled(next); + setSaving(true); try { const res = await fetch("/api/web-settings", { method: "PUT", @@ -301,11 +307,13 @@ function AutoResumeSessionsSetting() { } catch (error) { setEnabled(previous); toast.error(t("settingsConfig.autoResumeSessionsSaveFailed"), error instanceof Error ? error.message : String(error)); + } finally { + setSaving(false); } }; return ( - void change(next)} /> + void change(next)} /> ); } @@ -315,6 +323,13 @@ function AutoResumeSessionsSetting() { function AgentToolsSetting() { const { t } = useI18n(); const [enabled, setEnabled] = useState(null); + // While a save is in flight the toggle is disabled, like the notification + // toggles below: two overlapping PUTs can resolve out of order and leave + // the UI showing the opposite of the server value. This one is a security + // boundary — a user who believes they turned cross-session agent tools off + // while the server left them on has silently granted agents those tools — + // so a second click must wait for the first save to settle. + const [saving, setSaving] = useState(false); useEffect(() => { let alive = true; fetch("/api/web-settings") @@ -324,8 +339,10 @@ function AgentToolsSetting() { return () => { alive = false; }; }, []); const change = async (next: boolean) => { + if (saving) return; const previous = enabled; setEnabled(next); + setSaving(true); try { const res = await fetch("/api/web-settings", { method: "PUT", @@ -336,11 +353,13 @@ function AgentToolsSetting() { } catch (error) { setEnabled(previous); toast.error(t("settingsConfig.agentToolsSaveFailed"), error instanceof Error ? error.message : String(error)); + } finally { + setSaving(false); } }; return ( - void change(next)} /> + void change(next)} /> ); } @@ -1874,7 +1893,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal )} - {panelsUnavailable ? remoteUnavailable : } + {panelsUnavailable ? remoteUnavailable : } {!cwd &&

{t("settingsConfig.selectWorkspaceForMcp")}

} )} diff --git a/components/ui/toast.click.test.mjs b/components/ui/toast.click.test.mjs index dc5bbe032..162750739 100644 --- a/components/ui/toast.click.test.mjs +++ b/components/ui/toast.click.test.mjs @@ -2,11 +2,13 @@ import "../../tests/setup-dom.mjs"; import assert from "node:assert/strict"; import test, { afterEach, before } from "node:test"; import React from "react"; +import userEvent from "@testing-library/user-event"; const { act, cleanup, render, renderHook } = await import("@testing-library/react/pure.js"); // Same specifiers as useNotifications' own imports: on Windows a relative path // can load a second toast module, whose manager the rendered provider never sees. const { ClampedDescription, ToastProvider, toast } = await import("@/components/ui/toast"); +const { setLocale } = await import("@/lib/i18n"); const { useNotifications } = await import("@/hooks/useNotifications"); const { notificationHistory } = await import("@/lib/notification-history"); @@ -232,3 +234,57 @@ test("a push the service worker showed reloads the list from the server; other m act(() => notificationHistory.clear()); } }); + +test("clamped description is keyboard-operable: Tab focuses it, Space/Enter expand it", async () => { + render(React.createElement(ClampedDescription, null, "line1\nline2\nline3\nline4")); + const description = document.querySelector("[aria-expanded]"); + assert.ok(description, "clamped description renders"); + // Stays a span, not a button: base-ui's ToastRoot skips swipe gestures + // starting on buttons (and [role="button"]), so a button here would break + // swipe-to-dismiss starting on the description. + assert.equal(description.tagName, "SPAN"); + assert.equal(description.tabIndex, 0); + assert.equal(description.getAttribute("aria-expanded"), "false"); + const user = userEvent.setup(); + await user.tab(); + assert.equal(document.activeElement, description); + await user.keyboard(" "); + assert.equal(description.getAttribute("aria-expanded"), "true"); + await user.keyboard(" "); + assert.equal(description.getAttribute("aria-expanded"), "false"); + await user.keyboard("{Enter}"); + assert.equal(description.getAttribute("aria-expanded"), "true"); +}); + +test("a swipe starting on the clamped description still dismisses the toast", () => { + const { card } = show("line1\nline2\nline3\nline4", { clamp: true }); + const description = card().querySelector("[aria-expanded]"); + assert.ok(description, "clamped description renders inside the toast"); + // A touch swipe: base-ui ignores swipes starting on interactive elements, + // so if the description ever becomes a button again this swipe never + // starts and the toast stays. + const touch = (target, type, x, y) => { + const event = new window.MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0, detail: 1 }); + Object.defineProperties(event, { pointerId: { value: 1 }, pointerType: { value: "touch" } }); + act(() => { target.dispatchEvent(event); }); + }; + touch(description, "pointerdown", 100, 50); + touch(description, "pointermove", 110, 50); + touch(description, "pointermove", 200, 52); + touch(description, "pointerup", 200, 52); + assert.equal(card()?.hasAttribute("data-ending-style") ?? true, true); +}); + +test("toast close button uses the localized dismiss label, not hardcoded English", () => { + // In English the localized value happens to equal the old hardcoded + // "Dismiss", so this test switches to Japanese: pre-fix it sees the + // hardcoded English label, post-fix the Japanese one. + act(() => { setLocale("ja"); }); + try { + render(React.createElement(ToastProvider, null)); + act(() => { toast.info("Saved"); }); + assert.equal(document.querySelector(".toast-close-button").getAttribute("aria-label"), "閉じる"); + } finally { + act(() => { setLocale("en"); }); + } +}); diff --git a/components/ui/toast.tsx b/components/ui/toast.tsx index 095458e18..d5a8a7581 100644 --- a/components/ui/toast.tsx +++ b/components/ui/toast.tsx @@ -14,6 +14,7 @@ import { Toast } from "@base-ui/react/toast"; import { AlertCircle, Check, Info, X } from "lucide-react"; import { useRef, useState } from "react"; import { useIsMobile } from "@/hooks/useIsMobile"; +import { useI18n } from "@/lib/i18n"; import type React from "react"; type ToastKind = "success" | "error" | "info"; @@ -114,9 +115,23 @@ export function clampDescriptionStyle(expanded: boolean): React.CSSProperties { */ export function ClampedDescription({ children }: { children: React.ReactNode }) { const [expanded, setExpanded] = useState(false); + // Keyboard-operable, but deliberately NOT a