inspector/clients/tui/__tests__/ResourceTestModal.test.tsx
cliffhall ebc18e1d56 fix: expand each expression independently, and reject invalid varspecs
Addresses Copilot's round-5 review on #2035 — eight suppressed comments,
all of them real.

The consequential one overturns behavior I copied from the SDK and
defended in two earlier rounds. RFC 6570 expands each expression
independently; it carries no cross-expression state. The SDK tracks
whether a query expression has already emitted and rewrites a later
`{?two}`'s `?` to `&`. That looks friendlier and is wrong, and its own
matcher says so: for `x{?one}{?two}` it expands to `x?one=1&two=2`, and
`match("x?one=1&two=2")` on that same template returns **null**, while
`match("x?one=1?two=2")` returns both variables. So the rewrite emitted a
URI the advertised template cannot match — #1919 one level up. A server
that wants a continuation advertises `{?one}{&two}`, which expands to `&`
and matches; producing that shape is the server's choice to declare, not
ours to infer.

Also:

- `{id:abc}` was silently treated as `{id}`, and a test codified it. RFC
  6570's max-length is `%x31-39 0*3DIGIT`, so `{id:}`, `{id:0}`,
  `{id:abc}` and `{id:10000}` are invalid templates rather than templates
  with an ignorable modifier — and the SDK's constructor accepts them all,
  so nothing else rejects them. Strict expansion now throws; lenient
  returns the raw template. Discovery stays lenient so the panel still
  renders rather than going blank.

- The TUI could submit `{a,b}` completely blank while the web panel
  blocked the same request: ink-form has no way to express "any one of
  these", so its members are left optional and the modal needs its own
  group check. Added, with tests — it was also below the coverage gate
  without them (functions 76.92%).

- Added the integration test the config never had: it resolves the
  checked-in config and drives all four reads over a real transport, so a
  misspelt preset fails there rather than only when someone runs the repro
  by hand.

- "All three clients" was false. The CLI has no template form and its
  `resources/read` passes the already-expanded `--uri` straight to
  `readResource`, so nothing here runs for it. Corrected in the README,
  AGENTS.md, and the module comment, and dropped a docblock still
  describing the SDK-delegation path removed last round.

Signed-off-by: cliffhall <cliff@futurescale.com>
2026-08-16 21:38:52 -04:00

343 lines
11 KiB
TypeScript

import React from "react";
import { describe, it, expect, vi, afterEach } from "vitest";
import { render } from "ink-testing-library";
import type { InspectorClient } from "@inspector/core/mcp/index.js";
import { AuthRecoveryRequiredError } from "@inspector/core/auth/challenge.js";
// ScrollView passthrough so the results JSX actually mounts (and is covered).
vi.mock("ink-scroll-view", () => import("./helpers/inkScrollViewMock.js"));
// Form double that fires onSubmit when the user presses Enter ("\r").
vi.mock("ink-form", () => import("./helpers/inkFormMock.js"));
import { ResourceTestModal } from "../src/components/ResourceTestModal.js";
// These modals render position="absolute", which produces an EMPTY frame under
// ink-testing-library. So we assert on BEHAVIOR — the injected client fake's
// readResourceFromTemplate, onClose, and the state transitions they drive —
// rather than on lastFrame(). React still EXECUTES the inner results/error JSX,
// so its coverage is collected even though it isn't visible.
const tick = async () => {
// Flush several macrotask cycles so an effect -> setState -> re-render chain
// settles before assertions, even on slow/loaded CI (a single tick can race).
for (let i = 0; i < 8; i++)
await new Promise((resolve) => setTimeout(resolve, 4));
};
const ESC = String.fromCharCode(27);
const UP = `${ESC}[A`;
const DOWN = `${ESC}[B`;
const PAGE_UP = `${ESC}[5~`;
const PAGE_DOWN = `${ESC}[6~`;
type Template = {
name: string;
uriTemplate: string;
description?: string;
};
const makeTemplate = (over: Partial<Template> = {}): Template => ({
name: "Greeting",
uriTemplate: "greeting://{name}",
...over,
});
const fakeClient = (readResourceFromTemplate: unknown): InspectorClient =>
({ readResourceFromTemplate }) as unknown as InspectorClient;
const setSubmitValue = (value: Record<string, unknown>) => {
(globalThis as Record<string, unknown>).__INK_FORM_SUBMIT_VALUE__ = value;
};
afterEach(() => {
delete (globalThis as Record<string, unknown>).__INK_FORM_SUBMIT_VALUE__;
vi.restoreAllMocks();
});
const renderAndSubmit = async (
client: InspectorClient | null,
template: Template = makeTemplate(),
submitValue: Record<string, unknown> = { name: "world" },
) => {
const onClose = vi.fn();
const api = render(
<ResourceTestModal
template={template}
inspectorClient={client}
width={80}
height={24}
onClose={onClose}
/>,
);
await tick();
setSubmitValue(submitValue);
api.stdin.write("\r");
await tick();
await tick();
return { ...api, onClose };
};
describe("ResourceTestModal", () => {
// RFC 6570 keeps a required expression satisfied by any ONE of its names, so
// `{a,b}` cannot be expressed with ink-form's per-field `required` flag and
// its members are left optional there. Without the modal's own group check
// the TUI would submit blank -- dropping the expression and reading a
// different resource -- while the web panel blocks the same request (#1919).
describe("required-group validation", () => {
it("refuses to submit when no name in a required group has a value", async () => {
const read = vi.fn();
const { onClose, unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://{a,b}" }),
{ a: "", b: "" },
);
expect(read).not.toHaveBeenCalled();
expect(onClose).not.toHaveBeenCalled();
unmount();
});
it("submits once any one name in the group has a value", async () => {
const read = vi.fn().mockResolvedValue({
result: { contents: [] },
expandedUri: "x://only-a",
});
const { unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://{a,b}" }),
{ a: "only-a", b: "" },
);
expect(read).toHaveBeenCalledWith("x://{a,b}", { a: "only-a", b: "" });
unmount();
});
it("does not block a template whose only expression is omittable", async () => {
const read = vi.fn().mockResolvedValue({
result: { contents: [] },
expandedUri: "x://events",
});
const { unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://events{?topic}" }),
{ topic: "" },
);
expect(read).toHaveBeenCalled();
unmount();
});
});
it("renders the form initially without invoking the client", async () => {
const read = vi.fn();
const api = render(
<ResourceTestModal
template={makeTemplate()}
inspectorClient={fakeClient(read)}
width={80}
height={24}
onClose={vi.fn()}
/>,
);
await tick();
expect(read).not.toHaveBeenCalled();
api.unmount();
});
it("renders the template description when present", async () => {
const read = vi.fn();
const api = render(
<ResourceTestModal
template={makeTemplate({ description: "A friendly greeting" })}
inspectorClient={fakeClient(read)}
width={80}
height={24}
onClose={vi.fn()}
/>,
);
await tick();
api.unmount();
});
it("uses the 'Unknown Template' label when the template has an empty name", async () => {
const read = vi.fn();
const api = render(
<ResourceTestModal
template={makeTemplate({ name: "" })}
inspectorClient={fakeClient(read)}
width={80}
height={24}
onClose={vi.fn()}
/>,
);
await tick();
api.unmount();
});
it("renders the loading state while the read is in flight", async () => {
let resolveRead: (v: unknown) => void = () => {};
const pending = new Promise((resolve) => {
resolveRead = resolve;
});
const read = vi.fn().mockReturnValue(pending);
const api = render(
<ResourceTestModal
template={makeTemplate()}
inspectorClient={fakeClient(read)}
width={80}
height={24}
onClose={vi.fn()}
/>,
);
await tick();
setSubmitValue({ name: "world" });
api.stdin.write("\r");
await tick();
// The component is now committed in the "loading" state (read not resolved).
expect(read).toHaveBeenCalled();
resolveRead({
result: { contents: [{ uri: "greeting://world", text: "hi" }] },
expandedUri: "greeting://world",
});
await tick();
await tick();
api.unmount();
});
it("reads the resource and shows successful content", async () => {
const read = vi.fn().mockResolvedValue({
result: { contents: [{ uri: "greeting://world", text: "hi" }] },
expandedUri: "greeting://world",
});
const { onClose, stdin, unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate(),
{ name: "world" },
);
expect(read).toHaveBeenCalledWith("greeting://{name}", { name: "world" });
// Drive scroll keys in results state for scrollBy / page coverage.
stdin.write(DOWN);
await tick();
stdin.write(UP);
await tick();
stdin.write(PAGE_DOWN);
await tick();
stdin.write(PAGE_UP);
await tick();
expect(onClose).not.toHaveBeenCalled();
unmount();
});
it("catches an Error thrown by readResourceFromTemplate", async () => {
const read = vi.fn().mockRejectedValue(new Error("not found"));
const { unmount } = await renderAndSubmit(fakeClient(read));
expect(read).toHaveBeenCalled();
unmount();
});
it("catches a string thrown by readResourceFromTemplate", async () => {
const read = vi.fn().mockRejectedValue("boom");
const { unmount } = await renderAndSubmit(fakeClient(read));
expect(read).toHaveBeenCalled();
unmount();
});
it("catches an object error carrying uri and message (uri + Object.assign branches)", async () => {
const read = vi
.fn()
.mockRejectedValue({ message: "bad uri", uri: "greeting://expanded" });
const { unmount } = await renderAndSubmit(fakeClient(read));
expect(read).toHaveBeenCalled();
unmount();
});
it("catches an object error without message or uri (Object.assign + Unknown error)", async () => {
const read = vi.fn().mockRejectedValue({ code: 42 });
const { unmount } = await renderAndSubmit(fakeClient(read));
expect(read).toHaveBeenCalled();
unmount();
});
it("catches a non-object, non-string throw (else branch)", async () => {
const read = vi.fn().mockRejectedValue(12345);
const { unmount } = await renderAndSubmit(fakeClient(read));
expect(read).toHaveBeenCalled();
unmount();
});
it("does nothing on submit when inspectorClient is null (early-return guard)", async () => {
const { onClose, unmount } = await renderAndSubmit(null);
expect(onClose).not.toHaveBeenCalled();
unmount();
});
it("closes on ESC while in form state", async () => {
const onClose = vi.fn();
const api = render(
<ResourceTestModal
template={makeTemplate()}
inspectorClient={fakeClient(vi.fn())}
width={80}
height={24}
onClose={onClose}
/>,
);
await tick();
api.stdin.write(ESC);
await tick();
expect(onClose).toHaveBeenCalledTimes(1);
api.unmount();
});
it("closes on ESC while in results state", async () => {
const read = vi.fn().mockResolvedValue({
result: { contents: [{ uri: "greeting://world", text: "hi" }] },
expandedUri: "greeting://world",
});
const { onClose, stdin, unmount } = await renderAndSubmit(fakeClient(read));
stdin.write(ESC);
await tick();
expect(onClose).toHaveBeenCalledTimes(1);
unmount();
});
it("responds to a stdout resize event", async () => {
const api = render(
<ResourceTestModal
template={makeTemplate()}
inspectorClient={fakeClient(vi.fn())}
width={80}
height={24}
onClose={vi.fn()}
/>,
);
await tick();
process.stdout.emit("resize");
await tick();
api.unmount();
});
it("delegates AuthRecoveryRequiredError to onAuthRecoveryRequired and closes", async () => {
const recovery = new AuthRecoveryRequiredError(
new URL("https://auth.example.com/authorize"),
{ reason: "insufficient_scope", requiredScopes: ["weather:read"] },
);
const read = vi.fn().mockRejectedValue(recovery);
const onClose = vi.fn();
const onAuthRecoveryRequired = vi.fn();
const api = render(
<ResourceTestModal
template={makeTemplate()}
inspectorClient={fakeClient(read)}
width={80}
height={24}
onClose={onClose}
onAuthRecoveryRequired={onAuthRecoveryRequired}
/>,
);
await tick();
setSubmitValue({ name: "world" });
api.stdin.write("\r");
await tick();
await tick();
expect(onAuthRecoveryRequired).toHaveBeenCalledWith(recovery);
expect(onClose).toHaveBeenCalledTimes(1);
api.unmount();
});
});