Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions components/McpConfig.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
23 changes: 22 additions & 1 deletion components/McpConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?:
const [liveError, setLiveError] = useState<string | null>(null);
const [path, setPath] = useState<string | null>(null);
const [selected, setSelected] = useState<string | null>(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<string | null>(null);
const loadedCwdRef = useRef<string | null | undefined>(undefined);
const [name, setName] = useState("");
const [source, setSource] = useState(newServer);
const [loading, setLoading] = useState(true);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -130,13 +148,15 @@ 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));
setMessage(null);
};

const add = () => {
selectedRef.current = null;
setSelected(null);
setName("");
setSource(newServer());
Expand Down Expand Up @@ -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();
Expand Down
26 changes: 23 additions & 3 deletions components/NotificationList.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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, "");
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}
});
7 changes: 5 additions & 2 deletions components/NotificationList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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) => {
Expand Down
29 changes: 29 additions & 0 deletions components/SettingsConfig.toggles.test.mjs
Original file line number Diff line number Diff line change
@@ -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\);/);
});
}
25 changes: 22 additions & 3 deletions components/SettingsConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,10 @@ function SearchResultsList({ results, query, onSelect }: { results: SearchResult
function AutoResumeSessionsSetting() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(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")
Expand All @@ -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",
Expand All @@ -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 (
<NativeSetting searchId="auto-resume-sessions" label={t("settingsConfig.autoResumeSessions")} description={t("settingsConfig.autoResumeSessionsDesc")}>
<ToggleSwitch checked={enabled === true} disabled={enabled === null} onChange={(next) => void change(next)} />
<ToggleSwitch checked={enabled === true} disabled={enabled === null || saving} onChange={(next) => void change(next)} />
</NativeSetting>
);
}
Expand All @@ -319,6 +327,13 @@ function AutoResumeSessionsSetting() {
function AgentToolsSetting() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(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")
Expand All @@ -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",
Expand All @@ -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 (
<NativeSetting searchId="agent-tools-cross-session" label={t("settingsConfig.agentTools")} description={t("settingsConfig.agentToolsDesc")}>
<ToggleSwitch checked={enabled === true} disabled={enabled === null} onChange={(next) => void change(next)} />
<ToggleSwitch checked={enabled === true} disabled={enabled === null || saving} onChange={(next) => void change(next)} />
</NativeSetting>
);
}
Expand Down Expand Up @@ -1694,7 +1713,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal
</NativeSetting>
</div>
)}
<McpConfig cwd={cwd} sessionId={sessionId} />
<McpConfig key={cwd ?? ""} cwd={cwd} sessionId={sessionId} />
{!cwd && <p style={{ margin: 0, color: "var(--text-muted)", fontSize: 12 }}>{t("settingsConfig.selectWorkspaceForMcp")}</p>}
</div>
)}
Expand Down
32 changes: 32 additions & 0 deletions components/ui/toast.click.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down Expand Up @@ -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"); });
}
});
26 changes: 22 additions & 4 deletions components/ui/toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 (
<span
<button
type="button"
onClick={() => 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}
</span>
</button>
);
}

Expand Down Expand Up @@ -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<ToastData>();
const isMobile = useIsMobile();
const clickGuard = useDragClickGuard();
Expand Down Expand Up @@ -310,7 +328,7 @@ function Toaster() {
</Toast.Content>
<Toast.Close
className="toast-close-button"
aria-label="Dismiss"
aria-label={tr("toast.dismiss")}
style={dismissButtonStyle}
>
<X size={12} strokeWidth={2} aria-hidden />
Expand Down
Loading
Loading