@webmcp-agents/testing 0.0.0-stage → 0.5.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/chat.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import { n as loadedChat, t as loadChat } from "./chat-peer-CzVYDy7A.js";
|
|
2
|
+
import { a as toStep, i as text, n as fail, o as toolCall, r as reasoning, t as chunksOf } from "./script-C3gmfClf.js";
|
|
3
|
+
import { n as nextId } from "./ids-HmfSbtOs.js";
|
|
4
|
+
import { n as RUN_RECORD } from "./run-record-MOCfkhN0.js";
|
|
5
|
+
import { t as requirePeer } from "./peer-mZEQ4Hla.js";
|
|
6
|
+
import { t as recordRuns } from "./record-runs-DjiNzXC_.js";
|
|
7
|
+
import { n as until } from "./wait-DJ--Kfhb.js";
|
|
8
|
+
import { n as sentinelOf, t as SENTINEL } from "./sentinel-D154AjQn.js";
|
|
9
|
+
import { onTestFinished, vi } from "vitest";
|
|
10
|
+
// src/chat/mock-adapter.ts
|
|
11
|
+
const abortable = (ms, signal) => new Promise((resolve) => {
|
|
12
|
+
if (!ms || signal.aborted) return resolve();
|
|
13
|
+
const timer = setTimeout(resolve, ms);
|
|
14
|
+
signal.addEventListener("abort", () => {
|
|
15
|
+
clearTimeout(timer);
|
|
16
|
+
resolve();
|
|
17
|
+
}, { once: true });
|
|
18
|
+
});
|
|
19
|
+
const isStream = (value) => typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
20
|
+
const copy = (value) => {
|
|
21
|
+
try {
|
|
22
|
+
return structuredClone(value);
|
|
23
|
+
} catch {
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* An adapter that runs a script instead of a model: no network, no key. It owns the loop like a real adapter: a tool
|
|
29
|
+
* call step runs the call on the page (`req.callTool`, cursor and all), then the next step follows; a step without
|
|
30
|
+
* calls answers and ends the run. The run matchers (`toHaveCalledTools`, `toHaveAnswered`, `toHaveFinishedWith`,
|
|
31
|
+
* `toHaveBeenOfferedTools`) read it.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* const adapter = mockAdapter([toolCall("track_last_order"), toolCall("add_to_cart", { qty: 2 }), text("Done.")]);
|
|
35
|
+
* const run = await shopper.invoke("Reorder my last purchase.", { adapter });
|
|
36
|
+
* expect(run).toHaveCalledTools(["track_last_order", "add_to_cart"]);
|
|
37
|
+
* @example
|
|
38
|
+
* mockAdapter([fail("rate_limited")]); // the run fails with that code
|
|
39
|
+
* mockAdapter((req) => (req.tools.some((t) => t.name === "place_order") ? toolCall("place_order") : text("Nothing to order.")));
|
|
40
|
+
*/
|
|
41
|
+
function mockAdapter(script, options = {}) {
|
|
42
|
+
if (!Array.isArray(script) && typeof script !== "function") throw new TypeError("mockAdapter() takes a list of steps (text(), toolCall(), fail()…) or a function that returns one per model step.");
|
|
43
|
+
const record = {
|
|
44
|
+
calls: [],
|
|
45
|
+
answers: [],
|
|
46
|
+
finishes: [],
|
|
47
|
+
offered: [],
|
|
48
|
+
top: -1
|
|
49
|
+
};
|
|
50
|
+
const requests = [];
|
|
51
|
+
let cursor = 0;
|
|
52
|
+
let runs = 0;
|
|
53
|
+
let lastSignal;
|
|
54
|
+
const next = async (req, turn) => {
|
|
55
|
+
if (typeof script === "function") return script(req, turn);
|
|
56
|
+
return script[cursor++];
|
|
57
|
+
};
|
|
58
|
+
/** Record what flows through, whatever produced it. */
|
|
59
|
+
async function* observe(parts, run) {
|
|
60
|
+
for await (const part of parts) {
|
|
61
|
+
if (part.type === "tool-call") record.calls.push({
|
|
62
|
+
name: part.name,
|
|
63
|
+
input: part.input
|
|
64
|
+
});
|
|
65
|
+
if (part.type === "text-delta") record.answers[run - 1] = (record.answers[run - 1] ?? "") + part.delta;
|
|
66
|
+
if (part.type === "finish") record.finishes[run - 1] = { reason: part.reason };
|
|
67
|
+
if (part.type === "error") record.finishes[run - 1] = {
|
|
68
|
+
reason: "error",
|
|
69
|
+
error: part.error,
|
|
70
|
+
...part.code ? { code: part.code } : {}
|
|
71
|
+
};
|
|
72
|
+
yield part;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function* play(req, run) {
|
|
76
|
+
const finish = (f) => f.reason === "error" ? {
|
|
77
|
+
type: "error",
|
|
78
|
+
error: f.error ?? "Failed.",
|
|
79
|
+
...f.code ? { code: f.code } : {}
|
|
80
|
+
} : {
|
|
81
|
+
type: "finish",
|
|
82
|
+
reason: f.reason
|
|
83
|
+
};
|
|
84
|
+
const max = req.agent?.maxSteps ?? Number.POSITIVE_INFINITY;
|
|
85
|
+
for (let stepNo = 1;; stepNo++) {
|
|
86
|
+
const tools = req.tools;
|
|
87
|
+
record.offered.push(tools.map((t) => t.name));
|
|
88
|
+
const result = await next(req, {
|
|
89
|
+
run,
|
|
90
|
+
step: stepNo
|
|
91
|
+
});
|
|
92
|
+
if (isStream(result)) {
|
|
93
|
+
if (stepNo > 1) throw new TypeError("mockAdapter: a script function may return a stream of parts only for a run's first step.");
|
|
94
|
+
yield* result;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
yield {
|
|
98
|
+
type: "step-start",
|
|
99
|
+
step: stepNo
|
|
100
|
+
};
|
|
101
|
+
if (result === void 0) {
|
|
102
|
+
yield finish({
|
|
103
|
+
reason: "error",
|
|
104
|
+
error: `mockAdapter ran out of steps: it ${Array.isArray(script) ? `was scripted with ${script.length} step(s) and ` : ""}was asked for one more (run ${run}, step ${stepNo}). End a run with a step without tool calls, e.g. text("Done.").`
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const step = toStep(result);
|
|
109
|
+
if (step.error) {
|
|
110
|
+
yield finish({
|
|
111
|
+
reason: "error",
|
|
112
|
+
error: step.error.message ?? "Failed.",
|
|
113
|
+
...step.error.code ? { code: step.error.code } : {}
|
|
114
|
+
});
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const messageId = nextId("a");
|
|
118
|
+
yield {
|
|
119
|
+
type: "message-start",
|
|
120
|
+
messageId
|
|
121
|
+
};
|
|
122
|
+
const usage = options.usage === false ? void 0 : {
|
|
123
|
+
inputTokens: 10,
|
|
124
|
+
outputTokens: 5,
|
|
125
|
+
...step.usage
|
|
126
|
+
};
|
|
127
|
+
if (step.reasoning) yield {
|
|
128
|
+
type: "reasoning",
|
|
129
|
+
messageId,
|
|
130
|
+
text: step.reasoning.text,
|
|
131
|
+
...step.reasoning.signature ? { providerMetadata: { anthropic: { signature: step.reasoning.signature } } } : {}
|
|
132
|
+
};
|
|
133
|
+
for (const delta of step.text ? chunksOf(step.text, step.chunks) : []) {
|
|
134
|
+
await abortable(step.delayMs ?? 0, req.signal);
|
|
135
|
+
if (req.signal.aborted) break;
|
|
136
|
+
yield {
|
|
137
|
+
type: "text-delta",
|
|
138
|
+
messageId,
|
|
139
|
+
delta
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
const calls = req.signal.aborted ? [] : (step.calls ?? []).map((call) => ({
|
|
143
|
+
id: call.id ?? nextId("call"),
|
|
144
|
+
name: call.name,
|
|
145
|
+
input: call.input ?? {}
|
|
146
|
+
}));
|
|
147
|
+
for (const call of calls) yield {
|
|
148
|
+
type: "tool-call",
|
|
149
|
+
messageId,
|
|
150
|
+
...call
|
|
151
|
+
};
|
|
152
|
+
if (!req.signal.aborted) yield {
|
|
153
|
+
type: "step-finish",
|
|
154
|
+
step: stepNo,
|
|
155
|
+
...usage && {
|
|
156
|
+
usage,
|
|
157
|
+
model: options.model ?? "mock/model"
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
for (const call of calls) {
|
|
161
|
+
if (req.signal.aborted) break;
|
|
162
|
+
const output = await req.callTool(call);
|
|
163
|
+
yield {
|
|
164
|
+
type: "tool-result",
|
|
165
|
+
id: call.id,
|
|
166
|
+
output
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
if (req.signal.aborted) {
|
|
170
|
+
yield finish({ reason: "aborted" });
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (!calls.length) {
|
|
174
|
+
yield finish({ reason: "stop" });
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (stepNo >= max) {
|
|
178
|
+
yield finish({ reason: "max-steps" });
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const run = vi.fn((req) => {
|
|
184
|
+
const n = ++runs;
|
|
185
|
+
lastSignal = req.signal;
|
|
186
|
+
requests.push({
|
|
187
|
+
messages: copy(req.messages),
|
|
188
|
+
tools: [...req.tools],
|
|
189
|
+
...req.agent ? { agent: req.agent } : {},
|
|
190
|
+
signal: req.signal,
|
|
191
|
+
...req.ref ? { ref: { ...req.ref } } : {}
|
|
192
|
+
});
|
|
193
|
+
record.answers[n - 1] = void 0;
|
|
194
|
+
record.finishes[n - 1] = void 0;
|
|
195
|
+
if (!req.ref?.parent) record.top = n - 1;
|
|
196
|
+
return observe(play(req, n), n);
|
|
197
|
+
});
|
|
198
|
+
return {
|
|
199
|
+
id: options.id ?? "mock",
|
|
200
|
+
label: options.label ?? "Mock",
|
|
201
|
+
run,
|
|
202
|
+
requests,
|
|
203
|
+
get lastSignal() {
|
|
204
|
+
return lastSignal;
|
|
205
|
+
},
|
|
206
|
+
get calls() {
|
|
207
|
+
return record.calls;
|
|
208
|
+
},
|
|
209
|
+
[RUN_RECORD]: record
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
// src/chat/mock-chat-server.ts
|
|
213
|
+
const ERRORS = {
|
|
214
|
+
401: {
|
|
215
|
+
error: "session_required",
|
|
216
|
+
message: "No chat session: GET this endpoint first (the page does)."
|
|
217
|
+
},
|
|
218
|
+
403: {
|
|
219
|
+
error: "forbidden",
|
|
220
|
+
message: "Cross-site requests are not allowed."
|
|
221
|
+
},
|
|
222
|
+
429: {
|
|
223
|
+
error: "rate_limited",
|
|
224
|
+
message: "Too many requests: try again in a minute."
|
|
225
|
+
},
|
|
226
|
+
503: {
|
|
227
|
+
error: "chat_disabled",
|
|
228
|
+
message: "Chat is not configured on the server."
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const toResponse = (canned) => canned instanceof Response ? canned : new Response(JSON.stringify(canned.body ?? ERRORS[canned.status] ?? {
|
|
232
|
+
error: "error",
|
|
233
|
+
message: `Status ${canned.status}.`
|
|
234
|
+
}), {
|
|
235
|
+
status: canned.status,
|
|
236
|
+
headers: {
|
|
237
|
+
"content-type": "application/json",
|
|
238
|
+
...canned.headers
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
/**
|
|
242
|
+
* A fake `/api/chat` for the real cloud adapter: the real `createChatHandler` on `mockModel(steps)`, reached
|
|
243
|
+
* through `fetch` in memory. It records every request and keeps the session cookie like a browser. Needs
|
|
244
|
+
* `@webmcp-agents/chat` and `ai`, loaded on the first request.
|
|
245
|
+
*
|
|
246
|
+
* @example
|
|
247
|
+
* const server = mockChatServer({ steps: [toolCall("add_to_cart", { qty: 1 }), text("Added.")], session: true });
|
|
248
|
+
* const cloud = createCloudAdapter({ fetch: server.fetch });
|
|
249
|
+
* server.respondOnce({ status: 429, headers: { "retry-after": "30" } });
|
|
250
|
+
*/
|
|
251
|
+
function mockChatServer(options) {
|
|
252
|
+
if (!options || !Array.isArray(options.steps)) throw new TypeError("mockChatServer() needs { steps: [...] }, e.g. { steps: [text(\"Hi.\")] }.");
|
|
253
|
+
const requests = [];
|
|
254
|
+
const queue = [];
|
|
255
|
+
let cookie;
|
|
256
|
+
let handler;
|
|
257
|
+
const load = async () => {
|
|
258
|
+
const [{ createChatHandler }, { mockModel }] = await Promise.all([requirePeer(() => import("@webmcp-agents/chat/server"), {
|
|
259
|
+
peer: "@webmcp-agents/chat",
|
|
260
|
+
by: "mockChatServer()"
|
|
261
|
+
}), import("./server.js")]);
|
|
262
|
+
return createChatHandler({
|
|
263
|
+
...options.handler,
|
|
264
|
+
model: mockModel(options.steps),
|
|
265
|
+
session: options.session ?? false
|
|
266
|
+
});
|
|
267
|
+
};
|
|
268
|
+
const fakeFetch = (async (input, init) => {
|
|
269
|
+
const req = new Request(new URL(input instanceof Request ? input.url : String(input), "http://localhost"), input instanceof Request ? input : init);
|
|
270
|
+
const text = req.method === "GET" || req.method === "HEAD" ? "" : await req.clone().text();
|
|
271
|
+
let body;
|
|
272
|
+
try {
|
|
273
|
+
body = text ? JSON.parse(text) : void 0;
|
|
274
|
+
} catch {
|
|
275
|
+
body = { raw: text };
|
|
276
|
+
}
|
|
277
|
+
const headers = new Headers(req.headers);
|
|
278
|
+
if (cookie && !headers.has("cookie")) headers.set("cookie", cookie);
|
|
279
|
+
requests.push({
|
|
280
|
+
method: req.method,
|
|
281
|
+
url: req.url,
|
|
282
|
+
headers: Object.fromEntries(headers),
|
|
283
|
+
body
|
|
284
|
+
});
|
|
285
|
+
const canned = queue.shift();
|
|
286
|
+
if (canned) return toResponse(canned);
|
|
287
|
+
handler ??= load();
|
|
288
|
+
const res = await (await handler)(new Request(req, { headers }));
|
|
289
|
+
const set = res.headers.get("set-cookie");
|
|
290
|
+
if (set) cookie = set.split(";")[0];
|
|
291
|
+
return res;
|
|
292
|
+
});
|
|
293
|
+
return {
|
|
294
|
+
fetch: fakeFetch,
|
|
295
|
+
requests,
|
|
296
|
+
respondOnce(response) {
|
|
297
|
+
queue.push(response);
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
// src/chat/render-chat.ts
|
|
302
|
+
/** An adapter that is always ready and answers nothing: enough to render the idle chat. */
|
|
303
|
+
const silent = {
|
|
304
|
+
id: "silent",
|
|
305
|
+
label: "Silent",
|
|
306
|
+
async *run() {}
|
|
307
|
+
};
|
|
308
|
+
/**
|
|
309
|
+
* The sentinel catalog: every leaf of the English catalog replaced by `⟦its.path⟧` (functions included), so a render
|
|
310
|
+
* shows only markers where the chat's own words go.
|
|
311
|
+
*
|
|
312
|
+
* @example
|
|
313
|
+
* sentinelMessages().composer.send; // "⟦composer.send⟧"
|
|
314
|
+
*/
|
|
315
|
+
function sentinelMessages() {
|
|
316
|
+
return sentinelOf(loadedChat().en);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Render `<AgentChat>` open for a test, with a mock adapter, and give back its host and parts. Needs a page (browser
|
|
320
|
+
* mode) and React DOM. With `sentinel: true` every string the chat owns is a `⟦marker⟧`: pair it with
|
|
321
|
+
* `toHaveNoHardcodedText`.
|
|
322
|
+
*
|
|
323
|
+
* @example
|
|
324
|
+
* const chat = await renderChat({ adapter: mockAdapter([text("Hi.")]), sentinel: true });
|
|
325
|
+
* await expect(chat).toHaveNoHardcodedText({ allow: ["Hi."] });
|
|
326
|
+
*/
|
|
327
|
+
async function renderChat(options = {}) {
|
|
328
|
+
if (typeof document === "undefined") throw new Error("renderChat() needs a page: run this test in browser mode (a *.browser.test file).");
|
|
329
|
+
const by = "renderChat()";
|
|
330
|
+
const [{ createElement }, client, dom, chat] = await Promise.all([
|
|
331
|
+
requirePeer(() => import("react"), {
|
|
332
|
+
peer: "react",
|
|
333
|
+
by
|
|
334
|
+
}),
|
|
335
|
+
requirePeer(() => import("react-dom/client"), {
|
|
336
|
+
peer: "react-dom",
|
|
337
|
+
by
|
|
338
|
+
}),
|
|
339
|
+
requirePeer(() => import("react-dom"), {
|
|
340
|
+
peer: "react-dom",
|
|
341
|
+
by
|
|
342
|
+
}),
|
|
343
|
+
loadChat(by)
|
|
344
|
+
]);
|
|
345
|
+
const before = new Set(document.querySelectorAll("[data-web-agents-ui=\"chat\"]"));
|
|
346
|
+
const container = document.createElement("div");
|
|
347
|
+
document.body.append(container);
|
|
348
|
+
const root = client.createRoot(container);
|
|
349
|
+
const messages = options.sentinel ? sentinelMessages() : void 0;
|
|
350
|
+
let props = { ...options.props };
|
|
351
|
+
const element = () => {
|
|
352
|
+
const merged = {
|
|
353
|
+
adapter: options.adapter ?? silent,
|
|
354
|
+
defaultOpen: true,
|
|
355
|
+
storageKey: false,
|
|
356
|
+
...props,
|
|
357
|
+
...messages && { messages: chat.deepMerge(messages, props.messages ?? {}) }
|
|
358
|
+
};
|
|
359
|
+
const ui = createElement(chat.AgentChat, merged);
|
|
360
|
+
return options.wrapper ? createElement(options.wrapper, null, ui) : ui;
|
|
361
|
+
};
|
|
362
|
+
dom.flushSync(() => root.render(element()));
|
|
363
|
+
let mounted = true;
|
|
364
|
+
const unmount = () => {
|
|
365
|
+
if (!mounted) return;
|
|
366
|
+
mounted = false;
|
|
367
|
+
root.unmount();
|
|
368
|
+
container.remove();
|
|
369
|
+
};
|
|
370
|
+
try {
|
|
371
|
+
onTestFinished(unmount);
|
|
372
|
+
} catch {}
|
|
373
|
+
const find = () => [...document.querySelectorAll("[data-web-agents-ui=\"chat\"]")].find((el) => !before.has(el) && el.querySelector("[data-wa-part=\"panel\"]"));
|
|
374
|
+
await until(() => !!find(), options.timeout ?? 2e3).catch(() => {
|
|
375
|
+
unmount();
|
|
376
|
+
throw new Error(`renderChat(): the chat did not mount within ${options.timeout ?? 2e3} ms (no [data-wa-part="panel"] appeared).`);
|
|
377
|
+
});
|
|
378
|
+
const host = find();
|
|
379
|
+
return {
|
|
380
|
+
host,
|
|
381
|
+
get panel() {
|
|
382
|
+
return host.querySelector("[data-wa-part=\"panel\"]");
|
|
383
|
+
},
|
|
384
|
+
part: (name) => host.querySelector(`[data-wa-part="${CSS.escape(name)}"]`),
|
|
385
|
+
parts: (name) => [...host.querySelectorAll(`[data-wa-part="${CSS.escape(name)}"]`)],
|
|
386
|
+
async rerender(next) {
|
|
387
|
+
props = {
|
|
388
|
+
...props,
|
|
389
|
+
...next
|
|
390
|
+
};
|
|
391
|
+
dom.flushSync(() => root.render(element()));
|
|
392
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
393
|
+
},
|
|
394
|
+
unmount,
|
|
395
|
+
...messages && { messages }
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
// src/chat/index.ts
|
|
399
|
+
/**
|
|
400
|
+
* @webmcp-agents/testing/chat: test agents and the chat without a model.
|
|
401
|
+
*
|
|
402
|
+
* const adapter = mockAdapter([toolCall("track_last_order"), toolCall("add_to_cart", { qty: 2 }), text("Done.")]);
|
|
403
|
+
* const run = await shopper.invoke("Reorder my last purchase.", { adapter });
|
|
404
|
+
* expect(run).toHaveCalledTools(["track_last_order", "add_to_cart"]);
|
|
405
|
+
*
|
|
406
|
+
* Needs `@webmcp-agents/chat`: importing this entry without it fails with a sentence naming it.
|
|
407
|
+
*/
|
|
408
|
+
await loadChat("@webmcp-agents/testing/chat");
|
|
409
|
+
export { SENTINEL, fail, mockAdapter, mockChatServer, reasoning, recordRuns, renderChat, sentinelMessages, text, toolCall };
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { t as sleep } from "./wait-DJ--Kfhb.js";
|
|
2
|
+
// src/helpers/dom.ts
|
|
3
|
+
/** Page helpers for browser-mode tests: markup in, text out. */
|
|
4
|
+
/** The class every {@link fixture} root carries, so cleanup finds them. */
|
|
5
|
+
const FIXTURE_CLASS = "test-fixture";
|
|
6
|
+
/**
|
|
7
|
+
* Put `html` into the page and return its root (a `div.test-fixture` appended to `<body>`). `./setup` removes every
|
|
8
|
+
* fixture after each test; without it, call {@link cleanupFixtures}.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* const root = fixture('<form toolname="add_to_cart" tooldescription="Add mugs"><input name="qty"></form>');
|
|
12
|
+
*/
|
|
13
|
+
function fixture(html) {
|
|
14
|
+
if (typeof document === "undefined") throw new Error("fixture() needs a page: run this test in browser mode (a *.browser.test file).");
|
|
15
|
+
const root = document.createElement("div");
|
|
16
|
+
root.className = FIXTURE_CLASS;
|
|
17
|
+
root.innerHTML = html;
|
|
18
|
+
document.body.append(root);
|
|
19
|
+
return root;
|
|
20
|
+
}
|
|
21
|
+
/** Remove every {@link fixture} root from the page. */
|
|
22
|
+
function cleanupFixtures() {
|
|
23
|
+
if (typeof document === "undefined") return;
|
|
24
|
+
for (const el of document.querySelectorAll(`.${FIXTURE_CLASS}`)) el.remove();
|
|
25
|
+
}
|
|
26
|
+
/** True while the agent cursor is shown (`.agent-cursor.is-visible`). */
|
|
27
|
+
const cursorVisible = () => typeof document !== "undefined" && !!document.querySelector(".agent-cursor.is-visible");
|
|
28
|
+
/**
|
|
29
|
+
* The shadow root of a library UI host (`[data-web-agents-ui="<name>"]`): `"devtools"` for the devtools panel.
|
|
30
|
+
* Throws a sentence when it is not mounted.
|
|
31
|
+
*/
|
|
32
|
+
function uiRoot(name) {
|
|
33
|
+
const root = document.querySelector(`[data-web-agents-ui="${name}"]`)?.shadowRoot;
|
|
34
|
+
if (!root) throw new Error(`No [data-web-agents-ui="${name}"] host with an open shadow root is mounted.`);
|
|
35
|
+
return root;
|
|
36
|
+
}
|
|
37
|
+
/** The first element under `root` matching `selector` whose text includes `text`, or null. */
|
|
38
|
+
function byText(root, selector, text) {
|
|
39
|
+
return [...root.querySelectorAll(selector)].find((el) => el.textContent?.includes(text)) ?? null;
|
|
40
|
+
}
|
|
41
|
+
/** All the text under `node` (default `<body>`), open shadow roots included. */
|
|
42
|
+
function deepText(node = document.body) {
|
|
43
|
+
let text = "";
|
|
44
|
+
const walk = (n) => {
|
|
45
|
+
if (n.nodeType === Node.TEXT_NODE) text += n.textContent;
|
|
46
|
+
if (n instanceof Element && n.shadowRoot) walk(n.shadowRoot);
|
|
47
|
+
for (const child of n.childNodes) walk(child);
|
|
48
|
+
};
|
|
49
|
+
walk(node);
|
|
50
|
+
return text;
|
|
51
|
+
}
|
|
52
|
+
// src/guard.ts
|
|
53
|
+
/**
|
|
54
|
+
* What `./setup` checks after each test: no tool call it started is still running, and no tool it registered is still
|
|
55
|
+
* registered. Either fails the test with the tool's name, then is cleaned up so the next test starts from a clean page.
|
|
56
|
+
*
|
|
57
|
+
* Calls are tracked by wrapping `document.modelContext.executeTool` (every agent path goes through it: `callTool`,
|
|
58
|
+
* `tool.invoke`, the chat, the devtools). Registrations are compared by name: what is registered after the test
|
|
59
|
+
* minus what was registered before it (tools a `beforeAll` registered are the file's, not the test's).
|
|
60
|
+
*/
|
|
61
|
+
const WRAPPED = Symbol.for("web-agents.testing.guarded");
|
|
62
|
+
let epoch = 0;
|
|
63
|
+
const running = /* @__PURE__ */ new Set();
|
|
64
|
+
let before = /* @__PURE__ */ new Set();
|
|
65
|
+
const cleanups = [];
|
|
66
|
+
/** How long `end` lets a call that is about to answer finish, and a deferred release happen. */
|
|
67
|
+
const SETTLE_MS = {
|
|
68
|
+
calls: 1e3,
|
|
69
|
+
tools: 2e3
|
|
70
|
+
};
|
|
71
|
+
/** Wrap `mc.executeTool` once, so every call is tracked and can be cancelled. */
|
|
72
|
+
function guardModelContext(mc) {
|
|
73
|
+
const target = mc;
|
|
74
|
+
if (target[WRAPPED]) return;
|
|
75
|
+
const original = mc.executeTool.bind(mc);
|
|
76
|
+
target[WRAPPED] = true;
|
|
77
|
+
target.executeTool = (tool, args, options = {}) => {
|
|
78
|
+
const name = typeof tool === "string" ? tool : tool.name;
|
|
79
|
+
const controller = new AbortController();
|
|
80
|
+
const outer = options.signal;
|
|
81
|
+
if (outer?.aborted) controller.abort(outer.reason);
|
|
82
|
+
else outer?.addEventListener("abort", () => controller.abort(outer.reason), { once: true });
|
|
83
|
+
const call = {
|
|
84
|
+
name,
|
|
85
|
+
args: typeof args === "string" ? safeParse(args) : args,
|
|
86
|
+
epoch,
|
|
87
|
+
controller
|
|
88
|
+
};
|
|
89
|
+
running.add(call);
|
|
90
|
+
return original(tool, args, {
|
|
91
|
+
...options,
|
|
92
|
+
signal: controller.signal
|
|
93
|
+
}).finally(() => running.delete(call));
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const safeParse = (text) => {
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(text);
|
|
99
|
+
} catch {
|
|
100
|
+
return text;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
/** Run `fn` when the test ends, before the checks (the kit's fixtures register their teardown here). */
|
|
104
|
+
function deferCleanup(fn) {
|
|
105
|
+
cleanups.push(fn);
|
|
106
|
+
}
|
|
107
|
+
const registered = async () => new Set(typeof document === "undefined" || !document.modelContext ? [] : (await document.modelContext.getTools()).map((t) => t.name));
|
|
108
|
+
/** A new test starts: remember what is registered now. */
|
|
109
|
+
async function beginTest() {
|
|
110
|
+
epoch++;
|
|
111
|
+
before = await registered();
|
|
112
|
+
}
|
|
113
|
+
const preview = (value) => {
|
|
114
|
+
try {
|
|
115
|
+
const text = JSON.stringify(value);
|
|
116
|
+
return text === void 0 ? String(value) : text.length > 120 ? `${text.slice(0, 117)}...` : text;
|
|
117
|
+
} catch {
|
|
118
|
+
return String(value);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* The test ended: run the deferred cleanups, wait briefly for calls and releases under way, then report (and clean
|
|
123
|
+
* up) what is left. Resolves to the problems, in words; empty when the test left nothing behind.
|
|
124
|
+
*/
|
|
125
|
+
async function endTest(extraCleanup = () => {}) {
|
|
126
|
+
const problems = [];
|
|
127
|
+
for (const fn of cleanups.splice(0).reverse()) try {
|
|
128
|
+
await fn();
|
|
129
|
+
} catch (err) {
|
|
130
|
+
problems.push(`Cleaning up after the test failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
131
|
+
}
|
|
132
|
+
await extraCleanup();
|
|
133
|
+
const mine = () => [...running].filter((c) => c.epoch === epoch);
|
|
134
|
+
for (let waited = 0; mine().length && waited < SETTLE_MS.calls; waited += 25) await sleep(25);
|
|
135
|
+
for (const call of mine()) {
|
|
136
|
+
problems.push(`The test ended while a call to the tool "${call.name}" was still running (input ${preview(call.args)}). Await the call, or cancel it with an AbortSignal, before the test ends.`);
|
|
137
|
+
call.controller.abort(new DOMException("The test ended.", "AbortError"));
|
|
138
|
+
}
|
|
139
|
+
const left = async () => [...await registered()].filter((n) => !before.has(n));
|
|
140
|
+
let names = await left();
|
|
141
|
+
for (let waited = 0; names.length && waited < SETTLE_MS.tools; waited += 50) {
|
|
142
|
+
await sleep(50);
|
|
143
|
+
names = await left();
|
|
144
|
+
}
|
|
145
|
+
for (const name of names) {
|
|
146
|
+
problems.push(`The test left the tool "${name}" registered. Unregister it before the test ends (abort the signal passed to registerTool, unmount the component, remove the form), or register it with tools.mock(), which cleans up after the test.`);
|
|
147
|
+
document.modelContext?.unregisterTool?.(name);
|
|
148
|
+
}
|
|
149
|
+
return problems;
|
|
150
|
+
}
|
|
151
|
+
export { FIXTURE_CLASS as a, cursorVisible as c, uiRoot as d, guardModelContext as i, deepText as l, deferCleanup as n, byText as o, endTest as r, cleanupFixtures as s, beginTest as t, fixture as u };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// src/ids.ts
|
|
2
|
+
/**
|
|
3
|
+
* Deterministic ids. The chat (`newId` in @webmcp-agents/chat) reads an id source from a `globalThis` slot when one is
|
|
4
|
+
* installed; `./setup` installs one and resets it before every test, so the same test makes the same message, call
|
|
5
|
+
* and run ids every time (`u-1`, `a-1`, `call-1`…).
|
|
6
|
+
*/
|
|
7
|
+
/** The slot the library reads. Shared through `Symbol.for`, so source and dist copies of a package agree. */
|
|
8
|
+
const ID_SLOT = Symbol.for("web-agents.ids");
|
|
9
|
+
let counts = /* @__PURE__ */ new Map();
|
|
10
|
+
/** The kit's id source: per prefix, `prefix-1`, `prefix-2`… */
|
|
11
|
+
const sequence = (prefix) => {
|
|
12
|
+
const n = (counts.get(prefix) ?? 0) + 1;
|
|
13
|
+
counts.set(prefix, n);
|
|
14
|
+
return `${prefix}-${n}`;
|
|
15
|
+
};
|
|
16
|
+
/** Install the sequence on `globalThis` (idempotent). */
|
|
17
|
+
function installIds() {
|
|
18
|
+
globalThis[ID_SLOT] = sequence;
|
|
19
|
+
}
|
|
20
|
+
/** Start every prefix over at 1. */
|
|
21
|
+
function resetIds() {
|
|
22
|
+
counts = /* @__PURE__ */ new Map();
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The next id for `prefix`: from the installed source when there is one (so the kit's mocks and the library share
|
|
26
|
+
* one sequence), else from the kit's own.
|
|
27
|
+
*/
|
|
28
|
+
const nextId = (prefix) => (globalThis[ID_SLOT] ?? sequence)(prefix);
|
|
29
|
+
export { nextId as n, resetIds as r, installIds as t };
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @webmcp-agents/testing/telemetry: spans in memory, for tests of `observeAgents` and of the chat handler's telemetry.
|
|
3
|
+
*
|
|
4
|
+
* const memory = memoryExporter();
|
|
5
|
+
* observeAgents({ exporters: [memory] }); // browser spans
|
|
6
|
+
* defineObservability({ exporters: [memory], env: {} }); // server spans: it is an OpenTelemetry SpanExporter too
|
|
7
|
+
* expect(memory).toHaveSpan("execute_tool add_to_cart");
|
|
8
|
+
*
|
|
9
|
+
* Nothing here imports `@webmcp-agents/telemetry` or `@opentelemetry/*`: the exporter is structural, so this entry
|
|
10
|
+
* loads without either.
|
|
11
|
+
*/
|
|
12
|
+
/** A finished span, the same shape whichever side recorded it. Times are ms since the epoch (0 when unknown). */
|
|
13
|
+
interface RecordedSpan {
|
|
14
|
+
name: string;
|
|
15
|
+
traceId: string;
|
|
16
|
+
spanId: string;
|
|
17
|
+
/** Absent for a root span. */
|
|
18
|
+
parentSpanId?: string;
|
|
19
|
+
attributes: Record<string, unknown>;
|
|
20
|
+
events: {
|
|
21
|
+
name: string;
|
|
22
|
+
attributes?: Record<string, unknown>;
|
|
23
|
+
}[];
|
|
24
|
+
/** `unset`, `ok` or `error`. */
|
|
25
|
+
status: "unset" | "ok" | "error";
|
|
26
|
+
startTime: number;
|
|
27
|
+
endTime: number;
|
|
28
|
+
/** The instrumentation scope's name (`@webmcp-agents/telemetry` for this library's spans). */
|
|
29
|
+
scope?: string;
|
|
30
|
+
}
|
|
31
|
+
/** The marker that tells a memory exporter from any other object (and from a plain array). */
|
|
32
|
+
declare const MEMORY_EXPORTER: unique symbol;
|
|
33
|
+
/**
|
|
34
|
+
* Spans in memory. It is both a browser span exporter (`observeAgents({ exporters: [memory] })`) and an OpenTelemetry
|
|
35
|
+
* `SpanExporter` (`defineObservability({ exporters: [memory] })`, or any SDK provider), so one test can collect both
|
|
36
|
+
* sides of a trace.
|
|
37
|
+
*/
|
|
38
|
+
interface MemoryExporter {
|
|
39
|
+
/** The finished spans, in the order they were exported. */
|
|
40
|
+
readonly spans: readonly RecordedSpan[];
|
|
41
|
+
/** Forget them. */
|
|
42
|
+
reset(): void;
|
|
43
|
+
/** Takes spans of either side: browser span records, or OpenTelemetry `ReadableSpan`s with the result callback. */
|
|
44
|
+
export(spans: readonly unknown[], resultCallback?: (result: {
|
|
45
|
+
code: number;
|
|
46
|
+
}) => void): void;
|
|
47
|
+
/** Nothing to send: resolves. */
|
|
48
|
+
forceFlush(): Promise<void>;
|
|
49
|
+
/** Nothing to release: resolves. */
|
|
50
|
+
shutdown(): Promise<void>;
|
|
51
|
+
readonly [MEMORY_EXPORTER]: true;
|
|
52
|
+
}
|
|
53
|
+
/** A span with its children, for readable assertions on a trace. */
|
|
54
|
+
interface SpanNode {
|
|
55
|
+
span: RecordedSpan;
|
|
56
|
+
children: SpanNode[];
|
|
57
|
+
}
|
|
58
|
+
/** One span of either side as a {@link RecordedSpan}, or undefined for anything else. */
|
|
59
|
+
declare function recordSpan(value: unknown): RecordedSpan | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* An exporter that keeps every span in memory, for tests.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* const memory = memoryExporter();
|
|
65
|
+
* const stop = observeAgents({ exporters: [memory], batchSize: 1 });
|
|
66
|
+
* await runTurn();
|
|
67
|
+
* await stop.flush();
|
|
68
|
+
* expect(memory).toBeOneTrace();
|
|
69
|
+
*/
|
|
70
|
+
declare function memoryExporter(): MemoryExporter;
|
|
71
|
+
/** True for a {@link memoryExporter}. */
|
|
72
|
+
declare const isMemoryExporter: (value: unknown) => value is MemoryExporter;
|
|
73
|
+
/**
|
|
74
|
+
* Spans from a memory exporter, an array (span records, `ReadableSpan`s or recorded spans), an OpenTelemetry
|
|
75
|
+
* `InMemorySpanExporter` (`getFinishedSpans()`), or span trees. Anything else: undefined.
|
|
76
|
+
*/
|
|
77
|
+
declare function readSpans(value: unknown): RecordedSpan[] | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* The spans as trees: each root (a span whose parent is not among them) with its children, both in start order.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* const [run] = spanTree(memory.spans);
|
|
83
|
+
* expect(run.children.map((c) => c.span.name)).toEqual(["chat claude-sonnet-5-5", "execute_tool add_to_cart", "chat claude-sonnet-5-5"]);
|
|
84
|
+
*/
|
|
85
|
+
declare function spanTree(spans: readonly RecordedSpan[]): SpanNode[];
|
|
86
|
+
export { isMemoryExporter as a, recordSpan as c, SpanNode as i, spanTree as l, MemoryExporter as n, memoryExporter as o, RecordedSpan as r, readSpans as s, MEMORY_EXPORTER as t };
|