inspector/clients/tui/__tests__/ResourceTestModal.test.tsx
cliffhall 6acaff70ca fix: honor a defined-but-empty value, and announce the expansion error
Addresses Copilot's round-8 review on #2035 (one inline comment, one
suppressed). Both real.

1. RFC 6570 distinguishes an UNDEFINED variable, which omits its whole
   expression, from one defined as the empty string, which expands. The
   expander was calling `definedValues` on the way in, collapsing the two --
   so `x{?q}` with `{ q: "" }` gave `x` instead of `x?q=`, and there was no
   way for any caller, `readResourceFromTemplate` included, to request
   either that or `x;q`. Key presence is now honored, including §3.2.7's
   rule that the matrix operator drops the `=` for an empty value (`x{;q}`
   -> `x;q`, while `?`/`&` keep it).

   Dropping blanks is a FORM concern, so it moved to the two form
   boundaries: the web panel seeds every declared variable with "" and the
   TUI's ink-form returns "" for every untouched field, so neither can tell
   "never touched" from "deliberately empty" -- but that is a fact about a
   text input, not about the template, and it has no business deciding what
   a template means for every other caller.

   Six unit tests and one integration test encoded the old collapse and now
   assert the corrected meaning. The prototype-collision cases get stronger
   rather than weaker: a blank `{?toString}` expands to `?toString=` -- its
   OWN empty value -- where the original bug expanded the inherited
   function's body.

2. The expansion error is now `role="alert"`. It can appear while typing (a
   pasted value that cannot be encoded), and plain text is not announced, so
   a screen-reader user met a disabled Read Resource with no stated reason.

npm run ci passes.

Signed-off-by: cliffhall <cliff@futurescale.com>
2026-08-16 23:08:30 -04:00

363 lines
12 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("blocks a required variable whose name collides with Object.prototype", async () => {
// `constructor` is a valid RFC 6570 varname, and the modal's own filter
// used to read `Object` (length 1) as a filled value. The *message* built
// from that filter came out naming no field; since frames render empty
// here (see the header note), that half is asserted on
// `unmetRequiredGroups` in the core suite. This asserts the gate.
const read = vi.fn();
const { onClose, unmount } = await renderAndSubmit(
fakeClient(read),
makeTemplate({ uriTemplate: "x://{constructor}" }),
{ constructor: "" },
);
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: "" },
);
// The untouched field is dropped before the read: `""` is a *defined*
// RFC 6570 value that would expand to a valueless pair, and ink-form
// cannot distinguish "never touched" from "deliberately empty".
expect(read).toHaveBeenCalledWith("x://{a,b}", { a: "only-a" });
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();
});
});