@webmcp-agents/testing 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -2
- package/dist/chat-peer-CzVYDy7A.js +24 -0
- package/dist/chat.d.ts +193 -0
- package/dist/chat.js +409 -0
- package/dist/guard-9H8JcSkn.js +151 -0
- package/dist/ids-HmfSbtOs.js +29 -0
- package/dist/index-BYejUroK.d.ts +86 -0
- package/dist/index.d.ts +298 -0
- package/dist/index.js +338 -0
- package/dist/matchers-BwXSMeTG.d.ts +225 -0
- package/dist/matchers-CcMe-gCr.js +653 -0
- package/dist/matchers.d.ts +2 -0
- package/dist/matchers.js +1 -0
- package/dist/observe-spans-D8lEWEjY.js +28 -0
- package/dist/peer-mZEQ4Hla.js +30 -0
- package/dist/playwright.d.ts +38 -0
- package/dist/playwright.js +54 -0
- package/dist/record-runs-DjiNzXC_.js +36 -0
- package/dist/record-runs-DofdrRju.js +1 -0
- package/dist/run-record-8RdIf0RD.d.ts +65 -0
- package/dist/run-record-MOCfkhN0.js +196 -0
- package/dist/script-C3gmfClf.js +52 -0
- package/dist/script-CuyU-jLV.d.ts +71 -0
- package/dist/sentinel-D154AjQn.js +15 -0
- package/dist/server.d.ts +113 -0
- package/dist/server.js +266 -0
- package/dist/setup.d.ts +1 -0
- package/dist/setup.js +89 -0
- package/dist/telemetry-Ct63NJwU.js +130 -0
- package/dist/telemetry.d.ts +2 -0
- package/dist/telemetry.js +1 -0
- package/dist/vitest.d.ts +56 -0
- package/dist/vitest.js +164 -0
- package/dist/wait-DJ--Kfhb.js +29 -0
- package/package.json +133 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @webmcp-agents/testing: test WebMCP tools, confirmations, agents and privacy with Vitest.
|
|
3
|
+
*
|
|
4
|
+
* import { expect, test } from "@webmcp-agents/testing";
|
|
5
|
+
*
|
|
6
|
+
* test("adds to the cart", async ({ tools, events, mount }) => {
|
|
7
|
+
* mount(<WebAgentsProvider><Catalog /></WebAgentsProvider>);
|
|
8
|
+
* expect(await tools.call("add_to_cart_mug-01", { qty: 2 })).toBeToolResult(/2 × Field Mug/);
|
|
9
|
+
* expect(events).toHaveFilled("qty", "2");
|
|
10
|
+
* });
|
|
11
|
+
*
|
|
12
|
+
* Importing it registers the matchers. Config: `@webmcp-agents/testing/vitest`. Agents and the chat:
|
|
13
|
+
* `/chat`. The endpoint: `/server`. End to end: `/playwright`.
|
|
14
|
+
*/
|
|
15
|
+
import { r as NoHardcodedTextOptions, t as WebAgentsMatchers } from "./matchers-BwXSMeTG.js";
|
|
16
|
+
import { a as RunLog, c as isRunLog, i as RecordedFinish, o as RunLogOptions, r as RecordedCall, s as RunRecord, t as FinishReason } from "./run-record-8RdIf0RD.js";
|
|
17
|
+
import { n as MemoryExporter } from "./index-BYejUroK.js";
|
|
18
|
+
import { Mock, afterAll, afterEach, beforeAll, beforeEach, describe, expect, vi } from "vitest";
|
|
19
|
+
import { AgentEvent, JSONSchema, ModelContext, ModelContextToolInfo, ModelContextToolResult, WebTool } from "@webmcp-agents/core";
|
|
20
|
+
import { Redactor } from "@webmcp-agents/core/redact";
|
|
21
|
+
/**
|
|
22
|
+
* The person at the page, as trusted input. The agent cursor yields to the person and a confirmation goes on only for
|
|
23
|
+
* them: both look at `isTrusted`, which only real input (here, Playwright through `vitest/browser`) has.
|
|
24
|
+
*/
|
|
25
|
+
/** Where an action lands: an element, or something with an `element()` (a `vitest/browser` locator). */
|
|
26
|
+
type UserTarget = Element | {
|
|
27
|
+
element(): Element;
|
|
28
|
+
};
|
|
29
|
+
/** Trusted input in a browser-mode test. The `user` fixture is one. */
|
|
30
|
+
interface FakeUser {
|
|
31
|
+
/**
|
|
32
|
+
* Click the control a confirmation waits on: the element the cursor parked on (`[data-agent-active]`), or the button
|
|
33
|
+
* or link named `name`. Throws a sentence when nothing is waiting.
|
|
34
|
+
*/
|
|
35
|
+
confirm(name?: string): Promise<void>;
|
|
36
|
+
/** Move on: a trusted click away from every control (the top-left corner), which cancels a waiting confirmation. */
|
|
37
|
+
moveOn(): Promise<void>;
|
|
38
|
+
/** Scroll the page with the mouse wheel (default 200 px down). */
|
|
39
|
+
scroll(deltaY?: number): Promise<void>;
|
|
40
|
+
/** Click `target`. */
|
|
41
|
+
click(target: UserTarget): Promise<void>;
|
|
42
|
+
/** Type `text` into `target`, key by key (`{Enter}` presses Enter). */
|
|
43
|
+
type(target: UserTarget, text: string): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
/** Build a {@link FakeUser} on `vitest/browser`'s `userEvent`. Browser mode only. */
|
|
46
|
+
export declare function fakeUser(): Promise<FakeUser>;
|
|
47
|
+
/** Page helpers for browser-mode tests: markup in, text out. */
|
|
48
|
+
/** The class every {@link fixture} root carries, so cleanup finds them. */
|
|
49
|
+
export declare const FIXTURE_CLASS = "test-fixture";
|
|
50
|
+
/**
|
|
51
|
+
* Put `html` into the page and return its root (a `div.test-fixture` appended to `<body>`). `./setup` removes every
|
|
52
|
+
* fixture after each test; without it, call {@link cleanupFixtures}.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* const root = fixture('<form toolname="add_to_cart" tooldescription="Add mugs"><input name="qty"></form>');
|
|
56
|
+
*/
|
|
57
|
+
export declare function fixture(html: string): HTMLElement;
|
|
58
|
+
/** Remove every {@link fixture} root from the page. */
|
|
59
|
+
export declare function cleanupFixtures(): void;
|
|
60
|
+
/** True while the agent cursor is shown (`.agent-cursor.is-visible`). */
|
|
61
|
+
export declare const cursorVisible: () => boolean;
|
|
62
|
+
/**
|
|
63
|
+
* The shadow root of a library UI host (`[data-web-agents-ui="<name>"]`): `"devtools"` for the devtools panel.
|
|
64
|
+
* Throws a sentence when it is not mounted.
|
|
65
|
+
*/
|
|
66
|
+
export declare function uiRoot(name: string): ShadowRoot;
|
|
67
|
+
/** The first element under `root` matching `selector` whose text includes `text`, or null. */
|
|
68
|
+
export declare function byText<T extends Element = HTMLElement>(root: ParentNode, selector: string, text: string): T | null;
|
|
69
|
+
/** All the text under `node` (default `<body>`), open shadow roots included. */
|
|
70
|
+
export declare function deepText(node?: Node): string;
|
|
71
|
+
/** An `AgentEvent` of one type. */
|
|
72
|
+
type AgentEventOf<K extends AgentEvent["type"]> = Extract<AgentEvent, {
|
|
73
|
+
type: K;
|
|
74
|
+
}>;
|
|
75
|
+
/**
|
|
76
|
+
* Every `AgentEvent` the visual layer emitted since {@link recordEvents} started, in order. The event matchers
|
|
77
|
+
* (`toHaveStarted`, `toHaveFilled`, `toHaveParked`, `toHaveYielded`, `toHaveEventOrder`, `toContainSensitive`) read it.
|
|
78
|
+
*/
|
|
79
|
+
interface EventLog {
|
|
80
|
+
/** The events so far (the same array grows while recording). */
|
|
81
|
+
readonly events: AgentEvent[];
|
|
82
|
+
/** Their types, in order: `["start", "fill", "result"]`. */
|
|
83
|
+
types(): AgentEvent["type"][];
|
|
84
|
+
/** The events of one type. */
|
|
85
|
+
of<K extends AgentEvent["type"]>(type: K): AgentEventOf<K>[];
|
|
86
|
+
/** Forget what was recorded so far; keep recording. */
|
|
87
|
+
clear(): void;
|
|
88
|
+
/** Stop recording. Idempotent. The `events` fixture stops for you. */
|
|
89
|
+
stop(): void;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Record every agent event until `stop()`. The `events` fixture does this for you around each test.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* const log = recordEvents();
|
|
96
|
+
* await callTool("add_to_cart", { qty: 2 });
|
|
97
|
+
* expect(log).toHaveFilled("qty", "2");
|
|
98
|
+
* log.stop();
|
|
99
|
+
*/
|
|
100
|
+
export declare function recordEvents(): EventLog;
|
|
101
|
+
/** True for a log made by {@link recordEvents}. */
|
|
102
|
+
export declare const isEventLog: (value: unknown) => value is EventLog;
|
|
103
|
+
/** Options for {@link toolForm}. */
|
|
104
|
+
interface ToolFormOptions {
|
|
105
|
+
/** The fields' markup. Default one labelled number field, `qty` (min 1, value 1). */
|
|
106
|
+
fields?: string;
|
|
107
|
+
/** `tooldescription`. Default `"Add mugs to the cart"`. */
|
|
108
|
+
description?: string;
|
|
109
|
+
/** The submit button's text. Default `"Add to cart"`. */
|
|
110
|
+
submit?: string;
|
|
111
|
+
/** Submit as soon as the agent filled it (`toolautosubmit`). Default true; false parks on the submit button. */
|
|
112
|
+
autosubmit?: boolean;
|
|
113
|
+
/** What the form answers the agent: text, or a function of the form. Default `"ok"`. */
|
|
114
|
+
answer?: string | ((form: HTMLFormElement) => string);
|
|
115
|
+
/** Called on every submit, the agent's or the person's. */
|
|
116
|
+
onSubmit?: (form: HTMLFormElement) => void;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* A declarative tool form in a {@link fixture}, registered by the polyfill (or Chrome) as the tool `name`. Its submit
|
|
120
|
+
* never navigates; an agent's submit is answered with `answer`.
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* toolForm("add_to_cart", { autosubmit: false }); // parks on "Add to cart" until a trusted click
|
|
124
|
+
*/
|
|
125
|
+
export declare function toolForm(name: string, options?: ToolFormOptions): HTMLFormElement;
|
|
126
|
+
/** Options for {@link echoForm}. */
|
|
127
|
+
interface EchoFormOptions {
|
|
128
|
+
/** Submit as soon as the agent filled it. Default true. */
|
|
129
|
+
autosubmit?: boolean;
|
|
130
|
+
/** Put before the word in the answer. Default `"ok: "`. */
|
|
131
|
+
prefix?: string;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* A declarative tool form with one required field, `word`, that answers `prefix + word`. Handy for agent and chat
|
|
135
|
+
* tests that need a real page tool.
|
|
136
|
+
*/
|
|
137
|
+
export declare function echoForm(name: string, { autosubmit, prefix }?: EchoFormOptions): HTMLFormElement;
|
|
138
|
+
/**
|
|
139
|
+
* `base` with a number that is new on this page (`add_to_cart_3`). The WebMCP registry lives as long as the page, so
|
|
140
|
+
* tests that share a page and cannot clean up a tool give each one its own name. With `./setup` a test's tools are
|
|
141
|
+
* removed after it, so a fixed name is fine there too.
|
|
142
|
+
*/
|
|
143
|
+
export declare const uniqueName: (base: string) => string;
|
|
144
|
+
/**
|
|
145
|
+
* The page's `document.modelContext`, installing the polyfill where the browser has none. With `./setup` it is already
|
|
146
|
+
* installed; call this in a test file that set up its own page.
|
|
147
|
+
*/
|
|
148
|
+
export declare function modelContext(): ModelContext;
|
|
149
|
+
/** The text of a tool result (its text parts, joined with a space). A string is returned as is; null gives `""`. */
|
|
150
|
+
export declare const resultText: (res: unknown) => string;
|
|
151
|
+
/** The names of the tools registered on the page right now. */
|
|
152
|
+
export declare const toolNames: () => Promise<string[]>;
|
|
153
|
+
/** Count `toolchange` events from now on. `stop()` removes the listener. */
|
|
154
|
+
export declare function countToolChanges(): {
|
|
155
|
+
count: () => number;
|
|
156
|
+
stop: () => void;
|
|
157
|
+
};
|
|
158
|
+
/** Options for {@link callTool}. */
|
|
159
|
+
interface CallToolOptions {
|
|
160
|
+
/** Aborting it cancels the call; the promise then rejects with an AbortError. */
|
|
161
|
+
signal?: AbortSignal;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Call a tool the way an agent would and resolve to its MCP result (`{ content, isError?, structuredContent? }`); the
|
|
165
|
+
* tool matchers (`toBeToolResult`, `toBeToolError`, `toHaveStructuredContent`) read it. Never rejects for a tool's
|
|
166
|
+
* failure: that is an `isError` result, as the agent sees it.
|
|
167
|
+
*
|
|
168
|
+
* - `callTool("add_to_cart", input)`: through `document.modelContext` (browser): the cursor moves, confirmation applies.
|
|
169
|
+
* Resolves to null when the call navigated the page away.
|
|
170
|
+
* - `callTool(addToCart, input)` with a `defineWebTool` tool: through the page when it is registered there; otherwise
|
|
171
|
+
* (in Node, or before it is mounted) its `run` (schema, then `execute`) in-process, no page and no cursor.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* expect(await callTool(addToCart, { id: "mug-01", qty: 2 })).toBeToolResult(/2 × Field Mug/);
|
|
175
|
+
*/
|
|
176
|
+
export declare function callTool(tool: string | WebTool, input?: Record<string, unknown>, { signal }?: CallToolOptions): Promise<ModelContextToolResult | null>;
|
|
177
|
+
/** The tool definition {@link mockTool} registers, minus `execute`. */
|
|
178
|
+
interface MockToolDefinition {
|
|
179
|
+
/** Default `"Mock tool <name>."`. */
|
|
180
|
+
description?: string;
|
|
181
|
+
/** Default `{ type: "object", properties: {} }`: any input. */
|
|
182
|
+
inputSchema?: JSONSchema;
|
|
183
|
+
/** WebMCP annotations, e.g. `{ readOnlyHint: true }`. */
|
|
184
|
+
annotations?: ModelContextToolInfo["annotations"];
|
|
185
|
+
}
|
|
186
|
+
/** What a mocked tool's implementation gets and may return (a string, a value, or an MCP result). */
|
|
187
|
+
type MockToolImpl = (input: Record<string, unknown>, options: {
|
|
188
|
+
signal: AbortSignal;
|
|
189
|
+
}) => unknown;
|
|
190
|
+
/** A page tool backed by a `vi.fn`: every Vitest spy matcher and `mockResolvedValueOnce` work on it. */
|
|
191
|
+
type MockedTool = Mock<MockToolImpl> & {
|
|
192
|
+
/** The registered name. */
|
|
193
|
+
readonly toolName: string;
|
|
194
|
+
/** Take the tool off the page. Idempotent; `tools.mock` does it after the test. */
|
|
195
|
+
unregister(): void;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Register a page tool whose `execute` is a `vi.fn` (default: resolves `"ok"`). Returns the spy. Unregister it with
|
|
199
|
+
* `unregister()`, or use the `tools` fixture's `tools.mock`, which does it after the test.
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* const add = mockTool("add_to_cart", async ({ qty }) => `Added ${qty}`);
|
|
203
|
+
* await callTool("add_to_cart", { qty: 2 });
|
|
204
|
+
* expect(add).toHaveBeenCalledWith({ qty: 2 }, expect.anything());
|
|
205
|
+
*/
|
|
206
|
+
export declare function mockTool(name: string, impl?: MockToolImpl): MockedTool;
|
|
207
|
+
export declare function mockTool(name: string, definition: MockToolDefinition, impl?: MockToolImpl): MockedTool;
|
|
208
|
+
/** Waiting, without fixed sleeps where a condition can be checked. */
|
|
209
|
+
/** Options for {@link until}. */
|
|
210
|
+
interface UntilOptions {
|
|
211
|
+
/** Give up after this many ms. Default 3000. */
|
|
212
|
+
timeout?: number;
|
|
213
|
+
/** What is awaited, for the timeout message. Default `"condition"`. */
|
|
214
|
+
label?: string;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Resolve once `check` returns true (it may be async), polling every frame (every 16 ms in Node). Resolves to the ms
|
|
218
|
+
* it took. Rejects after `timeout` with `Timed out after <timeout> ms waiting for <label>`. The second argument is the
|
|
219
|
+
* timeout (ms), the label, or both as options.
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* await until(() => cursorVisible(), 2000, "the cursor");
|
|
223
|
+
* await until(async () => (await toolNames()).includes("add_to_cart"), { label: "add_to_cart to register" });
|
|
224
|
+
* await until(() => !!document.modelContext, "the polyfill");
|
|
225
|
+
*/
|
|
226
|
+
export declare function until(check: () => boolean | Promise<boolean>, timeoutOrOptions?: number | string | UntilOptions, label?: string): Promise<number>;
|
|
227
|
+
/** `setTimeout` as a promise. Prefer {@link until} when there is something to wait for. */
|
|
228
|
+
export declare const sleep: (ms: number) => Promise<void>;
|
|
229
|
+
/** What `mount` accepts: HTML, or a React element (`<WebAgentsProvider>…</WebAgentsProvider>`). */
|
|
230
|
+
type Mountable = string | {
|
|
231
|
+
type: unknown;
|
|
232
|
+
props: unknown;
|
|
233
|
+
};
|
|
234
|
+
/** Mounts `ui` into a fresh `div.test-fixture` and returns it. Removed (React roots unmounted) after the test. */
|
|
235
|
+
type Mount = (ui: Mountable) => HTMLElement;
|
|
236
|
+
/** The `spans` fixture: the spans in memory, `flush()` to wait for the ones still buffered, `stop()` to stop observing. */
|
|
237
|
+
interface SpansFixture extends MemoryExporter {
|
|
238
|
+
/** Send what `observeAgents` still buffers (spans are built when the first run starts) and resolve once they are here. */
|
|
239
|
+
flush(): Promise<void>;
|
|
240
|
+
/** Stop observing (the fixture does it after the test). */
|
|
241
|
+
stop(): void;
|
|
242
|
+
}
|
|
243
|
+
/** The `tools` fixture: the page's tools, as an agent reaches them. */
|
|
244
|
+
interface ToolsFixture {
|
|
245
|
+
/** `callTool`: the tool's MCP result (never rejects for the tool's own failure). */
|
|
246
|
+
call(tool: string | WebTool, input?: Record<string, unknown>, options?: CallToolOptions): Promise<ModelContextToolResult | null>;
|
|
247
|
+
/** The names of the tools registered right now, sorted. */
|
|
248
|
+
list(): Promise<string[]>;
|
|
249
|
+
/** `mockTool`, unregistered after the test. */
|
|
250
|
+
mock(name: string, impl?: MockToolImpl): MockedTool;
|
|
251
|
+
mock(name: string, definition: MockToolDefinition, impl?: MockToolImpl): MockedTool;
|
|
252
|
+
/** Resolve once the tool list has been quiet (no `toolchange`) for `quietMs` (default 150), e.g. after a navigation. */
|
|
253
|
+
settled(quietMs?: number): Promise<void>;
|
|
254
|
+
}
|
|
255
|
+
/** The fixtures the kit's `test` adds. */
|
|
256
|
+
interface WebAgentsFixtures {
|
|
257
|
+
/** The page's tools: `call`, `list`, `mock`, `settled`. Mocks are unregistered after the test. */
|
|
258
|
+
tools: ToolsFixture;
|
|
259
|
+
/** Every `AgentEvent` from the start of the test; recording stops after it. */
|
|
260
|
+
events: EventLog;
|
|
261
|
+
/** Trusted input: `confirm`, `moveOn`, `scroll`, `click`, `type`. Browser mode only. */
|
|
262
|
+
user: FakeUser;
|
|
263
|
+
/** Mount HTML or a React element; removed (React roots unmounted) after the test. Browser mode only. */
|
|
264
|
+
mount: Mount;
|
|
265
|
+
/** A fresh page redactor (`configureRedaction({})`), reset again after the test. */
|
|
266
|
+
redactor: Redactor;
|
|
267
|
+
/**
|
|
268
|
+
* Every `AgentRunEvent` of the test (the chat's, `useWebAgent`'s, `agent.invoke`'s, sub-agents'), redacted as a
|
|
269
|
+
* listener sees them by default; recording stops after the test. Needs `@webmcp-agents/chat`.
|
|
270
|
+
*/
|
|
271
|
+
runs: RunLog;
|
|
272
|
+
/**
|
|
273
|
+
* Every browser span of the test (`observeAgents` into a memory exporter, redacted as it would be exported), with
|
|
274
|
+
* `flush()` to wait for the buffered ones. Needs `@webmcp-agents/telemetry`.
|
|
275
|
+
*/
|
|
276
|
+
spans: SpansFixture;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Vitest's `test` with the kit's fixtures: `tools`, `events`, `user`, `mount`, `redactor`, `runs` and `spans`. Use it
|
|
280
|
+
* like `test`; destructure what the test needs.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* test("adds to the cart", async ({ tools, events, mount }) => {
|
|
284
|
+
* mount('<form toolname="add_to_cart" tooldescription="Add mugs" toolautosubmit><input name="qty"><button>Add</button></form>');
|
|
285
|
+
* expect(await tools.call("add_to_cart", { qty: "2" })).toBeToolResult();
|
|
286
|
+
* expect(events).toHaveFilled("qty", "2");
|
|
287
|
+
* });
|
|
288
|
+
*/
|
|
289
|
+
export declare const test: import("vitest").TestAPI<{
|
|
290
|
+
events: EventLog;
|
|
291
|
+
mount: Mount;
|
|
292
|
+
redactor: Redactor;
|
|
293
|
+
runs: RunLog;
|
|
294
|
+
spans: SpansFixture;
|
|
295
|
+
tools: ToolsFixture;
|
|
296
|
+
user: FakeUser;
|
|
297
|
+
}>;
|
|
298
|
+
export { type AgentEventOf, type CallToolOptions, type EchoFormOptions, type EventLog, type FakeUser, type FinishReason, type MockToolDefinition, type MockToolImpl, type MockedTool, type Mount, type Mountable, type NoHardcodedTextOptions, type RecordedCall, type RecordedFinish, type RunLog, type RunLogOptions, type RunRecord, type SpansFixture, type ToolFormOptions, type ToolsFixture, type UntilOptions, type UserTarget, type WebAgentsFixtures, type WebAgentsMatchers, afterAll, afterEach, beforeAll, beforeEach, describe, expect, isRunLog, vi };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import "./matchers-CcMe-gCr.js";
|
|
2
|
+
import { a as FIXTURE_CLASS, c as cursorVisible, d as uiRoot, l as deepText, n as deferCleanup, o as byText, s as cleanupFixtures, u as fixture } from "./guard-9H8JcSkn.js";
|
|
3
|
+
import { r as isRunLog, v as isEventLog, y as recordEvents } from "./run-record-MOCfkhN0.js";
|
|
4
|
+
import { n as until, t as sleep } from "./wait-DJ--Kfhb.js";
|
|
5
|
+
import { t as loadChat } from "./chat-peer-CzVYDy7A.js";
|
|
6
|
+
import { t as requirePeer } from "./peer-mZEQ4Hla.js";
|
|
7
|
+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test as test$1, vi, vi as vi$1 } from "vitest";
|
|
8
|
+
import { WebToolError, WebToolInputError, executeTool, toToolResult, toolError } from "@webmcp-agents/core";
|
|
9
|
+
import { installWebMCPPolyfill } from "@webmcp-agents/core/polyfill";
|
|
10
|
+
import { configureRedaction, getRedactor } from "@webmcp-agents/core/redact";
|
|
11
|
+
// src/fake-user.ts
|
|
12
|
+
const elementOf = (target) => target instanceof Element ? target : target.element();
|
|
13
|
+
/** The accessible name of a button or link, near enough: aria-label, else its text. */
|
|
14
|
+
const nameOf = (el) => (el.getAttribute("aria-label") ?? el.textContent ?? "").trim();
|
|
15
|
+
/** Build a {@link FakeUser} on `vitest/browser`'s `userEvent`. Browser mode only. */
|
|
16
|
+
async function fakeUser() {
|
|
17
|
+
let context;
|
|
18
|
+
try {
|
|
19
|
+
context = await import("vitest/browser");
|
|
20
|
+
} catch (err) {
|
|
21
|
+
throw new Error("The user fixture needs browser mode: name the file *.browser.test.* (webAgentsProject(\"browser\")).", { cause: err });
|
|
22
|
+
}
|
|
23
|
+
const { userEvent } = context;
|
|
24
|
+
return {
|
|
25
|
+
async confirm(name) {
|
|
26
|
+
const controls = [...document.querySelectorAll("button, a[href], [role=button], input[type=submit]")];
|
|
27
|
+
const el = name ? controls.find((c) => nameOf(c) === name) ?? controls.find((c) => nameOf(c).startsWith(name)) : document.querySelector("[data-agent-active]");
|
|
28
|
+
if (!el) throw new Error(name ? `user.confirm("${name}"): no button or link named "${name}" is on the page.` : "user.confirm(): no control is waiting for the person (nothing has [data-agent-active]).");
|
|
29
|
+
await userEvent.click(el);
|
|
30
|
+
},
|
|
31
|
+
async moveOn() {
|
|
32
|
+
const spot = document.createElement("div");
|
|
33
|
+
spot.setAttribute("aria-hidden", "true");
|
|
34
|
+
spot.style.cssText = "position:fixed;left:0;top:0;width:8px;height:8px;z-index:2147483647";
|
|
35
|
+
document.body.append(spot);
|
|
36
|
+
try {
|
|
37
|
+
await userEvent.click(spot);
|
|
38
|
+
} finally {
|
|
39
|
+
spot.remove();
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
async scroll(deltaY = 200) {
|
|
43
|
+
await userEvent.wheel(document.body, { delta: { y: deltaY } });
|
|
44
|
+
},
|
|
45
|
+
async click(target) {
|
|
46
|
+
await userEvent.click(elementOf(target));
|
|
47
|
+
},
|
|
48
|
+
async type(target, text) {
|
|
49
|
+
await userEvent.type(elementOf(target), text);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// src/helpers/forms.ts
|
|
54
|
+
/**
|
|
55
|
+
* A declarative tool form in a {@link fixture}, registered by the polyfill (or Chrome) as the tool `name`. Its submit
|
|
56
|
+
* never navigates; an agent's submit is answered with `answer`.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* toolForm("add_to_cart", { autosubmit: false }); // parks on "Add to cart" until a trusted click
|
|
60
|
+
*/
|
|
61
|
+
function toolForm(name, options = {}) {
|
|
62
|
+
const { fields = "<label>qty <input name=\"qty\" type=\"number\" min=\"1\" value=\"1\"></label>", description = "Add mugs to the cart", submit = "Add to cart", autosubmit = true, answer = "ok", onSubmit = () => {} } = options;
|
|
63
|
+
const form = fixture(`
|
|
64
|
+
<form toolname="${name}" tooldescription="${description}" ${autosubmit ? "toolautosubmit" : ""}>
|
|
65
|
+
${fields}
|
|
66
|
+
<button type="submit">${submit}</button>
|
|
67
|
+
</form>`).querySelector("form");
|
|
68
|
+
form.addEventListener("submit", (e) => {
|
|
69
|
+
e.preventDefault();
|
|
70
|
+
onSubmit(form);
|
|
71
|
+
const ev = e;
|
|
72
|
+
if (ev.agentInvoked) ev.respondWith?.(Promise.resolve(typeof answer === "function" ? answer(form) : answer));
|
|
73
|
+
});
|
|
74
|
+
return form;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A declarative tool form with one required field, `word`, that answers `prefix + word`. Handy for agent and chat
|
|
78
|
+
* tests that need a real page tool.
|
|
79
|
+
*/
|
|
80
|
+
function echoForm(name, { autosubmit = true, prefix = "ok: " } = {}) {
|
|
81
|
+
return toolForm(name, {
|
|
82
|
+
fields: "<input name=\"word\" required>",
|
|
83
|
+
description: "Echo a word back. Second sentence.",
|
|
84
|
+
submit: "Send it",
|
|
85
|
+
autosubmit,
|
|
86
|
+
answer: (form) => prefix + String(new FormData(form).get("word"))
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
// src/helpers/names.ts
|
|
90
|
+
let uid = 0;
|
|
91
|
+
/**
|
|
92
|
+
* `base` with a number that is new on this page (`add_to_cart_3`). The WebMCP registry lives as long as the page, so
|
|
93
|
+
* tests that share a page and cannot clean up a tool give each one its own name. With `./setup` a test's tools are
|
|
94
|
+
* removed after it, so a fixed name is fine there too.
|
|
95
|
+
*/
|
|
96
|
+
const uniqueName = (base) => `${base}_${++uid}`;
|
|
97
|
+
// src/helpers/tools.ts
|
|
98
|
+
/**
|
|
99
|
+
* The page's `document.modelContext`, installing the polyfill where the browser has none. With `./setup` it is already
|
|
100
|
+
* installed; call this in a test file that set up its own page.
|
|
101
|
+
*/
|
|
102
|
+
function modelContext() {
|
|
103
|
+
const mc = installWebMCPPolyfill();
|
|
104
|
+
if (!mc) throw new Error("modelContext() needs a page: run this test in browser mode (a *.browser.test file).");
|
|
105
|
+
return mc;
|
|
106
|
+
}
|
|
107
|
+
/** The text of a tool result (its text parts, joined with a space). A string is returned as is; null gives `""`. */
|
|
108
|
+
const resultText = (res) => typeof res === "string" ? res : (res?.content ?? []).map((c) => "text" in c && typeof c.text === "string" ? c.text : "").join(" ");
|
|
109
|
+
/** The names of the tools registered on the page right now. */
|
|
110
|
+
const toolNames = async () => (await modelContext().getTools()).map((t) => t.name);
|
|
111
|
+
/** Count `toolchange` events from now on. `stop()` removes the listener. */
|
|
112
|
+
function countToolChanges() {
|
|
113
|
+
let n = 0;
|
|
114
|
+
const onChange = () => {
|
|
115
|
+
n++;
|
|
116
|
+
};
|
|
117
|
+
const mc = modelContext();
|
|
118
|
+
mc.addEventListener("toolchange", onChange);
|
|
119
|
+
return {
|
|
120
|
+
count: () => n,
|
|
121
|
+
stop: () => mc.removeEventListener("toolchange", onChange)
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
const isWebTool = (value) => typeof value === "object" && value !== null && value.kind === "web-tool";
|
|
125
|
+
/** What a defined tool's run threw, as the result an agent would read. */
|
|
126
|
+
function failure(err) {
|
|
127
|
+
if (err instanceof WebToolInputError || err?.name === "WebToolInputError") return toolError("invalid_input", err.message);
|
|
128
|
+
if (err instanceof WebToolError || err?.name === "WebToolError") return toolError(err.code ?? "failed", err.message);
|
|
129
|
+
if (err?.name === "AbortError") throw err;
|
|
130
|
+
return toolError("failed", err instanceof Error ? err.message : String(err));
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Call a tool the way an agent would and resolve to its MCP result (`{ content, isError?, structuredContent? }`); the
|
|
134
|
+
* tool matchers (`toBeToolResult`, `toBeToolError`, `toHaveStructuredContent`) read it. Never rejects for a tool's
|
|
135
|
+
* failure: that is an `isError` result, as the agent sees it.
|
|
136
|
+
*
|
|
137
|
+
* - `callTool("add_to_cart", input)`: through `document.modelContext` (browser): the cursor moves, confirmation applies.
|
|
138
|
+
* Resolves to null when the call navigated the page away.
|
|
139
|
+
* - `callTool(addToCart, input)` with a `defineWebTool` tool: through the page when it is registered there; otherwise
|
|
140
|
+
* (in Node, or before it is mounted) its `run` (schema, then `execute`) in-process, no page and no cursor.
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* expect(await callTool(addToCart, { id: "mug-01", qty: 2 })).toBeToolResult(/2 × Field Mug/);
|
|
144
|
+
*/
|
|
145
|
+
async function callTool(tool, input = {}, { signal } = {}) {
|
|
146
|
+
if (typeof tool !== "string" && !isWebTool(tool)) throw new TypeError(`callTool() needs a tool name or a defineWebTool tool, got ${typeof tool === "object" ? JSON.stringify(tool) : String(tool)}.`);
|
|
147
|
+
const name = typeof tool === "string" ? tool : tool.id;
|
|
148
|
+
const mc = typeof document === "undefined" ? void 0 : document.modelContext;
|
|
149
|
+
const onPage = !!mc && (await mc.getTools()).some((t) => t.name === name);
|
|
150
|
+
if (typeof tool === "string" || onPage) {
|
|
151
|
+
if (!mc) throw new Error(`callTool("${name}") needs a page with WebMCP: run it in browser mode, or pass the defineWebTool tool to run it in Node.`);
|
|
152
|
+
return executeTool(name, input, { signal });
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const output = await tool.run(input, {
|
|
156
|
+
signal: signal ?? new AbortController().signal,
|
|
157
|
+
source: "test"
|
|
158
|
+
});
|
|
159
|
+
return toToolResult(output);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
return failure(err);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function mockTool(name, a, b) {
|
|
165
|
+
if (typeof name !== "string" || !name) throw new TypeError("mockTool() needs the tool's name first, e.g. mockTool(\"add_to_cart\", impl).");
|
|
166
|
+
const definition = typeof a === "function" ? {} : a ?? {};
|
|
167
|
+
const impl = (typeof a === "function" ? a : b) ?? (async () => "ok");
|
|
168
|
+
const spy = vi$1.fn(impl).mockName(name);
|
|
169
|
+
const controller = new AbortController();
|
|
170
|
+
modelContext().registerTool({
|
|
171
|
+
name,
|
|
172
|
+
description: definition.description ?? `Mock tool ${name}.`,
|
|
173
|
+
inputSchema: definition.inputSchema ?? {
|
|
174
|
+
type: "object",
|
|
175
|
+
properties: {}
|
|
176
|
+
},
|
|
177
|
+
...definition.annotations ? { annotations: definition.annotations } : {},
|
|
178
|
+
execute: async (input, options) => spy(input, options)
|
|
179
|
+
}, { signal: controller.signal });
|
|
180
|
+
return Object.assign(spy, {
|
|
181
|
+
toolName: name,
|
|
182
|
+
unregister: () => controller.abort()
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
// src/mount.ts
|
|
186
|
+
/** Mounting markup or React elements into the page, and taking them down again. */
|
|
187
|
+
const isReactElement = (ui) => typeof ui === "object" && ui !== null && typeof ui.$$typeof === "symbol";
|
|
188
|
+
/** A mount function and its teardown. React DOM is loaded up front (when installed), so `mount` stays synchronous. */
|
|
189
|
+
async function createMount() {
|
|
190
|
+
if (typeof document === "undefined") {
|
|
191
|
+
const unavailable = () => {
|
|
192
|
+
throw new Error("mount() needs a page: run this test in browser mode (a *.browser.test file).");
|
|
193
|
+
};
|
|
194
|
+
return {
|
|
195
|
+
mount: unavailable,
|
|
196
|
+
unmountAll: () => {}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
let react;
|
|
200
|
+
try {
|
|
201
|
+
const by = "mount(<JSX>)";
|
|
202
|
+
const [client, dom] = await Promise.all([requirePeer(() => import("react-dom/client"), {
|
|
203
|
+
peer: "react-dom",
|
|
204
|
+
by
|
|
205
|
+
}), requirePeer(() => import("react-dom"), {
|
|
206
|
+
peer: "react-dom",
|
|
207
|
+
by
|
|
208
|
+
})]);
|
|
209
|
+
react = {
|
|
210
|
+
client,
|
|
211
|
+
dom
|
|
212
|
+
};
|
|
213
|
+
} catch (err) {
|
|
214
|
+
react = err;
|
|
215
|
+
}
|
|
216
|
+
const roots = [];
|
|
217
|
+
const mount = (ui) => {
|
|
218
|
+
if (typeof ui === "string") return fixture(ui);
|
|
219
|
+
if (!isReactElement(ui)) throw new TypeError(`mount() takes an HTML string or a React element, got ${typeof ui}.`);
|
|
220
|
+
if (react instanceof Error) throw react;
|
|
221
|
+
const el = fixture("");
|
|
222
|
+
const root = react.client.createRoot(el);
|
|
223
|
+
const { dom } = react;
|
|
224
|
+
dom.flushSync(() => root.render(ui));
|
|
225
|
+
roots.push(root);
|
|
226
|
+
return el;
|
|
227
|
+
};
|
|
228
|
+
return {
|
|
229
|
+
mount,
|
|
230
|
+
unmountAll() {
|
|
231
|
+
for (const root of roots.splice(0).reverse()) root.unmount();
|
|
232
|
+
cleanupFixtures();
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
// src/test.ts
|
|
237
|
+
/**
|
|
238
|
+
* Register a teardown both with the guard (so `./setup` runs it before checking what the test left behind) and for
|
|
239
|
+
* the fixture's own end (without `./setup`). Each runs once.
|
|
240
|
+
*/
|
|
241
|
+
const once = (fn) => {
|
|
242
|
+
let done = false;
|
|
243
|
+
return () => {
|
|
244
|
+
if (done) return;
|
|
245
|
+
done = true;
|
|
246
|
+
return fn();
|
|
247
|
+
};
|
|
248
|
+
};
|
|
249
|
+
/**
|
|
250
|
+
* Vitest's `test` with the kit's fixtures: `tools`, `events`, `user`, `mount`, `redactor`, `runs` and `spans`. Use it
|
|
251
|
+
* like `test`; destructure what the test needs.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* test("adds to the cart", async ({ tools, events, mount }) => {
|
|
255
|
+
* mount('<form toolname="add_to_cart" tooldescription="Add mugs" toolautosubmit><input name="qty"><button>Add</button></form>');
|
|
256
|
+
* expect(await tools.call("add_to_cart", { qty: "2" })).toBeToolResult();
|
|
257
|
+
* expect(events).toHaveFilled("qty", "2");
|
|
258
|
+
* });
|
|
259
|
+
*/
|
|
260
|
+
const test = test$1.extend({
|
|
261
|
+
tools: async ({}, use) => {
|
|
262
|
+
const mocks = [];
|
|
263
|
+
const cleanup = once(() => {
|
|
264
|
+
for (const m of mocks.splice(0)) m.unregister();
|
|
265
|
+
});
|
|
266
|
+
deferCleanup(cleanup);
|
|
267
|
+
const mock = ((name, a, b) => {
|
|
268
|
+
const m = typeof a === "function" || a === void 0 ? mockTool(name, a) : mockTool(name, a, b);
|
|
269
|
+
mocks.push(m);
|
|
270
|
+
return m;
|
|
271
|
+
});
|
|
272
|
+
await use({
|
|
273
|
+
call: callTool,
|
|
274
|
+
list: async () => {
|
|
275
|
+
const mc = typeof document === "undefined" ? void 0 : document.modelContext;
|
|
276
|
+
return mc ? (await mc.getTools()).map((t) => t.name).sort() : [];
|
|
277
|
+
},
|
|
278
|
+
mock,
|
|
279
|
+
async settled(quietMs = 150) {
|
|
280
|
+
const mc = document.modelContext;
|
|
281
|
+
if (!mc) return;
|
|
282
|
+
let last = performance.now();
|
|
283
|
+
const onChange = () => {
|
|
284
|
+
last = performance.now();
|
|
285
|
+
};
|
|
286
|
+
mc.addEventListener("toolchange", onChange);
|
|
287
|
+
try {
|
|
288
|
+
while (performance.now() - last < quietMs) await sleep(Math.max(10, quietMs - (performance.now() - last)));
|
|
289
|
+
} finally {
|
|
290
|
+
mc.removeEventListener("toolchange", onChange);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
await cleanup();
|
|
295
|
+
},
|
|
296
|
+
events: async ({}, use) => {
|
|
297
|
+
const log = recordEvents();
|
|
298
|
+
await use(log);
|
|
299
|
+
log.stop();
|
|
300
|
+
},
|
|
301
|
+
user: async ({}, use) => {
|
|
302
|
+
await use(await fakeUser());
|
|
303
|
+
},
|
|
304
|
+
mount: async ({}, use) => {
|
|
305
|
+
const { mount, unmountAll } = await createMount();
|
|
306
|
+
const cleanup = once(unmountAll);
|
|
307
|
+
deferCleanup(cleanup);
|
|
308
|
+
await use(mount);
|
|
309
|
+
await cleanup();
|
|
310
|
+
},
|
|
311
|
+
redactor: async ({}, use) => {
|
|
312
|
+
configureRedaction({});
|
|
313
|
+
const reset = once(() => configureRedaction({}));
|
|
314
|
+
deferCleanup(reset);
|
|
315
|
+
await use(getRedactor());
|
|
316
|
+
await reset();
|
|
317
|
+
},
|
|
318
|
+
runs: async ({}, use) => {
|
|
319
|
+
const [{ recordRuns }] = await Promise.all([import("./record-runs-DofdrRju.js"), loadChat("The runs fixture")]);
|
|
320
|
+
const log = recordRuns();
|
|
321
|
+
const stop = once(() => log.stop());
|
|
322
|
+
deferCleanup(stop);
|
|
323
|
+
await use(log);
|
|
324
|
+
await stop();
|
|
325
|
+
},
|
|
326
|
+
spans: async ({}, use) => {
|
|
327
|
+
const { observeSpans } = await requirePeer(() => import("./observe-spans-D8lEWEjY.js"), {
|
|
328
|
+
peer: "@webmcp-agents/telemetry",
|
|
329
|
+
by: "The spans fixture"
|
|
330
|
+
});
|
|
331
|
+
const spans = observeSpans();
|
|
332
|
+
const stop = once(() => spans.stop());
|
|
333
|
+
deferCleanup(stop);
|
|
334
|
+
await use(spans);
|
|
335
|
+
await stop();
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
export { FIXTURE_CLASS, afterAll, afterEach, beforeAll, beforeEach, byText, callTool, cleanupFixtures, countToolChanges, cursorVisible, deepText, describe, echoForm, expect, fakeUser, fixture, isEventLog, isRunLog, mockTool, modelContext, recordEvents, resultText, sleep, test, toolForm, toolNames, uiRoot, uniqueName, until, vi };
|