diff --git a/.claude/skills/test-servers/SKILL.md b/.claude/skills/test-servers/SKILL.md index 27d2dbfcfd..07a7eabc7c 100644 --- a/.claude/skills/test-servers/SKILL.md +++ b/.claude/skills/test-servers/SKILL.md @@ -59,7 +59,8 @@ row, never by the caller's category. process: - **A script.** `scripts/smoke-web-elicitation.mjs` spawns it directly; `scripts/lib/mcp-app-flow.mjs` (`startMcpAppServer`) does it for - `smoke:web:app`, `smoke:web:tabs` and `pack:verify`. These are automated and + `smoke:web:app`, `smoke:web:tabs`, `smoke:web:events` and `pack:verify`. + These are automated and config-driven, and the whole of this skill applies to them. ⚠️ **Not every smoke is here** — `smoke:cli` and `smoke:tui` use the two shapes above and pick no config at all. diff --git a/.claude/skills/testing/SKILL.md b/.claude/skills/testing/SKILL.md index 519e64e2a4..b79032246a 100644 --- a/.claude/skills/testing/SKILL.md +++ b/.claude/skills/testing/SKILL.md @@ -50,8 +50,8 @@ ways to depend on one, and they need different halves of that skill: override, so if the case needs a specific tool set it is an in-process HTTP test instead. - **A config-driven web smoke, or `pack:verify` → spawned composable HTTP.** - `smoke:web:elicitation`, `smoke:web:app`, `smoke:web:tabs` and `pack:verify` - all spawn `server-composable.js --config .json`. **The showcase-config + `smoke:web:elicitation`, `smoke:web:app`, `smoke:web:tabs`, + `smoke:web:events` and `pack:verify` all spawn `server-composable.js --config .json`. **The showcase-config and protocol-era guidance applies to you in full** — being automated does not exempt a smoke from it. @@ -189,7 +189,7 @@ Storybook play functions (`test:storybook`) → the published-tarball check across the tiers rather than along them.** Needing `test-servers/`: the web integration tests **that drive one**, the out-of-process CLI tests, the smokes that connect (`smoke:cli`, `smoke:web:app`, `smoke:web:elicit`, -`smoke:web:tabs`), `pack:verify`, and **`smoke:tui`** — which never asserts a +`smoke:web:tabs`, `smoke:web:events`), `pack:verify`, and **`smoke:tui`** — which never asserts a round trip but calls `ensureTestServers({ requires: ["stdio"] })` and hands the built fixture to the TUI as its catalog's stdio command. Not needing it: the pure tests inside the same integration project, the connecting tests that diff --git a/clients/web/README.md b/clients/web/README.md index 3e81a779d7..8b27f77f3a 100644 --- a/clients/web/README.md +++ b/clients/web/README.md @@ -52,12 +52,23 @@ Components live under `src/components/` in four layers, smallest to largest: | Layer | Count | What it is | | ----------- | ----- | ------------------------------------------------------------------------------ | -| `elements/` | ~48 | Leaf presentational pieces (badges, buttons, toggles) over Mantine primitives. | -| `groups/` | ~64 | Composite pieces (cards, panels, modals, control bars). | -| `screens/` | ~11 | Full tab screens (Tools, Resources, Servers, monitoring screens…). | +| `elements/` | ~51 | Leaf presentational pieces (badges, buttons, toggles) over Mantine primitives. | +| `groups/` | ~73 | Composite pieces (cards, panels, modals, control bars). | +| `screens/` | ~12 | Full tab screens (Tools, Resources, Servers, monitoring screens…). | | `views/` | 1 | `InspectorView` — the top-level layout that composes the screens. | -Every screen and element has a `*.stories.tsx` (see [Storybook](#storybook)). Styling follows the Mantine-first rules in [`AGENTS.md`](../../AGENTS.md) — theme variants and component props over CSS, `--inspector-*` tokens over raw colors. +Every screen and element has a `*.stories.tsx` (see [Storybook](#storybook)). + +## The Events tab + +The **Events** tab ([#3030](https://github.com/modelcontextprotocol/inspector/issues/3030)) inspects a server's [Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). It is shown only on a **modern-era** connection to a server that advertises the extension; a legacy connection never shows it, even when the server declares the key, because the client never sends `events/*` there. + +- **Event types** (`EventControls`): `events/list`, with each type's description and a badge per advertised delivery mode, following `notifications/events/list_changed` and the paginated-lists setting like the Tools list. Types excluded for invalid `x-mcp-header` annotations are listed below with the reason. +- **Subscribe form** (`EventDetailPanel`): the type's `inputSchema` and `payloadSchema`, the `Mcp-Name` and `Mcp-Param-*` headers its requests carry, an argument form generated from `inputSchema` by the shared `SchemaForm`, a mode picker limited to the type's advertised modes, and `maxAgeMs` plus `maxEvents` (poll) or `heartbeatMs` (push). +- **Subscriptions** (`EventSubscriptionCard`): mode, state (starting, active, reconnecting, terminated, stopped), current cursor, granted heartbeat or `nextPollMs`, tallies including gaps and errors, the last error and how a termination was handled, with Stop, Resume and Remove. +- **Occurrences** (`EventLogPanel`): newest first, each occurrence's `data` rendered as **inert JSON text only** (payloads are untrusted), with a payload-schema validation badge, interleaved with the gap, error, reconnect and termination markers. + +The subscriptions and the log are the core subscription engine's (`EventSubscriptionsState`); the screen only renders them. **Webhook** management is a later phase ([#3031](https://github.com/modelcontextprotocol/inspector/issues/3031)): the mode picker is built from `SUBSCRIBABLE_DELIVERY_MODES` in `src/utils/eventsUtils.ts` (`poll`, `push`), so a webhook-only type still lists with its badge but explains that it cannot be subscribed to here yet. Styling follows the Mantine-first rules in [`AGENTS.md`](../../AGENTS.md) — theme variants and component props over CSS, `--inspector-*` tokens over raw colors. ## Load testing (`#2911`) @@ -115,12 +126,14 @@ Nothing _enforces_ the boundary — no path alias keys off it, and the coverage ## Core tab automation contract -The Tools, Resources, Prompts and Skills screens each expose a `data-testid` plus a +The Tools, Resources, Prompts, Skills and Events screens each expose a `data-testid` plus a small set of `data-*` attributes, so a headless driver can `waitForSelector` on a deterministic signal rather than on visible copy. `scripts/smoke-web-tabs.mjs` drives the first three of those four against `test-servers/configs/web-tabs-http.json` ([#2148](https://github.com/modelcontextprotocol/inspector/issues/2148)); Skills publishes the same contract but is not smoked yet ([#2234](https://github.com/modelcontextprotocol/inspector/issues/2234)). +`scripts/smoke-web-events.mjs` drives Events against `test-servers/configs/events-modern-http.json` +([#3030](https://github.com/modelcontextprotocol/inspector/issues/3030)). Treat them as a public contract, for the same reason as the Apps ones below: | Attribute | Where | Meaning | @@ -142,6 +155,12 @@ Treat them as a public contract, for the same reason as the Apps ones below: | `data-skill-count` | on `skills-screen` | Entries accumulated from `skills/list`. | | `data-skill-page-count` | on `skills-screen` | Pages the last `skills/list` walk took — a **separate** fact from the count, and the one that shows pagination actually happened. | | `data-testid="skill-manifest"` | detail pane | The selected skill's resource manifest. Absent for a `resources: "dynamic"` skill, which has no manifest to render. | +| `data-testid="events-screen"` | Events root | The element carrying the three attributes below ([#3030](https://github.com/modelcontextprotocol/inspector/issues/3030)). | +| `data-event-count` | on `events-screen` | Event types listed (`events/list`, after exclusions). | +| `data-subscription-count` | on `events-screen` | Subscriptions in the engine's registry, live or not. | +| `data-log-count` | on `events-screen` | Entries in the occurrence log, every subscription's. | +| `data-testid="event-subscription"` | each subscription | One per subscription, with `data-status` = `starting` / `active` / `reconnecting` / `terminated` / `stopped`. | +| `data-testid="event-log-entry"` | each log entry | One per log entry, with `data-kind` = `event` / `gap` / `error` / `reconnect` / `terminated`. | Why attributes rather than text: a smoke that waited on a label fails the next time the label is reworded, which is noise rather than signal — and it fails as diff --git a/clients/web/src/App.tsx b/clients/web/src/App.tsx index 26c7f8b207..d5a6981bbd 100644 --- a/clients/web/src/App.tsx +++ b/clients/web/src/App.tsx @@ -79,6 +79,7 @@ import type { ServerListProps, ShellProps, SkillsPanelProps, + EventsPanelProps, TasksPanelProps, ToolsPanelProps, } from "./components/views/InspectorView/types"; @@ -484,6 +485,14 @@ function App() { skillsPageCount, skillsLoadError, refreshSkills, + eventsPagination, + excludedEventTypes, + eventsListChanged, + clearEventsListChanged, + refreshEvents, + loadEventsPage, + eventSubscriptions, + eventLog, subscriptions, subscriptionStreamState, messages, @@ -930,6 +939,8 @@ function App() { onLoadMoreTools, onLoadMorePrompts, onLoadMoreResources, + onRefreshEvents, + onLoadMoreEvents, } = useServerCommands({ sessionRef, servers, @@ -964,6 +975,10 @@ function App() { loadToolsPage, loadPromptsPage, loadResourcesPage, + eventsPagination, + refreshEvents, + clearEventsListChanged, + loadEventsPage, lastPersistedSettings, applyLiveServerSettings, updateServerSettings, @@ -1101,6 +1116,14 @@ function App() { loadedPages: resourcesPagination.loadedPages, onLoadMore: onLoadMoreResources, }; + const eventsPaginationControls: ListPaginationControlsProps = { + paginated: eventsPagination.paginated, + onPaginatedChange: onTogglePaginatedLists, + canLoadMore: eventsPagination.canLoadMore, + loadedPages: eventsPagination.loadedPages, + loaded: eventsPagination.loaded, + onLoadMore: onLoadMoreEvents, + }; // Clear / Export / Replay for the four log-ish views (Logs, Protocol, // Network, Console), plus the Protocol per-section variants. @@ -1973,6 +1996,33 @@ function App() { : {}), }; + // Events (SEP-3415, #3030). The subscription engine is per session, so the + // actions read the live one; with none (between sessions) a subscribe has + // nothing to run on and says so, and the rest have nothing to act on. + const eventSubscriptionsState = stores?.eventSubscriptionsState ?? null; + const eventsPanelProps: EventsPanelProps = { + eventTypes: eventsPagination.items, + excludedEventTypes, + eventsListChanged, + eventsLoadError: eventsPagination.error, + eventsPagination: eventsPaginationControls, + eventSubscriptions, + eventLog, + eventsUi: ui.eventsUi, + onEventsUiChange: setUi.setEventsUi, + onRefreshEvents, + onSubscribeEvent: (eventType, options) => { + if (!eventSubscriptionsState) throw new Error("Not connected."); + eventSubscriptionsState.subscribe(eventType, options); + }, + onStopEventSubscription: (id) => eventSubscriptionsState?.stop(id), + onResumeEventSubscription: (id) => { + eventSubscriptionsState?.resubscribe(id); + }, + onRemoveEventSubscription: (id) => eventSubscriptionsState?.remove(id), + onClearEventLog: () => eventSubscriptionsState?.clearLog(), + }; + const tasksPanelProps: TasksPanelProps = { tasks, progressByTaskId, @@ -2047,6 +2097,7 @@ function App() { resources={resourcesPanelProps} apps={appsPanelProps} skills={skillsPanelProps} + events={eventsPanelProps} tasks={tasksPanelProps} logs={logsPanelProps} protocol={protocolPanelProps} diff --git a/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.stories.tsx b/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.stories.tsx new file mode 100644 index 0000000000..359376fb47 --- /dev/null +++ b/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.stories.tsx @@ -0,0 +1,15 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { DeliveryModeBadge } from "./DeliveryModeBadge"; + +const meta: Meta = { + title: "Elements/DeliveryModeBadge", + component: DeliveryModeBadge, +}; + +export default meta; +type Story = StoryObj; + +export const Poll: Story = { args: { mode: "poll" } }; +export const Push: Story = { args: { mode: "push" } }; +export const Webhook: Story = { args: { mode: "webhook" } }; +export const UnknownMode: Story = { args: { mode: "carrier-pigeon" } }; diff --git a/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.test.tsx b/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.test.tsx new file mode 100644 index 0000000000..2950eee237 --- /dev/null +++ b/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.test.tsx @@ -0,0 +1,20 @@ +import { describe, it, expect } from "vitest"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { DeliveryModeBadge } from "./DeliveryModeBadge"; + +describe("DeliveryModeBadge", () => { + it.each(["poll", "push", "webhook"])("renders the %s mode", (mode) => { + renderWithMantine(); + expect(screen.getByText(mode)).toBeInTheDocument(); + }); + + it("renders a mode named after an Object member as an unknown one", () => { + renderWithMantine(); + expect(screen.getByText("constructor")).toBeInTheDocument(); + }); + + it("still renders a mode this client does not know", () => { + renderWithMantine(); + expect(screen.getByText("carrier-pigeon")).toBeInTheDocument(); + }); +}); diff --git a/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.tsx b/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.tsx new file mode 100644 index 0000000000..4ec7a95c88 --- /dev/null +++ b/clients/web/src/components/elements/DeliveryModeBadge/DeliveryModeBadge.tsx @@ -0,0 +1,40 @@ +import { Badge } from "@mantine/core"; +import { filledBadgeColor } from "../filledBadgeColor"; + +export interface DeliveryModeBadgeProps { + /** + * A delivery mode from an event type's `delivery` (SEP-3415). A string + * rather than the three known modes: a server may advertise one this client + * does not know, and the list still shows it (in gray) rather than hiding it. + */ + mode: string; +} + +// A Map, not an object literal: the mode is server-controlled, and a name like +// `constructor` or `__proto__` must miss rather than hit an inherited member. +const COLOR_BY_MODE: ReadonlyMap = new Map([ + ["poll", "blue"], + ["push", "teal"], + ["webhook", "grape"], +]); + +const ModeBadge = Badge.withProps({ + variant: "filled", + autoContrast: true, + size: "sm", + // Mode names are lowercase protocol literals; keep their casing. + tt: "none", +}); + +/** + * Badge naming one Events delivery mode (`poll`, `push`, `webhook`), one + * distinct color each so an event type's offer reads at a glance in the list. + * Filled + `autoContrast` like the other semantic badges, for WCAG AA. + */ +export function DeliveryModeBadge({ mode }: DeliveryModeBadgeProps) { + return ( + + {mode} + + ); +} diff --git a/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.stories.tsx b/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.stories.tsx new file mode 100644 index 0000000000..d3fac712de --- /dev/null +++ b/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.stories.tsx @@ -0,0 +1,16 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { EventSubscriptionStatusBadge } from "./EventSubscriptionStatusBadge"; + +const meta: Meta = { + title: "Elements/EventSubscriptionStatusBadge", + component: EventSubscriptionStatusBadge, +}; + +export default meta; +type Story = StoryObj; + +export const Starting: Story = { args: { status: "starting" } }; +export const Active: Story = { args: { status: "active" } }; +export const Reconnecting: Story = { args: { status: "reconnecting" } }; +export const Terminated: Story = { args: { status: "terminated" } }; +export const Stopped: Story = { args: { status: "stopped" } }; diff --git a/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.test.tsx b/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.test.tsx new file mode 100644 index 0000000000..aee6611575 --- /dev/null +++ b/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.test.tsx @@ -0,0 +1,19 @@ +import { describe, it, expect } from "vitest"; +import type { EventSubscriptionStatus } from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { EventSubscriptionStatusBadge } from "./EventSubscriptionStatusBadge"; + +describe("EventSubscriptionStatusBadge", () => { + const statuses: EventSubscriptionStatus[] = [ + "starting", + "active", + "reconnecting", + "terminated", + "stopped", + ]; + + it.each(statuses)("renders %s", (status) => { + renderWithMantine(); + expect(screen.getByText(status)).toBeInTheDocument(); + }); +}); diff --git a/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.tsx b/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.tsx new file mode 100644 index 0000000000..326944131a --- /dev/null +++ b/clients/web/src/components/elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge.tsx @@ -0,0 +1,35 @@ +import { Badge } from "@mantine/core"; +import type { EventSubscriptionStatus } from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { filledBadgeColor } from "../filledBadgeColor"; + +export interface EventSubscriptionStatusBadgeProps { + status: EventSubscriptionStatus; +} + +const statusColor: Record = { + starting: "blue", + active: "green", + reconnecting: "yellow", + terminated: "red", + stopped: "gray", +}; + +const FilledBadge = Badge.withProps({ + variant: "filled", + autoContrast: true, +}); + +/** + * The state of one Events subscription (SEP-3415, #3030): starting, active, + * reconnecting, terminated by the server, or stopped by the user. The + * TaskStatusBadge treatment, so the two read alike. + */ +export function EventSubscriptionStatusBadge({ + status, +}: EventSubscriptionStatusBadgeProps) { + return ( + + {status} + + ); +} diff --git a/clients/web/src/components/groups/EventControls/EventControls.test.tsx b/clients/web/src/components/groups/EventControls/EventControls.test.tsx new file mode 100644 index 0000000000..1ac7b6b1a4 --- /dev/null +++ b/clients/web/src/components/groups/EventControls/EventControls.test.tsx @@ -0,0 +1,119 @@ +import { useState } from "react"; +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { EventControls, type EventControlsProps } from "./EventControls"; +import { noopPagination } from "../../../test/fixtures/pagination"; +import { eventTypes, pollOnlyType } from "../../../test/fixtures/events"; + +const excluded = [ + { + eventType: { ...pollOnlyType, name: "invalid.header" }, + reason: "x-mcp-header value is not an RFC 9110 token", + }, +]; + +const baseProps: EventControlsProps = { + eventTypes, + listChanged: false, + onRefreshList: vi.fn(), + pagination: noopPagination, + onSearchChange: vi.fn(), + onSelectEventType: vi.fn(), +}; + +function Controlled(props: Partial) { + const [searchText, setSearchText] = useState(""); + return ( + + ); +} + +describe("EventControls", () => { + it("lists every event type sorted, with the server's count", () => { + renderWithMantine(); + expect(screen.getByRole("heading", { name: "Events (4)" })).toBeVisible(); + const names = screen + .getAllByRole("button", { name: /\./ }) + .map((b) => b.getAttribute("aria-label")); + expect(names).toEqual([ + "deploy.completed", + "email.received", + "incident.created", + "payment.settled", + ]); + }); + + it("selects a type, but not the one already selected", async () => { + const onSelectEventType = vi.fn(); + renderWithMantine( + , + ); + await userEvent.click( + screen.getByRole("button", { name: "email.received" }), + ); + expect(onSelectEventType).not.toHaveBeenCalled(); + await userEvent.click( + screen.getByRole("button", { name: "incident.created" }), + ); + expect(onSelectEventType).toHaveBeenCalledWith("incident.created"); + }); + + it("filters the list and the exclusions, and clears the search", async () => { + renderWithMantine(); + expect(screen.getByText("invalid.header")).toBeInTheDocument(); + await userEvent.type( + screen.getByPlaceholderText("Search events..."), + "deploy", + ); + expect( + screen.getByRole("button", { name: "deploy.completed" }), + ).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "email.received" }), + ).not.toBeInTheDocument(); + expect(screen.queryByText("invalid.header")).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: /clear/i })); + expect(screen.getByPlaceholderText("Search events...")).toHaveValue(""); + }); + + it("shows the reason an excluded type was left out", async () => { + renderWithMantine( + , + ); + await userEvent.hover(screen.getByText("invalid.header")); + expect( + await screen.findByText(/not an RFC 9110 token/), + ).toBeInTheDocument(); + }); + + it("withholds the count before the first load and on a failure", async () => { + const onRefreshList = vi.fn(); + const { rerender } = renderWithMantine( + , + ); + expect(screen.getByRole("heading", { name: "Events" })).toBeVisible(); + rerender( + , + ); + expect(screen.getByRole("heading", { name: "Events" })).toBeVisible(); + expect(screen.getByText("list failed")).toBeInTheDocument(); + }); +}); diff --git a/clients/web/src/components/groups/EventControls/EventControls.tsx b/clients/web/src/components/groups/EventControls/EventControls.tsx new file mode 100644 index 0000000000..71e159ccec --- /dev/null +++ b/clients/web/src/components/groups/EventControls/EventControls.tsx @@ -0,0 +1,197 @@ +import { + Divider, + Group, + ScrollArea, + Stack, + Text, + TextInput, + ThemeIcon, + Title, + Tooltip, +} from "@mantine/core"; +import { RiErrorWarningLine } from "react-icons/ri"; +import type { EventType } from "@inspector/core/extension/events/schemas.js"; +import type { ExcludedEventType } from "@inspector/core/extension/events/headers.js"; +import { ClearButton } from "../../elements/ClearButton/ClearButton"; +import { ListChangedIndicator } from "../../elements/ListChangedIndicator/ListChangedIndicator"; +import { ListLoadError } from "../../elements/ListLoadError/ListLoadError"; +import { + ListPaginationControls, + type ListPaginationControlsProps, +} from "../../elements/ListPaginationControls/ListPaginationControls"; +import { EventTypeListItem } from "../EventTypeListItem/EventTypeListItem"; +import { useScrollMemory } from "../../../hooks/useScrollMemory"; +import { filterEventTypes } from "../../../utils/eventsUtils"; +import { formatCountedLabel, listCountOf } from "../../../utils/listCount"; + +export interface EventControlsProps { + eventTypes: EventType[]; + /** + * Event types the client left out of `events/list` for invalid + * `x-mcp-header` annotations, shown below the list with the reason — the + * Tools sidebar's treatment of excluded tools (#1632). + */ + excludedEventTypes?: ExcludedEventType[]; + selectedName?: string; + /** Controlled by the parent so it survives tab navigation (#1417). */ + searchText?: string; + /** A `notifications/events/list_changed` arrived since the last refresh. */ + listChanged: boolean; + onRefreshList: () => void; + /** The last list load's failure, shown above the list (#1953). */ + loadError?: Error | null; + pagination: ListPaginationControlsProps; + onSearchChange: (value: string) => void; + onSelectEventType: (name: string) => void; +} + +// Fills the full-height `sidebar` Card so the list runs to the card's bottom +// before it scrolls; `mih: 0` lets the scroll child shrink (see ToolControls). +const SidebarStack = Stack.withProps({ + gap: "sm", + flex: 1, + mih: 0, +}); + +// h2 sized as h4: a panel heading under the page's hidden h1 (#2827). +const EventsTitle = Title.withProps({ + order: 2, + size: "h4", +}); + +const SearchInput = TextInput.withProps({ + placeholder: "Search events...", + rightSectionPointerEvents: "auto", +}); + +const SidebarScroll = ScrollArea.withProps({ + flex: 1, + mih: 0, +}); + +const ExcludedDivider = Divider.withProps({ + label: "Excluded (SEP-2243)", + labelPosition: "left", + mt: "sm", +}); + +const ExcludedTooltip = Tooltip.withProps({ + multiline: true, + w: 280, + withArrow: true, + position: "right", +}); + +const ExcludedRow = Group.withProps({ + gap: "xs", + wrap: "nowrap", + align: "center", +}); + +const ExcludedWarningIcon = ThemeIcon.withProps({ + size: "sm", + variant: "transparent", + c: "var(--inspector-log-warning)", + "aria-hidden": true, +}); + +const ExcludedName = Text.withProps({ + size: "sm", + td: "line-through", + c: "var(--inspector-text-secondary)", + truncate: "end", +}); + +/** + * The Events sidebar (SEP-3415, #3030): the server's event types with their + * delivery modes, a search, the list-changed indicator, pagination, and the + * types excluded for invalid header annotations. + */ +export function EventControls({ + eventTypes, + excludedEventTypes = [], + selectedName, + searchText = "", + listChanged, + onRefreshList, + loadError, + pagination, + onSearchChange, + onSelectEventType, +}: EventControlsProps) { + const viewportRef = useScrollMemory("events-sidebar"); + const visible = filterEventTypes(eventTypes, searchText); + const excludedTypes = filterEventTypes( + excludedEventTypes.map((excluded) => excluded.eventType), + searchText, + ); + const reasonOf = new Map( + excludedEventTypes.map((excluded) => [ + excluded.eventType.name, + excluded.reason, + ]), + ); + // The server's total, not the filtered view, withheld until a first load + // (#2607) — "(0)" before then would read as an empty server. + const title = formatCountedLabel( + "Events", + listCountOf({ + items: eventTypes, + canLoadMore: pagination.canLoadMore, + error: loadError ?? null, + loaded: pagination.loaded ?? true, + }), + ); + + return ( + + + {title} + + + onSearchChange(e.currentTarget.value)} + rightSection={ + searchText ? onSearchChange("")} /> : null + } + /> + + + + + {visible.map((eventType) => ( + { + if (eventType.name !== selectedName) { + onSelectEventType(eventType.name); + } + }} + /> + ))} + {excludedTypes.length > 0 && ( + <> + + {excludedTypes.map((eventType) => ( + + + + + + {eventType.name} + + + ))} + + )} + + + + ); +} diff --git a/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.stories.tsx b/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.stories.tsx new file mode 100644 index 0000000000..0b1f2e9609 --- /dev/null +++ b/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.stories.tsx @@ -0,0 +1,75 @@ +import { useState } from "react"; +import type { ComponentProps } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { expect, fn, userEvent, within } from "storybook/test"; +import type { EventSubscriptionMode } from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { EventDetailPanel } from "./EventDetailPanel"; +import type { SubscribeTuning } from "../../../utils/eventsUtils"; +import { + allModesType, + headerAnnotatedType, + pollOnlyType, + webhookOnlyType, +} from "../../../test/fixtures/events"; + +// Mode, tuning and arguments are lifted to the screen; this holds them so the +// story's controls respond. +function Stateful(args: ComponentProps) { + const [mode, setMode] = useState( + args.mode, + ); + const [tuning, setTuning] = useState(args.tuning); + const [formValues, setFormValues] = useState(args.formValues); + return ( + + ); +} + +const meta: Meta = { + title: "Groups/EventDetailPanel", + component: EventDetailPanel, + render: (args) => , + args: { + formValues: {}, + tuning: {}, + mode: "poll", + onFormChange: fn(), + onModeChange: fn(), + onTuningChange: fn(), + onSubscribe: fn(), + }, +}; + +export default meta; +type Story = StoryObj; + +export const AllModes: Story = { + args: { eventType: allModesType }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByText("Push")); + await expect(canvas.getByLabelText("heartbeatMs")).toBeInTheDocument(); + }, +}; +export const PollOnly: Story = { args: { eventType: pollOnlyType } }; +export const MirroredHeaders: Story = { + args: { eventType: headerAnnotatedType, formValues: { region: "us-west1" } }, +}; +export const WebhookOnly: Story = { + args: { eventType: webhookOnlyType, mode: undefined }, +}; +export const SubscribeRefused: Story = { + args: { + eventType: pollOnlyType, + subscribeError: + "The server does not offer the Events extension on this connection.", + }, +}; diff --git a/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.test.tsx b/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.test.tsx new file mode 100644 index 0000000000..6eec9cb645 --- /dev/null +++ b/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.test.tsx @@ -0,0 +1,172 @@ +import { useState } from "react"; +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import type { EventSubscriptionMode } from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { + EventDetailPanel, + type EventDetailPanelProps, +} from "./EventDetailPanel"; +import type { SubscribeTuning } from "../../../utils/eventsUtils"; +import { + allModesType, + headerAnnotatedType, + pollOnlyType, + webhookOnlyType, +} from "../../../test/fixtures/events"; + +const baseProps: EventDetailPanelProps = { + eventType: allModesType, + formValues: {}, + onFormChange: vi.fn(), + mode: "poll", + onModeChange: vi.fn(), + tuning: {}, + onTuningChange: vi.fn(), + onSubscribe: vi.fn(), +}; + +/** Holds the mode and tuning the way the screen does. */ +function Stateful(props: Partial) { + const [mode, setMode] = useState( + props.mode ?? "poll", + ); + const [tuning, setTuning] = useState({}); + const [formValues, setFormValues] = useState>({}); + return ( + <> + + {JSON.stringify({ mode, tuning })} + + ); +} + +function state() { + return JSON.parse(screen.getByTestId("state").textContent ?? "{}"); +} + +describe("EventDetailPanel", () => { + it("shows the type, its modes and its schemas as text", async () => { + renderWithMantine(); + // The title, and again as the Mcp-Name header value. + expect(screen.getAllByText("incident.created")).toHaveLength(2); + expect(screen.getByText(/new incident is created/)).toBeInTheDocument(); + expect(screen.getByText("webhook")).toBeInTheDocument(); + await userEvent.click( + screen.getByRole("button", { name: "Payload schema" }), + ); + expect(screen.getByText(/"incidentId"/)).toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "Input schema" })); + expect(screen.getByText(/"severity"/)).toBeInTheDocument(); + }); + + it("says when a type has no payload schema", async () => { + renderWithMantine( + , + ); + await userEvent.click( + screen.getByRole("button", { name: "Payload schema" }), + ); + expect(screen.getByText(/occurrences are not validated/)).toBeVisible(); + }); + + it("names the Mcp-Name header and every mirrored Mcp-Param header", () => { + renderWithMantine( + , + ); + expect(screen.getByText("Mcp-Name")).toBeInTheDocument(); + expect(screen.getAllByText("deploy.completed")).toHaveLength(2); + expect(screen.getByText("Mcp-Param-Region")).toBeInTheDocument(); + }); + + it("offers only the subscribable modes, and switches between them", async () => { + renderWithMantine(); + const group = screen.getByRole("radiogroup", { name: "Delivery mode" }); + expect(group).toHaveTextContent("Poll"); + expect(group).toHaveTextContent("Push"); + expect(group).not.toHaveTextContent(/webhook/i); + // Poll tuning: maxEvents, not heartbeatMs. + expect(screen.getByLabelText("maxEvents")).toBeInTheDocument(); + expect(screen.queryByLabelText("heartbeatMs")).not.toBeInTheDocument(); + await userEvent.click(screen.getByText("Push")); + expect(state().mode).toBe("push"); + expect(screen.getByLabelText("heartbeatMs")).toBeInTheDocument(); + expect(screen.queryByLabelText("maxEvents")).not.toBeInTheDocument(); + }); + + it("reports each tuning field as a whole number, or unset when cleared", async () => { + renderWithMantine(); + await userEvent.type(screen.getByLabelText("maxAgeMs"), "6000"); + await userEvent.type(screen.getByLabelText("maxEvents"), "5"); + expect(state().tuning).toEqual({ maxAgeMs: 6000, maxEvents: 5 }); + await userEvent.clear(screen.getByLabelText("maxEvents")); + expect(state().tuning).toEqual({ maxAgeMs: 6000 }); + await userEvent.click(screen.getByText("Push")); + await userEvent.type(screen.getByLabelText("heartbeatMs"), "15000"); + expect(state().tuning).toEqual({ maxAgeMs: 6000, heartbeatMs: 15000 }); + }); + + it("subscribes, and gates the button on a mode and the required arguments", async () => { + const onSubscribe = vi.fn(); + const { rerender } = renderWithMantine( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Subscribe" })); + expect(onSubscribe).toHaveBeenCalledTimes(1); + + // `region` is required and empty. + rerender( + , + ); + expect(screen.getByRole("button", { name: "Subscribe" })).toBeDisabled(); + }); + + it("refuses a restored maxEvents of 0", () => { + renderWithMantine( + , + ); + expect(screen.getByRole("button", { name: "Subscribe" })).toBeDisabled(); + }); + + it("explains a type with no subscribable mode", () => { + renderWithMantine( + , + ); + expect( + screen.getByText(/no delivery mode the Inspector can/), + ).toBeVisible(); + expect(screen.queryByRole("radiogroup")).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Subscribe" })).toBeDisabled(); + }); + + it("shows why the last subscribe was refused", () => { + renderWithMantine( + , + ); + expect(screen.getByText("Subscribe failed")).toBeInTheDocument(); + expect( + screen.getByText("does not advertise push delivery"), + ).toBeInTheDocument(); + }); +}); diff --git a/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.tsx b/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.tsx new file mode 100644 index 0000000000..6179c1c5c3 --- /dev/null +++ b/clients/web/src/components/groups/EventDetailPanel/EventDetailPanel.tsx @@ -0,0 +1,340 @@ +import { useState } from "react"; +import { + Accordion, + Alert, + Button, + Code, + Divider, + Group, + NumberInput, + ScrollArea, + SegmentedControl, + Stack, + Text, +} from "@mantine/core"; +import type { EventType } from "@inspector/core/extension/events/schemas.js"; +import type { EventSubscriptionMode } from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { DeliveryModeBadge } from "../../elements/DeliveryModeBadge/DeliveryModeBadge"; +import { SchemaForm } from "../SchemaForm/SchemaForm"; +import { + hasMissingRequiredFields, + toFormSchema, +} from "../../../utils/jsonUtils"; +import { + formatPayload, + isTuningValid, + mirroredEventHeaders, + optionalWholeNumber, + subscribableModes, + type SubscribeTuning, +} from "../../../utils/eventsUtils"; + +export interface EventDetailPanelProps { + eventType: EventType; + formValues: Record; + onFormChange: (values: Record) => void; + /** + * The mode to subscribe with, already resolved against what the type + * offers; `undefined` when it offers no mode this tab subscribes with. + */ + mode: EventSubscriptionMode | undefined; + onModeChange: (mode: EventSubscriptionMode) => void; + tuning: SubscribeTuning; + onTuningChange: (tuning: SubscribeTuning) => void; + onSubscribe: () => void; + /** Why the last subscribe was refused, shown above the button. */ + subscribeError?: string; + /** Per-selection identity for the schema form; see `SchemaFormProps`. */ + resetKey?: string; +} + +// Header pinned, body scrolls, Subscribe footer pinned — ToolDetailPanel's +// layout, so the form and its action stay in view together. +const PanelStack = Stack.withProps({ + gap: "md", + miw: 0, + mih: 0, +}); + +const PinnedHeader = Stack.withProps({ + gap: "xs", + flex: "0 0 auto", +}); + +const BodyScroll = ScrollArea.withProps({ + flex: "0 1 auto", + miw: 0, + mih: 0, + scrollbars: "y", + offsetScrollbars: true, +}); + +const BodyStack = Stack.withProps({ + gap: "md", +}); + +const EventTitle = Text.withProps({ + fw: 700, + size: "lg", + truncate: "end", +}); + +const DescriptionText = Text.withProps({ + size: "sm", + c: "dimmed", +}); + +const ModeRow = Group.withProps({ + gap: 4, +}); + +const SectionTitle = Text.withProps({ + size: "sm", + fw: 600, +}); + +const SectionNote = Text.withProps({ + size: "xs", + c: "var(--inspector-text-secondary)", +}); + +const HeaderSection = Stack.withProps({ + gap: "xs", +}); + +// Wraps rather than squeezing a header name into a narrow column. +const HeaderRow = Group.withProps({ + gap: 6, +}); + +const HeaderArrow = Text.withProps({ + size: "sm", + c: "var(--inspector-text-secondary)", +}); + +// The schemas are shown as text, in a block that wraps rather than scrolling +// sideways inside an already narrow column. +const SchemaBlock = Code.withProps({ + block: true, + variant: "wrapping", +}); + +const TuningRow = Group.withProps({ + gap: "sm", + grow: true, + align: "flex-start", +}); + +const TuningInput = NumberInput.withProps({ + min: 0, + allowDecimal: false, + allowNegative: false, + size: "sm", +}); + +// A batch cap or a heartbeat interval of zero means nothing a server can +// honor (the test fixture answers InvalidParams), so these start at 1. +const PositiveTuningInput = NumberInput.withProps({ + min: 1, + allowDecimal: false, + allowNegative: false, + size: "sm", +}); + +const FooterRow = Group.withProps({ + justify: "flex-start", + flex: "0 0 auto", +}); + +const ErrorAlert = Alert.withProps({ + color: "red", + variant: "light", +}); + +const NoModeNote = Text.withProps({ + size: "sm", + c: "var(--inspector-text-secondary)", +}); + +const MODE_LABELS: Record = { + poll: "Poll", + push: "Push", +}; + +/** + * The selected event type and the form that subscribes to it (SEP-3415, + * #3030): its description and delivery modes, its `inputSchema` and + * `payloadSchema`, the `Mcp-Param-*` headers its arguments mirror into, an + * argument form generated from `inputSchema`, a mode picker limited to the + * modes it advertises, and the replay and pacing options each mode accepts. + */ +export function EventDetailPanel({ + eventType, + formValues, + onFormChange, + mode, + onModeChange, + tuning, + onTuningChange, + onSubscribe, + subscribeError, + resetKey, +}: EventDetailPanelProps) { + const { name, description, delivery, inputSchema, payloadSchema } = eventType; + const formSchema = toFormSchema(inputSchema) ?? {}; + const modes = subscribableModes(eventType); + const mirrored = mirroredEventHeaders(eventType); + // A field holding text it could not turn into a value (#2020). + const [hasInvalidDraft, setHasInvalidDraft] = useState(false); + + const subscribeDisabled = + mode === undefined || + hasMissingRequiredFields(formSchema, formValues) || + hasInvalidDraft || + !isTuningValid(mode, tuning); + + return ( + + + {name} + + {delivery.map((m) => ( + + ))} + + + + + + {description && {description}} + + {/* Inline: `Accordion` is a compound, `multiple`-discriminated + generic whose `.withProps` loses its JSX signature (AGENTS.md). */} + + + Input schema + + {formatPayload(inputSchema)} + + + + Payload schema + + {payloadSchema ? ( + {formatPayload(payloadSchema)} + ) : ( + + No payload schema: occurrences are not validated. + + )} + + + + + + Request headers + + Mcp-Name + = + {name} + + {mirrored.map((param) => ( + + {param.path} + → + {param.header} + + ))} + + Sent on every poll and stream request for this event type, so a + Streamable HTTP server can route it without reading the body. + + + + + + + + {mode !== undefined ? ( + <> + { + const picked = modes.find((m) => m === value); + /* v8 ignore next -- the control only offers `modes` */ + if (picked) onModeChange(picked); + }} + data={modes.map((m) => ({ value: m, label: MODE_LABELS[m] }))} + /> + + + onTuningChange({ + ...tuning, + maxAgeMs: optionalWholeNumber(value), + }) + } + /> + {mode === "poll" ? ( + + onTuningChange({ + ...tuning, + maxEvents: optionalWholeNumber(value), + }) + } + /> + ) : ( + + onTuningChange({ + ...tuning, + heartbeatMs: optionalWholeNumber(value), + }) + } + /> + )} + + + ) : ( + + This event type offers no delivery mode the Inspector can + subscribe with here ({delivery.join(", ")}). + + )} + + + + {subscribeError && ( + {subscribeError} + )} + + + + + + ); +} diff --git a/clients/web/src/components/groups/EventLogPanel/EventLogPanel.stories.tsx b/clients/web/src/components/groups/EventLogPanel/EventLogPanel.stories.tsx new file mode 100644 index 0000000000..3cb52b35fd --- /dev/null +++ b/clients/web/src/components/groups/EventLogPanel/EventLogPanel.stories.tsx @@ -0,0 +1,23 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { fn } from "storybook/test"; +import { EventLogPanel } from "./EventLogPanel"; +import { eventLog, subscriptions } from "../../../test/fixtures/events"; + +const meta: Meta = { + title: "Groups/EventLogPanel", + component: EventLogPanel, + args: { onClear: fn(), subscriptions }, +}; + +export default meta; +type Story = StoryObj; + +/** Every entry kind: occurrences (valid, invalid, unchecked), gap, error, reconnect, termination. */ +export const EveryKind: Story = { args: { entries: eventLog } }; +export const Empty: Story = { args: { entries: [] } }; +export const FilteredToOne: Story = { + args: { + entries: eventLog.filter((e) => e.subscription === subscriptions[0]!.id), + filteredTo: "email.received (poll)", + }, +}; diff --git a/clients/web/src/components/groups/EventLogPanel/EventLogPanel.test.tsx b/clients/web/src/components/groups/EventLogPanel/EventLogPanel.test.tsx new file mode 100644 index 0000000000..e69bf69368 --- /dev/null +++ b/clients/web/src/components/groups/EventLogPanel/EventLogPanel.test.tsx @@ -0,0 +1,111 @@ +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { EventLogPanel } from "./EventLogPanel"; +import { + eventLog, + subscriptions, + terminatedPush, +} from "../../../test/fixtures/events"; + +describe("EventLogPanel", () => { + it("renders every entry kind, newest first", () => { + renderWithMantine( + , + ); + const kinds = screen + .getAllByTestId("event-log-entry") + .map((e) => e.getAttribute("data-kind")); + expect(kinds).toEqual([ + "event", + "terminated", + "reconnect", + "error", + "gap", + "event", + "event", + ]); + expect(screen.getByText("Occurrences (7)")).toBeInTheDocument(); + expect(screen.getByText(/Resuming from cursor c-42/)).toBeInTheDocument(); + expect( + screen.getByText("-32025 ResourceExhausted: Too many streams"), + ).toBeInTheDocument(); + expect( + screen.getByText("Reconnecting: no heartbeat for 90 s"), + ).toBeInTheDocument(); + expect( + screen.getByText(/removed: -32023 NotFound: Event type removed/), + ).toHaveTextContent(/Resume is offered/); + expect(screen.getByText(/cursor c-41/)).toBeInTheDocument(); + }); + + it("renders a payload as inert text, never as markup", () => { + renderWithMantine( + , + ); + // The fixture's subject is `not bold`: it must arrive as text. + expect(screen.getByText(/not bold<\/b>/)).toBeInTheDocument(); + expect(document.querySelector("b")).toBeNull(); + }); + + it("badges the recorded payload verdict: invalid, valid, or not checked", async () => { + renderWithMantine( + , + ); + expect(screen.getByText("payload valid")).toBeInTheDocument(); + expect(screen.getByText("payload not checked")).toBeInTheDocument(); + await userEvent.hover(screen.getByText("payload invalid")); + expect( + await screen.findByText("data must have required property 'from'"), + ).toBeInTheDocument(); + }); + + it("does not offer a resume on a termination that has none", () => { + renderWithMantine( + e.kind === "terminated")} + subscriptions={[ + { + ...terminatedPush, + termination: { + ...terminatedPush.termination!, + canResubscribe: false, + }, + }, + ]} + filteredTo="deploy.completed (push)" + onClear={vi.fn()} + />, + ); + expect( + screen.getByText("Occurrences — deploy.completed (push) (1)"), + ).toBeInTheDocument(); + expect(screen.queryByText(/Resume is offered/)).not.toBeInTheDocument(); + }); + + it("clears, and says when there is nothing yet", async () => { + const onClear = vi.fn(); + const { rerender } = renderWithMantine( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Clear" })); + expect(onClear).toHaveBeenCalled(); + rerender( + , + ); + expect(screen.getByText("No occurrences yet.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Clear" })).toBeDisabled(); + }); +}); diff --git a/clients/web/src/components/groups/EventLogPanel/EventLogPanel.tsx b/clients/web/src/components/groups/EventLogPanel/EventLogPanel.tsx new file mode 100644 index 0000000000..ad2d8c3818 --- /dev/null +++ b/clients/web/src/components/groups/EventLogPanel/EventLogPanel.tsx @@ -0,0 +1,256 @@ +import { + Badge, + Button, + Code, + Group, + Paper, + ScrollArea, + Stack, + Text, + Title, + Tooltip, +} from "@mantine/core"; +import type { + EventLogEntry, + EventSubscription, +} from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { + describeEventsError, + formatCursor, + formatPayload, +} from "../../../utils/eventsUtils"; + +export interface EventLogPanelProps { + /** The entries to show, oldest first (the store's order). */ + entries: EventLogEntry[]; + /** Every subscription, to name each entry's and find its payload schema. */ + subscriptions: EventSubscription[]; + /** Set when the log is narrowed to one subscription, to say so. */ + filteredTo?: string; + onClear: () => void; +} + +const PanelStack = Stack.withProps({ + gap: "sm", + flex: 1, + mih: 0, +}); + +const HeaderRow = Group.withProps({ + justify: "space-between", + wrap: "nowrap", +}); + +// h3 under the screen's h2 panel headings. +const PanelTitle = Title.withProps({ + order: 3, + size: "h5", +}); + +const ClearLogButton = Button.withProps({ + size: "compact-xs", + variant: "subtle", +}); + +// `tabIndex: 0` on the viewport: a log of payloads may hold nothing focusable, +// and axe's `scrollable-region-focusable` requires a scroll region to be +// reachable from the keyboard (the EmbeddableScrollArea treatment). +const LogScroll = ScrollArea.withProps({ + flex: 1, + mih: 0, + viewportProps: { tabIndex: 0 }, +}); + +const EntryFrame = Paper.withProps({ + withBorder: true, + p: "xs", + radius: "sm", +}); + +const EntryStack = Stack.withProps({ + gap: 4, +}); + +const EntryHeader = Group.withProps({ + gap: "xs", + wrap: "wrap", +}); + +const KindBadge = Badge.withProps({ + variant: "filled", + autoContrast: true, + size: "sm", + tt: "none", +}); + +const ValidationBadge = Badge.withProps({ + variant: "light", + size: "sm", + tt: "none", +}); + +const PayloadErrorTooltip = Tooltip.withProps({ + multiline: true, + w: 280, + withArrow: true, +}); + +const EntryMeta = Text.withProps({ + size: "xs", + c: "var(--inspector-text-secondary)", +}); + +const EntryText = Text.withProps({ + size: "xs", +}); + +// Payloads are untrusted (spec, Security): rendered as a text node in a code +// block, never as Markdown or HTML. +// `wrapping` so a long value wraps instead of opening a horizontal scroll +// region of its own. +const PayloadBlock = Code.withProps({ + block: true, + variant: "wrapping", +}); + +const EmptyText = Text.withProps({ + size: "sm", + c: "dimmed", + ta: "center", + py: "md", +}); + +const KIND_COLORS: Record = { + event: "blue", + gap: "yellow.5", + error: "red", + reconnect: "orange.5", + terminated: "red", +}; + +function EntryBody({ + entry, + subscription, +}: { + entry: EventLogEntry; + subscription: EventSubscription | undefined; +}) { + switch (entry.kind) { + case "event": + return ( + <> + + {entry.occurrence.timestamp} · eventId {entry.occurrence.eventId} + {entry.occurrence.cursor != null && + ` · cursor ${entry.occurrence.cursor}`} + + {formatPayload(entry.occurrence.data)} + + ); + case "gap": + return ( + + Events may have been missed (the server truncated the replay). + Resuming from cursor {formatCursor(entry.cursor)}. + + ); + case "error": + return {describeEventsError(entry.error)}; + case "reconnect": + return Reconnecting: {entry.reason}; + case "terminated": + return ( + + {entry.reason}: {describeEventsError(entry.error)} + {subscription?.termination?.canResubscribe && + " — the event type is still listed; Resume is offered."} + + ); + } +} + +/** + * The verdict the engine recorded when the occurrence arrived — not one + * re-derived from the subscription's current descriptor, which a re-list can + * replace after the fact. + */ +function ValidationFlag({ entry }: { entry: EventLogEntry }) { + if (entry.kind !== "event") return null; + switch (entry.payload) { + case "invalid": + return ( + + payload invalid + + ); + case "valid": + return payload valid; + case "unchecked": + return ( + payload not checked + ); + } +} + +/** + * The Events occurrence stream (SEP-3415, #3030), newest first: each + * occurrence with its `data` as inert JSON and a payload-schema validation + * badge, interleaved with the gap, error, reconnect and termination markers + * the subscription engine logs, so every outcome is visible. + */ +export function EventLogPanel({ + entries, + subscriptions, + filteredTo, + onClear, +}: EventLogPanelProps) { + const byId = new Map(subscriptions.map((s) => [s.id, s])); + const newestFirst = [...entries].reverse(); + + return ( + + + + Occurrences{filteredTo ? ` — ${filteredTo}` : ""} ({entries.length}) + + + Clear + + + + {newestFirst.length === 0 ? ( + No occurrences yet. + ) : ( + + {newestFirst.map((entry) => { + const subscription = byId.get(entry.subscription); + return ( + + + + + {entry.kind} + + + {subscription + ? `${subscription.name} (${subscription.mode})` + : entry.subscription}{" "} + · {entry.at.toLocaleTimeString()} + + + + + + + ); + })} + + )} + + + ); +} diff --git a/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.stories.tsx b/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.stories.tsx new file mode 100644 index 0000000000..8e8b82f6a5 --- /dev/null +++ b/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.stories.tsx @@ -0,0 +1,38 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { fn } from "storybook/test"; +import { EventSubscriptionCard } from "./EventSubscriptionCard"; +import { + activePoll, + forbiddenPoll, + reconnectingPush, + terminatedPush, +} from "../../../test/fixtures/events"; + +const meta: Meta = { + title: "Groups/EventSubscriptionCard", + component: EventSubscriptionCard, + args: { + logFiltered: false, + onStop: fn(), + onResume: fn(), + onRemove: fn(), + onToggleLogFilter: fn(), + }, +}; + +export default meta; +type Story = StoryObj; + +export const ActivePoll: Story = { args: { subscription: activePoll } }; +export const ReconnectingPush: Story = { + args: { subscription: reconnectingPush }, +}; +export const TerminatedResumable: Story = { + args: { subscription: terminatedPush }, +}; +export const TerminatedForbidden: Story = { + args: { subscription: forbiddenPoll }, +}; +export const LogFiltered: Story = { + args: { subscription: activePoll, logFiltered: true }, +}; diff --git a/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.test.tsx b/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.test.tsx new file mode 100644 index 0000000000..b561f57b46 --- /dev/null +++ b/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.test.tsx @@ -0,0 +1,102 @@ +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { + EventSubscriptionCard, + type EventSubscriptionCardProps, +} from "./EventSubscriptionCard"; +import { + activePoll, + forbiddenPoll, + reconnectingPush, + terminatedPush, +} from "../../../test/fixtures/events"; + +function props( + overrides: Partial = {}, +): EventSubscriptionCardProps { + return { + subscription: activePoll, + logFiltered: false, + onStop: vi.fn(), + onResume: vi.fn(), + onRemove: vi.fn(), + onToggleLogFilter: vi.fn(), + ...overrides, + }; +} + +describe("EventSubscriptionCard", () => { + it("shows a live poll's state, cursor, interval and tallies, and stops", async () => { + const p = props(); + renderWithMantine(); + expect(screen.getByText("email.received")).toBeInTheDocument(); + expect(screen.getByText("poll")).toBeInTheDocument(); + expect(screen.getByText("active")).toBeInTheDocument(); + expect(screen.getByText("no arguments")).toBeInTheDocument(); + expect(screen.getByText("c-42")).toBeInTheDocument(); + expect(screen.getByText("Next poll")).toBeInTheDocument(); + expect(screen.getByText("5 s")).toBeInTheDocument(); + expect(screen.getByText(/3 events · 1 gaps/)).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Resume" }), + ).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "Stop" })); + expect(p.onStop).toHaveBeenCalled(); + }); + + it("shows a reconnecting push's heartbeat, null cursor and last error", () => { + renderWithMantine( + , + ); + expect(screen.getByText("reconnecting")).toBeInTheDocument(); + expect(screen.getByText('{"severity":"P1"}')).toBeInTheDocument(); + expect(screen.getByText("none (from now)")).toBeInTheDocument(); + expect(screen.getByText("Heartbeat")).toBeInTheDocument(); + expect(screen.getByText("30 s")).toBeInTheDocument(); + expect( + screen.getByText("Last error: -32603: stream dropped"), + ).toBeInTheDocument(); + }); + + it("offers resume and remove after a resumable termination", async () => { + const p = props({ subscription: terminatedPush }); + renderWithMantine(); + expect( + screen.getByText( + /Terminated \(removed, event types re-listed\): -32023 NotFound: Event type removed/, + ), + ).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Stop" }), + ).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "Resume" })); + await userEvent.click(screen.getByRole("button", { name: "Remove" })); + expect(p.onResume).toHaveBeenCalled(); + expect(p.onRemove).toHaveBeenCalled(); + }); + + it("offers only remove after a forbidden termination", () => { + renderWithMantine( + , + ); + expect(screen.getByText(/forbidden, no re-list/)).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Resume" }), + ).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Remove" })).toBeInTheDocument(); + }); + + it("toggles the log filter and says which way it points", async () => { + const p = props(); + const { rerender } = renderWithMantine(); + await userEvent.click( + screen.getByRole("button", { name: "Only this in log" }), + ); + expect(p.onToggleLogFilter).toHaveBeenCalled(); + rerender(); + expect( + screen.getByRole("button", { name: "Show all events" }), + ).toHaveAttribute("aria-pressed", "true"); + }); +}); diff --git a/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.tsx b/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.tsx new file mode 100644 index 0000000000..db6ffeb970 --- /dev/null +++ b/clients/web/src/components/groups/EventSubscriptionCard/EventSubscriptionCard.tsx @@ -0,0 +1,177 @@ +import { Button, Group, Paper, Stack, Text } from "@mantine/core"; +import type { EventSubscription } from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { DeliveryModeBadge } from "../../elements/DeliveryModeBadge/DeliveryModeBadge"; +import { EventSubscriptionStatusBadge } from "../../elements/EventSubscriptionStatusBadge/EventSubscriptionStatusBadge"; +import { + canResumeSubscription, + describeEventsError, + formatCursor, + formatInterval, + formatSubscriptionArguments, + isSubscriptionLive, + subscriptionInterval, +} from "../../../utils/eventsUtils"; + +export interface EventSubscriptionCardProps { + subscription: EventSubscription; + /** Whether the occurrence log is narrowed to this subscription. */ + logFiltered: boolean; + onStop: () => void; + onResume: () => void; + onRemove: () => void; + /** Narrow the occurrence log to this subscription, or widen it again. */ + onToggleLogFilter: () => void; +} + +const CardFrame = Paper.withProps({ + withBorder: true, + p: "sm", + radius: "sm", +}); + +const CardStack = Stack.withProps({ + gap: 6, +}); + +// The name gets a line of its own and the badges the next, so neither is +// squeezed when the column is narrow (the monitoring sidebar open beside it). +const BadgeRow = Group.withProps({ + gap: "xs", +}); + +const NameText = Text.withProps({ + fw: 600, + size: "sm", + truncate: "end", +}); + +const DetailRow = Group.withProps({ + gap: "xs", + wrap: "nowrap", + align: "baseline", +}); + +const DetailLabel = Text.withProps({ + size: "xs", + c: "var(--inspector-text-secondary)", + w: 72, + flex: "0 0 auto", +}); + +const DetailValue = Text.withProps({ + size: "xs", + ff: "monospace", + truncate: "end", + miw: 0, +}); + +const CountsText = Text.withProps({ + size: "xs", + c: "var(--inspector-text-secondary)", +}); + +const ErrorText = Text.withProps({ + size: "xs", + c: "var(--inspector-danger-text)", +}); + +const ActionRow = Group.withProps({ + gap: "xs", +}); + +const ActionButton = Button.withProps({ + size: "compact-xs", + variant: "default", +}); + +const StopButton = Button.withProps({ + size: "compact-xs", + variant: "light", + color: "red", +}); + +const RELIST_LABELS = { + pending: "re-listing event types…", + done: "event types re-listed", + failed: "re-list failed", + skipped: "no re-list", +} as const; + +/** + * One Events subscription (SEP-3415, #3030): its mode and state, the cursor it + * would resume from, the granted heartbeat or recommended poll interval, its + * tallies (including gaps and errors), the last error, how it ended, and the + * controls to stop, resume or forget it. + */ +export function EventSubscriptionCard({ + subscription, + logFiltered, + onStop, + onResume, + onRemove, + onToggleLogFilter, +}: EventSubscriptionCardProps) { + const { name, mode, status, cursor, counts, lastError, termination } = + subscription; + const interval = subscriptionInterval(subscription); + const live = isSubscriptionLive(subscription); + + return ( + + + {name} + + + + + + Arguments + + {formatSubscriptionArguments(subscription.arguments)} + + + + Cursor + {formatCursor(cursor)} + + {interval && ( + + {interval.label} + {formatInterval(interval.ms)} + + )} + + {counts.events} events · {counts.gaps} gaps · {counts.errors} errors ·{" "} + {counts.reconnects} reconnects · {counts.duplicates} duplicates ·{" "} + {counts.invalidPayloads} invalid payloads + + {termination ? ( + + Terminated ({termination.reason},{" "} + {RELIST_LABELS[termination.relist]} + ): {describeEventsError(termination.error)} + + ) : ( + lastError && ( + Last error: {describeEventsError(lastError)} + ) + )} + + {live ? ( + Stop + ) : ( + <> + {canResumeSubscription(subscription) && ( + Resume + )} + Remove + + )} + + {logFiltered ? "Show all events" : "Only this in log"} + + + + + ); +} diff --git a/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.stories.tsx b/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.stories.tsx new file mode 100644 index 0000000000..3b3b584689 --- /dev/null +++ b/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.stories.tsx @@ -0,0 +1,23 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { fn } from "storybook/test"; +import { EventTypeListItem } from "./EventTypeListItem"; +import { + allModesType, + pollOnlyType, + webhookOnlyType, +} from "../../../test/fixtures/events"; + +const meta: Meta = { + title: "Groups/EventTypeListItem", + component: EventTypeListItem, + args: { onClick: fn(), selected: false }, +}; + +export default meta; +type Story = StoryObj; + +export const AllModes: Story = { args: { eventType: allModesType } }; +export const Selected: Story = { + args: { eventType: pollOnlyType, selected: true }, +}; +export const NoDescription: Story = { args: { eventType: webhookOnlyType } }; diff --git a/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.test.tsx b/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.test.tsx new file mode 100644 index 0000000000..1affd87b71 --- /dev/null +++ b/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.test.tsx @@ -0,0 +1,37 @@ +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { renderWithMantine, screen } from "../../../test/renderWithMantine"; +import { EventTypeListItem } from "./EventTypeListItem"; +import { allModesType, webhookOnlyType } from "../../../test/fixtures/events"; + +describe("EventTypeListItem", () => { + it("shows the name, description and a badge per delivery mode", () => { + renderWithMantine( + , + ); + expect(screen.getByText("incident.created")).toBeInTheDocument(); + expect(screen.getByText(/new incident is created/)).toBeInTheDocument(); + for (const mode of ["poll", "push", "webhook"]) { + expect(screen.getByText(mode)).toBeInTheDocument(); + } + }); + + it("omits the description when there is none, and reports clicks", async () => { + const onClick = vi.fn(); + renderWithMantine( + , + ); + await userEvent.click( + screen.getByRole("button", { name: "payment.settled" }), + ); + expect(onClick).toHaveBeenCalledTimes(1); + }); +}); diff --git a/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.tsx b/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.tsx new file mode 100644 index 0000000000..f083c34751 --- /dev/null +++ b/clients/web/src/components/groups/EventTypeListItem/EventTypeListItem.tsx @@ -0,0 +1,65 @@ +import { Group, Stack, Text, UnstyledButton } from "@mantine/core"; +import type { EventType } from "@inspector/core/extension/events/schemas.js"; +import { DeliveryModeBadge } from "../../elements/DeliveryModeBadge/DeliveryModeBadge"; + +export interface EventTypeListItemProps { + eventType: EventType; + selected: boolean; + onClick: () => void; +} + +const ListItemButton = UnstyledButton.withProps({ + w: "100%", + p: "sm", + variant: "listItem", +}); + +const ItemBody = Stack.withProps({ + gap: 4, + miw: 0, +}); + +const ItemLabel = Text.withProps({ + fw: 500, + truncate: true, +}); + +const ItemDescription = Text.withProps({ + size: "xs", + c: "dimmed", + lineClamp: 2, +}); + +const ModeRow = Group.withProps({ + gap: 4, +}); + +/** + * One row of the Events sidebar (SEP-3415, #3030): the event type's name, its + * description, and a badge per advertised delivery mode — including any this + * client cannot subscribe with yet, so the server's whole offer is visible. + */ +export function EventTypeListItem({ + eventType, + selected, + onClick, +}: EventTypeListItemProps) { + const { name, description, delivery } = eventType; + return ( + + + {name} + {description && {description}} + + {delivery.map((mode) => ( + + ))} + + + + ); +} diff --git a/clients/web/src/components/screens/EventsScreen/EventsScreen.stories.tsx b/clients/web/src/components/screens/EventsScreen/EventsScreen.stories.tsx new file mode 100644 index 0000000000..f0c47be083 --- /dev/null +++ b/clients/web/src/components/screens/EventsScreen/EventsScreen.stories.tsx @@ -0,0 +1,69 @@ +import { useState } from "react"; +import type { ComponentProps } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { expect, fn, userEvent, within } from "storybook/test"; +import { EventsScreen, type EventsUiState } from "./EventsScreen"; +import { EMPTY_EVENTS_UI } from "../screenUiState"; +import { noopPagination } from "../../../test/fixtures/pagination"; +import { + eventLog, + eventTypes, + subscriptions, +} from "../../../test/fixtures/events"; + +// The screen's ui is lifted to App; this holds it so the story is interactive. +function Stateful(args: ComponentProps) { + const [ui, setUi] = useState(args.ui); + return ; +} + +const meta: Meta = { + title: "Screens/EventsScreen", + component: EventsScreen, + parameters: { layout: "fullscreen" }, + render: (args) => , + args: { + eventTypes, + listChanged: false, + pagination: noopPagination, + subscriptions, + log: eventLog, + ui: EMPTY_EVENTS_UI, + onUiChange: fn(), + onRefreshList: fn(), + onSubscribe: fn(), + onStopSubscription: fn(), + onResumeSubscription: fn(), + onRemoveSubscription: fn(), + onClearLog: fn(), + }, +}; + +export default meta; +type Story = StoryObj; + +export const Default: Story = {}; + +export const SelectedType: Story = { + args: { + ui: { ...EMPTY_EVENTS_UI, selectedEventName: "incident.created" }, + }, + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Subscribe" })); + await expect(args.onSubscribe).toHaveBeenCalled(); + }, +}; + +export const Empty: Story = { + args: { subscriptions: [], log: [], listChanged: true }, +}; + +export const LoadFailed: Story = { + args: { + eventTypes: [], + subscriptions: [], + log: [], + loadError: new Error("events/list failed: -32603 Internal error"), + }, +}; diff --git a/clients/web/src/components/screens/EventsScreen/EventsScreen.test.tsx b/clients/web/src/components/screens/EventsScreen/EventsScreen.test.tsx new file mode 100644 index 0000000000..f6fb497999 --- /dev/null +++ b/clients/web/src/components/screens/EventsScreen/EventsScreen.test.tsx @@ -0,0 +1,254 @@ +import { useState } from "react"; +import { describe, it, expect, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { + renderWithMantine, + screen, + within, +} from "../../../test/renderWithMantine"; +import { + EventsScreen, + type EventsScreenProps, + type EventsUiState, +} from "./EventsScreen"; +import { EMPTY_EVENTS_UI } from "../screenUiState"; +import { noopPagination } from "../../../test/fixtures/pagination"; +import { + activePoll, + eventLog, + eventTypes, + subscriptions, + terminatedPush, +} from "../../../test/fixtures/events"; + +function baseProps(): EventsScreenProps { + return { + eventTypes, + listChanged: false, + pagination: noopPagination, + subscriptions, + log: eventLog, + ui: EMPTY_EVENTS_UI, + onUiChange: vi.fn(), + onRefreshList: vi.fn(), + onSubscribe: vi.fn(), + onStopSubscription: vi.fn(), + onResumeSubscription: vi.fn(), + onRemoveSubscription: vi.fn(), + onClearLog: vi.fn(), + }; +} + +/** Holds the lifted ui the way App does, and records every change. */ +function Stateful( + props: Partial & { initialUi?: EventsUiState }, +) { + const [ui, setUi] = useState( + props.initialUi ?? EMPTY_EVENTS_UI, + ); + return ( + <> + { + setUi(next); + props.onUiChange?.(next); + }} + /> + {JSON.stringify(ui)} + + ); +} + +function ui(): EventsUiState { + return JSON.parse(screen.getByTestId("ui").textContent ?? "{}"); +} + +describe("EventsScreen", () => { + it("publishes its readiness contract and starts on a placeholder", () => { + renderWithMantine(); + const root = screen.getByTestId("events-screen"); + expect(root).toHaveAttribute("data-event-count", "4"); + expect(root).toHaveAttribute("data-subscription-count", "3"); + expect(root).toHaveAttribute("data-log-count", "7"); + expect( + screen.getByText("Select an event type to subscribe"), + ).toBeInTheDocument(); + expect(screen.getByText("Subscriptions (3)")).toBeInTheDocument(); + }); + + it("says when there are no subscriptions", () => { + renderWithMantine( + , + ); + expect(screen.getByText("No subscriptions yet.")).toBeInTheDocument(); + }); + + it("selects a type with its schema defaults, and searches", async () => { + const withDefault = { + ...eventTypes[0]!, + inputSchema: { + type: "object", + properties: { from: { type: "string", default: "me@example.com" } }, + }, + }; + renderWithMantine( + , + ); + await userEvent.click( + screen.getByRole("button", { name: "email.received" }), + ); + expect(ui().selectedEventName).toBe("email.received"); + expect(ui().formValues).toEqual({ from: "me@example.com" }); + await userEvent.type( + screen.getByPlaceholderText("Search events..."), + "inc", + ); + expect(ui().search).toBe("inc"); + }); + + it("subscribes with converted arguments and the mode's tuning", async () => { + const onSubscribe = vi.fn(); + renderWithMantine( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Subscribe" })); + expect(onSubscribe).toHaveBeenCalledWith( + expect.objectContaining({ name: "incident.created" }), + { + mode: "push", + arguments: { service: "api" }, + maxAgeMs: 1000, + heartbeatMs: 5000, + }, + ); + }); + + it("lifts the form, mode and tuning edits", async () => { + renderWithMantine( + , + ); + await userEvent.type(screen.getByRole("textbox", { name: "service" }), "x"); + expect(ui().formValues).toEqual({ service: "x" }); + await userEvent.click(screen.getByText("Push")); + expect(ui().mode).toBe("push"); + await userEvent.type(screen.getByLabelText("maxAgeMs"), "9"); + expect(ui().tuning).toEqual({ maxAgeMs: 9 }); + }); + + it("shows a refused subscribe, and clears it on the next selection", async () => { + const onSubscribe = vi.fn(() => { + throw new Error("not offered"); + }); + renderWithMantine( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Subscribe" })); + expect(screen.getByText("not offered")).toBeInTheDocument(); + await userEvent.click( + screen.getByRole("button", { name: "incident.created" }), + ); + expect(screen.queryByText("not offered")).not.toBeInTheDocument(); + }); + + it("reports a non-Error refusal as text", async () => { + const onSubscribe = vi.fn(() => { + throw "plain refusal"; + }); + renderWithMantine( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Subscribe" })); + expect(screen.getByText("plain refusal")).toBeInTheDocument(); + }); + + it("stops, resumes and removes subscriptions", async () => { + const p = baseProps(); + renderWithMantine(); + const cards = screen.getAllByTestId("event-subscription"); + await userEvent.click( + within(cards[0]!).getByRole("button", { name: "Stop" }), + ); + expect(p.onStopSubscription).toHaveBeenCalledWith(activePoll.id); + await userEvent.click( + within(cards[2]!).getByRole("button", { name: "Resume" }), + ); + expect(p.onResumeSubscription).toHaveBeenCalledWith(terminatedPush.id); + await userEvent.click( + within(cards[2]!).getByRole("button", { name: "Remove" }), + ); + expect(p.onRemoveSubscription).toHaveBeenCalledWith(terminatedPush.id); + expect(p.onUiChange).not.toHaveBeenCalled(); + }); + + it("shows a refused resume beside the form", async () => { + renderWithMantine( + { + throw new Error("cannot be resumed"); + }} + initialUi={{ ...EMPTY_EVENTS_UI, selectedEventName: "email.received" }} + />, + ); + const cards = screen.getAllByTestId("event-subscription"); + await userEvent.click( + within(cards[2]!).getByRole("button", { name: "Resume" }), + ); + expect(screen.getByText("cannot be resumed")).toBeInTheDocument(); + }); + + it("narrows the log to one subscription, widens it, and drops a removed filter", async () => { + renderWithMantine(); + const cards = () => screen.getAllByTestId("event-subscription"); + await userEvent.click( + within(cards()[2]!).getByRole("button", { name: "Only this in log" }), + ); + expect(ui().logFilter).toBe(terminatedPush.id); + expect(screen.getAllByTestId("event-log-entry")).toHaveLength(1); + expect( + screen.getByText("Occurrences — deploy.completed (push) (1)"), + ).toBeInTheDocument(); + await userEvent.click( + within(cards()[2]!).getByRole("button", { name: "Show all events" }), + ); + expect(ui().logFilter).toBeUndefined(); + expect(screen.getAllByTestId("event-log-entry")).toHaveLength(7); + + await userEvent.click( + within(cards()[2]!).getByRole("button", { name: "Only this in log" }), + ); + await userEvent.click( + within(cards()[2]!).getByRole("button", { name: "Remove" }), + ); + expect(ui().logFilter).toBeUndefined(); + }); + + it("clears the log", async () => { + const p = baseProps(); + renderWithMantine(); + await userEvent.click(screen.getByRole("button", { name: "Clear" })); + expect(p.onClearLog).toHaveBeenCalled(); + }); +}); diff --git a/clients/web/src/components/screens/EventsScreen/EventsScreen.tsx b/clients/web/src/components/screens/EventsScreen/EventsScreen.tsx new file mode 100644 index 0000000000..1ff446359e --- /dev/null +++ b/clients/web/src/components/screens/EventsScreen/EventsScreen.tsx @@ -0,0 +1,340 @@ +import { useState } from "react"; +import { Card, Flex, ScrollArea, Stack, Text, Title } from "@mantine/core"; +import type { EventType } from "@inspector/core/extension/events/schemas.js"; +import type { ExcludedEventType } from "@inspector/core/extension/events/headers.js"; +import type { + EventLogEntry, + EventSubscribeOptions, + EventSubscription, + EventSubscriptionMode, +} from "@inspector/core/mcp/state/eventSubscriptionsState.js"; +import { EventControls } from "../../groups/EventControls/EventControls"; +import { EventDetailPanel } from "../../groups/EventDetailPanel/EventDetailPanel"; +import { EventSubscriptionCard } from "../../groups/EventSubscriptionCard/EventSubscriptionCard"; +import { EventLogPanel } from "../../groups/EventLogPanel/EventLogPanel"; +import type { ListPaginationControlsProps } from "../../elements/ListPaginationControls/ListPaginationControls"; +import { collectSchemaDefaults, toFormSchema } from "../../../utils/jsonUtils"; +import { + buildSubscribeOptions, + eventArguments, + filterEventLog, + resolveSubscribeMode, + type SubscribeTuning, +} from "../../../utils/eventsUtils"; + +/** + * The Events tab's selection, form and filter state, lifted to App so it + * survives tab navigation within a session (#1417). The subscriptions and the + * occurrence log are not here: they live in the core subscription engine. + */ +export interface EventsUiState { + selectedEventName?: string; + formValues: Record; + search: string; + /** The last mode picked; resolved against each type's offer on render. */ + mode?: EventSubscriptionMode; + tuning: SubscribeTuning; + /** Narrows the occurrence log to one subscription (its registry id). */ + logFilter?: string; +} + +export interface EventsScreenProps { + eventTypes: EventType[]; + excludedEventTypes?: ExcludedEventType[]; + listChanged: boolean; + loadError?: Error | null; + pagination: ListPaginationControlsProps; + subscriptions: EventSubscription[]; + /** The occurrence log, every subscription's, oldest first. */ + log: EventLogEntry[]; + ui: EventsUiState; + onUiChange: (next: EventsUiState) => void; + onRefreshList: () => void; + /** + * Start a subscription. Throws when the engine refuses it (the connection + * no longer offers Events, or the type does not advertise the mode); the + * screen shows the message beside the form. + */ + onSubscribe: (eventType: EventType, options: EventSubscribeOptions) => void; + onStopSubscription: (id: string) => void; + /** Start a stopped or resumable terminated subscription; may throw. */ + onResumeSubscription: (id: string) => void; + onRemoveSubscription: (id: string) => void; + onClearLog: () => void; +} + +// Each column caps at the screen's height so its card scrolls inside rather +// than pushing the page (ToolsScreen's arrangement). +const SCROLL_MAX_HEIGHT = + "calc(100dvh - var(--app-shell-header-height, 0px) - var(--app-shell-footer-height, 0px) - var(--mantine-spacing-xl) * 2)"; + +const ScreenLayout = Flex.withProps({ + variant: "screen", + h: "calc(100dvh - var(--app-shell-header-height, 0px) - var(--app-shell-footer-height, 0px))", + gap: "md", + p: "xl", +}); + +const Sidebar = Stack.withProps({ + w: 300, + flex: "0 0 auto", +}); + +const SidebarCard = Card.withProps({ + withBorder: true, + padding: "lg", + variant: "sidebar", +}); + +const ContentPane = Flex.withProps({ + flex: 1, + miw: 0, + direction: "column", + align: "stretch", +}); + +const ContentCard = Card.withProps({ + withBorder: true, + padding: "lg", + variant: "preview", +}); + +// The activity column gets the larger share: its cards hold the most text. +const ActivityPane = Flex.withProps({ + flex: 1.4, + miw: 0, + direction: "column", + align: "stretch", +}); + +// The right column: subscriptions above, the occurrence log filling the rest. +const ActivityStack = Stack.withProps({ + gap: "md", + flex: 1, + mih: 0, +}); + +const SubscriptionsCard = Card.withProps({ + withBorder: true, + padding: "md", + flex: "0 1 auto", + mah: "45%", + variant: "preview", +}); + +const LogCard = Card.withProps({ + withBorder: true, + padding: "md", + flex: 1, + mih: 0, + variant: "preview", +}); + +const SubscriptionsStack = Stack.withProps({ + gap: "xs", + mih: 0, +}); + +const SubscriptionsScroll = ScrollArea.withProps({ + flex: "0 1 auto", + mih: 0, + scrollbars: "y", +}); + +const SubscriptionsTitle = Title.withProps({ + order: 3, + size: "h5", +}); + +const EmptyState = Text.withProps({ + c: "dimmed", + ta: "center", + py: "xl", +}); + +const EmptySubscriptions = Text.withProps({ + size: "sm", + c: "dimmed", +}); + +function errorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** + * The Events tab (SEP-3415, #3030): the server's event types, a subscribe form + * for the selected one, the live subscriptions with their state and controls, + * and the occurrence stream every subscription feeds. + */ +export function EventsScreen({ + eventTypes, + excludedEventTypes, + listChanged, + loadError, + pagination, + subscriptions, + log, + ui, + onUiChange, + onRefreshList, + onSubscribe, + onStopSubscription, + onResumeSubscription, + onRemoveSubscription, + onClearLog, +}: EventsScreenProps) { + const selected = eventTypes.find((e) => e.name === ui.selectedEventName); + const mode = selected ? resolveSubscribeMode(selected, ui.mode) : undefined; + // Screen-local: a refusal belongs to the attempt the user is looking at, so + // it clears on the next selection and on the next attempt. + const [subscribeError, setSubscribeError] = useState(); + const filtered = subscriptions.find((s) => s.id === ui.logFilter); + const entries = filterEventLog(log, filtered?.id); + + const handleSelect = (name: string) => { + const eventType = eventTypes.find((e) => e.name === name); + /* v8 ignore next -- the sidebar only emits names from this list */ + if (!eventType) return; + setSubscribeError(undefined); + onUiChange({ + ...ui, + selectedEventName: name, + // Seeded with the schema's defaults so a default-only field is sent + // without being edited (the Tools tab's rule). + formValues: collectSchemaDefaults( + toFormSchema(eventType.inputSchema) ?? {}, + ), + }); + }; + + const handleSubscribe = () => { + /* v8 ignore next -- Subscribe is disabled without a type and a mode */ + if (!selected || !mode) return; + setSubscribeError(undefined); + try { + onSubscribe( + selected, + buildSubscribeOptions( + mode, + eventArguments(selected.inputSchema, ui.formValues), + ui.tuning, + ), + ); + } catch (err) { + setSubscribeError(errorMessage(err)); + } + }; + + const handleResume = (id: string) => { + try { + onResumeSubscription(id); + } catch (err) { + setSubscribeError(errorMessage(err)); + } + }; + + const handleRemove = (id: string) => { + onRemoveSubscription(id); + if (ui.logFilter === id) onUiChange({ ...ui, logFilter: undefined }); + }; + + return ( + // `data-*` readiness contract for the headless Events smoke; see + // clients/web/README.md#core-tab-automation-contract. Passed here because + // `data-*` attributes are not part of a component's typed props. + + + + onUiChange({ ...ui, search })} + onSelectEventType={handleSelect} + /> + + + + + {selected ? ( + + onUiChange({ ...ui, formValues })} + mode={mode} + onModeChange={(next) => onUiChange({ ...ui, mode: next })} + tuning={ui.tuning} + onTuningChange={(tuning) => onUiChange({ ...ui, tuning })} + onSubscribe={handleSubscribe} + subscribeError={subscribeError} + /> + + ) : ( + + Select an event type to subscribe + + )} + + + + + + + + Subscriptions ({subscriptions.length}) + + {subscriptions.length === 0 ? ( + No subscriptions yet. + ) : ( + + + {subscriptions.map((subscription) => ( + onStopSubscription(subscription.id)} + onResume={() => handleResume(subscription.id)} + onRemove={() => handleRemove(subscription.id)} + onToggleLogFilter={() => + onUiChange({ + ...ui, + logFilter: + filtered?.id === subscription.id + ? undefined + : subscription.id, + }) + } + /> + ))} + + + )} + + + + + + + + + ); +} diff --git a/clients/web/src/components/screens/screenUiState.ts b/clients/web/src/components/screens/screenUiState.ts index 2e52459f5d..443a9bb2b5 100644 --- a/clients/web/src/components/screens/screenUiState.ts +++ b/clients/web/src/components/screens/screenUiState.ts @@ -8,6 +8,7 @@ import type { PromptsUiState } from "./PromptsScreen/PromptsScreen"; import type { ResourcesUiState } from "./ResourcesScreen/ResourcesScreen"; import type { AppsUiState } from "./AppsScreen/AppsScreen"; import type { SkillsUiState } from "./SkillsScreen/SkillsScreen"; +import type { EventsUiState } from "./EventsScreen/EventsScreen"; import type { TasksUiState } from "./TasksScreen/TasksScreen"; import type { LogsUiState } from "./LoggingScreen/LoggingScreen"; import type { ProtocolUiState } from "./ProtocolScreen/ProtocolScreen"; @@ -49,6 +50,15 @@ export const EMPTY_SKILLS_UI: SkillsUiState = { search: "", }; +export const EMPTY_EVENTS_UI: EventsUiState = { + selectedEventName: undefined, + formValues: {}, + search: "", + mode: undefined, + tuning: {}, + logFilter: undefined, +}; + export const EMPTY_TASKS_UI: TasksUiState = { search: "", statusFilter: undefined, @@ -81,6 +91,7 @@ export const TAB_UI_REGISTRY = { Prompts: { empty: EMPTY_PROMPTS_UI }, Resources: { empty: EMPTY_RESOURCES_UI }, Skills: { empty: EMPTY_SKILLS_UI }, + Events: { empty: EMPTY_EVENTS_UI }, Tasks: { empty: EMPTY_TASKS_UI }, Logs: { empty: EMPTY_LOGS_UI }, Protocol: { empty: EMPTY_PROTOCOL_UI }, diff --git a/clients/web/src/components/views/InspectorView/InspectorView.test.tsx b/clients/web/src/components/views/InspectorView/InspectorView.test.tsx index e1f2508a2b..6480297cbd 100644 --- a/clients/web/src/components/views/InspectorView/InspectorView.test.tsx +++ b/clients/web/src/components/views/InspectorView/InspectorView.test.tsx @@ -45,6 +45,7 @@ import { EMPTY_PROTOCOL_UI, EMPTY_NETWORK_UI, EMPTY_CONSOLE_UI, + EMPTY_EVENTS_UI, } from "../../screens/screenUiState"; // Stub bridge factory — AppsScreen mounts the inner iframe and invokes @@ -1453,6 +1454,83 @@ describe("InspectorView", () => { expect(labels).toContain("Skills"); }); + describe("the Events tab (SEP-3415, #3030)", () => { + const eventsCapabilities = initWithCapabilities({ + tools: {}, + extensions: { "io.modelcontextprotocol/events": { listChanged: true } }, + }); + const eventsBundle: NonNullable = { + eventTypes: [ + { + name: "email.received", + delivery: ["poll"], + inputSchema: { type: "object" }, + }, + ], + eventsListChanged: false, + eventsPagination: noopPagination, + eventSubscriptions: [], + eventLog: [], + eventsUi: EMPTY_EVENTS_UI, + onEventsUiChange: vi.fn(), + onRefreshEvents: vi.fn(), + onSubscribeEvent: vi.fn(), + onStopEventSubscription: vi.fn(), + onResumeEventSubscription: vi.fn(), + onRemoveEventSubscription: vi.fn(), + onClearEventLog: vi.fn(), + }; + const connected = (protocolEra: "modern" | "legacy") => + makeProps({ + connection: { + activeServer: "alpha", + connectionStatus: "connected", + protocolEra, + initializeResult: eventsCapabilities, + }, + servers: { servers: [sampleServer] }, + }); + + it("shows the tab on a modern connection that advertises Events, and renders the screen", async () => { + const props = connected("modern"); + renderWithMantine( + , + ); + const radios = await screen.findAllByRole("radio"); + expect(radios.map((r) => r.getAttribute("value"))).toContain("Events"); + expect(screen.getByTestId("events-screen")).toHaveAttribute( + "data-event-count", + "1", + ); + }); + + it("hides the tab on a legacy connection, even when the key is declared", async () => { + renderWithMantine( + , + ); + const radios = await screen.findAllByRole("radio"); + expect(radios.map((r) => r.getAttribute("value"))).not.toContain( + "Events", + ); + }); + + it("hides the tab when the host supplies no Events surface", async () => { + renderWithMantine(); + const radios = await screen.findAllByRole("radio"); + expect(radios.map((r) => r.getAttribute("value"))).not.toContain( + "Events", + ); + expect(screen.queryByTestId("events-screen")).not.toBeInTheDocument(); + }); + }); + it("shows the Tasks tab when the server advertises tasks even with no tasks yet", async () => { renderWithMantine(