inspector/clients/tui/__tests__/HistoryTab.test.tsx
Cliff Hall f43fafc08b
test(tui): extend coverage gate to Ink components + App.tsx (closes #1501) (#1538)
* test(tui): cover useSelectableList hook + leaf Ink components (#1501)

Add ink-testing-library and renderer-based tests for useSelectableList,
SelectableItem, and Tabs. Widen the vitest include glob to .test.tsx and
lift these files from the interim React-surface coverage exclusion. The
blanket src/components/**/*.tsx exclude is expanded into an explicit
per-file list so remaining components can be lifted incrementally.

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

* test(tui): add ink-scroll-view passthrough mock for renderer tests (#1501)

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

* test(tui): add ink-form passthrough mock for modal renderer tests (#1501)

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

* test(tui): cover all Ink tab + modal components via renderer tests (#1501)

Add ink-testing-library tests for the 12 Ink components (InfoTab, AuthTab,
ResourcesTab, PromptsTab, ToolsTab, NotificationsTab, HistoryTab,
RequestsTab, and the Tool/Resource/Prompt test modals + DetailsModal),
mounting them through the ink-scroll-view / ink-form passthrough doubles
and driving keypresses via stdin. Modal components render position:absolute
(empty frame under the test renderer) so their tests assert on behavior —
injected InspectorClient fakes and onClose — while the passthrough
ScrollView still mounts the inner JSX for coverage.

Lift these 12 components from the interim React-surface exclusion in
vitest.config.ts; only App.tsx remains excluded. All files clear the
uniform 90/90/90/90 per-file gate.

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

* test(tui): add App.tsx renderer-test harness + foundation tests (#1501)

Mock the full @inspector/core surface (InspectorClient, the 7 managed-state
classes, the 8 react hooks, transport + auth) behind a controllable harness,
plus the ink-scroll-view/ink-form passthroughs, so App renders under
ink-testing-library and its keyboard state machine can be driven via stdin.
Concurrent ink mounts share raw-mode stdin, so each render is unmounted in
afterEach. Foundation covers server-list nav, tab accelerators, connect/
disconnect, OAuth-tab gating, and connected-status rendering (~50% baseline).

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

* test(tui): cover App.tsx via mocked-core renderer tests; lift final exclusion (#1501)

Extend App.test.tsx to 67 tests driving the keyboard state machine, tab
content, modals, OAuth flows, and connect/disconnect across the controllable
@inspector/core mock. App.tsx now clears the 90/90/90/90 per-file gate
(94.6/90.6/94.5/96.6).

Remove the last React-surface exclusion (src/App.tsx) from
clients/tui/vitest.config.ts. The whole clients/tui/src tree is now under
the uniform per-file coverage gate with no React-surface exclusions,
completing the interim-scope lift from #1484.

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

* test(tui): raise stdout max-listeners in App test to silence warning (#1501)

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

* test(tui): raise App.tsx branch coverage >90 and de-flake coverage runs (#1501)

Add targeted App.tsx tests for the OAuth handlers' non-Error throw arms
(quick onCallback, guided start/advance, run-to-completion) and a re-entrant
quick-auth guard, lifting App.tsx branch coverage 90.6% -> 91.48% for a
safer margin above the 90 gate.

Harden the App renderer tests against the heavier v8 coverage instrumentation,
where React+ink's multi-macrotask render scheduling races fixed ticks:
- press() now settles two ticks per key so focus/tab changes flush before the
  next key is routed (ink re-subscribes useInput on re-render);
- expectFrame()/waitUntil() poll for frame content and async flow state
  (callbackServer opts) instead of asserting after a single fixed tick;
- ResourcesTab's content-clear test polls for fetched content likewise.

Plain 'npm test' (the CI path) was already stable; this makes the local
coverage gate stable too (13/13 clean runs vs ~2/8 flaky before).

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

* test(tui): de-flake component renderer tests under slow CI (#1501)

CI flaked on AuthTab's 'renders quick auth results' under the plain test run:
its oauthFlowState is populated by a post-mount useEffect reading the
inspectorClient, and a single-macrotask tick can race that effect -> setState
-> re-render chain on a slow/loaded CI runner.

Make each component test file's tick() flush several macrotask cycles so such
chains settle deterministically before assertions (no test relies on precise
tick timing — no fake timers / debounce). App.test.tsx already polls via
expectFrame/waitUntil and passed CI, so it's unchanged.

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

* test(tui): address review — shared setupFile for max-listeners, consume-once ink-form global (#1501)

Review follow-ups on #1538 (both non-blocking cleanups):

- Hoist process.std{out,in}.setMaxListeners into a shared vitest setupFile
  (__tests__/setup.ts) wired via setupFiles, so every renderer test file
  inherits it and the MaxListenersExceededWarning is silenced across the
  whole suite — not just App.test.tsx. Remove the per-file call.
- Make the ink-form double consume (clear) __INK_FORM_SUBMIT_VALUE__ on
  submit, eliminating the latent cross-test coupling on the shared global
  regardless of how the modal test files are organized.

No production code changed; suite + coverage gate stay green (App.tsx
94.8/91.5/94.5/96.6), and the warning no longer prints.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 08:19:12 -04:00

275 lines
7.9 KiB
TypeScript

import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render } from "ink-testing-library";
import type { MessageEntry } from "@inspector/core/mcp/index.js";
// MUST mock ink-scroll-view: the real ScrollView renders a placeholder minimap
// in the non-TTY test env and never mounts its children. This passthrough
// renders children directly and stubs scrollBy/scrollTo/getViewportHeight.
vi.mock("ink-scroll-view", () => import("./helpers/inkScrollViewMock.js"));
import { HistoryTab } from "../src/components/HistoryTab.js";
// Ink processes stdin keypresses asynchronously — await this after stdin.write
// and after rerender() before asserting.
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));
};
// Real terminal escape sequences so ink parses them as arrow / page keys.
const ESC = String.fromCharCode(27);
const UP = `${ESC}[A`;
const DOWN = `${ESC}[B`;
const PAGE_UP = `${ESC}[5~`;
const PAGE_DOWN = `${ESC}[6~`;
const ts = new Date("2024-01-01T12:34:56Z");
const entry = (over: Partial<MessageEntry>): MessageEntry =>
({
id: "id",
timestamp: ts,
direction: "request",
message: { jsonrpc: "2.0", id: 1, method: "ping" },
...over,
}) as unknown as MessageEntry;
// One entry exercising each label / direction / detail branch.
const reqWithResponse = entry({
id: "m0",
direction: "request",
message: { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} },
response: { jsonrpc: "2.0", id: 1, result: { tools: [] } },
duration: 5,
});
const reqPending = entry({
id: "m1",
direction: "request",
message: { jsonrpc: "2.0", id: 2, method: "tools/call" },
});
const respResult = entry({
id: "m2",
direction: "response",
message: { jsonrpc: "2.0", id: 3, result: { ok: true } },
});
const respError = entry({
id: "m3",
direction: "response",
message: { jsonrpc: "2.0", id: 4, error: { code: -32601, message: "no" } },
});
const respPlain = entry({
id: "m4",
direction: "response",
message: { jsonrpc: "2.0", id: 5 },
});
const notification = entry({
id: "m5",
direction: "notification",
message: { jsonrpc: "2.0", method: "notifications/message" },
});
const unknownEntry = entry({
id: "m6",
direction: "notification",
message: { jsonrpc: "2.0" },
});
const allMessages: MessageEntry[] = [
reqWithResponse,
reqPending,
respResult,
respError,
respPlain,
notification,
unknownEntry,
];
describe("HistoryTab", () => {
it("renders the empty state when there are no messages", () => {
const onCountChange = vi.fn();
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={[]}
width={120}
height={30}
onCountChange={onCountChange}
/>,
);
const frame = lastFrame() ?? "";
expect(frame).toContain("Messages (0)");
expect(frame).toContain("No messages");
expect(frame).toContain("Select a message to view details");
expect(onCountChange).toHaveBeenCalledWith(0);
});
it("renders every list-label and direction-symbol variant", () => {
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={allMessages}
width={120}
height={40}
/>,
);
const frame = lastFrame() ?? "";
expect(frame).toContain("Messages (7)");
// request with response → "✓"; pending request → "..."
expect(frame).toContain("→ tools/list ✓");
expect(frame).toContain("→ tools/call ...");
// response labels
expect(frame).toContain("← Response (result)");
expect(frame).toContain("← Response (error: -32601)");
expect(frame).toContain("← Response");
// notification + unknown
expect(frame).toContain("• notifications/message");
expect(frame).toContain("• Unknown");
expect(frame).toContain("▶ ");
});
it("renders request details with a response section and duration", () => {
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={[reqWithResponse]}
width={120}
height={40}
/>,
);
const frame = lastFrame() ?? "";
expect(frame).toContain("Direction: request");
expect(frame).toContain("(5ms)");
expect(frame).toContain("Request:");
expect(frame).toContain("Response:");
});
it("renders the waiting-for-response placeholder for a pending request", () => {
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={[reqPending]}
width={120}
height={40}
/>,
);
const frame = lastFrame() ?? "";
expect(frame).toContain("Request:");
expect(frame).toContain("Waiting for response...");
});
it("renders response details with a Response label and Response header", () => {
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={[respResult]}
width={120}
height={40}
/>,
);
const frame = lastFrame() ?? "";
expect(frame).toContain("Direction: response");
expect(frame).toContain("Response:");
});
it("renders notification details with a Notification label", () => {
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={[notification]}
width={120}
height={40}
/>,
);
const frame = lastFrame() ?? "";
expect(frame).toContain("Direction: notification");
expect(frame).toContain("Notification:");
// header uses the notification method
expect(frame).toContain("notifications/message");
});
it("falls back to the Message header for a methodless notification", () => {
const { lastFrame } = render(
<HistoryTab
serverName="srv"
messages={[unknownEntry]}
width={120}
height={40}
/>,
);
expect(lastFrame() ?? "").toContain("Message");
});
it("moves selection with arrows and page keys when the list is focused", async () => {
const { lastFrame, stdin } = render(
<HistoryTab
serverName="srv"
messages={allMessages}
width={120}
height={12}
focusedPane="messages"
/>,
);
// up at top boundary: no movement
stdin.write(UP);
await tick();
// down to the next message
stdin.write(DOWN);
await tick();
expect(lastFrame() ?? "").toContain("Direction: request");
// pageDown jumps toward the end, pageUp back toward the start
stdin.write(PAGE_DOWN);
await tick();
stdin.write(PAGE_UP);
await tick();
// up to move back toward the top
stdin.write(UP);
await tick();
expect(lastFrame() ?? "").toContain("Messages (7)");
});
it("handles details-pane scrolling, footer, and zoom shortcut", async () => {
const onViewDetails = vi.fn();
const { lastFrame, stdin } = render(
<HistoryTab
serverName="srv"
messages={allMessages}
width={120}
height={40}
focusedPane="details"
onViewDetails={onViewDetails}
/>,
);
expect(lastFrame() ?? "").toContain("↑/↓ to scroll, + to zoom");
stdin.write(UP);
await tick();
stdin.write(DOWN);
await tick();
stdin.write(PAGE_UP);
await tick();
stdin.write(PAGE_DOWN);
await tick();
stdin.write("+");
await tick();
expect(onViewDetails).toHaveBeenCalledWith(allMessages[0]);
});
it("does not fire input handlers when a modal is open", async () => {
const onViewDetails = vi.fn();
const { stdin } = render(
<HistoryTab
serverName="srv"
messages={allMessages}
width={120}
height={40}
focusedPane="details"
onViewDetails={onViewDetails}
modalOpen={true}
/>,
);
stdin.write("+");
await tick();
expect(onViewDetails).not.toHaveBeenCalled();
});
});