Wire App.tsx to v2 core/ hook layer; remove demo stub from InspectorView (#1322)
* feat(web): wire App.tsx to v2 core/ hook layer; remove demo stub from InspectorView
App.tsx mounts InspectorView with live data from the v2 hook layer instead
of the title-page placeholder. InspectorView becomes pure prop-driven; the
demo handshake stub and connection state machinery are removed.
Connection lifecycle:
- App.tsx lazily instantiates `InspectorClient` on the connect edge,
rebuilding it (and its state managers) when the user picks a different
server. State managers (Managed{Tools,Prompts,Resources,ResourceTemplates,
RequestorTasks}State + MessageLog/FetchRequestLog/StderrLog) are
destroyed on switch.
- `useInspectorClient` + the per-primitive `useManaged*` hooks drive the
view's data. `latencyMs` is captured at the connecting → connected edge
via a ref so the intermediate rerenders don't lose the start timestamp.
- `errorMessage` is captured from `client.connect()` rejection; status-
machine-driven errors that don't surface through the promise are a known
follow-up (no `error` event in the v2 InspectorClientEventMap yet).
Action handlers:
- `onCallTool` / `onGetPrompt` / `onReadResource` await the corresponding
InspectorClient method and reflect pending → ok/error in `ToolCallState`
/ `GetPromptState` / `ReadResourceState` panel props. Manually verified
end-to-end against `npx @modelcontextprotocol/server-filesystem` —
the Tools result panel renders the real "Allowed directories: /private/tmp"
output rather than a stub.
- `onSetLogLevel` calls `client.setLoggingLevel(level)` and optimistically
bumps `currentLogLevel` locally (the request has no echo notification).
- `onSubscribeResource` / `onUnsubscribeResource` / `onCancelTask` route to
their respective client methods. Server CRUD (`onServerAdd`/`onServerEdit`
/…) and history pinning are intentionally `todoNoop` for now; the seed
server list is hardcoded per the agreed scope (a `useServers` v2-only
hook is a separate effort).
- `notifications/message` notifications flowing through `MessageLogState`
are filtered into `LogEntryData[]` and passed to the Logs screen, so
`logging/setLevel` and the resulting log stream round-trip.
InspectorView (`InspectorView.tsx`):
- Removed: `STUB_*` constants, `handshakeTimer` ref, `handleToggleConnection`
/ `disconnect` functions, stub `bridgeFactory`/`sandboxPath`, internal
connection state, `logLevel` state.
- Added 38 props covering connection state, panel states, log level, and
action callbacks. The view is pure presentational.
- `availableTabs` is derived from `connectionStatus`; `activeTab` is
clamped to whatever's currently available (avoiding the `set-state-in-effect`
lint and keeping the previously-selected tab on reconnect).
Stories + tests:
- `InspectorView.stories.tsx` adds spy callbacks for every action prop and
new `Connected` / `ConnectionError` stories for the connected/error
narratives.
- `InspectorView.test.tsx` is rewritten around the prop-driven contract
(10 tests covering the empty list, server cards, toggle dispatch,
connected header, error banner, tab snap-back on disconnect, app
filtering, log-level dispatch, autoScroll local toggle).
Dev backend port wiring (`vite.config.ts`):
- Vite's dev server is now pinned to `CLIENT_PORT` (default 6274) with
`strictPort: true`, matching the dev backend's `allowedOrigins`. Without
this, Vite would fall back to 5173 while the Hono origin check still
required 6274 — breaking every browser `/api/*` fetch out of the box.
- Top-level `resolve.alias` now spreads the same bare-module aliases the
vitest projects use. Rolldown can't reach `pino/browser.js` /
`zustand/middleware` from `core/`'s parent (no node_modules there); the
wired App pulls those modules into the browser dep graph for the first
time, so the aliases need to be visible at build time too.
createWebEnvironment helper (`src/lib/environmentFactory.ts`):
- Mirrors v1.5's `lib/adapters/environmentFactory.ts`: builds
`InspectorClientEnvironment` from `createRemoteTransport` +
`createRemoteFetch` + `createRemoteLogger` + `BrowserOAuthStorage` +
`BrowserNavigation`. Returns the assembled environment plus the logger
for direct app-level use.
Closes #1244.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(web): wire dev-backend auth token into createWebEnvironment + show full stdio command in ServerCard
Two issues surfaced after the #1244 wiring landed locally:
1. **401 on `/api/mcp/connect`** when running `npm run dev` with the
default auth (no `DANGEROUSLY_OMIT_AUTH`). The dev backend generates a
random token and prints `http://localhost:6274?MCP_INSPECTOR_API_TOKEN=…`
in the banner, but App.tsx was calling `createWebEnvironment(undefined, …)`
so the browser never sent `x-mcp-remote-auth`. The Hono middleware
correctly rejected with "Authentication required. Use the
x-mcp-remote-auth header with Bearer token."
Adds a small `getAuthToken()` helper in App.tsx that reads
`MCP_INSPECTOR_API_TOKEN` off `window.location.search`, falls back to
`sessionStorage`, and persists fresh values into sessionStorage so
client-side navigation / OAuth round-trips don't drop the token. The
resolved value is passed to `createWebEnvironment` whenever a new
InspectorClient is built.
2. **Misleading ServerCard display** — the seed server's `config` is
`{ command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem",
"/tmp"] }` but the card only rendered `"npx"`, so it looked like the
command was incomplete. `getCommandOrUrl` now joins `command + args`
for stdio configs, so the card shows the same string that gets spawned.
SSE / streamable-http paths unchanged.
Manual end-to-end re-verified against `npm run dev` (no DANGEROUSLY_OMIT_AUTH):
- Banner prints the auth-token URL.
- Browser navigates to that URL → `getAuthToken()` picks the token off the
query string, persists to sessionStorage, threads it through to every
`/api/*` request.
- Server card shows `npx -y @modelcontextprotocol/server-filesystem /tmp`.
- Toggle connect → connection succeeds; ViewHeader shows
`Connected (~1.3s)`; Tools tab populates with the 14 filesystem tools.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(web): use dark-9 instead of blue-9 for dark-mode page background
`main.tsx` overrode `--mantine-color-body` to `--mantine-color-blue-9` in
dark mode, while `.storybook/preview.tsx` used `--mantine-color-dark-9`.
The dev app then rendered with a blue background while every story (and
the design intent visible in storybook) used dark grey.
Switch main.tsx to `--mantine-color-dark-9` so the dev app matches the
storybook reference.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(web): seed the Servers screen with the "everything" reference server
Adds `@modelcontextprotocol/server-everything` to the hardcoded seed list
alongside the filesystem server. The everything server exposes tools,
prompts, resources, sampling, and completion — covering most of the
surface a developer might want to exercise against the wired-up
InspectorView without configuring anything.
Comment updated to explain the two-seed shape.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(web): address #1244 PR review feedback (JsonValue cast, client lifecycle, dead code)
- **#1 — Misleading `Record<string, never>` cast**: Imported `JsonValue`
from `@inspector/core/mcp/index.js` and changed `args as Record<string,
never>` to `args as Record<string, JsonValue>` in `onCallTool`. The new
cast honestly narrows from the screen-level `Record<string, unknown>`
to what `InspectorClient.callTool` actually requires. Added a comment
explaining the boundary.
- **#2 + #3 — Previous InspectorClient not disconnected on server switch
or unmount**: Added a `useEffect` keyed on `inspectorClient` whose
cleanup calls `inspectorClient.disconnect()`. One effect covers both
the swap-on-switch leak (prior session's transport stayed open until
GC) and the unmount-during-connected leak (HMR / tests).
`setupClientForServer`'s existing state-manager `destroy()` calls
handle the listener side; the new effect handles the transport side.
- **#4 — Dead `void` block at bottom of file**: Deleted the trailing
`void FetchRequestLogState; void StderrLogState;` block. The state
managers are already constructed via `new FetchRequestLogState(client)`
/ `new StderrLogState(client)`, so the imports are referenced by the
linter's reckoning. The `void` pair was dead code with a comment that
no longer matched reality.
- **#5 / #7 / #8 — Follow-up TODOs**: Added TODO refs to the new
follow-up issues:
- TODO(#1323): `error` event in InspectorClientEventMap so mid-session
transport failures surface (connect-only catch is incomplete).
- TODO(#1324): negotiated `protocolVersion` through `useInspectorClient`
(currently hard-coded `"2025-06-18"`).
- TODO(#1325): `useResourceSubscriptions` hook so subscribe/unsubscribe
buttons reflect their server-side effect.
Items #6 (useCallback dep churn), #9 (helper unit tests), and #10
(shared no-op bridge factory fixture) are acknowledged in the PR reply
as deferred — no functional impact and out of scope for a "wire the
hook layer" PR.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
37a4d99575
commit
4d74b94bed
4 changed files with 1241 additions and 335 deletions
|
|
@ -75,7 +75,13 @@ function getCommandOrUrl(config: MCPServerConfig): string {
|
|||
if (config.type === "sse" || config.type === "streamable-http") {
|
||||
return config.url;
|
||||
}
|
||||
return config.command;
|
||||
// Show the full argv for stdio so the card displays the same thing
|
||||
// that gets spawned. Otherwise a `command: "npx", args: ["-y", "pkg"]`
|
||||
// config renders as just "npx", which is misleading.
|
||||
const args = config.args ?? [];
|
||||
return args.length > 0
|
||||
? `${config.command} ${args.join(" ")}`
|
||||
: config.command;
|
||||
}
|
||||
|
||||
export function ServerCard({
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
import type {
|
||||
InitializeResult,
|
||||
Prompt,
|
||||
Resource,
|
||||
ResourceTemplate,
|
||||
Task,
|
||||
Tool,
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { AppBridge } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import type {
|
||||
InspectorResourceSubscription,
|
||||
MessageEntry,
|
||||
|
|
@ -17,6 +19,19 @@ import { mixedEntries as demoLogs } from "../../screens/LoggingScreen/LoggingScr
|
|||
import { longToolList as demoRegularTools } from "../../screens/ToolsScreen/ToolsScreen.fixtures";
|
||||
import { SUN_ICON_SVG } from "../../../test/fixtures/storyIcons";
|
||||
import type { TaskProgress } from "../../groups/TaskCard/TaskCard";
|
||||
import type { BridgeFactory } from "../../elements/AppRenderer/AppRenderer";
|
||||
|
||||
// Stories never drive a real MCP App bridge — render the iframe stage with
|
||||
// a no-op factory so the AppsScreen mounts without trying to postMessage to
|
||||
// a real sandbox.
|
||||
const noopBridgeFactory: BridgeFactory = () =>
|
||||
({
|
||||
sendToolInput: async () => {},
|
||||
sendToolResult: async () => {},
|
||||
sendToolCancelled: async () => {},
|
||||
teardownResource: async () => ({}),
|
||||
close: async () => {},
|
||||
}) as unknown as AppBridge;
|
||||
|
||||
// MCP App tools — `isAppTool` detects these via `_meta.ui.resourceUri`,
|
||||
// so they get filtered into the Apps tab while still appearing on Tools.
|
||||
|
|
@ -234,12 +249,18 @@ const demoHistory: MessageEntry[] = [
|
|||
},
|
||||
];
|
||||
|
||||
const demoInitializeResult: InitializeResult = {
|
||||
protocolVersion: "2025-06-18",
|
||||
capabilities: {},
|
||||
serverInfo: { name: "Local Dev Server", version: "1.2.0" },
|
||||
};
|
||||
|
||||
const meta: Meta<typeof InspectorView> = {
|
||||
title: "Views/InspectorView",
|
||||
component: InspectorView,
|
||||
parameters: { layout: "fullscreen" },
|
||||
args: {
|
||||
onToggleTheme: fn(),
|
||||
// Data
|
||||
servers: demoServers,
|
||||
tools: demoTools,
|
||||
prompts: demoPrompts,
|
||||
|
|
@ -250,6 +271,57 @@ const meta: Meta<typeof InspectorView> = {
|
|||
tasks: demoTasks,
|
||||
progressByTaskId: demoProgressByTaskId,
|
||||
history: demoHistory,
|
||||
|
||||
// Connection state — stories default to "disconnected"; per-story
|
||||
// overrides drive the connected / error narratives.
|
||||
activeServer: undefined,
|
||||
connectionStatus: "disconnected",
|
||||
initializeResult: undefined,
|
||||
latencyMs: undefined,
|
||||
errorMessage: undefined,
|
||||
|
||||
// Misc state
|
||||
currentLogLevel: "info",
|
||||
sandboxPath: "about:blank",
|
||||
bridgeFactory: noopBridgeFactory,
|
||||
|
||||
// Callbacks — all wired to storybook spies so play functions can assert
|
||||
// on dispatch. Real wiring routes these to InspectorClient methods (the
|
||||
// app shell at clients/web/src/App.tsx).
|
||||
onToggleTheme: fn(),
|
||||
onToggleConnection: fn(),
|
||||
onDisconnect: fn(),
|
||||
onServerAdd: fn(),
|
||||
onServerImportConfig: fn(),
|
||||
onServerImportJson: fn(),
|
||||
onServerInfo: fn(),
|
||||
onServerSettings: fn(),
|
||||
onServerEdit: fn(),
|
||||
onServerClone: fn(),
|
||||
onServerRemove: fn(),
|
||||
onCallTool: fn(),
|
||||
onRefreshTools: fn(),
|
||||
onGetPrompt: fn(),
|
||||
onRefreshPrompts: fn(),
|
||||
onReadResource: fn(),
|
||||
onSubscribeResource: fn(),
|
||||
onUnsubscribeResource: fn(),
|
||||
onRefreshResources: fn(),
|
||||
onCancelTask: fn(),
|
||||
onClearCompletedTasks: fn(),
|
||||
onRefreshTasks: fn(),
|
||||
onSetLogLevel: fn(),
|
||||
onClearLogs: fn(),
|
||||
onExportLogs: fn(),
|
||||
onCopyAllLogs: fn(),
|
||||
onClearHistory: fn(),
|
||||
onExportHistory: fn(),
|
||||
onReplayHistory: fn(),
|
||||
onTogglePinHistory: fn(),
|
||||
onSelectApp: fn(),
|
||||
onOpenApp: fn(),
|
||||
onCloseApp: fn(),
|
||||
onRefreshApps: fn(),
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -263,3 +335,24 @@ export const NoServers: Story = {
|
|||
servers: [],
|
||||
},
|
||||
};
|
||||
|
||||
// Renders the connected-state shell (full tab list, ViewHeader in connected
|
||||
// mode). The other tabs still render their disconnected fixtures because
|
||||
// the lists are passed through as static data — that's fine for visual
|
||||
// regression / storybook play function coverage.
|
||||
export const Connected: Story = {
|
||||
args: {
|
||||
activeServer: demoServers[0]!.id,
|
||||
connectionStatus: "connected",
|
||||
initializeResult: demoInitializeResult,
|
||||
latencyMs: 142,
|
||||
},
|
||||
};
|
||||
|
||||
export const ConnectionError: Story = {
|
||||
args: {
|
||||
activeServer: demoServers[0]!.id,
|
||||
connectionStatus: "error",
|
||||
errorMessage: "Handshake timeout",
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,26 +1,94 @@
|
|||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||
import type {
|
||||
InitializeResult,
|
||||
Tool,
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { AppBridge } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import type { ServerEntry } from "@inspector/core/mcp/types.js";
|
||||
import {
|
||||
renderWithMantine,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "../../../test/renderWithMantine";
|
||||
import { InspectorView } from "./InspectorView";
|
||||
import { InspectorView, type InspectorViewProps } from "./InspectorView";
|
||||
import type { BridgeFactory } from "../../elements/AppRenderer/AppRenderer";
|
||||
|
||||
const baseProps = {
|
||||
servers: [],
|
||||
tools: [],
|
||||
prompts: [],
|
||||
resources: [],
|
||||
resourceTemplates: [],
|
||||
subscriptions: [],
|
||||
logs: [],
|
||||
tasks: [],
|
||||
history: [],
|
||||
onToggleTheme: vi.fn(),
|
||||
};
|
||||
// Stub bridge factory — AppsScreen mounts the inner iframe and invokes
|
||||
// `bridgeFactory(...)` on selection. The stub keeps that path quiet by
|
||||
// returning a no-op AppBridge so tests don't try to postMessage to a
|
||||
// real sandbox.
|
||||
const noopBridgeFactory: BridgeFactory = () =>
|
||||
({
|
||||
sendToolInput: async () => {},
|
||||
sendToolResult: async () => {},
|
||||
sendToolCancelled: async () => {},
|
||||
teardownResource: async () => ({}),
|
||||
close: async () => {},
|
||||
}) as unknown as AppBridge;
|
||||
|
||||
// Returns a fresh fixture each call so per-test spies can be asserted on
|
||||
// in isolation. The view is purely prop-driven; every callback is
|
||||
// dispatched up to the parent — these spies stand in for App.tsx's
|
||||
// hook-routed handlers in the real wiring.
|
||||
function makeProps(
|
||||
overrides: Partial<InspectorViewProps> = {},
|
||||
): InspectorViewProps {
|
||||
return {
|
||||
servers: [],
|
||||
activeServer: undefined,
|
||||
connectionStatus: "disconnected",
|
||||
initializeResult: undefined,
|
||||
latencyMs: undefined,
|
||||
errorMessage: undefined,
|
||||
tools: [],
|
||||
prompts: [],
|
||||
resources: [],
|
||||
resourceTemplates: [],
|
||||
subscriptions: [],
|
||||
logs: [],
|
||||
tasks: [],
|
||||
history: [],
|
||||
currentLogLevel: "info",
|
||||
sandboxPath: "about:blank",
|
||||
bridgeFactory: noopBridgeFactory,
|
||||
onToggleTheme: vi.fn(),
|
||||
onToggleConnection: vi.fn(),
|
||||
onDisconnect: vi.fn(),
|
||||
onServerAdd: vi.fn(),
|
||||
onServerImportConfig: vi.fn(),
|
||||
onServerImportJson: vi.fn(),
|
||||
onServerInfo: vi.fn(),
|
||||
onServerSettings: vi.fn(),
|
||||
onServerEdit: vi.fn(),
|
||||
onServerClone: vi.fn(),
|
||||
onServerRemove: vi.fn(),
|
||||
onCallTool: vi.fn(),
|
||||
onRefreshTools: vi.fn(),
|
||||
onGetPrompt: vi.fn(),
|
||||
onRefreshPrompts: vi.fn(),
|
||||
onReadResource: vi.fn(),
|
||||
onSubscribeResource: vi.fn(),
|
||||
onUnsubscribeResource: vi.fn(),
|
||||
onRefreshResources: vi.fn(),
|
||||
onCancelTask: vi.fn(),
|
||||
onClearCompletedTasks: vi.fn(),
|
||||
onRefreshTasks: vi.fn(),
|
||||
onSetLogLevel: vi.fn(),
|
||||
onClearLogs: vi.fn(),
|
||||
onExportLogs: vi.fn(),
|
||||
onCopyAllLogs: vi.fn(),
|
||||
onClearHistory: vi.fn(),
|
||||
onExportHistory: vi.fn(),
|
||||
onReplayHistory: vi.fn(),
|
||||
onTogglePinHistory: vi.fn(),
|
||||
onSelectApp: vi.fn(),
|
||||
onOpenApp: vi.fn(),
|
||||
onCloseApp: vi.fn(),
|
||||
onRefreshApps: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const sampleServer: ServerEntry = {
|
||||
id: "alpha",
|
||||
|
|
@ -29,20 +97,15 @@ const sampleServer: ServerEntry = {
|
|||
connection: { status: "disconnected" },
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
const connectedInit: InitializeResult = {
|
||||
protocolVersion: "2025-06-18",
|
||||
capabilities: {},
|
||||
serverInfo: { name: "Alpha", version: "1.0.0" },
|
||||
};
|
||||
|
||||
// The InspectorView's demo handshake stub uses Math.random() twice on each
|
||||
// connect: first to pick a delay (50–500 ms), then to decide success vs.
|
||||
// error against `STUB_SUCCESS_RATE = 0.85`. Mocking Math.random to a low
|
||||
// value (0.1) forces both a short delay and a "success" outcome (0.1 < 0.85);
|
||||
// 0.99 forces a short-ish delay and a "failure" (0.99 < 0.85 is false). Both
|
||||
// constants are defined in InspectorView.tsx — keep these values in sync if
|
||||
// the success rate ever changes.
|
||||
describe("InspectorView", () => {
|
||||
it("renders the disconnected header by default", () => {
|
||||
renderWithMantine(<InspectorView {...baseProps} />);
|
||||
it("renders the empty-server-list placeholder when no servers are configured", () => {
|
||||
renderWithMantine(<InspectorView {...makeProps()} />);
|
||||
expect(
|
||||
screen.getByText("No servers configured. Add a server to get started."),
|
||||
).toBeInTheDocument();
|
||||
|
|
@ -50,86 +113,105 @@ describe("InspectorView", () => {
|
|||
|
||||
it("renders the server card from the input list", () => {
|
||||
renderWithMantine(
|
||||
<InspectorView {...baseProps} servers={[sampleServer]} />,
|
||||
<InspectorView {...makeProps({ servers: [sampleServer] })} />,
|
||||
);
|
||||
expect(screen.getByText("Alpha")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("transitions to connected on a successful handshake", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.1);
|
||||
it("dispatches onToggleConnection with the server id when the card toggle is clicked", async () => {
|
||||
const onToggleConnection = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
renderWithMantine(
|
||||
<InspectorView {...baseProps} servers={[sampleServer]} />,
|
||||
<InspectorView
|
||||
{...makeProps({ servers: [sampleServer], onToggleConnection })}
|
||||
/>,
|
||||
);
|
||||
await user.click(screen.getByRole("switch"));
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(
|
||||
screen.queryByText(
|
||||
"No servers configured. Add a server to get started.",
|
||||
),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
expect(onToggleConnection).toHaveBeenCalledWith("alpha");
|
||||
});
|
||||
|
||||
it("transitions to error on a failed handshake", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.99);
|
||||
const user = userEvent.setup();
|
||||
it("renders the connected header when connectionStatus + initializeResult are set", () => {
|
||||
renderWithMantine(
|
||||
<InspectorView {...baseProps} servers={[sampleServer]} />,
|
||||
);
|
||||
await user.click(screen.getByRole("switch"));
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(
|
||||
screen.getByText("Server returned invalid response"),
|
||||
).toBeInTheDocument();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
});
|
||||
|
||||
it("disconnects when the connected server is toggled off", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.1);
|
||||
const user = userEvent.setup();
|
||||
renderWithMantine(
|
||||
<InspectorView {...baseProps} servers={[sampleServer]} />,
|
||||
);
|
||||
const toggle = screen.getByRole("switch");
|
||||
await user.click(toggle);
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(toggle).toBeChecked();
|
||||
expect(toggle).not.toBeDisabled();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
await user.click(toggle);
|
||||
expect(toggle).not.toBeChecked();
|
||||
});
|
||||
|
||||
it("renders ViewHeader connected when handshake succeeds", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.1);
|
||||
const user = userEvent.setup();
|
||||
renderWithMantine(
|
||||
<InspectorView {...baseProps} servers={[sampleServer]} />,
|
||||
);
|
||||
const toggle = screen.getByRole("switch");
|
||||
await user.click(toggle);
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(toggle).toBeChecked();
|
||||
expect(toggle).not.toBeDisabled();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
<InspectorView
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: "alpha",
|
||||
connectionStatus: "connected",
|
||||
initializeResult: connectedInit,
|
||||
latencyMs: 50,
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
// ServerCard renders the server name AND ViewHeader does (in connected
|
||||
// mode it shows the serverInfo.name); checking ≥1 occurrence accepts
|
||||
// both. The connected toggle being on confirms the connected mode.
|
||||
expect(screen.getAllByText("Alpha").length).toBeGreaterThan(0);
|
||||
expect(screen.getByRole("switch")).toBeChecked();
|
||||
});
|
||||
|
||||
it("renders the error banner when connectionStatus is 'error' with an errorMessage", () => {
|
||||
renderWithMantine(
|
||||
<InspectorView
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: "alpha",
|
||||
connectionStatus: "error",
|
||||
errorMessage: "Handshake timeout",
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText("Handshake timeout")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("snaps activeTab back to Servers when connection drops", async () => {
|
||||
const { rerender } = renderWithMantine(
|
||||
<InspectorView
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: "alpha",
|
||||
connectionStatus: "connected",
|
||||
initializeResult: connectedInit,
|
||||
latencyMs: 50,
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
const tabSelect = await screen.findByDisplayValue("Servers");
|
||||
await user.click(tabSelect);
|
||||
await user.click(await screen.findByText("Tools"));
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByDisplayValue("Tools")).toBeInTheDocument(),
|
||||
);
|
||||
|
||||
rerender(
|
||||
<InspectorView
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: undefined,
|
||||
connectionStatus: "disconnected",
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Disconnected ViewHeader has no tab Select. The previously-selected
|
||||
// "Tools" display value should be gone after the snap-back.
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByDisplayValue("Tools")).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it("disables non-Servers tabs while disconnected", () => {
|
||||
renderWithMantine(<InspectorView {...makeProps()} />);
|
||||
// The disconnected ViewHeader doesn't render the tab Select at all —
|
||||
// only the connected branch does. Asserting on the empty-state copy is
|
||||
// enough; a follow-up could deepen this once the disconnected header
|
||||
// grows additional affordances.
|
||||
expect(
|
||||
screen.getByText("No servers configured. Add a server to get started."),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters tools to apps and auto-launches a no-fields app on the Apps tab", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.1);
|
||||
const user = userEvent.setup();
|
||||
const opsApp: Tool = {
|
||||
name: "ops",
|
||||
|
|
@ -153,49 +235,72 @@ describe("InspectorView", () => {
|
|||
};
|
||||
renderWithMantine(
|
||||
<InspectorView
|
||||
{...baseProps}
|
||||
servers={[sampleServer]}
|
||||
tools={[opsApp, plainTool, malformedAppTool]}
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: "alpha",
|
||||
connectionStatus: "connected",
|
||||
initializeResult: connectedInit,
|
||||
latencyMs: 50,
|
||||
tools: [opsApp, plainTool, malformedAppTool],
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
await user.click(screen.getByRole("switch"));
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByRole("switch")).toBeChecked();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
const tabSelect = await screen.findByDisplayValue("Servers");
|
||||
await user.click(tabSelect);
|
||||
await user.click(await screen.findByText("Apps"));
|
||||
expect(screen.getByText("MCP Apps (1)")).toBeInTheDocument();
|
||||
// Auto-launch on selection mounts the AppRenderer, which invokes the
|
||||
// stub bridge factory wired in InspectorView.
|
||||
await user.click(screen.getByText("Ops Dashboard"));
|
||||
expect(screen.getByTitle("Ops Dashboard")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("toggles autoScroll on the Logs screen after connecting", async () => {
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.1);
|
||||
it("dispatches onSetLogLevel through to the Logs screen", async () => {
|
||||
const onSetLogLevel = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
renderWithMantine(
|
||||
<InspectorView {...baseProps} servers={[sampleServer]} />,
|
||||
<InspectorView
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: "alpha",
|
||||
connectionStatus: "connected",
|
||||
initializeResult: connectedInit,
|
||||
latencyMs: 50,
|
||||
onSetLogLevel,
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
const toggle = screen.getByRole("switch");
|
||||
await user.click(toggle);
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(toggle).toBeChecked();
|
||||
expect(toggle).not.toBeDisabled();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
// Switch to Logs via the header Select. Mantine renders options into a
|
||||
// hidden portal in happy-dom — find via getAllByText with hidden traversal.
|
||||
const tabSelect = await screen.findByDisplayValue("Servers");
|
||||
await user.click(tabSelect);
|
||||
const logsOption = await screen.findByText("Logs");
|
||||
await user.click(logsOption);
|
||||
await user.click(await screen.findByText("Logs"));
|
||||
// LogControls renders Mantine's Select with the current level — picking
|
||||
// a value in the dropdown dispatches onSetLevel directly. (Mantine
|
||||
// renders the visible search input and a hidden combobox input, both
|
||||
// with the same displayValue; pick the first.)
|
||||
const levelInputs = screen.getAllByDisplayValue("info");
|
||||
await user.click(levelInputs[0]!);
|
||||
const warningOption = await screen.findByRole("option", {
|
||||
name: "warning",
|
||||
hidden: true,
|
||||
});
|
||||
await user.click(warningOption);
|
||||
expect(onSetLogLevel).toHaveBeenCalledWith("warning");
|
||||
});
|
||||
|
||||
it("toggles autoScroll locally on the Logs screen after connecting", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithMantine(
|
||||
<InspectorView
|
||||
{...makeProps({
|
||||
servers: [sampleServer],
|
||||
activeServer: "alpha",
|
||||
connectionStatus: "connected",
|
||||
initializeResult: connectedInit,
|
||||
latencyMs: 50,
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
const tabSelect = await screen.findByDisplayValue("Servers");
|
||||
await user.click(tabSelect);
|
||||
await user.click(await screen.findByText("Logs"));
|
||||
const autoScroll = await screen.findByRole("checkbox", {
|
||||
name: "Auto-scroll",
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import type {
|
|||
Task,
|
||||
Tool,
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { AppBridge } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import type {
|
||||
ConnectionStatus,
|
||||
InspectorResourceSubscription,
|
||||
|
|
@ -19,14 +18,23 @@ import type {
|
|||
import { isAppTool } from "@inspector/core/mcp/apps.js";
|
||||
import { ViewHeader } from "../../groups/ViewHeader/ViewHeader";
|
||||
import { ServerListScreen } from "../../screens/ServerListScreen/ServerListScreen";
|
||||
import { ToolsScreen } from "../../screens/ToolsScreen/ToolsScreen";
|
||||
import {
|
||||
ToolsScreen,
|
||||
type ToolCallState,
|
||||
} from "../../screens/ToolsScreen/ToolsScreen";
|
||||
import { AppsScreen } from "../../screens/AppsScreen/AppsScreen";
|
||||
import type {
|
||||
AppRendererHandle,
|
||||
BridgeFactory,
|
||||
} from "../../elements/AppRenderer/AppRenderer";
|
||||
import { PromptsScreen } from "../../screens/PromptsScreen/PromptsScreen";
|
||||
import { ResourcesScreen } from "../../screens/ResourcesScreen/ResourcesScreen";
|
||||
import {
|
||||
PromptsScreen,
|
||||
type GetPromptState,
|
||||
} from "../../screens/PromptsScreen/PromptsScreen";
|
||||
import {
|
||||
ResourcesScreen,
|
||||
type ReadResourceState,
|
||||
} from "../../screens/ResourcesScreen/ResourcesScreen";
|
||||
import { LoggingScreen } from "../../screens/LoggingScreen/LoggingScreen";
|
||||
import type { LogEntryData } from "../../elements/LogEntry/LogEntry";
|
||||
import { TasksScreen } from "../../screens/TasksScreen/TasksScreen";
|
||||
|
|
@ -46,20 +54,6 @@ const ALL_TABS: string[] = [
|
|||
"History",
|
||||
];
|
||||
|
||||
// Demo stub: Phase 3 wiring will replace this with a factory derived from
|
||||
// the active MCP `Client`. Apps are detected from the tools list, so the
|
||||
// "Apps" tab is exposed whenever the server advertises tools capability —
|
||||
// the screen itself receives only the already-filtered subset.
|
||||
const STUB_SANDBOX_PATH = "about:blank";
|
||||
const stubBridgeFactory: BridgeFactory = () =>
|
||||
({
|
||||
sendToolInput: async () => {},
|
||||
sendToolResult: async () => {},
|
||||
sendToolCancelled: async () => {},
|
||||
teardownResource: async () => ({}),
|
||||
close: async () => {},
|
||||
}) as unknown as AppBridge;
|
||||
|
||||
const SCREEN_ENTER_MS = 350;
|
||||
const SCREEN_EXIT_MS = 250;
|
||||
|
||||
|
|
@ -67,8 +61,7 @@ const SCREEN_EXIT_MS = 250;
|
|||
// children. `mih: "100%"` requires `AppShell.Main` to provide a definite
|
||||
// height for the stack itself to fill — the absolute children render
|
||||
// regardless, but nested ScrollArea screens need a non-collapsing parent
|
||||
// for their scroll containment to work. Revisit if Phase 3 reveals
|
||||
// scroll issues in real screens.
|
||||
// for their scroll containment to work.
|
||||
const ScreenStageContainer = Stack.withProps({
|
||||
pos: "relative",
|
||||
gap: 0,
|
||||
|
|
@ -79,10 +72,7 @@ const ScreenStageContainer = Stack.withProps({
|
|||
// Wraps each screen in a Mantine Transition. With Transition's default
|
||||
// (`keepMounted={false}`), the outgoing screen unmounts after its exit
|
||||
// animation — any local screen state (search filters, scroll position,
|
||||
// expanded sections) is reset on tab switch. This matches the previous
|
||||
// `{activeTab === "X" && <Screen />}` behavior. If Phase 3 needs state
|
||||
// to persist across tab switches, add `keepMounted` to the Transition
|
||||
// below.
|
||||
// expanded sections) is reset on tab switch.
|
||||
function ScreenStage({
|
||||
active,
|
||||
children,
|
||||
|
|
@ -109,26 +99,20 @@ function ScreenStage({
|
|||
);
|
||||
}
|
||||
|
||||
// Demo stub: every screen-action callback below resolves to noop. Phase 3
|
||||
// wiring will replace each with its real `useManaged*` / `useConnection`
|
||||
// hook call. Anything still pointing here in Phase 3 is unfinished.
|
||||
const noop = () => undefined;
|
||||
|
||||
// Demo stub: simulated handshake delays and a sample of plausible failure
|
||||
// reasons. Replace with real handshake telemetry once `useConnection` is wired.
|
||||
const STUB_MIN_DELAY_MS = 50;
|
||||
const STUB_MAX_DELAY_MS = 500;
|
||||
const STUB_SUCCESS_RATE = 0.85;
|
||||
const STUB_ERROR_MESSAGES = [
|
||||
"Connection refused",
|
||||
"Handshake timeout",
|
||||
"Protocol version mismatch",
|
||||
"Authentication required",
|
||||
"Server returned invalid response",
|
||||
];
|
||||
|
||||
export interface InspectorViewProps {
|
||||
// Server list (static config; runtime connection state comes from the
|
||||
// separate fields below and is merged into each card by this component).
|
||||
servers: ServerEntry[];
|
||||
|
||||
// Connection state — driven by the parent via `useInspectorClient`.
|
||||
activeServer?: string;
|
||||
connectionStatus: ConnectionStatus;
|
||||
initializeResult?: InitializeResult;
|
||||
latencyMs?: number;
|
||||
errorMessage?: string;
|
||||
|
||||
// Primitive lists, log streams, task state — all sourced from the
|
||||
// per-primitive `useManaged*` / `useMessageLog` hooks in the parent.
|
||||
tools: Tool[];
|
||||
prompts: Prompt[];
|
||||
resources: Resource[];
|
||||
|
|
@ -138,11 +122,86 @@ export interface InspectorViewProps {
|
|||
tasks: Task[];
|
||||
progressByTaskId?: Record<string, TaskProgress>;
|
||||
history: MessageEntry[];
|
||||
|
||||
// Per-screen "operation in flight" states (panel-level; optional because
|
||||
// the underlying screens accept them as optional).
|
||||
toolCallState?: ToolCallState;
|
||||
getPromptState?: GetPromptState;
|
||||
readResourceState?: ReadResourceState;
|
||||
|
||||
// Logging level. The MCP `logging/setLevel` request has no echo
|
||||
// notification, so the parent keeps the optimistic current value.
|
||||
currentLogLevel: LoggingLevel;
|
||||
|
||||
// MCP Apps sandbox. The parent's web environment provides both the
|
||||
// sandbox iframe URL and the per-app bridge factory.
|
||||
sandboxPath: string;
|
||||
bridgeFactory: BridgeFactory;
|
||||
|
||||
// History pinning. Optional because pin state isn't persisted yet (#1244
|
||||
// is single-PR; persistence is a separate concern).
|
||||
pinnedHistoryIds?: Set<string>;
|
||||
|
||||
// Theme toggle (lives in the parent so the color scheme can also flow
|
||||
// into other top-level UI later).
|
||||
onToggleTheme: () => void;
|
||||
|
||||
// Connection lifecycle (dispatched to `useInspectorClient.connect/disconnect`).
|
||||
onToggleConnection: (id: string) => void;
|
||||
onDisconnect: () => void;
|
||||
|
||||
// Server list actions.
|
||||
onServerAdd: () => void;
|
||||
onServerImportConfig: () => void;
|
||||
onServerImportJson: () => void;
|
||||
onServerInfo: (id: string) => void;
|
||||
onServerSettings: (id: string) => void;
|
||||
onServerEdit: (id: string) => void;
|
||||
onServerClone: (id: string) => void;
|
||||
onServerRemove: (id: string) => void;
|
||||
|
||||
// Per-primitive actions (route to `inspectorClient` methods / hook refresh).
|
||||
onCallTool: (name: string, args: Record<string, unknown>) => void;
|
||||
onCancelToolCall?: () => void;
|
||||
onClearToolResult?: () => void;
|
||||
onRefreshTools: () => void;
|
||||
|
||||
onGetPrompt: (name: string, args: Record<string, string>) => void;
|
||||
onCopyPromptMessages?: () => void;
|
||||
onRefreshPrompts: () => void;
|
||||
|
||||
onReadResource: (uri: string) => void;
|
||||
onSubscribeResource: (uri: string) => void;
|
||||
onUnsubscribeResource: (uri: string) => void;
|
||||
onRefreshResources: () => void;
|
||||
|
||||
onCancelTask: (taskId: string) => void;
|
||||
onClearCompletedTasks: () => void;
|
||||
onRefreshTasks: () => void;
|
||||
|
||||
onSetLogLevel: (level: LoggingLevel) => void;
|
||||
onClearLogs: () => void;
|
||||
onExportLogs: () => void;
|
||||
onCopyAllLogs: () => void;
|
||||
|
||||
onClearHistory: () => void;
|
||||
onExportHistory: () => void;
|
||||
onReplayHistory: (id: string) => void;
|
||||
onTogglePinHistory: (id: string) => void;
|
||||
|
||||
onSelectApp: (name: string) => void;
|
||||
onOpenApp: (name: string, args: Record<string, unknown>) => void;
|
||||
onCloseApp: () => void;
|
||||
onRefreshApps: () => void;
|
||||
}
|
||||
|
||||
export function InspectorView({
|
||||
servers: serversInput,
|
||||
activeServer,
|
||||
connectionStatus,
|
||||
initializeResult,
|
||||
latencyMs,
|
||||
errorMessage,
|
||||
tools,
|
||||
prompts,
|
||||
resources,
|
||||
|
|
@ -152,29 +211,76 @@ export function InspectorView({
|
|||
tasks,
|
||||
progressByTaskId,
|
||||
history,
|
||||
toolCallState,
|
||||
getPromptState,
|
||||
readResourceState,
|
||||
currentLogLevel,
|
||||
sandboxPath,
|
||||
bridgeFactory,
|
||||
pinnedHistoryIds,
|
||||
onToggleTheme,
|
||||
onToggleConnection,
|
||||
onDisconnect,
|
||||
onServerAdd,
|
||||
onServerImportConfig,
|
||||
onServerImportJson,
|
||||
onServerInfo,
|
||||
onServerSettings,
|
||||
onServerEdit,
|
||||
onServerClone,
|
||||
onServerRemove,
|
||||
onCallTool,
|
||||
onCancelToolCall,
|
||||
onClearToolResult,
|
||||
onRefreshTools,
|
||||
onGetPrompt,
|
||||
onCopyPromptMessages,
|
||||
onRefreshPrompts,
|
||||
onReadResource,
|
||||
onSubscribeResource,
|
||||
onUnsubscribeResource,
|
||||
onRefreshResources,
|
||||
onCancelTask,
|
||||
onClearCompletedTasks,
|
||||
onRefreshTasks,
|
||||
onSetLogLevel,
|
||||
onClearLogs,
|
||||
onExportLogs,
|
||||
onCopyAllLogs,
|
||||
onClearHistory,
|
||||
onExportHistory,
|
||||
onReplayHistory,
|
||||
onTogglePinHistory,
|
||||
onSelectApp,
|
||||
onOpenApp,
|
||||
onCloseApp,
|
||||
onRefreshApps,
|
||||
}: InspectorViewProps) {
|
||||
const [activeServer, setActiveServer] = useState<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const [initializeResult, setInitializeResult] = useState<
|
||||
InitializeResult | undefined
|
||||
>(undefined);
|
||||
const [connectionStatus, setConnectionStatus] =
|
||||
useState<ConnectionStatus>("disconnected");
|
||||
const [latencyMs, setLatencyMs] = useState<number | undefined>(undefined);
|
||||
const [errorMessage, setErrorMessage] = useState<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const [activeTab, setActiveTab] = useState<string>(SERVERS_TAB);
|
||||
const [availableTabs, setAvailableTabs] = useState<string[]>([SERVERS_TAB]);
|
||||
const [logLevel, setLogLevel] = useState<LoggingLevel>("info");
|
||||
// UI-only state. Connection state, primitive lists, and all action
|
||||
// dispatching live in the parent; this component only owns navigation
|
||||
// (which tab is visible) and a couple of view-local toggles.
|
||||
const [selectedTab, setSelectedTab] = useState<string>(SERVERS_TAB);
|
||||
const [autoScroll, setAutoScroll] = useState<boolean>(true);
|
||||
// Tracks the in-flight stub handshake timer so rapid Connect→Connect
|
||||
// toggles can cancel the previous attempt before it resolves and
|
||||
// overwrites the new server's state.
|
||||
const handshakeTimer = useRef<number | undefined>(undefined);
|
||||
const appRendererRef = useRef<AppRendererHandle>(null);
|
||||
|
||||
// Only show the non-Servers tabs when actually connected. Capability-aware
|
||||
// tab gating (hide Tools when the server doesn't advertise `tools`, etc.)
|
||||
// can layer in later once the parent passes capabilities through.
|
||||
const availableTabs = useMemo<string[]>(
|
||||
() => (connectionStatus === "connected" ? ALL_TABS : [SERVERS_TAB]),
|
||||
[connectionStatus],
|
||||
);
|
||||
|
||||
// Clamp the rendered tab to whatever's currently available. If the user
|
||||
// had "Tools" selected and the connection drops, `availableTabs` becomes
|
||||
// `[Servers]` and the view renders Servers without us having to imperatively
|
||||
// reset the state (and trip the `set-state-in-effect` lint). When the
|
||||
// connection comes back, the previous selection pops in again because
|
||||
// `selectedTab` is preserved.
|
||||
const activeTab = availableTabs.includes(selectedTab)
|
||||
? selectedTab
|
||||
: SERVERS_TAB;
|
||||
|
||||
const appTools = useMemo<Tool[]>(() => {
|
||||
return tools.filter((tool) => {
|
||||
try {
|
||||
|
|
@ -188,10 +294,9 @@ export function InspectorView({
|
|||
});
|
||||
}, [tools]);
|
||||
|
||||
// The view is the single source of truth for connection state. Any
|
||||
// `connection` field on incoming `serversInput` items is intentionally
|
||||
// ignored — cards mirror the global `connectionStatus` for the active
|
||||
// server and render as `disconnected` otherwise.
|
||||
// Merge the parent's `serversInput` (static config) with the runtime
|
||||
// connection state owned by the parent — only the active server reflects
|
||||
// the live status; the rest render as `disconnected`.
|
||||
const servers = useMemo<ServerEntry[]>(
|
||||
() =>
|
||||
serversInput.map((s) => {
|
||||
|
|
@ -212,75 +317,6 @@ export function InspectorView({
|
|||
[serversInput, activeServer, connectionStatus, errorMessage],
|
||||
);
|
||||
|
||||
function disconnect() {
|
||||
if (handshakeTimer.current !== undefined) {
|
||||
window.clearTimeout(handshakeTimer.current);
|
||||
handshakeTimer.current = undefined;
|
||||
}
|
||||
setActiveServer(undefined);
|
||||
setConnectionStatus("disconnected");
|
||||
setInitializeResult(undefined);
|
||||
setLatencyMs(undefined);
|
||||
setErrorMessage(undefined);
|
||||
setAvailableTabs([SERVERS_TAB]);
|
||||
setActiveTab(SERVERS_TAB);
|
||||
}
|
||||
|
||||
// Demo stub: simulates the full connect → connecting → connected/error
|
||||
// transition with a randomized handshake delay. Real wiring will dispatch
|
||||
// `useConnection.connect(id)` and let the hook drive these state changes.
|
||||
// The `protocolVersion`, `capabilities`, and `serverInfo` populated below
|
||||
// are placeholders until a real `InitializeResult` arrives from the server.
|
||||
function handleToggleConnection(id: string) {
|
||||
if (id === activeServer && connectionStatus === "connected") {
|
||||
disconnect();
|
||||
return;
|
||||
}
|
||||
const target = serversInput.find((s) => s.id === id);
|
||||
if (!target) return;
|
||||
|
||||
// Cancel any in-flight handshake so a rapid switch to a different
|
||||
// server doesn't get overwritten by the previous server's resolver.
|
||||
if (handshakeTimer.current !== undefined) {
|
||||
window.clearTimeout(handshakeTimer.current);
|
||||
}
|
||||
|
||||
// Capture `start` at the "connecting" edge and compute observed
|
||||
// latency at the "connected" edge. Both edges are owned by this
|
||||
// handler so the timing is deterministic — no useEffect chain needed
|
||||
// (which would otherwise trip `react-hooks/set-state-in-effect`).
|
||||
const start = Date.now();
|
||||
setActiveServer(id);
|
||||
setLatencyMs(undefined);
|
||||
setErrorMessage(undefined);
|
||||
setConnectionStatus("connecting");
|
||||
|
||||
const delay =
|
||||
STUB_MIN_DELAY_MS +
|
||||
Math.floor(Math.random() * (STUB_MAX_DELAY_MS - STUB_MIN_DELAY_MS + 1));
|
||||
|
||||
handshakeTimer.current = window.setTimeout(() => {
|
||||
handshakeTimer.current = undefined;
|
||||
if (Math.random() < STUB_SUCCESS_RATE) {
|
||||
setInitializeResult({
|
||||
protocolVersion: "2025-06-18",
|
||||
capabilities: {},
|
||||
serverInfo: target.info ?? { name: target.name, version: "0.0.0" },
|
||||
});
|
||||
setAvailableTabs(ALL_TABS);
|
||||
setLatencyMs(Date.now() - start);
|
||||
setConnectionStatus("connected");
|
||||
} else {
|
||||
setErrorMessage(
|
||||
STUB_ERROR_MESSAGES[
|
||||
Math.floor(Math.random() * STUB_ERROR_MESSAGES.length)
|
||||
],
|
||||
);
|
||||
setConnectionStatus("error");
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell header={{ height: 60 }} padding="md">
|
||||
<AppShell.Header>
|
||||
|
|
@ -292,8 +328,8 @@ export function InspectorView({
|
|||
latencyMs={latencyMs}
|
||||
activeTab={activeTab}
|
||||
availableTabs={availableTabs}
|
||||
onTabChange={setActiveTab}
|
||||
onDisconnect={disconnect}
|
||||
onTabChange={setSelectedTab}
|
||||
onDisconnect={onDisconnect}
|
||||
onToggleTheme={onToggleTheme}
|
||||
/>
|
||||
) : (
|
||||
|
|
@ -306,44 +342,49 @@ export function InspectorView({
|
|||
<ServerListScreen
|
||||
servers={servers}
|
||||
activeServer={activeServer}
|
||||
onAddManually={noop}
|
||||
onImportConfig={noop}
|
||||
onImportServerJson={noop}
|
||||
onToggleConnection={handleToggleConnection}
|
||||
onServerInfo={noop}
|
||||
onSettings={noop}
|
||||
onEdit={noop}
|
||||
onClone={noop}
|
||||
onRemove={noop}
|
||||
onAddManually={onServerAdd}
|
||||
onImportConfig={onServerImportConfig}
|
||||
onImportServerJson={onServerImportJson}
|
||||
onToggleConnection={onToggleConnection}
|
||||
onServerInfo={onServerInfo}
|
||||
onSettings={onServerSettings}
|
||||
onEdit={onServerEdit}
|
||||
onClone={onServerClone}
|
||||
onRemove={onServerRemove}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "Tools"}>
|
||||
<ToolsScreen
|
||||
tools={tools}
|
||||
callState={toolCallState}
|
||||
listChanged={false}
|
||||
onRefreshList={noop}
|
||||
onCallTool={noop}
|
||||
onRefreshList={onRefreshTools}
|
||||
onCallTool={onCallTool}
|
||||
onCancelCall={onCancelToolCall}
|
||||
onClearResult={onClearToolResult}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "Apps"}>
|
||||
<AppsScreen
|
||||
tools={appTools}
|
||||
listChanged={false}
|
||||
sandboxPath={STUB_SANDBOX_PATH}
|
||||
bridgeFactory={stubBridgeFactory}
|
||||
sandboxPath={sandboxPath}
|
||||
bridgeFactory={bridgeFactory}
|
||||
rendererRef={appRendererRef}
|
||||
onRefreshList={noop}
|
||||
onSelectApp={noop}
|
||||
onOpenApp={noop}
|
||||
onCloseApp={noop}
|
||||
onRefreshList={onRefreshApps}
|
||||
onSelectApp={onSelectApp}
|
||||
onOpenApp={onOpenApp}
|
||||
onCloseApp={onCloseApp}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "Prompts"}>
|
||||
<PromptsScreen
|
||||
prompts={prompts}
|
||||
getPromptState={getPromptState}
|
||||
listChanged={false}
|
||||
onRefreshList={noop}
|
||||
onGetPrompt={noop}
|
||||
onRefreshList={onRefreshPrompts}
|
||||
onGetPrompt={onGetPrompt}
|
||||
onCopyMessages={onCopyPromptMessages}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "Resources"}>
|
||||
|
|
@ -351,42 +392,43 @@ export function InspectorView({
|
|||
resources={resources}
|
||||
templates={resourceTemplates}
|
||||
subscriptions={subscriptions}
|
||||
readState={readResourceState}
|
||||
listChanged={false}
|
||||
onRefreshList={noop}
|
||||
onReadResource={noop}
|
||||
onSubscribeResource={noop}
|
||||
onUnsubscribeResource={noop}
|
||||
onRefreshList={onRefreshResources}
|
||||
onReadResource={onReadResource}
|
||||
onSubscribeResource={onSubscribeResource}
|
||||
onUnsubscribeResource={onUnsubscribeResource}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "Tasks"}>
|
||||
<TasksScreen
|
||||
tasks={tasks}
|
||||
progressByTaskId={progressByTaskId}
|
||||
onRefresh={noop}
|
||||
onClearCompleted={noop}
|
||||
onCancel={noop}
|
||||
onRefresh={onRefreshTasks}
|
||||
onClearCompleted={onClearCompletedTasks}
|
||||
onCancel={onCancelTask}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "Logs"}>
|
||||
<LoggingScreen
|
||||
entries={logs}
|
||||
currentLevel={logLevel}
|
||||
onSetLevel={setLogLevel}
|
||||
onClear={noop}
|
||||
onExport={noop}
|
||||
currentLevel={currentLogLevel}
|
||||
onSetLevel={onSetLogLevel}
|
||||
onClear={onClearLogs}
|
||||
onExport={onExportLogs}
|
||||
autoScroll={autoScroll}
|
||||
onToggleAutoScroll={() => setAutoScroll((prev) => !prev)}
|
||||
onCopyAll={noop}
|
||||
onCopyAll={onCopyAllLogs}
|
||||
/>
|
||||
</ScreenStage>
|
||||
<ScreenStage active={activeTab === "History"}>
|
||||
<HistoryScreen
|
||||
entries={history}
|
||||
pinnedIds={new Set()}
|
||||
onClearAll={noop}
|
||||
onExport={noop}
|
||||
onReplay={noop}
|
||||
onTogglePin={noop}
|
||||
pinnedIds={pinnedHistoryIds ?? new Set()}
|
||||
onClearAll={onClearHistory}
|
||||
onExport={onExportHistory}
|
||||
onReplay={onReplayHistory}
|
||||
onTogglePin={onTogglePinHistory}
|
||||
/>
|
||||
</ScreenStage>
|
||||
</ScreenStageContainer>
|
||||
|
|
|
|||
Loading…
Reference in a new issue