diff --git a/components/McpConfig.test.mjs b/components/McpConfig.test.mjs index d513cf3ac..2b1ecf565 100644 --- a/components/McpConfig.test.mjs +++ b/components/McpConfig.test.mjs @@ -41,3 +41,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 5de2cc16c..9d8f09767 100644 --- a/components/McpConfig.tsx +++ b/components/McpConfig.tsx @@ -44,6 +44,11 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: 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); @@ -89,7 +94,20 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: 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 @@ -130,6 +148,7 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: }; const choose = (server: McpServer) => { + selectedRef.current = server.name; setSelected(server.name); setName(server.name); setSource(JSON.stringify(server.config, null, 2)); @@ -137,6 +156,7 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: }; const add = () => { + selectedRef.current = null; setSelected(null); setName(""); setSource(newServer()); @@ -179,6 +199,7 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: 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 7c5050bcd..44e609a95 100644 --- a/components/NotificationList.test.mjs +++ b/components/NotificationList.test.mjs @@ -69,7 +69,7 @@ test("short, mostly vertical, curved-into-vertical, mouse, and button-started dr drag(description(), [[100, 50], [180, 52], [140, 52]]); drag(description(), [[200, 50], [80, 52], [140, 52]]); drag(description(), [[100, 50], [150, 51], [200, 52]], { pointerType: "mouse" }); - drag(row().querySelector("button"), [[100, 50], [150, 51], [200, 52]]); + drag(row().querySelector("button[aria-label='Dismiss notification']"), [[100, 50], [150, 51], [200, 52]]); await settle(); assert.equal(notificationHistory.get().length, 1); assert.equal(row().style.transform, ""); @@ -122,10 +122,10 @@ test("clicking or pressing Enter on a row marks it read and opens its session, b window.getSelection().selectAllChildren(row().querySelector(".display-serif")); act(() => row().querySelector(".display-serif").click()); window.getSelection().removeAllRanges(); - enter(row().querySelector("button")); + enter(row().querySelector("button[aria-label='Dismiss notification']")); assert.equal(opened.length, 2); // The dismiss button removes the entry without opening it. - act(() => row().querySelector("button").click()); + act(() => row().querySelector("button[aria-label='Dismiss notification']").click()); assert.equal(opened.length, 2); assert.equal(notificationHistory.get().length, 0); } finally { @@ -153,3 +153,23 @@ test("an entry without a session is not focusable or clickable", () => { assert.equal(row.hasAttribute("tabindex"), false); assert.equal(row.style.cursor, ""); }); + +test("pressing Space on a row marks it read and opens its session, but not from its controls", () => { + const opened = []; + const onOpen = (event) => opened.push(event.detail); + window.addEventListener(OPEN_SESSION_EVENT, onOpen); + try { + const { row } = mount(); + 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. + const description = row().querySelector("[aria-expanded]"); + space(description); + space(row().querySelector("button[aria-label='Dismiss notification']")); + assert.equal(opened.length, 1); + } finally { + window.removeEventListener(OPEN_SESSION_EVENT, onOpen); + } +}); diff --git a/components/NotificationList.tsx b/components/NotificationList.tsx index 82881b496..9fc4958e3 100644 --- a/components/NotificationList.tsx +++ b/components/NotificationList.tsx @@ -104,7 +104,7 @@ function NotificationRow({ entry }: { entry: NotificationHistoryEntry }) { tabIndex={open ? 0 : undefined} className={open ? "ui-focus-ring" : undefined} onKeyDown={open ? (event) => { - if (event.key !== "Enter" || event.target !== event.currentTarget) return; + if ((event.key !== "Enter" && event.key !== " ") || event.target !== event.currentTarget) return; event.preventDefault(); open(); } : undefined} @@ -114,7 +114,10 @@ function NotificationRow({ entry }: { entry: NotificationHistoryEntry }) { // leftover (a pen lifted outside the row) is simply replaced. if (drag.current?.claimed || leaving || event.pointerType === "mouse" || event.button !== 0) return; drag.current = null; - if (event.target instanceof Element && event.target.closest("button, a, input, textarea, select")) return; + // The expandable description is text, not a control: a swipe starting + // on it dismisses the row exactly as it did when it was a span. Only + // real controls (e.g. the dismiss button) opt out of starting a drag. + if (event.target instanceof Element && event.target.closest("button:not([aria-expanded]), a, input, textarea, select")) return; drag.current = { id: event.pointerId, x: event.clientX, y: event.clientY, claimed: false, tracker: createSwipeTracker(event.clientX) }; }} onPointerMove={(event) => { diff --git a/components/SettingsConfig.toggles.test.mjs b/components/SettingsConfig.toggles.test.mjs new file mode 100644 index 000000000..0c9f40a65 --- /dev/null +++ b/components/SettingsConfig.toggles.test.mjs @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { readFile } from "node:fs/promises"; + +// AutoResumeSessionsSetting and AgentToolsSetting are module-private and +// SettingsConfig has no render harness, so this test asserts the guard in +// source, following the AppShell.test.mjs precedent. It fails pre-fix: the +// toggles rendered with disabled={enabled === null} only, so two overlapping +// PUTs could resolve out of order and leave the UI showing the opposite of +// the server value (for the agent-tools toggle, a security boundary). +const source = await readFile(new URL("./SettingsConfig.tsx", import.meta.url), "utf8"); + +function bodyOf(name) { + const start = source.indexOf(`function ${name}()`); + assert.notEqual(start, -1, `${name} must exist`); + const end = source.indexOf("\nfunction ", start + 1); + return source.slice(start, end === -1 ? undefined : end); +} + +for (const name of ["AutoResumeSessionsSetting", "AgentToolsSetting"]) { + test(`${name} disables its toggle while a save is in flight`, () => { + const body = bodyOf(name); + assert.match(body, /const \[saving, setSaving\] = useState\(false\)/); + assert.match(body, /if \(saving\) return;/); + assert.match(body, /setSaving\(true\)/); + assert.match(body, /disabled=\{enabled === null \|\| saving\}/); + assert.match(body, /finally \{\s*setSaving\(false\);/); + }); +} diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 77f7240db..8d333b9ce 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -284,6 +284,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") @@ -293,8 +297,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", @@ -305,11 +311,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)} /> ); } @@ -319,6 +327,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") @@ -328,8 +343,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", @@ -340,11 +357,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)} /> ); } @@ -1694,7 +1713,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal )} - + {!cwd &&

{t("settingsConfig.selectWorkspaceForMcp")}

} )} diff --git a/components/ui/toast.click.test.mjs b/components/ui/toast.click.test.mjs index 861808e7f..2a458ae9f 100644 --- a/components/ui/toast.click.test.mjs +++ b/components/ui/toast.click.test.mjs @@ -3,12 +3,14 @@ import assert from "node:assert/strict"; import test, { afterEach, before } from "node:test"; import React from "react"; import { act, cleanup, render, renderHook } from "@testing-library/react/pure.js"; +import userEvent from "@testing-library/user-event"; import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tryNative: false, tsconfigPaths: true }); // 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 jiti.import("@/components/ui/toast"); +const { setLocale } = await jiti.import("@/lib/i18n"); const { useNotifications } = await jiti.import("@/hooks/useNotifications"); const { notificationHistory } = await jiti.import("@/lib/notification-history"); @@ -175,3 +177,33 @@ test("a push the service worker showed reloads the list from the server; other m act(() => notificationHistory.clear()); } }); + +test("clamped description is a keyboard-operable button: Tab focuses it, Space/Enter expand it", async () => { + render(React.createElement(ClampedDescription, null, "line1\nline2\nline3\nline4")); + const button = document.querySelector("button[aria-expanded]"); + assert.ok(button, "clamped description renders as a focusable button"); + assert.equal(button.getAttribute("aria-expanded"), "false"); + const user = userEvent.setup(); + await user.tab(); + assert.equal(document.activeElement, button); + await user.keyboard(" "); + assert.equal(button.getAttribute("aria-expanded"), "true"); + await user.keyboard(" "); + assert.equal(button.getAttribute("aria-expanded"), "false"); + await user.keyboard("{Enter}"); + assert.equal(button.getAttribute("aria-expanded"), "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..bf8258670 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,15 +115,30 @@ export function clampDescriptionStyle(expanded: boolean): React.CSSProperties { */ export function ClampedDescription({ children }: { children: React.ReactNode }) { const [expanded, setExpanded] = useState(false); + // A real button, not a clickable span: keyboard-only users must be able to + // focus and expand it with Enter/Space, like any other control. It keeps + // aria-expanded so the toast card's and notification row's click guards + // (which skip [aria-expanded] targets) still treat it as expandable text + // rather than the row/card action. return ( - setExpanded((v) => !v)} aria-expanded={expanded} title={expanded ? undefined : "Click to expand"} - style={clampDescriptionStyle(expanded)} + style={{ + ...clampDescriptionStyle(expanded), + width: "100%", + padding: 0, + border: 0, + background: "transparent", + color: "inherit", + font: "inherit", + textAlign: "left", + }} > {children} - + ); } @@ -196,6 +212,8 @@ export function createSwipeTracker(startX: number): SwipeTracker { } function Toaster() { + // Aliased: the toasts.map() below binds each toast item as `t`. + const { t: tr } = useI18n(); const { toasts } = Toast.useToastManager(); const isMobile = useIsMobile(); const clickGuard = useDragClickGuard(); @@ -310,7 +328,7 @@ function Toaster() { diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 1ad043f14..1492e9512 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -99,6 +99,7 @@ "appShell.notificationsEmpty": "No recent notifications", "appShell.notificationsClear": "Clear all", "appShell.notificationDismiss": "Dismiss notification", + "toast.dismiss": "Dismiss", "appShell.notificationsMarkRead": "Mark all as read", "appShell.notificationUnread": "Unread", "appShell.notificationsUnreadCount": "{count} unread", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index af23a236a..5dc59ed1b 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -99,6 +99,7 @@ "appShell.notificationsEmpty": "最近の通知はありません", "appShell.notificationsClear": "すべてクリア", "appShell.notificationDismiss": "通知を閉じる", + "toast.dismiss": "閉じる", "appShell.notificationsMarkRead": "すべて既読にする", "appShell.notificationUnread": "未読", "appShell.notificationsUnreadCount": "未読 {count} 件", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 75878b912..1fde5a8ec 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -99,6 +99,7 @@ "appShell.notificationsEmpty": "暂无最近通知", "appShell.notificationsClear": "全部清除", "appShell.notificationDismiss": "关闭通知", + "toast.dismiss": "关闭", "appShell.notificationsMarkRead": "全部标为已读", "appShell.notificationUnread": "未读", "appShell.notificationsUnreadCount": "{count} 条未读",