inspector/core/react/useInspectorClient.ts
Cliff Hall e3e70470b5
feat(core): port v1.5 hook layer (#1243) (#1300)
* feat(core): port v1.5 hook layer (useInspectorClient + useManaged*/usePaged* + log hooks)

Wholesale port of v1.5's React hook layer and the EventTarget-based state machinery the hooks subscribe to (#1243). Hooks decouple from the concrete InspectorClient via a new `InspectorClientProtocol` interface so this layer can land before the runtime class is ported.

Added under `core/`:
- `core/react/` — useInspectorClient + 5 useManaged* + 5 usePaged* + 3 log hooks
- `core/mcp/state/` — 5 managed*State + 5 paged*State + messageLogState + stderrLogState + fetchRequestLogState
- `core/mcp/inspectorClientProtocol.ts`, `inspectorClientEventTarget.ts`, `typedEventTarget.ts`, `samplingCreateMessage.ts`, `sessionStorage.ts`
- v2-only wrapper types in `core/mcp/types.ts`: InspectorUrlElicitRequest, InspectorPendingRequest, InspectorRequestHistoryItem

Tests live under `clients/web/src/test/core/` (28 new test files, 264 new tests). Test fake: `core/mcp/__tests__/fakeInspectorClient.ts`.

Build wiring:
- `vite.config.ts`: dedupe react/react-dom so core/ files resolve them via clients/web/node_modules.
- `tsconfig.app.json` / `tsconfig.test.json`: paths map react/react-dom/vitest to clients/web/node_modules so `tsc -b` resolves bare imports from core/ source files (which sit above the package's node_modules). Exclude core/__tests__ from app config; include in test config.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* review: address PR #1300 review findings

Bugs:
- fetchRequestLogState: add .catch() on sessionStorage.loadSession so a corrupt
  or unreadable session doesn't surface as an unhandled rejection (matches the
  saveSession swallow pattern).
- messageLogState: sync pendingRequestEntries when clearMessages() evicts a
  pending request entry, so a later response with the same id falls through
  to the append branch instead of mutating an unreachable map entry. Add tests
  for both predicate and no-predicate paths.

Cleanups:
- Extract mergeTaskIntoList helper to core/mcp/state/mergeTaskIntoList.ts so
  managed/paged RequestorTasks state classes share one definition.
- Add a one-line JSDoc note on each PagedTools/Prompts/Resources/Templates
  state explaining why they deliberately do not subscribe to *ListChanged
  (cursor invalidation mid-pagination).
- Document on useInspectorClient that appRendererClient is read lazily on
  every render and is not subscribed (changes once at connect time).

Carry-overs from v1.5 deliberately left for the follow-up InspectorClient
runtime port:
- Refresh/status-change race in Managed*State.refresh() (status check is only
  at entry; a disconnect during await can re-clear before refresh resumes).
- nextCursor exposure asymmetry across usePaged* (only usePagedRequestorTasks
  surfaces it via state field; others return it from loadPage() only).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 17:43:07 -04:00

124 lines
4.1 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
import type { InspectorClientProtocol } from "../mcp/inspectorClientProtocol.js";
import type { AppRendererClient } from "../mcp/inspectorClientProtocol.js";
import type { TypedEvent } from "../mcp/inspectorClientEventTarget.js";
import type { ConnectionStatus } from "../mcp/types.js";
import type {
ServerCapabilities,
Implementation,
} from "@modelcontextprotocol/sdk/types.js";
export interface UseInspectorClientResult {
status: ConnectionStatus;
capabilities?: ServerCapabilities;
serverInfo?: Implementation;
instructions?: string;
appRendererClient: AppRendererClient | null;
connect: () => Promise<void>;
disconnect: () => Promise<void>;
}
/**
* React hook that subscribes to InspectorClient events and provides reactive
* connection state. Log lists (message / stderr / fetch) live in dedicated
* state managers consumed via useMessageLog / useStderrLog / useFetchRequestLog.
*
* Note: `appRendererClient` is read lazily from the client on every render
* and is NOT subscribed. It changes once at connect time and is not expected
* to change again during a session, so callers will see the current value
* on any rerender triggered by status / capabilities / serverInfo / instructions.
* If a future use case requires autonomous updates when the renderer attaches,
* add an `appRendererClientChange` event to `InspectorClientEventMap` and
* subscribe here.
*/
export function useInspectorClient(
inspectorClient: InspectorClientProtocol | null,
): UseInspectorClientResult {
const [status, setStatus] = useState<ConnectionStatus>(
inspectorClient?.getStatus() ?? "disconnected",
);
const [capabilities, setCapabilities] = useState<
ServerCapabilities | undefined
>(inspectorClient?.getCapabilities());
const [serverInfo, setServerInfo] = useState<Implementation | undefined>(
inspectorClient?.getServerInfo(),
);
const [instructions, setInstructions] = useState<string | undefined>(
inspectorClient?.getInstructions(),
);
useEffect(() => {
if (!inspectorClient) {
setStatus("disconnected");
setCapabilities(undefined);
setServerInfo(undefined);
setInstructions(undefined);
return;
}
setStatus(inspectorClient.getStatus());
setCapabilities(inspectorClient.getCapabilities());
setServerInfo(inspectorClient.getServerInfo());
setInstructions(inspectorClient.getInstructions());
const onStatusChange = (event: TypedEvent<"statusChange">) => {
setStatus(event.detail);
};
const onCapabilitiesChange = (event: TypedEvent<"capabilitiesChange">) => {
setCapabilities(event.detail);
};
const onServerInfoChange = (event: TypedEvent<"serverInfoChange">) => {
setServerInfo(event.detail);
};
const onInstructionsChange = (event: TypedEvent<"instructionsChange">) => {
setInstructions(event.detail);
};
inspectorClient.addEventListener("statusChange", onStatusChange);
inspectorClient.addEventListener(
"capabilitiesChange",
onCapabilitiesChange,
);
inspectorClient.addEventListener("serverInfoChange", onServerInfoChange);
inspectorClient.addEventListener(
"instructionsChange",
onInstructionsChange,
);
return () => {
inspectorClient.removeEventListener("statusChange", onStatusChange);
inspectorClient.removeEventListener(
"capabilitiesChange",
onCapabilitiesChange,
);
inspectorClient.removeEventListener(
"serverInfoChange",
onServerInfoChange,
);
inspectorClient.removeEventListener(
"instructionsChange",
onInstructionsChange,
);
};
}, [inspectorClient]);
const connect = useCallback(async () => {
if (!inspectorClient) return;
await inspectorClient.connect();
}, [inspectorClient]);
const disconnect = useCallback(async () => {
if (!inspectorClient) return;
await inspectorClient.disconnect();
}, [inspectorClient]);
return {
status,
capabilities,
serverInfo,
instructions,
appRendererClient: inspectorClient?.getAppRendererClient() ?? null,
connect,
disconnect,
};
}