refactor(web): rename "History" tab/feature to "Protocol" (#1623)

Rename the web client's History tab and its supporting code to Protocol
so the feature reads as the MCP "Protocol" view.

- Tab renders as "Protocol"; INSPECTOR_TAB_IDS, InspectorView tab
  constants/MonitorTab, TAB_UI_REGISTRY key, and navigation.ts tab id all
  updated to Protocol.
- Rename components + folders: HistoryScreen -> ProtocolScreen,
  HistoryListPanel -> ProtocolListPanel, HistoryEntry -> ProtocolEntry,
  HistoryControls -> ProtocolControls, historyUtils -> protocolUtils
  (plus their tests and stories, and exported types).
- Rename App/InspectorView plumbing: historyUi, pinnedHistoryIds,
  on*History* handlers/props, replayHistoryRequest,
  isReplayableHistoryMethod, sort/compact scopes, etc. -> Protocol names.
- Export filenames use the "protocol" slug (buildExportFilename +
  ExportKind).

Preserved (per issue #1623 decisions):
- The in-panel section discriminator keeps its "pinned" | "history"
  values, and the sub-sections stay labeled Pinned / History.
- window.history and core message-log/replay concepts are untouched.

npm run ci passes (format, lint, build, unit tests, >=90 per-file
coverage gate, smoke, Storybook).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BrihGWcrM9JGRyu41nzZYw
This commit is contained in:
cliffhall 2026-07-09 19:04:54 -04:00
commit ace4250d31
20 changed files with 413 additions and 405 deletions

View file

@ -28,7 +28,7 @@ export interface MessageDirectionFilterProps {
/**
* "Filter by Message Direction" section — a Select/Deselect All control plus a
* FilterToggleButton per direction (client → server / client ← server). Used by
* the History controls. (Kept as its own component so the section is testable in
* the Protocol controls. (Kept as its own component so the section is testable in
* isolation and reusable if another screen ever needs a direction filter.)
*/
export function MessageDirectionFilter({

View file

@ -6,7 +6,7 @@ const meta: Meta<typeof MonitoringControls> = {
title: "Groups/MonitoringControls",
component: MonitoringControls,
args: {
tabs: ["Logs", "History", "Network"],
tabs: ["Logs", "Protocol", "Network"],
value: "Logs",
onChange: fn(),
searchValue: "",
@ -29,7 +29,7 @@ export const AllTabs: Story = {
};
export const StdioServer: Story = {
args: { tabs: ["Logs", "History"], value: "History" },
args: { tabs: ["Logs", "Protocol"], value: "Protocol" },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
expect(canvas.queryByRole("radio", { name: "Network" })).toBeNull();

View file

@ -6,7 +6,7 @@ import {
type MonitoringControlsProps,
} from "./MonitoringControls";
const TABS = ["Logs", "History", "Network"];
const TABS = ["Logs", "Protocol", "Network"];
function renderControls(overrides: Partial<MonitoringControlsProps> = {}) {
const props: MonitoringControlsProps = {
@ -31,7 +31,7 @@ describe("MonitoringControls", () => {
});
it("renders only the tabs it is given", () => {
renderControls({ tabs: ["Logs", "History"] });
renderControls({ tabs: ["Logs", "Protocol"] });
expect(screen.getAllByRole("radio")).toHaveLength(2);
expect(screen.queryByRole("radio", { name: "Network" })).toBeNull();
});
@ -53,8 +53,8 @@ describe("MonitoringControls", () => {
});
it("marks the active tab as selected", () => {
renderControls({ value: "History" });
expect(screen.getByRole("radio", { name: "History" })).toBeChecked();
renderControls({ value: "Protocol" });
expect(screen.getByRole("radio", { name: "Protocol" })).toBeChecked();
});
it("calls onChange when a different tab is chosen", async () => {

View file

@ -3,7 +3,7 @@ import { TbLayoutSidebarRightCollapse } from "react-icons/tb";
import { ClearButton } from "../../elements/ClearButton/ClearButton";
export interface MonitoringControlsProps {
/** The monitor screens currently available to pin (e.g. Logs/History/Network). */
/** The monitor screens currently available to pin (e.g. Logs/Protocol/Network). */
tabs: string[];
/** The active monitor tab shown in the column below. */
value: string;

View file

@ -9,7 +9,7 @@ const demoScreens = {
<Text>Log stream</Text>
</Box>
),
History: (
Protocol: (
<Box p="md">
<Text>Request history</Text>
</Box>
@ -32,7 +32,7 @@ const meta: Meta<typeof MonitoringScreen> = {
),
],
args: {
tabs: ["Logs", "History", "Network"],
tabs: ["Logs", "Protocol", "Network"],
value: "Logs",
onChange: fn(),
searchValue: "",
@ -52,8 +52,8 @@ export const Logs: Story = {
},
};
export const History: Story = {
args: { value: "History" },
export const Protocol: Story = {
args: { value: "Protocol" },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
expect(canvas.getByText("Request history")).toBeInTheDocument();

View file

@ -6,12 +6,12 @@ import {
type MonitoringScreenProps,
} from "./MonitoringScreen";
const TABS = ["Logs", "History", "Network"];
const TABS = ["Logs", "Protocol", "Network"];
function screens() {
return {
Logs: <div>logs-body</div>,
History: <div>history-body</div>,
Protocol: <div>history-body</div>,
Network: <div>network-body</div>,
};
}
@ -33,7 +33,7 @@ function renderScreen(overrides: Partial<MonitoringScreenProps> = {}) {
describe("MonitoringScreen", () => {
it("renders the screen for the active tab", () => {
renderScreen({ value: "History" });
renderScreen({ value: "Protocol" });
expect(screen.getByText("history-body")).toBeInTheDocument();
expect(screen.queryByText("logs-body")).toBeNull();
expect(screen.queryByText("network-body")).toBeNull();

View file

@ -3,7 +3,7 @@ import { Divider, Stack } from "@mantine/core";
import { MonitoringControls } from "../MonitoringControls/MonitoringControls";
export interface MonitoringScreenProps {
/** Available monitor tabs (Logs/History/Network, filtered by capability). */
/** Available monitor tabs (Logs/Protocol/Network, filtered by capability). */
tabs: string[];
/** Active monitor tab; keys into `screens` to pick what renders below. */
value: string;

View file

@ -58,7 +58,7 @@ const UrlScroll = Text.withProps({
variant: "nowrap",
});
// Left / right clusters for a compact header line (mirrors HistoryEntry).
// Left / right clusters for a compact header line (mirrors ProtocolEntry).
const HeaderCluster = Group.withProps({
gap: "sm",
wrap: "nowrap",
@ -240,7 +240,7 @@ export function NetworkEntry({
// The list-level Expand/Collapse toggle is authoritative: each time the
// parent changes `isListExpanded`, every entry snaps to that state and
// any per-entry override is intentionally discarded. Mirrors
// HistoryEntry; do not change without aligning both. This re-runs on
// ProtocolEntry; do not change without aligning both. This re-runs on
// re-render when `isListExpanded` keeps its reference, but the setter
// is a no-op when the next value equals the current one.
useEffect(() => {

View file

@ -0,0 +1,41 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import type { MessageMethod } from "@inspector/core/mcp/types.js";
import { ProtocolControls } from "./ProtocolControls";
const SAMPLE_METHODS: MessageMethod[] = [
"tools/call",
"tools/list",
"resources/read",
"resources/list",
"prompts/get",
"prompts/list",
"sampling/createMessage",
"elicitation/create",
];
const meta: Meta<typeof ProtocolControls> = {
title: "Groups/ProtocolControls",
component: ProtocolControls,
args: {
searchText: "",
availableMethods: SAMPLE_METHODS,
visibleDirections: { client: true, server: true },
onSearchChange: fn(),
onMethodFilterChange: fn(),
onToggleDirection: fn(),
onToggleAllDirections: fn(),
},
};
export default meta;
type Story = StoryObj<typeof ProtocolControls>;
export const Default: Story = {};
export const WithFilters: Story = {
args: {
searchText: "tools",
methodFilter: "tools/call",
},
};

View file

@ -0,0 +1,122 @@
import { describe, it, expect, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import type { MessageMethod } from "@inspector/core/mcp/types.js";
import { renderWithMantine, screen } from "../../../test/renderWithMantine";
import { ProtocolControls } from "./ProtocolControls";
const baseProps = {
searchText: "",
availableMethods: ["tools/list", "prompts/list"] as MessageMethod[],
visibleDirections: { client: true, server: true },
onSearchChange: vi.fn(),
onMethodFilterChange: vi.fn(),
onToggleDirection: vi.fn(),
onToggleAllDirections: vi.fn(),
};
describe("ProtocolControls", () => {
it("renders the title and search input", () => {
renderWithMantine(<ProtocolControls {...baseProps} />);
expect(screen.getByText("Protocol")).toBeInTheDocument();
expect(screen.getByPlaceholderText("Search...")).toBeInTheDocument();
});
it("invokes onSearchChange when typing in the search input", async () => {
const user = userEvent.setup();
const onSearchChange = vi.fn();
renderWithMantine(
<ProtocolControls {...baseProps} onSearchChange={onSearchChange} />,
);
await user.type(screen.getByPlaceholderText("Search..."), "a");
expect(onSearchChange).toHaveBeenCalledWith("a");
});
it("clears the search input when the Clear button is clicked", async () => {
const user = userEvent.setup();
const onSearchChange = vi.fn();
renderWithMantine(
<ProtocolControls
{...baseProps}
searchText="abc"
onSearchChange={onSearchChange}
/>,
);
await user.click(screen.getByRole("button", { name: "Clear" }));
expect(onSearchChange).toHaveBeenCalledWith("");
});
it("keeps the search Clear button out of the keyboard tab order", () => {
renderWithMantine(<ProtocolControls {...baseProps} searchText="abc" />);
expect(screen.getByRole("button", { name: "Clear" })).toHaveAttribute(
"tabindex",
"-1",
);
});
it("renders the method filter placeholder", () => {
renderWithMantine(<ProtocolControls {...baseProps} />);
expect(screen.getByPlaceholderText("All methods")).toBeInTheDocument();
});
it("displays the active method filter value", () => {
renderWithMantine(
<ProtocolControls {...baseProps} methodFilter="tools/list" />,
);
const inputs = screen.getAllByDisplayValue("tools/list");
expect(inputs.length).toBeGreaterThan(0);
});
it("invokes onMethodFilterChange with undefined when cleared", async () => {
const user = userEvent.setup();
const onMethodFilterChange = vi.fn();
const { container } = renderWithMantine(
<ProtocolControls
{...baseProps}
methodFilter="tools/list"
onMethodFilterChange={onMethodFilterChange}
/>,
);
const clearButton = container.querySelector(
"button.mantine-InputClearButton-root",
) as HTMLButtonElement | null;
expect(clearButton).not.toBeNull();
await user.click(clearButton!);
expect(onMethodFilterChange).toHaveBeenCalledWith(undefined);
});
it("renders the Filter by Message Direction section with both directions", () => {
renderWithMantine(<ProtocolControls {...baseProps} />);
expect(screen.getByText("Filter by Message Direction")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "client → server" }),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "client ← server" }),
).toBeInTheDocument();
});
it("toggles a direction's visibility when its button is clicked", async () => {
const user = userEvent.setup();
const onToggleDirection = vi.fn();
renderWithMantine(
<ProtocolControls {...baseProps} onToggleDirection={onToggleDirection} />,
);
// Currently visible → clicking turns it off.
await user.click(screen.getByRole("button", { name: "client ← server" }));
expect(onToggleDirection).toHaveBeenCalledWith("server", false);
});
it("invokes onToggleAllDirections from the Deselect/Select All control", async () => {
const user = userEvent.setup();
const onToggleAllDirections = vi.fn();
renderWithMantine(
<ProtocolControls
{...baseProps}
onToggleAllDirections={onToggleAllDirections}
/>,
);
// Both visible → the control reads "Deselect All".
await user.click(screen.getByRole("button", { name: "Deselect All" }));
expect(onToggleAllDirections).toHaveBeenCalledTimes(1);
});
});

View file

@ -0,0 +1,61 @@
import { Select, Stack, TextInput, Title } from "@mantine/core";
import { ClearButton } from "../../elements/ClearButton/ClearButton";
import type {
MessageMethod,
MessageOrigin,
} from "@inspector/core/mcp/types.js";
import { MessageDirectionFilter } from "../MessageDirectionFilter/MessageDirectionFilter";
export interface ProtocolControlsProps {
searchText: string;
methodFilter?: MessageMethod;
availableMethods: MessageMethod[];
visibleDirections: Record<MessageOrigin, boolean>;
onSearchChange: (text: string) => void;
onMethodFilterChange: (method: MessageMethod | undefined) => void;
onToggleDirection: (direction: MessageOrigin, visible: boolean) => void;
onToggleAllDirections: () => void;
}
export function ProtocolControls({
searchText,
methodFilter,
availableMethods,
visibleDirections,
onSearchChange,
onMethodFilterChange,
onToggleDirection,
onToggleAllDirections,
}: ProtocolControlsProps) {
return (
<Stack gap="md">
<Title order={4}>Protocol</Title>
<TextInput
placeholder="Search..."
value={searchText}
onChange={(event) => onSearchChange(event.currentTarget.value)}
rightSectionPointerEvents="auto"
rightSection={
searchText ? <ClearButton onClick={() => onSearchChange("")} /> : null
}
/>
<Title order={6}>Filter by Method</Title>
<Select
placeholder="All methods"
data={availableMethods}
value={methodFilter ?? null}
onChange={(value) =>
onMethodFilterChange((value as MessageMethod | null) ?? undefined)
}
clearable
/>
<MessageDirectionFilter
visibleDirections={visibleDirections}
onToggleDirection={onToggleDirection}
onToggleAllDirections={onToggleAllDirections}
/>
</Stack>
);
}

View file

@ -0,0 +1,130 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { MessageEntry } from "../../../../../../core/mcp/types.js";
import { fn } from "storybook/test";
import { ProtocolEntry } from "./ProtocolEntry";
const meta: Meta<typeof ProtocolEntry> = {
title: "Groups/ProtocolEntry",
component: ProtocolEntry,
args: {
onReplay: fn(),
onTogglePin: fn(),
},
};
export default meta;
type Story = StoryObj<typeof ProtocolEntry>;
const toolCallEntry: MessageEntry = {
id: "req-1",
timestamp: new Date("2026-03-17T10:30:00Z"),
direction: "request",
origin: "client",
message: {
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name: "get_weather", arguments: { city: "San Francisco" } },
},
response: {
jsonrpc: "2.0",
id: 1,
result: {
content: [{ type: "text", text: "18°C, partly cloudy" }],
},
},
duration: 142,
};
const errorEntry: MessageEntry = {
id: "req-2",
timestamp: new Date("2026-03-17T10:31:15Z"),
direction: "request",
origin: "client",
message: {
jsonrpc: "2.0",
id: 2,
method: "tools/call",
params: { name: "query_database" },
},
response: {
jsonrpc: "2.0",
id: 2,
error: { code: -32000, message: "Connection timeout" },
},
duration: 3200,
};
const resourceReadEntry: MessageEntry = {
id: "req-3",
timestamp: new Date("2026-03-17T10:33:00Z"),
direction: "request",
origin: "client",
message: {
jsonrpc: "2.0",
id: 3,
method: "resources/read",
params: { uri: "file:///config.json" },
},
response: {
jsonrpc: "2.0",
id: 3,
result: {
contents: [{ uri: "file:///config.json", text: '{"debug": true}' }],
},
},
duration: 45,
};
const pendingEntry: MessageEntry = {
id: "req-4",
timestamp: new Date("2026-03-17T10:34:00Z"),
direction: "request",
origin: "client",
message: {
jsonrpc: "2.0",
id: 4,
method: "tools/call",
params: { name: "long_operation" },
},
};
export const SuccessCollapsed: Story = {
args: {
entry: toolCallEntry,
isPinned: false,
isListExpanded: false,
},
};
export const SuccessExpanded: Story = {
args: {
entry: toolCallEntry,
isPinned: false,
isListExpanded: true,
},
};
export const Error: Story = {
args: {
entry: errorEntry,
isPinned: false,
isListExpanded: true,
},
};
export const Pinned: Story = {
args: {
entry: resourceReadEntry,
isPinned: true,
isListExpanded: false,
},
};
export const Pending: Story = {
args: {
entry: pendingEntry,
isPinned: false,
isListExpanded: false,
},
};

View file

@ -0,0 +1,355 @@
import { describe, it, expect, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import type { MessageEntry } from "@inspector/core/mcp/types.js";
import { renderWithMantine, screen } from "../../../test/renderWithMantine";
import { ProtocolEntry } from "./ProtocolEntry";
const successEntry: MessageEntry = {
id: "req-1",
timestamp: new Date("2026-03-17T10:30:00Z"),
direction: "request",
origin: "client",
message: {
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name: "get_weather", arguments: { city: "San Francisco" } },
},
response: {
jsonrpc: "2.0",
id: 1,
result: {
content: [{ type: "text", text: "18C" }],
},
},
duration: 142,
};
const errorEntry: MessageEntry = {
id: "req-2",
timestamp: new Date("2026-03-17T10:31:15Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 2,
method: "tools/call",
params: { name: "query_database" },
},
response: {
jsonrpc: "2.0",
id: 2,
error: { code: -32000, message: "Connection timeout" },
},
duration: 3200,
};
const resourceReadEntry: MessageEntry = {
id: "req-3",
timestamp: new Date("2026-03-17T10:33:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 3,
method: "resources/read",
params: { uri: "file:///config.json" },
},
response: {
jsonrpc: "2.0",
id: 3,
result: {
contents: [{ uri: "file:///config.json", text: '{"debug": true}' }],
},
},
duration: 45,
};
const pendingEntry: MessageEntry = {
id: "req-4",
timestamp: new Date("2026-03-17T10:34:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 4,
method: "tools/call",
params: { name: "long_operation" },
},
};
const noParamsEntry: MessageEntry = {
id: "req-5",
timestamp: new Date("2026-03-17T10:35:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 5,
method: "tools/list",
},
response: {
jsonrpc: "2.0",
id: 5,
result: { tools: [] },
},
};
const notificationEntry: MessageEntry = {
id: "note-1",
timestamp: new Date("2026-03-17T10:36:00Z"),
direction: "notification",
origin: "server",
message: {
jsonrpc: "2.0",
method: "notifications/message",
params: {
level: "info",
logger: "everything-server",
data: "Roots updated: 2 root(s) received from client",
},
},
};
const baseProps = {
isPinned: false,
isListExpanded: false,
onReplay: vi.fn(),
onTogglePin: vi.fn(),
};
describe("ProtocolEntry", () => {
it("renders the method, target name, status OK, and duration", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={successEntry} />);
expect(screen.getByText("tools/call")).toBeInTheDocument();
expect(screen.getByText("get_weather")).toBeInTheDocument();
expect(screen.getByText("OK")).toBeInTheDocument();
expect(screen.getByText("142ms")).toBeInTheDocument();
});
it("renders the URI target for resources/read", () => {
renderWithMantine(
<ProtocolEntry {...baseProps} entry={resourceReadEntry} />,
);
expect(screen.getByText("file:///config.json")).toBeInTheDocument();
expect(screen.getByText("resources/read")).toBeInTheDocument();
});
it("renders Error status when response has error", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={errorEntry} />);
expect(screen.getByText("Error")).toBeInTheDocument();
});
it("renders Pending status when no response present", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={pendingEntry} />);
expect(screen.getByText("Pending")).toBeInTheDocument();
});
it("renders no request-style status badge for a notification", () => {
renderWithMantine(
<ProtocolEntry {...baseProps} entry={notificationEntry} />,
);
// The method badge still labels it; there is no Pending/OK/Error badge,
// since a fire-and-forget notification has no request lifecycle.
expect(screen.getByText("notifications/message")).toBeInTheDocument();
expect(screen.queryByText("Pending")).not.toBeInTheDocument();
expect(screen.queryByText("OK")).not.toBeInTheDocument();
expect(screen.queryByText("Error")).not.toBeInTheDocument();
});
it("shows client → server for a client-originated entry", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={successEntry} />);
expect(screen.getByText("client → server")).toBeInTheDocument();
});
it("shows client ← server for a server-originated entry", () => {
renderWithMantine(
<ProtocolEntry {...baseProps} entry={notificationEntry} />,
);
expect(screen.getByText("client ← server")).toBeInTheDocument();
});
it("renders Pin label when not pinned", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={successEntry} />);
expect(screen.getByRole("button", { name: "Pin" })).toBeInTheDocument();
});
it("renders Unpin label when pinned", () => {
renderWithMantine(
<ProtocolEntry {...baseProps} entry={successEntry} isPinned={true} />,
);
expect(screen.getByRole("button", { name: "Unpin" })).toBeInTheDocument();
});
it("invokes onReplay when Replay button is clicked", async () => {
const user = userEvent.setup();
const onReplay = vi.fn();
renderWithMantine(
<ProtocolEntry {...baseProps} entry={successEntry} onReplay={onReplay} />,
);
await user.click(screen.getByRole("button", { name: "Replay" }));
expect(onReplay).toHaveBeenCalledTimes(1);
});
it("hides the Replay button for a method that can't be replayed", () => {
// A notification isn't a replayable client→server request.
renderWithMantine(
<ProtocolEntry {...baseProps} entry={notificationEntry} />,
);
expect(
screen.queryByRole("button", { name: "Replay" }),
).not.toBeInTheDocument();
// Pin stays available.
expect(screen.getByRole("button", { name: "Pin" })).toBeInTheDocument();
});
it("orders the actions Replay, then Pin, then the expand toggle on the right", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={successEntry} />);
const names = screen
.getAllByRole("button")
.map((b) => b.getAttribute("aria-label") ?? b.textContent);
expect(names.indexOf("Replay")).toBeLessThan(names.indexOf("Pin"));
expect(names.indexOf("Pin")).toBeLessThan(names.indexOf("Expand"));
});
it("renders the compact two-line layout with Replay as an icon when embedded", () => {
renderWithMantine(
<ProtocolEntry {...baseProps} entry={successEntry} embedded />,
);
// Line 1 essentials plus the method are still shown. The timestamp is the
// compact time-only form (not the full ISO) to fit the narrow line.
expect(screen.getByText("10:30:00")).toBeInTheDocument();
expect(
screen.queryByText("2026-03-17T10:30:00.000Z"),
).not.toBeInTheDocument();
expect(screen.getByText("client → server")).toBeInTheDocument();
expect(screen.getByText("142ms")).toBeInTheDocument();
expect(screen.getByText("OK")).toBeInTheDocument();
expect(screen.getByText("tools/call")).toBeInTheDocument();
// Replay is an icon button (aria-label), not the text button.
expect(screen.getByRole("button", { name: "Replay" })).toBeInTheDocument();
expect(screen.queryByText("Replay")).toBeNull();
});
it("keeps action order Replay, Pin, Expand in the compact layout", () => {
renderWithMantine(
<ProtocolEntry {...baseProps} entry={successEntry} embedded />,
);
const names = screen
.getAllByRole("button")
.map((b) => b.getAttribute("aria-label") ?? b.textContent);
expect(names.indexOf("Replay")).toBeLessThan(names.indexOf("Pin"));
expect(names.indexOf("Pin")).toBeLessThan(names.indexOf("Expand"));
});
it("does not render a Replay icon for a non-replayable method when embedded", () => {
// A server→client response isn't replayable.
const responseEntry: MessageEntry = {
id: "resp-1",
timestamp: new Date("2026-03-17T10:30:00Z"),
direction: "response",
origin: "server",
message: { jsonrpc: "2.0", id: 1, result: {} },
};
renderWithMantine(
<ProtocolEntry {...baseProps} entry={responseEntry} embedded />,
);
expect(
screen.queryByRole("button", { name: "Replay" }),
).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Pin" })).toBeInTheDocument();
});
it("invokes onTogglePin when Pin button is clicked", async () => {
const user = userEvent.setup();
const onTogglePin = vi.fn();
renderWithMantine(
<ProtocolEntry
{...baseProps}
entry={successEntry}
onTogglePin={onTogglePin}
/>,
);
await user.click(screen.getByRole("button", { name: "Pin" }));
expect(onTogglePin).toHaveBeenCalledTimes(1);
});
it("toggles the local expand/collapse state when clicking Expand/Collapse", async () => {
const user = userEvent.setup();
renderWithMantine(<ProtocolEntry {...baseProps} entry={successEntry} />);
expect(screen.getByRole("button", { name: "Expand" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Expand" }));
expect(
screen.getByRole("button", { name: "Collapse" }),
).toBeInTheDocument();
});
it("toggles the local expand/collapse state when clicking Expand/Collapse in the compact layout", async () => {
const user = userEvent.setup();
renderWithMantine(
<ProtocolEntry {...baseProps} entry={successEntry} embedded />,
);
expect(screen.getByRole("button", { name: "Expand" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Expand" }));
expect(
screen.getByRole("button", { name: "Collapse" }),
).toBeInTheDocument();
});
it("starts expanded when isListExpanded is true and shows Parameters and Response", () => {
renderWithMantine(
<ProtocolEntry
{...baseProps}
entry={successEntry}
isListExpanded={true}
/>,
);
expect(screen.getByText("Parameters:")).toBeInTheDocument();
expect(screen.getByText("Response:")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Collapse" }),
).toBeInTheDocument();
});
it("syncs the local expanded state when isListExpanded prop changes", () => {
const { rerender } = renderWithMantine(
<ProtocolEntry {...baseProps} entry={successEntry} />,
);
expect(screen.getByRole("button", { name: "Expand" })).toBeInTheDocument();
rerender(
<ProtocolEntry
{...baseProps}
entry={successEntry}
isListExpanded={true}
/>,
);
expect(
screen.getByRole("button", { name: "Collapse" }),
).toBeInTheDocument();
});
it("does not render the Parameters section when message has no params", () => {
renderWithMantine(
<ProtocolEntry
{...baseProps}
entry={noParamsEntry}
isListExpanded={true}
/>,
);
expect(screen.queryByText("Parameters:")).not.toBeInTheDocument();
expect(screen.getByText("Response:")).toBeInTheDocument();
});
it("does not render the Response section when no response is present", () => {
renderWithMantine(
<ProtocolEntry
{...baseProps}
entry={pendingEntry}
isListExpanded={true}
/>,
);
expect(screen.getByText("Parameters:")).toBeInTheDocument();
expect(screen.queryByText("Response:")).not.toBeInTheDocument();
});
it("does not render duration when duration is undefined", () => {
renderWithMantine(<ProtocolEntry {...baseProps} entry={pendingEntry} />);
expect(screen.queryByText(/ms$/)).not.toBeInTheDocument();
});
});

View file

@ -0,0 +1,264 @@
import { useEffect, useState } from "react";
import {
Badge,
Button,
Card,
Collapse,
Divider,
Group,
Stack,
Text,
} from "@mantine/core";
import type { MessageEntry } from "../../../../../../core/mcp/types.js";
import { ContentViewer } from "../../elements/ContentViewer/ContentViewer";
import { MessageDirectionBadge } from "../../elements/MessageDirectionBadge/MessageDirectionBadge";
import { ExpandToggle } from "../../elements/ExpandToggle/ExpandToggle";
import { PinToggle } from "../../elements/PinToggle/PinToggle";
import { ReplayButton } from "../../elements/ReplayButton/ReplayButton";
import { extractMethod, isReplayableProtocolMethod } from "../protocolUtils.js";
export interface ProtocolEntryProps {
entry: MessageEntry;
isPinned: boolean;
isListExpanded: boolean;
onReplay: () => void;
onTogglePin: () => void;
/**
* Compact two-line header for the narrow monitoring column (#1616): line 1 is
* time + direction + duration + status; line 2 is the method (and target) with
* the controls — Replay as an icon — on the right.
*/
embedded?: boolean;
}
const EntryContainer = Card.withProps({
withBorder: true,
padding: "md",
});
const HeaderRow = Group.withProps({
justify: "space-between",
wrap: "nowrap",
});
// Left / right clusters within a compact header line. The left cluster shrinks
// (`miw: 0`) so a long target can truncate rather than push the row wider.
const HeaderCluster = Group.withProps({
gap: "sm",
wrap: "nowrap",
miw: 0,
});
const ControlsCluster = Group.withProps({
gap: "xs",
wrap: "nowrap",
});
const TimestampText = Text.withProps({
size: "sm",
c: "dimmed",
ff: "monospace",
});
const TargetText = Text.withProps({
size: "sm",
fw: 500,
});
const DurationText = Text.withProps({
size: "sm",
c: "dimmed",
});
const SubtleButton = Button.withProps({
variant: "subtle",
size: "xs",
});
function formatDuration(ms: number): string {
return `${ms}ms`;
}
function formatTimestamp(date: Date): string {
return date.toISOString();
}
// Time-only (HH:MM:SS, UTC) for the compact column header, where the full ISO
// string would eat most of the narrow line-1 width (#1616).
function formatTimestampCompact(date: Date): string {
return date.toISOString().slice(11, 19);
}
function extractTarget(entry: MessageEntry): string | undefined {
const msg = entry.message;
if (!("params" in msg) || !msg.params) return undefined;
const params = msg.params as Record<string, unknown>;
if (typeof params.name === "string") return params.name;
if (typeof params.uri === "string") return params.uri;
return undefined;
}
// The pending → OK/Error lifecycle only applies to requests: messageLogState
// attaches a `response` to request entries by JSON-RPC id. A notification is
// fire-and-forget (no id, no response, ever) and an unmatched standalone
// response has none either — so those carry no request-style status ("none")
// and render no badge, rather than a misleading permanent "Pending".
function extractStatus(
entry: MessageEntry,
): "success" | "error" | "pending" | "none" {
if (entry.direction !== "request") return "none";
if (!entry.response) return "pending";
if ("error" in entry.response) return "error";
return "success";
}
function statusColor(status: "success" | "error" | "pending"): string {
if (status === "success") return "green";
if (status === "error") return "red";
return "gray";
}
function statusLabel(status: "success" | "error" | "pending"): string {
if (status === "success") return "OK";
if (status === "error") return "Error";
return "Pending";
}
function serializeMessage(value: unknown): string {
return JSON.stringify(value);
}
export function ProtocolEntry({
entry,
isPinned,
isListExpanded,
onReplay,
onTogglePin,
embedded = false,
}: ProtocolEntryProps) {
const [isExpanded, setIsExpanded] = useState(isListExpanded);
const method = extractMethod(entry);
const target = extractTarget(entry);
const status = extractStatus(entry);
const canReplay = isReplayableProtocolMethod(method);
useEffect(() => {
setIsExpanded(isListExpanded);
}, [isListExpanded]);
const directionBadge = entry.origin && (
<MessageDirectionBadge
direction={entry.origin === "client" ? "outgoing" : "incoming"}
/>
);
const statusBadge = status !== "none" && (
<Badge color={statusColor(status)}>{statusLabel(status)}</Badge>
);
const durationText = entry.duration != null && (
<DurationText>{formatDuration(entry.duration)}</DurationText>
);
return (
<EntryContainer>
<Stack gap="sm">
{embedded ? (
// Compact two-line header for the narrow column.
<Stack gap="xs">
<HeaderRow>
<HeaderCluster>
<TimestampText>
{formatTimestampCompact(entry.timestamp)}
</TimestampText>
{directionBadge}
</HeaderCluster>
<ControlsCluster>
{durationText}
{statusBadge}
</ControlsCluster>
</HeaderRow>
<HeaderRow>
<HeaderCluster flex={1}>
<Badge color="dark">{method}</Badge>
{target && (
<TargetText truncate="end" miw={0}>
{target}
</TargetText>
)}
</HeaderCluster>
<ControlsCluster>
{canReplay && <ReplayButton onReplay={onReplay} />}
<PinToggle pinned={isPinned} onToggle={onTogglePin} />
<ExpandToggle
expanded={isExpanded}
onToggle={() => setIsExpanded((v) => !v)}
/>
</ControlsCluster>
</HeaderRow>
</Stack>
) : (
<>
<HeaderRow>
<Group gap="sm">
<TimestampText>
{formatTimestamp(entry.timestamp)}
</TimestampText>
{directionBadge}
<Badge color="dark">{method}</Badge>
{target && <TargetText>{target}</TargetText>}
</Group>
<Group gap="sm">
{durationText}
{statusBadge}
</Group>
</HeaderRow>
<Group gap="xs" justify="space-between">
<Group gap="xs">
{canReplay && (
<SubtleButton onClick={onReplay}>Replay</SubtleButton>
)}
</Group>
<Group gap="xs">
<PinToggle pinned={isPinned} onToggle={onTogglePin} />
<ExpandToggle
expanded={isExpanded}
onToggle={() => setIsExpanded((v) => !v)}
/>
</Group>
</Group>
</>
)}
<Collapse in={isExpanded}>
<Stack gap="sm">
<Divider />
{"params" in entry.message && entry.message.params && (
<Stack gap="xs">
<Text size="sm">Parameters:</Text>
<ContentViewer
block={{
type: "text",
text: serializeMessage(entry.message.params),
}}
copyable
/>
</Stack>
)}
{entry.response && (
<Stack gap="xs">
<Text size="sm">Response:</Text>
<ContentViewer
block={{
type: "text",
text: serializeMessage(entry.response),
}}
copyable
/>
</Stack>
)}
</Stack>
</Collapse>
</Stack>
</EntryContainer>
);
}

View file

@ -0,0 +1,118 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { MessageEntry } from "../../../../../../core/mcp/types.js";
import { fn } from "storybook/test";
import { ProtocolListPanel } from "./ProtocolListPanel.js";
import { expectScrollbarGutterIdleHidden } from "../../../test/scrollAreaStoryAssertions";
const meta: Meta<typeof ProtocolListPanel> = {
title: "Groups/ProtocolListPanel",
component: ProtocolListPanel,
args: {
searchText: "",
pinnedIds: new Set<string>(),
onClearAll: fn(),
onExport: fn(),
onClearSection: fn(),
onExportSection: fn(),
onReplay: fn(),
onTogglePin: fn(),
sortDirection: "newest-first",
onSortChange: fn(),
compact: true,
onToggleCompact: fn(),
},
};
export default meta;
type Story = StoryObj<typeof ProtocolListPanel>;
const sampleEntries: MessageEntry[] = [
{
id: "req-1",
timestamp: new Date("2026-03-17T10:00:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name: "send_message", arguments: { message: "Hello!" } },
},
response: {
jsonrpc: "2.0",
id: 1,
result: { content: [{ type: "text", text: "Sent" }] },
},
duration: 120,
},
{
id: "req-2",
timestamp: new Date("2026-03-17T10:01:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 2,
method: "resources/read",
params: { uri: "file:///config.json" },
},
response: {
jsonrpc: "2.0",
id: 2,
result: {
contents: [{ uri: "file:///config.json", text: "{}" }],
},
},
duration: 45,
},
{
id: "req-3",
timestamp: new Date("2026-03-17T10:02:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 3,
method: "tools/call",
params: { name: "delete_records", arguments: { ids: [1, 2, 3] } },
},
response: {
jsonrpc: "2.0",
id: 3,
error: { code: -32000, message: "Permission denied" },
},
duration: 350,
},
{
id: "req-4",
timestamp: new Date("2026-03-17T09:30:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 4,
method: "tools/list",
},
response: {
jsonrpc: "2.0",
id: 4,
result: { tools: [] },
},
duration: 80,
},
];
export const WithEntries: Story = {
args: {
entries: sampleEntries,
pinnedIds: new Set(["req-4"]),
},
// The list ScrollArea reserves a scrollbar gutter (offsetScrollbars) so the
// bar never overlays the cards, and uses type="scroll" so it stays hidden
// when idle rather than appearing on hover (#1474).
play: async ({ canvasElement }) => {
expectScrollbarGutterIdleHidden(canvasElement);
},
};
export const Empty: Story = {
args: {
entries: [],
},
};

View file

@ -0,0 +1,450 @@
import { describe, it, expect, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import type { MessageEntry } from "@inspector/core/mcp/types.js";
import { renderWithMantine, screen } from "../../../test/renderWithMantine";
import { ProtocolListPanel } from "./ProtocolListPanel";
const sampleEntries: MessageEntry[] = [
{
id: "req-1",
timestamp: new Date("2026-03-17T10:00:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name: "send_message", arguments: { message: "Hello!" } },
},
response: {
jsonrpc: "2.0",
id: 1,
result: { content: [{ type: "text", text: "Sent" }] },
},
duration: 120,
},
{
id: "req-2",
timestamp: new Date("2026-03-17T10:01:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 2,
method: "resources/read",
params: { uri: "file:///config.json" },
},
response: {
jsonrpc: "2.0",
id: 2,
result: {
contents: [{ uri: "file:///config.json", text: "{}" }],
},
},
duration: 45,
},
{
id: "req-3",
timestamp: new Date("2026-03-17T10:02:00Z"),
direction: "request",
message: {
jsonrpc: "2.0",
id: 3,
method: "tools/list",
},
response: {
jsonrpc: "2.0",
id: 3,
result: { tools: [] },
},
duration: 80,
},
];
const baseProps = {
pinnedIds: new Set<string>(),
searchText: "",
visibleDirections: { client: true, server: true },
onClearAll: vi.fn(),
onExport: vi.fn(),
onClearSection: vi.fn(),
onExportSection: vi.fn(),
onReplay: vi.fn(),
onTogglePin: vi.fn(),
sortDirection: "newest-first" as const,
onSortChange: vi.fn(),
compact: true,
onToggleCompact: vi.fn(),
};
describe("ProtocolListPanel", () => {
it("renders the title and Export button", () => {
renderWithMantine(<ProtocolListPanel {...baseProps} entries={[]} />);
expect(screen.getByText("Requests")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Export" })).toBeInTheDocument();
});
it("renders the empty state when there are no entries", () => {
renderWithMantine(<ProtocolListPanel {...baseProps} entries={[]} />);
expect(screen.getByText("No request history")).toBeInTheDocument();
});
it("renders the empty state when entries exist but none match the filter", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
searchText="zzznotfound"
/>,
);
expect(screen.getByText("No request history")).toBeInTheDocument();
});
it("hides the History header when there are no pinned entries", () => {
renderWithMantine(
<ProtocolListPanel {...baseProps} entries={sampleEntries} />,
);
// With no pinned section to distinguish it from, the header is dropped...
expect(screen.queryByText("History (3)")).toBeNull();
// ...but the entries themselves are still shown.
expect(screen.getByText("resources/read")).toBeInTheDocument();
});
it("renders the Pinned title with count when entries are pinned", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
pinnedIds={new Set(["req-1"])}
/>,
);
expect(screen.getByText("Pinned Requests (1)")).toBeInTheDocument();
expect(screen.getByText("History (2)")).toBeInTheDocument();
});
it("toggles a section's expanded state when its header is clicked", async () => {
const user = userEvent.setup();
// Both sections present so the headers are collapsible toggles.
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
pinnedIds={new Set(["req-1"])}
/>,
);
const header = screen.getByRole("button", { name: "History (2)" });
expect(header).toHaveAttribute("aria-expanded", "true");
await user.click(header);
expect(header).toHaveAttribute("aria-expanded", "false");
await user.click(header);
expect(header).toHaveAttribute("aria-expanded", "true");
});
it("renders a lone unpinned section headerless, with its entries shown", () => {
// Only the unpinned section → no header at all, no accordion toggle,
// entries always visible.
renderWithMantine(
<ProtocolListPanel {...baseProps} entries={sampleEntries} />,
);
expect(screen.queryByText("History (3)")).toBeNull();
expect(
screen.queryByRole("button", { name: "History (3)" }),
).not.toBeInTheDocument();
// An entry's method badge is visible (content shown, not collapsed).
expect(screen.getByText("resources/read")).toBeInTheDocument();
});
it("shows the surviving section's entries after the other is removed, even if it was collapsed", async () => {
const user = userEvent.setup();
const { rerender } = renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
pinnedIds={new Set(["req-1"])}
/>,
);
// Collapse the History section while both sections are present.
await user.click(screen.getByRole("button", { name: "History (2)" }));
expect(screen.getByRole("button", { name: "History (2)" })).toHaveAttribute(
"aria-expanded",
"false",
);
// Remove the pinned section → History is now the only section. Its entries
// must show despite the stale collapsed state, and the header is plain.
rerender(<ProtocolListPanel {...baseProps} entries={sampleEntries} />);
expect(
screen.queryByRole("button", { name: "History (3)" }),
).not.toBeInTheDocument();
expect(screen.getByText("resources/read")).toBeInTheDocument();
});
it("collapses the Pinned and History sections independently", async () => {
const user = userEvent.setup();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
pinnedIds={new Set(["req-1"])}
/>,
);
const pinned = screen.getByRole("button", {
name: "Pinned Requests (1)",
});
const history = screen.getByRole("button", { name: "History (2)" });
await user.click(pinned);
expect(pinned).toHaveAttribute("aria-expanded", "false");
// Collapsing Pinned leaves History untouched.
expect(history).toHaveAttribute("aria-expanded", "true");
});
it("shows per-section Clear/Export only when both sections are present", () => {
// Only an unpinned section → just the panel-level Clear/Export.
const { unmount } = renderWithMantine(
<ProtocolListPanel {...baseProps} entries={sampleEntries} />,
);
expect(screen.getAllByRole("button", { name: "Clear" })).toHaveLength(1);
expect(screen.getAllByRole("button", { name: "Export" })).toHaveLength(1);
unmount();
// Both sections → panel-level plus one Clear/Export per section.
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
pinnedIds={new Set(["req-1"])}
/>,
);
expect(screen.getAllByRole("button", { name: "Clear" })).toHaveLength(3);
expect(screen.getAllByRole("button", { name: "Export" })).toHaveLength(3);
});
it("invokes onClearSection/onExportSection for the clicked section", async () => {
const user = userEvent.setup();
const onClearSection = vi.fn();
const onExportSection = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
pinnedIds={new Set(["req-1"])}
onClearSection={onClearSection}
onExportSection={onExportSection}
/>,
);
// [0] = panel-level, [1] = Pinned section, [2] = History section.
const clears = screen.getAllByRole("button", { name: "Clear" });
const exports = screen.getAllByRole("button", { name: "Export" });
await user.click(clears[1]);
expect(onClearSection).toHaveBeenCalledWith("pinned");
await user.click(exports[2]);
expect(onExportSection).toHaveBeenCalledWith("history");
});
it("hides entries whose message direction is toggled off", () => {
const directional: MessageEntry[] = [
{ ...sampleEntries[0], id: "from-client", origin: "client" },
{ ...sampleEntries[1], id: "from-server", origin: "server" },
];
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={directional}
visibleDirections={{ client: true, server: false }}
/>,
);
// The server-origin entry is filtered out, leaving the client one.
expect(screen.getByText("tools/call")).toBeInTheDocument();
expect(screen.queryByText("resources/read")).toBeNull();
});
it("filters entries by searchText (case-insensitive)", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
searchText="config.json"
/>,
);
// Only the resources/read entry references config.json.
expect(screen.getByText("resources/read")).toBeInTheDocument();
expect(screen.queryByText("tools/call")).toBeNull();
expect(screen.queryByText("tools/list")).toBeNull();
});
it("filters entries by methodFilter", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
methodFilter="tools/list"
/>,
);
expect(screen.getByText("tools/list")).toBeInTheDocument();
expect(screen.queryByText("tools/call")).toBeNull();
expect(screen.queryByText("resources/read")).toBeNull();
});
it("invokes onExport when Export is clicked", async () => {
const user = userEvent.setup();
const onExport = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
onExport={onExport}
/>,
);
await user.click(screen.getByRole("button", { name: "Export" }));
expect(onExport).toHaveBeenCalledTimes(1);
});
it("invokes onClearAll when Clear is clicked", async () => {
const user = userEvent.setup();
const onClearAll = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
onClearAll={onClearAll}
/>,
);
await user.click(screen.getByRole("button", { name: "Clear" }));
expect(onClearAll).toHaveBeenCalledTimes(1);
});
it("invokes onReplay with the entry id when Replay is clicked", async () => {
const user = userEvent.setup();
const onReplay = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={[sampleEntries[0]]}
onReplay={onReplay}
/>,
);
await user.click(screen.getByRole("button", { name: "Replay" }));
expect(onReplay).toHaveBeenCalledWith("req-1");
});
it("invokes onTogglePin with the entry id when Pin is clicked", async () => {
const user = userEvent.setup();
const onTogglePin = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={[sampleEntries[0]]}
onTogglePin={onTogglePin}
/>,
);
await user.click(screen.getByRole("button", { name: "Pin" }));
expect(onTogglePin).toHaveBeenCalledWith("req-1");
});
it("renders only pinned section when all entries are pinned", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={[sampleEntries[0]]}
pinnedIds={new Set(["req-1"])}
/>,
);
expect(screen.getByText("Pinned Requests (1)")).toBeInTheDocument();
expect(screen.queryByText(/^History \(/)).not.toBeInTheDocument();
});
it("invokes onReplay and onTogglePin from the pinned section", async () => {
const user = userEvent.setup();
const onReplay = vi.fn();
const onTogglePin = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={[sampleEntries[0]]}
pinnedIds={new Set(["req-1"])}
onReplay={onReplay}
onTogglePin={onTogglePin}
/>,
);
await user.click(screen.getByRole("button", { name: "Replay" }));
expect(onReplay).toHaveBeenCalledWith("req-1");
await user.click(screen.getByRole("button", { name: "Unpin" }));
expect(onTogglePin).toHaveBeenCalledWith("req-1");
});
it("renders entries newest-first by default", () => {
renderWithMantine(
<ProtocolListPanel {...baseProps} entries={sampleEntries} />,
);
const methods = screen.getAllByText(
/tools\/call|resources\/read|tools\/list/,
);
expect(methods[0]).toHaveTextContent("tools/list");
expect(methods[methods.length - 1]).toHaveTextContent("tools/call");
});
it("reorders entries when sortDirection is oldest-first", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
sortDirection="oldest-first"
/>,
);
const methods = screen.getAllByText(
/tools\/call|resources\/read|tools\/list/,
);
expect(methods[0]).toHaveTextContent("tools/call");
expect(methods[methods.length - 1]).toHaveTextContent("tools/list");
});
it("invokes onSortChange when the user picks a new sort", async () => {
const user = userEvent.setup();
const onSortChange = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
onSortChange={onSortChange}
/>,
);
await user.click(
screen.getByRole("textbox", { name: "History sort direction" }),
);
await user.click(await screen.findByText("Oldest First"));
expect(onSortChange).toHaveBeenCalledWith("oldest-first");
});
it("renders entries collapsed when compact is true (default parity with Network)", () => {
renderWithMantine(
<ProtocolListPanel {...baseProps} entries={sampleEntries} compact />,
);
expect(
screen.getAllByRole("button", { name: "Expand" }).length,
).toBeGreaterThan(0);
});
it("renders entries expanded when compact is false", () => {
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
compact={false}
/>,
);
expect(
screen.getAllByRole("button", { name: "Collapse" }).length,
).toBeGreaterThan(0);
});
it("invokes onToggleCompact when the ListToggle is clicked", async () => {
const user = userEvent.setup();
const onToggleCompact = vi.fn();
renderWithMantine(
<ProtocolListPanel
{...baseProps}
entries={sampleEntries}
onToggleCompact={onToggleCompact}
/>,
);
await user.click(screen.getByRole("button", { name: "Expand all" }));
expect(onToggleCompact).toHaveBeenCalledTimes(1);
});
});

View file

@ -0,0 +1,365 @@
import { useMemo, useState, type ReactNode } from "react";
import {
Button,
Collapse,
Group,
Paper,
Stack,
Text,
Title,
UnstyledButton,
} from "@mantine/core";
import type {
MessageEntry,
MessageMethod,
MessageOrigin,
} from "@inspector/core/mcp/types.js";
import { ProtocolEntry } from "../ProtocolEntry/ProtocolEntry";
import { ListToggle } from "../../elements/ListToggle/ListToggle";
import {
SortToggle,
type SortDirection,
} from "../../elements/SortToggle/SortToggle";
import { PinColumnButton } from "../../elements/PinColumnButton/PinColumnButton";
import { EmbeddableScrollArea } from "../../elements/EmbeddableScrollArea/EmbeddableScrollArea";
import { extractMethod } from "../protocolUtils.js";
import { useScrollMemory } from "../../../hooks/useScrollMemory";
export interface ProtocolListPanelProps {
entries: MessageEntry[];
pinnedIds: Set<string>;
searchText: string;
methodFilter?: MessageMethod;
/** Which message directions to show, keyed by entry origin. */
visibleDirections: Record<MessageOrigin, boolean>;
onClearAll: () => void;
onExport: () => void;
/** Clear just one section's entries (pinned vs unpinned history). */
onClearSection: (section: ProtocolSectionName) => void;
/** Export just one section's entries. */
onExportSection: (section: ProtocolSectionName) => void;
onReplay: (id: string) => void;
onTogglePin: (id: string) => void;
sortDirection: SortDirection;
onSortChange: (next: SortDirection) => void;
compact: boolean;
onToggleCompact: () => void;
/** See LogStreamPanel: shows a "pin as column" button when set (#1616). */
onPin?: () => void;
/** See LogStreamPanel: fills the flex parent instead of the viewport calc. */
embedded?: boolean;
}
const PanelContainer = Paper.withProps({
withBorder: true,
p: "lg",
flex: 1,
variant: "panel",
});
const EmptyState = Text.withProps({
c: "dimmed",
ta: "center",
py: "xl",
});
// The section header is a single "pleat" bar (rounded, with the filter-button
// outline-on-hover treatment and the active background passed per instance via
// `bg`). Inside it sit the
// clickable toggle area (the title, filling the left) and the optional
// Clear/Export actions on the right — so the actions live on the pleat itself,
// not beside it. The toggle is its own button (the actions can't nest inside a
// button), `flex: 1` so it spans the bar up to the actions.
const SectionHeaderBar = Group.withProps({
variant: "sectionHeader",
gap: "sm",
wrap: "nowrap",
p: "sm",
});
const SectionToggleArea = UnstyledButton.withProps({
flex: 1,
});
const SectionTitle = Text.withProps({
fw: 600,
});
const SectionActionGroup = Group.withProps({
gap: "sm",
wrap: "nowrap",
});
// Subtle link-style button, matching the Select/Deselect All control in
// ProtocolControls.
const SectionLinkButton = Button.withProps({
variant: "subtle",
size: "xs",
});
function formatPinnedTitle(count: number): string {
return `Pinned Requests (${count})`;
}
function formatHistoryTitle(count: number): string {
return `History (${count})`;
}
type ProtocolSectionName = "pinned" | "history";
// Per-section Clear / Export links, shown to the right of a section header when
// both sections are present (so each can be cleared/exported on its own).
function SectionActions({
onClear,
onExport,
}: {
onClear: () => void;
onExport: () => void;
}) {
return (
<SectionActionGroup>
<SectionLinkButton onClick={onClear}>Clear</SectionLinkButton>
<SectionLinkButton onClick={onExport}>Export</SectionLinkButton>
</SectionActionGroup>
);
}
// A History section. When `collapsible` (both sections are on screen) the header
// is a `listItem` toggle — with an optional actions slot on the right — over a
// `Collapse` of the entries. When it's the only section, the accordion makes no
// sense: the header is a plain title and the entries always show (so a stale
// collapsed state from when both sections were present can't hide them) —
// unless `hideHeaderWhenAlone`, in which case the lone section drops its title
// entirely (the "Protocol" label is redundant when there's nothing to
// distinguish it from).
function CollapsibleSection({
title,
collapsible,
hideHeaderWhenAlone = false,
open,
onToggle,
actions,
children,
}: {
title: string;
collapsible: boolean;
hideHeaderWhenAlone?: boolean;
open: boolean;
onToggle: () => void;
actions?: ReactNode;
children: ReactNode;
}) {
if (!collapsible) {
return (
<Stack gap="md">
{hideHeaderWhenAlone ? null : <Title order={5}>{title}</Title>}
<Stack gap="md">{children}</Stack>
</Stack>
);
}
return (
<Stack gap="md">
<SectionHeaderBar
bg={open ? "var(--mantine-primary-color-light)" : undefined}
>
<SectionToggleArea aria-expanded={open} onClick={onToggle}>
<SectionTitle>{title}</SectionTitle>
</SectionToggleArea>
{actions}
</SectionHeaderBar>
<Collapse in={open}>
<Stack gap="md">{children}</Stack>
</Collapse>
</Stack>
);
}
function matchesFilters(
entry: MessageEntry,
searchText: string,
visibleDirections: Record<MessageOrigin, boolean>,
methodFilter: MessageMethod | undefined,
// The embedded column exposes only the search box (no direction/method
// controls), so it applies the text filter but skips those (#1616).
ignoreDirectionAndMethod: boolean,
): boolean {
const method = extractMethod(entry);
if (!ignoreDirectionAndMethod) {
// Hide a direction when its toggle is off. Entries with no recorded origin
// (legacy / pre-origin logs) are never filtered out by direction.
if (entry.origin && !visibleDirections[entry.origin]) return false;
if (methodFilter && method !== methodFilter) return false;
}
if (searchText) {
const term = searchText.toLowerCase();
const responseText = entry.response ? JSON.stringify(entry.response) : "";
const searchable =
`${method} ${entry.id} ${JSON.stringify(entry.message)} ${responseText}`.toLowerCase();
if (!searchable.includes(term)) return false;
}
return true;
}
export function ProtocolListPanel({
entries,
pinnedIds,
searchText,
methodFilter,
visibleDirections,
onClearAll,
onExport,
onClearSection,
onExportSection,
onReplay,
onTogglePin,
sortDirection,
onSortChange,
compact,
onToggleCompact,
onPin,
embedded = false,
}: ProtocolListPanelProps) {
const viewportRef = useScrollMemory("protocol-list");
// Per-section expand/collapse, like the LogControls level toggles. Both start
// open; collapsing hides that section's entries without affecting the other.
const [pinnedOpen, setPinnedOpen] = useState(true);
const [historyOpen, setHistoryOpen] = useState(true);
const filteredEntries = useMemo(() => {
// Embedded column filters by text only (its direction/method controls live
// in the full-size sidebar). See LogStreamPanel (#1616). `.filter()` returns
// a fresh array, so sorting in-place is safe.
const sorted = entries
.filter((e) =>
matchesFilters(
e,
searchText,
visibleDirections,
methodFilter,
embedded,
),
)
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
if (sortDirection === "newest-first") sorted.reverse();
return sorted;
}, [
entries,
searchText,
visibleDirections,
methodFilter,
sortDirection,
embedded,
]);
const pinnedEntries = useMemo(
() => filteredEntries.filter((e) => pinnedIds.has(e.id)),
[filteredEntries, pinnedIds],
);
const unpinnedEntries = useMemo(
() => filteredEntries.filter((e) => !pinnedIds.has(e.id)),
[filteredEntries, pinnedIds],
);
const hasResults = filteredEntries.length > 0;
// Per-section Clear/Export only make sense when both sections are on screen;
// with a single section the panel-level Clear/Export already covers it.
const bothSections = pinnedEntries.length > 0 && unpinnedEntries.length > 0;
return (
<PanelContainer>
<Group justify="space-between" mb="sm">
<Title order={4}>Requests</Title>
<Group gap="xs">
<SortToggle
value={sortDirection}
onChange={onSortChange}
aria-label="History sort direction"
/>
<Button
variant="default"
onClick={onClearAll}
disabled={unpinnedEntries.length === 0}
>
Clear
</Button>
<Button variant="default" onClick={onExport} disabled={!hasResults}>
Export
</Button>
{hasResults && (
<ListToggle compact={compact} onToggle={onToggleCompact} />
)}
{onPin ? <PinColumnButton onPin={onPin} /> : null}
</Group>
</Group>
{!hasResults ? (
<EmptyState>No request history</EmptyState>
) : (
<EmbeddableScrollArea embedded={embedded} viewportRef={viewportRef}>
<Stack gap="md">
{pinnedEntries.length > 0 && (
<CollapsibleSection
title={formatPinnedTitle(pinnedEntries.length)}
collapsible={bothSections}
open={pinnedOpen}
onToggle={() => setPinnedOpen((v) => !v)}
actions={
bothSections ? (
<SectionActions
onClear={() => onClearSection("pinned")}
onExport={() => onExportSection("pinned")}
/>
) : undefined
}
>
{pinnedEntries.map((entry) => (
<ProtocolEntry
key={entry.id}
entry={entry}
isPinned={true}
isListExpanded={!compact}
embedded={embedded}
onReplay={() => onReplay(entry.id)}
onTogglePin={() => onTogglePin(entry.id)}
/>
))}
</CollapsibleSection>
)}
{unpinnedEntries.length > 0 && (
<CollapsibleSection
title={formatHistoryTitle(unpinnedEntries.length)}
collapsible={bothSections}
// With no pinned section to distinguish it from, the lone
// "History (N)" header is redundant — drop it.
hideHeaderWhenAlone
open={historyOpen}
onToggle={() => setHistoryOpen((v) => !v)}
actions={
bothSections ? (
<SectionActions
onClear={() => onClearSection("history")}
onExport={() => onExportSection("history")}
/>
) : undefined
}
>
{unpinnedEntries.map((entry) => (
<ProtocolEntry
key={entry.id}
entry={entry}
isPinned={false}
isListExpanded={!compact}
embedded={embedded}
onReplay={() => onReplay(entry.id)}
onTogglePin={() => onTogglePin(entry.id)}
/>
))}
</CollapsibleSection>
)}
</Stack>
</EmbeddableScrollArea>
)}
</PanelContainer>
);
}

View file

@ -33,7 +33,7 @@ export const Connected: Story = {
"Prompts",
"Tasks",
"Logs",
"History",
"Protocol",
],
onTabChange: fn(),
onDisconnect: fn(),

View file

@ -0,0 +1,60 @@
import { describe, it, expect } from "vitest";
import type { MessageEntry } from "@inspector/core/mcp/types.js";
import { extractMethod } from "./protocolUtils";
describe("extractMethod", () => {
it("returns the method name for a request entry", () => {
const entry: MessageEntry = {
id: "1",
timestamp: new Date(),
direction: "request",
message: {
jsonrpc: "2.0",
id: 1,
method: "tools/list",
},
};
expect(extractMethod(entry)).toBe("tools/list");
});
it("returns the method name for a notification entry", () => {
const entry: MessageEntry = {
id: "2",
timestamp: new Date(),
direction: "notification",
message: {
jsonrpc: "2.0",
method: "notifications/initialized",
},
};
expect(extractMethod(entry)).toBe("notifications/initialized");
});
it("returns 'response' for a result-response entry without a method", () => {
const entry: MessageEntry = {
id: "3",
timestamp: new Date(),
direction: "response",
message: {
jsonrpc: "2.0",
id: 1,
result: { tools: [] },
},
};
expect(extractMethod(entry)).toBe("response");
});
it("returns 'response' for an error-response entry without a method", () => {
const entry: MessageEntry = {
id: "4",
timestamp: new Date(),
direction: "response",
message: {
jsonrpc: "2.0",
id: 1,
error: { code: -32600, message: "Invalid Request" },
},
};
expect(extractMethod(entry)).toBe("response");
});
});

View file

@ -0,0 +1,34 @@
import type { MessageEntry, MessageMethod } from "@inspector/core/mcp/types.js";
export function extractMethod(entry: MessageEntry): MessageMethod {
if ("method" in entry.message) {
// Cast: SDK types message.method as `string`, but every entry in this
// app's MessageEntry log originates from MCP SDK schemas.
return entry.message.method as MessageMethod;
}
return "response";
}
/**
* Request methods the Protocol Replay action can re-issue (client→server reads
* and calls). Server→client requests (roots/list, sampling, elicitation) and
* side-effectful methods (logging/setLevel, subscribe) are intentionally
* excluded. Single source of truth: `ProtocolEntry` hides the Replay button for
* anything not listed here, and App's `replayProtocolRequest` gates dispatch on
* the same set.
*/
export const REPLAYABLE_PROTOCOL_METHODS: ReadonlySet<string> = new Set([
"tools/call",
"prompts/get",
"resources/read",
"tools/list",
"prompts/list",
"resources/list",
"resources/templates/list",
"tasks/list",
"ping",
]);
export function isReplayableProtocolMethod(method: string): boolean {
return REPLAYABLE_PROTOCOL_METHODS.has(method);
}