@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 CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # @webmcp-agents/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test what you build with `@webmcp-agents/*`, with Vitest and nothing hand-written: a tool in Node, a tool on the page
4
+ with the cursor and a confirmation, an agent without a model, the `/api/chat` endpoint without a key, and where a secret
5
+ does or does not end up.
6
+
7
+ ```sh
8
+ pnpm add -D @webmcp-agents/testing vitest @vitest/browser-playwright
9
+ pnpm exec playwright install chromium
10
+ ```
11
+
12
+ ## Configure
13
+
14
+ ```ts
15
+ // vitest.config.ts
16
+ import { webAgentsProject } from "@webmcp-agents/testing/vitest";
17
+ import { defineConfig } from "vitest/config";
18
+
19
+ export default defineConfig({
20
+ test: { projects: [webAgentsProject("unit"), webAgentsProject("browser")] },
21
+ });
22
+ ```
23
+
24
+ `*.test.*` files run in Node. `*.browser.test.*` files run in Chromium with `@webmcp-agents/testing/setup`: the WebMCP
25
+ polyfill is installed, motion is reduced so the cursor snaps, ids are deterministic, and after each test what it
26
+ mounted is removed. A test that leaves a tool call running, or a tool registered, fails with the tool's name.
27
+
28
+ ## A tool on the page
29
+
30
+ ```tsx
31
+ import { expect, test } from "@webmcp-agents/testing";
32
+
33
+ test("waits for the person before placing the order", async ({ tools, events, user, mount }) => {
34
+ mount(<WebAgentsProvider><Checkout /></WebAgentsProvider>);
35
+ await expect.poll(() => tools.list()).toContain("place_order");
36
+
37
+ const call = tools.call("place_order");
38
+ await expect.poll(() => events).toHaveParked("place_order");
39
+ await user.confirm("Place order"); // a trusted click on the parked control
40
+ expect(await call).toBeToolResult();
41
+ });
42
+ ```
43
+
44
+ ## An agent, without a model
45
+
46
+ ```ts
47
+ import { mockAdapter, text, toolCall } from "@webmcp-agents/testing/chat";
48
+
49
+ const adapter = mockAdapter([toolCall("track_last_order"), toolCall("add_to_cart", { qty: 2 }), text("Done.")]);
50
+ const run = await shopper.invoke("Reorder my last purchase.", { adapter });
51
+
52
+ expect(run).toHaveCalledTools(["track_last_order", "add_to_cart"]);
53
+ expect(run).toHaveAnswered("Done.");
54
+ ```
55
+
56
+ A failing matcher says what happened, not just a diff:
57
+
58
+ ```
59
+ expect(received).toHaveCalledTools(["track_last_order","add_to_cart"])
60
+
61
+ Expected tools, in order: track_last_order → add_to_cart
62
+ Called: track_last_order → add_to_cart → place_order
63
+ ^ unexpected
64
+ place_order input: {"confirm":true}
65
+ ```
66
+
67
+ ## Entries
68
+
69
+ | Entry | Contents |
70
+ |---|---|
71
+ | `@webmcp-agents/testing` | `test` with the fixtures (`tools`, `events`, `user`, `mount`, `redactor`), `callTool`, `mockTool`, page helpers, `expect`, `vi` |
72
+ | `/vitest` | `webAgentsProject("unit" \| "browser", options?)` |
73
+ | `/setup`, `/matchers` | setup files: everything, or the matchers alone (a page that must stay without WebMCP) |
74
+ | `/chat` | `mockAdapter`, `text`, `toolCall`, `reasoning`, `fail`, `mockChatServer`, `renderChat` (with `sentinelMessages`) |
75
+ | `/server` | `mockModel`, `chatRequest`, `readChatStream`, `withSession` |
76
+ | `/playwright` | `openApp`, `runTool`, `listTools`, `parkedOn`, `confirm` |
77
+ | `/telemetry` | `memoryExporter` (browser and OpenTelemetry spans in one shape), `spanTree` |
78
+
79
+ Vitest 4 or later is the one required peer. `@webmcp-agents/chat`, `@webmcp-agents/telemetry`, `ai`, `react`, `react-dom`, `@playwright/test` and
80
+ `@vitest/browser-playwright` are optional: an entry that needs a missing one fails at import with a sentence naming it.
81
+
82
+ `renderChat` and `toHaveNoHardcodedText` check the chat (the sentinel-catalog check: no string of the chat bypasses its
83
+ messages catalog). The `runs` fixture records every run event of the test (`onAgentRun`), which the run matchers read
84
+ (it tells `"max-steps"` from `"stop"`); the `spans` fixture records every browser span (`observeAgents`), which
85
+ `toHaveSpan`, `toBeOneTrace` and `toContainSensitive` read.
86
+
87
+ Never import this package from runtime code: it is for tests (the repository's lint enforces it for its own packages).
88
+
89
+ Docs: [webmcp-agents.dev/docs/reference/testing](https://webmcp-agents.dev/docs/reference/testing).
@@ -0,0 +1,24 @@
1
+ import { t as requirePeer } from "./peer-mZEQ4Hla.js";
2
+ // src/chat/chat-peer.ts
3
+ let chat;
4
+ /**
5
+ * Load `@webmcp-agents/chat` (once). Rejects with one sentence naming the package when it is not installed.
6
+ *
7
+ * @param by Who needs it, for that sentence (`"@webmcp-agents/testing/chat"`, `"The runs fixture"`).
8
+ */
9
+ async function loadChat(by) {
10
+ chat ??= await requirePeer(() => import("@webmcp-agents/chat"), {
11
+ peer: "@webmcp-agents/chat",
12
+ by
13
+ });
14
+ return chat;
15
+ }
16
+ /**
17
+ * The chat module, for synchronous code that runs after {@link loadChat} resolved (the `./chat` entry awaits it at
18
+ * import, the `runs` fixture before it records).
19
+ */
20
+ function loadedChat() {
21
+ if (!chat) throw new Error("@webmcp-agents/chat is not loaded yet: import from @webmcp-agents/testing/chat, which loads it.");
22
+ return chat;
23
+ }
24
+ export { loadedChat as n, loadChat as t };
package/dist/chat.d.ts ADDED
@@ -0,0 +1,193 @@
1
+ import { a as StepUsage, c as reasoning, i as StepInput, l as text, n as StepCall, o as TextOptions, r as StepError, s as fail, t as Step, u as toolCall } from "./script-CuyU-jLV.js";
2
+ import { a as RunLog, n as RUN_RECORD, o as RunLogOptions, s as RunRecord } from "./run-record-8RdIf0RD.js";
3
+ import { Mock } from "vitest";
4
+ import { AgentAdapter, AgentChatProps, AgentMessage, AgentRunRequest, AgentStreamPart, ChatMessagesInput, RunRef, ToolDescriptor, WebAgent } from "@webmcp-agents/chat";
5
+ /** Where a scripted function is called from: which run of the adapter, which model step of it. */
6
+ interface MockTurn {
7
+ /** The adapter's run, from 1 (each `agent.invoke`, each chat message, each sub-agent run is one). */
8
+ run: number;
9
+ /** The model step within the run, from 1. */
10
+ step: number;
11
+ }
12
+ /**
13
+ * What a function script returns for a model step: a step (or steps merged into one), `undefined` when it has
14
+ * nothing more to say (the run fails with a sentence), or a whole stream of parts (the run is that stream: for
15
+ * behavior no step can express, e.g. waiting on `req.signal`).
16
+ */
17
+ type MockStepResult = StepInput | undefined | AsyncIterable<AgentStreamPart>;
18
+ /**
19
+ * The script: steps played in order across runs (a run takes steps until one has no tool calls), or a function
20
+ * called for every model step.
21
+ */
22
+ type MockScript = StepInput[] | ((req: AgentRunRequest, turn: MockTurn) => MockStepResult | Promise<MockStepResult>);
23
+ /** Options for {@link mockAdapter}. */
24
+ interface MockAdapterOptions {
25
+ /** The adapter's id. Default `"mock"`. */
26
+ id?: string;
27
+ /** Its label in the adapter switcher. Default `"Mock"`. */
28
+ label?: string;
29
+ /**
30
+ * Report each step's token usage on its `step-finish` part, as the cloud adapter does when the server sends it: the
31
+ * step's `usage`, or `{ inputTokens: 10, outputTokens: 5 }`. `false` reports none, like an on-device adapter.
32
+ * Default true.
33
+ */
34
+ usage?: boolean;
35
+ /** The model id each `step-finish` reports (with `usage`). Default `"mock/model"`. */
36
+ model?: string;
37
+ }
38
+ /** A request as the adapter received it: the messages copied at that moment, the tools as they were offered. */
39
+ interface MockRequest {
40
+ messages: AgentMessage[];
41
+ tools: ToolDescriptor[];
42
+ agent?: WebAgent;
43
+ signal: AbortSignal;
44
+ /** The run's ids (`conversation`, `run`, `parent` for a sub-agent's run), as the cloud adapter would send them. */
45
+ ref?: RunRef;
46
+ }
47
+ /** A model-free `AgentAdapter` that plays a script, and remembers what it was sent and what it did. */
48
+ type MockAdapter = AgentAdapter & {
49
+ /** `run`, as a spy. */
50
+ run: Mock<(req: AgentRunRequest) => AsyncIterable<AgentStreamPart>>;
51
+ /** Every request, in order (sub-agent runs included). */
52
+ readonly requests: MockRequest[];
53
+ /** The signal of the last run. */
54
+ readonly lastSignal: AbortSignal | undefined;
55
+ /** Every tool call it made, every run, in order. */
56
+ readonly calls: RunRecord["calls"];
57
+ /** What it remembers for the matchers. */
58
+ readonly [RUN_RECORD]: RunRecord;
59
+ };
60
+ /**
61
+ * An adapter that runs a script instead of a model: no network, no key. It owns the loop like a real adapter: a tool
62
+ * call step runs the call on the page (`req.callTool`, cursor and all), then the next step follows; a step without
63
+ * calls answers and ends the run. The run matchers (`toHaveCalledTools`, `toHaveAnswered`, `toHaveFinishedWith`,
64
+ * `toHaveBeenOfferedTools`) read it.
65
+ *
66
+ * @example
67
+ * const adapter = mockAdapter([toolCall("track_last_order"), toolCall("add_to_cart", { qty: 2 }), text("Done.")]);
68
+ * const run = await shopper.invoke("Reorder my last purchase.", { adapter });
69
+ * expect(run).toHaveCalledTools(["track_last_order", "add_to_cart"]);
70
+ * @example
71
+ * mockAdapter([fail("rate_limited")]); // the run fails with that code
72
+ * mockAdapter((req) => (req.tools.some((t) => t.name === "place_order") ? toolCall("place_order") : text("Nothing to order.")));
73
+ */
74
+ export declare function mockAdapter(script: MockScript, options?: MockAdapterOptions): MockAdapter;
75
+ /** Options for {@link mockChatServer}. */
76
+ interface MockChatServerOptions {
77
+ /** The model's steps, one per request (the last repeats). */
78
+ steps: StepInput[];
79
+ /** Require a chat session, as `createChatHandler({ session })`. Default false. */
80
+ session?: boolean;
81
+ /** Any other `createChatHandler` option (`agents`, `tools`, `maxSteps`, `beforeModel`…). */
82
+ handler?: Record<string, unknown>;
83
+ }
84
+ /** A request the server received. */
85
+ interface MockChatServerRequest {
86
+ method: string;
87
+ url: string;
88
+ headers: Record<string, string>;
89
+ /** The parsed JSON body (`messages`, `tools`, `agent`, `trace`…); undefined for a GET. */
90
+ body: Record<string, unknown> | undefined;
91
+ }
92
+ /** A canned answer for {@link MockChatServer.respondOnce}. */
93
+ interface CannedResponse {
94
+ status: number;
95
+ headers?: Record<string, string>;
96
+ /** JSON body. Default `{ error, message }` for the status (429 `rate_limited`, 401 `session_required`…). */
97
+ body?: unknown;
98
+ }
99
+ /** An in-memory `/api/chat`: the real handler on a scripted model, behind a `fetch` with a cookie jar. */
100
+ interface MockChatServer {
101
+ /** Give it to `createCloudAdapter({ fetch })`. */
102
+ fetch: typeof fetch;
103
+ /** Every request, in order. */
104
+ readonly requests: MockChatServerRequest[];
105
+ /** Answer the next request with `response` instead of the handler (once; queued in order). */
106
+ respondOnce(response: CannedResponse | Response): void;
107
+ }
108
+ /**
109
+ * A fake `/api/chat` for the real cloud adapter: the real `createChatHandler` on `mockModel(steps)`, reached
110
+ * through `fetch` in memory. It records every request and keeps the session cookie like a browser. Needs
111
+ * `@webmcp-agents/chat` and `ai`, loaded on the first request.
112
+ *
113
+ * @example
114
+ * const server = mockChatServer({ steps: [toolCall("add_to_cart", { qty: 1 }), text("Added.")], session: true });
115
+ * const cloud = createCloudAdapter({ fetch: server.fetch });
116
+ * server.respondOnce({ status: 429, headers: { "retry-after": "30" } });
117
+ */
118
+ export declare function mockChatServer(options: MockChatServerOptions): MockChatServer;
119
+ /**
120
+ * Record every `AgentRunEvent` (the chat's, `useWebAgent`'s, `agent.invoke`'s, sub-agents' included) until `stop()`.
121
+ * The `runs` fixture does this for you around each test. Inputs and outputs are recorded redacted, as an analytics
122
+ * listener sees them; `{ raw: true }` records them as they are.
123
+ *
124
+ * @example
125
+ * const log = recordRuns();
126
+ * await shopper.invoke("Reorder my last purchase.", { adapter });
127
+ * expect(log).toHaveCalledTools(["track_last_order", "add_to_cart"]);
128
+ * expect(log.types()).toContain("step-finish");
129
+ * log.stop();
130
+ */
131
+ export declare function recordRuns(options?: RunLogOptions): RunLog;
132
+ /**
133
+ * Sentinel markers: a catalog whose every entry is `⟦its.path⟧`, so a render's text can be checked for anything that
134
+ * did not come from the catalog. Shared by `renderChat` (which builds the catalog) and `toHaveNoHardcodedText` (which
135
+ * reads the page); no import of the chat, so the matchers entry stays free of it.
136
+ */
137
+ /** One marker: `⟦composer.send⟧`. Global, for `replace`. */
138
+ export declare const SENTINEL: RegExp;
139
+ /** Options for {@link renderChat}. */
140
+ interface RenderChatOptions {
141
+ /** The adapter the chat runs (a `mockAdapter`). Default: one that answers nothing and is always ready. */
142
+ adapter?: AgentAdapter;
143
+ /** `<AgentChat>`'s other props (`messages`, `locale`, `theme`, `components`…). `defaultOpen` and `storageKey: false` are set. */
144
+ props?: Partial<AgentChatProps>;
145
+ /**
146
+ * Render with the sentinel catalog: every entry of `en` becomes `⟦its.path⟧`, so any other letter on screen is a
147
+ * string that bypassed the catalog (`toHaveNoHardcodedText`). Laid under `props.messages` when both are given.
148
+ * Default false.
149
+ */
150
+ sentinel?: boolean;
151
+ /** Wrap the chat (a `<WebAgentsProvider>`, an error boundary). Receives the chat as `children`. */
152
+ wrapper?: (props: {
153
+ children: unknown;
154
+ }) => unknown;
155
+ /** How long to wait for the chat to mount (ms). Default 2000. */
156
+ timeout?: number;
157
+ }
158
+ /** A rendered chat. Unmounted after the test (or call `unmount`). */
159
+ interface RenderedChat {
160
+ /** The chat's root (`[data-wa-part="root"]`, the body-level host): what `toHaveNoHardcodedText` reads. */
161
+ readonly host: HTMLElement;
162
+ /** The panel (`[data-wa-part="panel"]`). */
163
+ readonly panel: HTMLElement;
164
+ /** The first element of part `name` (`[data-wa-part="<name>"]`), or null. */
165
+ part(name: string): HTMLElement | null;
166
+ /** Every element of part `name`. */
167
+ parts(name: string): HTMLElement[];
168
+ /** Render again with other props (merged over the first ones). */
169
+ rerender(props: Partial<AgentChatProps>): Promise<void>;
170
+ /** Take the chat down now (it is taken down after the test anyway). */
171
+ unmount(): void;
172
+ /** The catalog it was rendered with when `sentinel` was set. */
173
+ readonly messages?: ChatMessagesInput;
174
+ }
175
+ /**
176
+ * The sentinel catalog: every leaf of the English catalog replaced by `⟦its.path⟧` (functions included), so a render
177
+ * shows only markers where the chat's own words go.
178
+ *
179
+ * @example
180
+ * sentinelMessages().composer.send; // "⟦composer.send⟧"
181
+ */
182
+ export declare function sentinelMessages(): ChatMessagesInput;
183
+ /**
184
+ * Render `<AgentChat>` open for a test, with a mock adapter, and give back its host and parts. Needs a page (browser
185
+ * mode) and React DOM. With `sentinel: true` every string the chat owns is a `⟦marker⟧`: pair it with
186
+ * `toHaveNoHardcodedText`.
187
+ *
188
+ * @example
189
+ * const chat = await renderChat({ adapter: mockAdapter([text("Hi.")]), sentinel: true });
190
+ * await expect(chat).toHaveNoHardcodedText({ allow: ["Hi."] });
191
+ */
192
+ export declare function renderChat(options?: RenderChatOptions): Promise<RenderedChat>;
193
+ export { type CannedResponse, type MockAdapter, type MockAdapterOptions, type MockChatServer, type MockChatServerOptions, type MockChatServerRequest, type MockRequest, type MockScript, type MockStepResult, type MockTurn, type RenderChatOptions, type RenderedChat, type Step, type StepCall, type StepError, type StepInput, type StepUsage, type TextOptions, fail, reasoning, text, toolCall };