Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MilestoneEvents.test.ts

793 lines32.7 KB

1import { NodeHttpServer } from "@effect/platform-node";
2import { expect, it } from "@effect/vitest";
3import {
4 EnvironmentId,
5 type MilestoneEvent,
6 MilestoneId,
7 ProjectId,
8 ProviderInstanceId,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as ConfigProvider from "effect/ConfigProvider";
13import * as Mac from "effect/crypto/Mac";
14import * as SecureRandom from "effect/crypto/SecureRandom";
15import * as Base64 from "effect/encoding/Base64";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as Queue from "effect/Queue";
21import * as Stream from "effect/Stream";
22import * as TestClock from "effect/testing/TestClock";
23import {
24 HttpBody,
25 HttpClient,
26 HttpRouter,
27 HttpServer,
28 type HttpServerRequest,
29 HttpServerResponse,
30} from "effect/http";
31​
32import * as SessionStore from "../auth/SessionStore.ts";
33import * as McpHttpServer from "../mcp/McpHttpServer.ts";
34import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
35import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
36import * as McpWebhookTransport from "../mcp/McpWebhookTransport.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import * as MilestoneHub from "./MilestoneHub.ts";
39​
40const environmentId = EnvironmentId.make("environment-milestone-events-test");
41const clientToken = "clientTokenWithoutDots";
42const threadToken = "threadTokenWithoutDots";
43const hostToken = "hostTokenWithoutDots";
44const scopes: Record<string, McpInvocationContext.McpInvocationScope> = {
45 [clientToken]: {
46 environmentId,
47 requestNamespace: "client-session",
48 thread: undefined,
49 client: { sessionId: "client-session", label: "Bot", access: "read-only" },
50 capabilities: new Set(["orchestration"]),
51 issuedAt: 1,
52 },
53 [threadToken]: {
54 environmentId,
55 requestNamespace: "provider-session",
56 thread: {
57 threadId: ThreadId.make("thread-agent"),
58 providerSessionId: "provider-session",
59 providerInstanceId: ProviderInstanceId.make("codex"),
60 },
61 client: undefined,
62 capabilities: new Set(["orchestration"]),
63 issuedAt: 1,
64 },
65 // A script on the host: signed in as no outside client.
66 [hostToken]: {
67 environmentId,
68 requestNamespace: "host",
69 thread: undefined,
70 client: undefined,
71 capabilities: new Set(["orchestration"]),
72 issuedAt: 1,
73 },
74};
75​
76// The Standard Webhooks example secret: base64 of 24 bytes.
77const secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
78​
79/** The Standard Webhooks check a receiver runs: any `v1,` signature over id, timestamp and body. */
80const signedBy = Effect.fnUntraced(function* (
81 secretValue: string,
82 headers: Readonly<Record<string, string | undefined>>,
83 body: string,
84) {
85 const mac = yield* Mac.Mac;
86 const bytes = Base64.decode(secretValue.slice("whsec_".length));
87 if (bytes._tag === "Failure") return false;
88 const key = yield* Mac.key(Mac.hmacSha256, bytes.success);
89 const tag = yield* mac.sign(
90 key,
91 new TextEncoder().encode(`${headers["webhook-id"]}.${headers["webhook-timestamp"]}.${body}`),
92 );
93 return (headers["webhook-signature"] ?? "").split(" ").includes(`v1,${Base64.encode(tag)}`);
94}, Effect.orDie);
95​
96interface Delivery {
97 readonly headers: Readonly<Record<string, string | undefined>>;
98 readonly raw: string;
99 readonly body: Record<string, any>;
100 readonly reply: Deferred.Deferred<Answer>;
102​
103/** `open` sends the body and never ends it. */
104interface Answer {
105 readonly status: number;
106 readonly body?: string;
107 readonly open?: boolean;
109​
110const settled = (
111 id: string,
112 options: { readonly project?: string; readonly at?: string } = {},
113): MilestoneEvent => ({
114 id: MilestoneId.make(id),
115 type: "thread.run_settled",
116 occurredAt: options.at ?? "1970-01-01T00:00:00.000Z",
117 projectId: ProjectId.make(options.project ?? "project:a"),
118 threadId: ThreadId.make(`thread:${id}`),
119 parentThreadId: null,
120 actor: { type: "agent" },
121 isSubagentChild: false,
122 runId: RunId.make(`run:${id}`),
123 outcome: "completed",
124});
125​
126type JsonRpcResponse = {
127 readonly result?: Record<string, any>;
128 readonly error?: { readonly code: number; readonly data?: unknown };
129};
130​
131const serveWith = Effect.fnUntraced(function* (settings: { readonly workflowsEnabled: boolean }) {
132 const revoked = yield* Deferred.make<void>();
133 const deliveries = yield* Queue.unbounded<Delivery>();
134 const replies = new Set<Delivery["reply"]>();
135 // The webhook receiver: each POST waits for the test to answer it.
136 const receiver = HttpRouter.add(
137 "POST",
138 "/hook",
139 Effect.fnUntraced(function* (request: HttpServerRequest.HttpServerRequest) {
140 const raw = yield* request.text;
141 const reply = yield* Deferred.make<Answer>();
142 replies.add(reply);
143 yield* Queue.offer(deliveries, {
144 headers: request.headers,
145 raw,
146 body: JSON.parse(raw),
147 reply,
148 });
149 const answer = yield* Deferred.await(reply);
150 return answer.open === true
151 ? HttpServerResponse.stream(
152 Stream.make(new TextEncoder().encode(answer.body)).pipe(Stream.concat(Stream.never)),
153 { status: answer.status, contentType: "application/json" },
154 )
155 : HttpServerResponse.text(answer.body ?? "", { status: answer.status });
156 }, Effect.orDie),
157 );
158 yield* HttpRouter.serve(
159 Layer.merge(McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents), receiver).pipe(
160 Layer.provide(
161 ConfigProvider.layer(
162 ConfigProvider.fromEnv({
163 env: { [McpWebhookTransport.ALLOWED_HOSTS_ENV]: "127.0.0.1" },
164 }),
165 ),
166 ),
167 Layer.provide(ServerSettings.layerTest(settings)),
168 Layer.provide(
169 Layer.mock(SessionStore.SessionStore)({
170 cookieName: "t3-session",
171 legacyCookieName: undefined,
172 awaitInvalidation: (sessionId) =>
173 sessionId === "client-session" ? Deferred.await(revoked) : Effect.never,
174 }),
175 ),
176 Layer.provide(
177 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
178 resolve: (presented) =>
179 Effect.succeed(scopes[presented] as McpInvocationContext.McpThreadInvocationScope),
180 }),
181 ),
182 ),
183 { disableListenLog: true, disableLogger: true },
184 ).pipe(Layer.build);
185 const http = yield* HttpClient.HttpClient;
186 const post = (
187 method: string,
188 params: Record<string, unknown> = {},
189 options: { readonly token?: string; readonly name?: string | null; readonly id?: number } = {},
190 ) => {
191 const name = options.name === undefined ? params.name : options.name;
192 return http.post("/mcp", {
193 headers: {
194 accept: "application/json, text/event-stream",
195 authorization: `Bearer ${options.token ?? clientToken}`,
196 "mcp-method": method,
197 "mcp-protocol-version": "2026-07-28",
198 ...(typeof name === "string" ? { "mcp-name": name } : {}),
199 },
200 body: HttpBody.text(
201 JSON.stringify({
202 jsonrpc: "2.0",
203 id: options.id ?? 1,
204 method,
205 params: {
206 ...params,
207 _meta: {
208 "io.modelcontextprotocol/protocolVersion": "2026-07-28",
209 "io.modelcontextprotocol/clientCapabilities": {
210 extensions: { "io.modelcontextprotocol/events": {} },
211 },
212 "io.modelcontextprotocol/clientInfo": { name: "bot", version: "1.0.0" },
213 },
214 },
215 }),
216 "application/json",
217 ),
218 });
219 };
220 const call = (...args: Parameters<typeof post>) =>
221 post(...args).pipe(
222 Effect.flatMap((response) => response.json),
223 Effect.map((body) => body as JsonRpcResponse),
224 );
225 const poll = (args: Record<string, unknown>) =>
226 call("events/poll", { name: "thread.run_settled", ...args }).pipe(
227 Effect.map(({ result }) => ({
228 cursor: result!.cursor as string,
229 truncated: result!.truncated as boolean,
230 hasMore: result!.hasMore as boolean,
231 ids: (result!.events as ReadonlyArray<{ data: { id: string } }>).map(
232 (event) => event.data.id,
233 ),
234 })),
235 );
236 const stream = (args: Record<string, unknown>, id = 7) =>
237 post("events/stream", { name: "thread.run_settled", ...args }, { id }).pipe(
238 Effect.flatMap((response) =>
239 response.stream.pipe(
240 Stream.decodeText,
241 Stream.splitLines,
242 Stream.filter((line) => line.startsWith("data: ")),
243 Stream.map(
244 (line) =>
245 JSON.parse(line.slice("data: ".length)) as {
246 readonly method: string;
247 readonly params: Record<string, any>;
248 },
249 ),
250 Stream.toQueue({ capacity: "unbounded" }),
251 ),
252 ),
253 );
254 // Shutting the server down waits for open requests, so a test that stops early answers them.
255 yield* Effect.addFinalizer(() =>
256 Effect.forEach(replies, (reply) => Deferred.succeed(reply, { status: 503 }), { discard: true }),
257 );
258 const hookUrl = `${HttpServer.formatAddress((yield* HttpServer.HttpServer).address)}/hook`;
259 const answer = (delivery: Delivery, status: number, body?: string, open = false) =>
260 Deferred.succeed(delivery.reply, body === undefined ? { status } : { status, body, open });
261 const subscribeParams = (params: Record<string, unknown> = {}) => ({
262 name: "thread.run_settled",
263 delivery: { mode: "webhook", url: hookUrl, secret },
264 cursor: null,
265 ...params,
266 });
267 // Subscribes; a first subscription to the URL is verified, so this echoes the challenge.
268 const subscribe = Effect.fnUntraced(function* (params: Record<string, unknown> = {}) {
269 const pending = yield* Effect.forkChild(call("events/subscribe", subscribeParams(params)));
270 const verification = yield* Queue.take(deliveries);
271 expect(verification.body.type).toBe("verification");
272 expect(yield* signedBy(secret, verification.headers, verification.raw)).toBe(true);
273 yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge }));
274 return { verification, response: yield* Fiber.join(pending) };
275 });
276 return {
277 post,
278 call,
279 poll,
280 stream,
281 revoke: Deferred.succeed(revoked, undefined),
282 deliveries,
283 answer,
284 subscribeParams,
285 subscribe,
286 };
287});
288const serve = serveWith({ workflowsEnabled: true });
289​
290const layerTest = Layer.mergeAll(
291 MilestoneHub.layer,
292 NodeHttpServer.layerTest,
293 Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)),
294);
295​
296it.effect("advertises the extension and lists each milestone type to outside clients only", () =>
297 Effect.gen(function* () {
298 const { call } = yield* serve;
299 const discovered = yield* call("server/discover");
300 expect(discovered.result!.capabilities.extensions).toEqual({
301 "io.modelcontextprotocol/events": {},
302 });
303 // TODO(#41158): drop with the bridge for clients predating SEP-3415.
304 expect(discovered.result!.capabilities.events).toEqual({});
305​
306 const { events } = (yield* call("events/list")).result!;
307 expect(events).toHaveLength(12);
308 const settledType = events.find(
309 (event: { name: string }) => event.name === "thread.run_settled",
310 );
311 for (const event of events) {
312 expect(event.delivery).toEqual(["poll", "push", "webhook"]);
313 }
314 expect(Object.keys(settledType.inputSchema.properties)).toEqual([
315 "projectIds",
316 "threadIds",
317 "workflowRunIds",
318 "includeSubagentChildren",
319 ]);
320 expect(settledType.payloadSchema.properties.outcome).toBeDefined();
321 const workflowType = events.find(
322 (event: { name: string }) => event.name === "workflow.run_ended",
323 );
324 // A workflow run belongs to no project or thread, so it is picked by workflow and run.
325 expect(Object.keys(workflowType.inputSchema.properties)).toEqual([
326 "workflows",
327 "workflowRunIds",
328 "includeSubagentChildren",
329 ]);
330 expect((yield* call("events/list", {}, { token: threadToken })).result!.events).toEqual([]);
331 }).pipe(Effect.scoped, Effect.provide(layerTest)),
332);
333​
334it.effect("lists workflow event types only while Labs → Workflows is on", () =>
335 Effect.gen(function* () {
336 const { call } = yield* serveWith({ workflowsEnabled: false });
337 const { events } = (yield* call("events/list")).result!;
338 const names = (events as ReadonlyArray<{ name: string }>).map((event) => event.name);
339 expect(names).toHaveLength(6);
340 expect(names.some((name) => name.startsWith("workflow."))).toBe(false);
341 const poll = yield* call("events/poll", { name: "workflow.run_ended", cursor: null });
342 expect(poll.error).toBeDefined();
343 }).pipe(Effect.scoped, Effect.provide(layerTest)),
344);
345​
346it.effect("polls from now, then pages forward and says when a cursor fell behind", () =>
347 Effect.gen(function* () {
348 const hub = yield* MilestoneHub.MilestoneHub;
349 const { poll } = yield* serve;
350 yield* hub.publish(settled("before"));
351​
352 // A null cursor starts from now: nothing earlier is replayed.
353 const bootstrap = yield* poll({ cursor: null });
354 expect(bootstrap).toMatchObject({ ids: [], truncated: false, hasMore: false });
355​
356 yield* hub.publish(settled("a"));
357 yield* hub.publish(settled("b", { project: "project:b" }));
358 yield* hub.publish(settled("c"));
359 const first = yield* poll({
360 cursor: bootstrap.cursor,
361 arguments: { projectIds: ["project:a"] },
362 maxEvents: 1,
363 });
364 expect(first).toMatchObject({ ids: ["a"], hasMore: true, truncated: false });
365 const rest = yield* poll({ cursor: first.cursor, arguments: { projectIds: ["project:a"] } });
366 expect(rest).toMatchObject({ ids: ["c"], hasMore: false });
367 expect(yield* poll({ cursor: rest.cursor })).toMatchObject({ ids: [] });
368​
369 // A cursor from before a restart replays what is kept, and says some may be missing.
370 expect(yield* poll({ cursor: "previous-boot.3" })).toMatchObject({
371 ids: ["before", "a", "b", "c"],
372 truncated: true,
373 });
374 yield* TestClock.adjust("10 minutes");
375 yield* hub.publish(settled("fresh", { at: "1970-01-01T00:10:00.000Z" }));
376 expect(yield* poll({ cursor: bootstrap.cursor, maxAgeMs: 60_000 })).toMatchObject({
377 ids: ["fresh"],
378 truncated: true,
379 });
380 }).pipe(Effect.scoped, Effect.provide(layerTest)),
381);
382​
383it.effect("rejects a mismatched Mcp-Name, an unknown event and a bad webhook callback", () =>
384 Effect.gen(function* () {
385 const { post, call, deliveries, answer, subscribeParams } = yield* serve;
386 const params = { name: "thread.run_settled", cursor: null };
387 const missing = yield* post("events/poll", params, { name: null });
388 expect(missing.status).toBe(400);
389 expect(((yield* missing.json) as JsonRpcResponse).error?.code).toBe(-32020);
390 const mismatched = yield* post("events/poll", params, { name: "thread.needs_input" });
391 expect(mismatched.status).toBe(400);
392 // TODO(#41158): drop with the bridge for clients predating SEP-3415. Subscribing needs no Mcp-Name,
393 // but one that is sent must match.
394 const wrongName = yield* post("events/subscribe", subscribeParams(), {
395 name: "thread.needs_input",
396 });
397 expect(((yield* wrongName.json) as JsonRpcResponse).error?.code).toBe(-32020);
398 // Arguments are checked before the endpoint hears anything.
399 const badArguments = yield* call(
400 "events/subscribe",
401 subscribeParams({ arguments: { projectIds: "project:a" } }),
402 ).pipe(Effect.forkChild);
403 expect(
404 yield* Effect.raceFirst(
405 Effect.map(Fiber.join(badArguments), (response) => ({ answered: response.error })),
406 Effect.map(Queue.take(deliveries), (delivery) => ({ posted: delivery.body })),
407 ),
408 ).toMatchObject({ answered: { code: -32602 } });
409 const unnamed = yield* post("events/subscribe", subscribeParams(), { name: null }).pipe(
410 Effect.flatMap((response) => response.json),
411 Effect.forkChild,
412 );
413 const verification = yield* Queue.take(deliveries);
414 yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge }));
415 expect(((yield* Fiber.join(unnamed)) as JsonRpcResponse).result?.id).toMatch(/^sub_/);
416​
417 expect((yield* call("events/poll", { name: "nope", cursor: null })).error).toMatchObject({
418 code: -32023,
419 data: { kind: "event" },
420 });
421​
422 const subscribe = (delivery: Record<string, unknown>, token = clientToken) =>
423 call("events/subscribe", { name: "thread.run_settled", delivery }, { token }).pipe(
424 Effect.map((response) => response.error),
425 );
426 const valid = { mode: "webhook", url: "https://example.com/hook", secret };
427 // Webhooks need an outside client's sign-in; threads cannot see events at all.
428 expect(yield* subscribe(valid, hostToken)).toMatchObject({ code: -32024 });
429 expect(yield* subscribe(valid, threadToken)).toMatchObject({ code: -32023 });
430 expect(yield* subscribe({ ...valid, secret: "whsec_c2hvcnQ=" })).toMatchObject({
431 code: -32602,
432 });
433 expect(yield* subscribe({ ...valid, secret: { toString: 1 } })).toMatchObject({
434 code: -32602,
435 });
436 // Plain http and private addresses are refused unless allowlisted.
437 expect(yield* subscribe({ ...valid, url: "http://example.com/hook" })).toMatchObject({
438 code: -32602,
439 });
440 expect(yield* subscribe({ ...valid, url: "https://10.0.0.1/hook" })).toMatchObject({
441 code: -32602,
442 });
443 expect(
444 (yield* call("events/unsubscribe", { name: "thread.run_settled", delivery: valid })).error,
445 ).toMatchObject({ code: -32023, data: { kind: "subscription" } });
446 }).pipe(Effect.scoped, Effect.provide(layerTest)),
447);
448​
449it.effect("streams live milestones after active, replays from a cursor and sends heartbeats", () =>
450 Effect.gen(function* () {
451 const hub = yield* MilestoneHub.MilestoneHub;
452 const { stream } = yield* serve;
453 yield* hub.publish(settled("a"));
454​
455 const live = yield* stream({ cursor: null, heartbeatMs: 5_000 }, 7);
456 const active = yield* Queue.take(live);
457 expect(active).toMatchObject({
458 method: "notifications/events/active",
459 params: { truncated: false, heartbeatMs: 5_000 },
460 });
461 expect(active.params._meta["io.modelcontextprotocol/subscriptionId"]).toBe(7);
462​
463 yield* hub.publish(settled("b", { project: "project:b" }));
464 const event = yield* Queue.take(live);
465 expect(event).toMatchObject({
466 method: "notifications/events/event",
467 params: {
468 eventId: expect.stringMatching(/^evt_[\w-]{22}$/),
469 name: "thread.run_settled",
470 data: { id: "b", projectId: "project:b" },
471 _meta: { "io.modelcontextprotocol/subscriptionId": 7 },
472 },
473 });
474​
475 // The heartbeat is due 5 seconds after the last message, however late the loop reads the clock.
476 yield* TestClock.adjust("5 seconds");
477 expect(yield* Queue.take(live)).toMatchObject({
478 method: "notifications/events/heartbeat",
479 params: { cursor: event.params.cursor },
480 });
481​
482 const replay = yield* stream({ cursor: "previous-boot.1" }, 8);
483 expect(yield* Queue.takeN(replay, 3)).toMatchObject([
484 { method: "notifications/events/active", params: { truncated: true } },
485 { method: "notifications/events/event", params: { data: { id: "a" } } },
486 { method: "notifications/events/event", params: { data: { id: "b" } } },
487 ]);
488 }).pipe(Effect.scoped, Effect.provide(layerTest)),
489);
490​
491it.effect("ends an open stream when the client's session is revoked", () =>
492 Effect.gen(function* () {
493 const { stream, revoke } = yield* serve;
494 const live = yield* stream({ cursor: null });
495 expect(yield* Queue.take(live)).toMatchObject({ method: "notifications/events/active" });
496​
497 yield* revoke;
498 // It says why, then closes.
499 expect(yield* Queue.take(live)).toMatchObject({
500 method: "notifications/events/terminated",
501 params: { error: { code: -32024 } },
502 });
503 while ((yield* Effect.exit(Queue.take(live)))._tag === "Success") {
504 // The request's own response follows the notice.
505 }
506 }).pipe(Effect.scoped, Effect.provide(layerTest)),
507);
508​
509it.effect("signs like the Standard Webhooks reference", () =>
510 Effect.gen(function* () {
511 expect(
512 yield* signedBy(
513 secret,
514 {
515 "webhook-id": "msg_p5jXN8AQM9LWM0D4loKWxJek",
516 "webhook-timestamp": "1614265330",
517 "webhook-signature": "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=",
518 },
519 '{"test": 2432232314}',
520 ),
521 ).toBe(true);
522 }).pipe(Effect.provide(layerTest)),
523);
524​
525it.effect("verifies a webhook endpoint and refuses one that does not echo the challenge", () =>
526 Effect.gen(function* () {
527 const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve;
528 const at = (url: string) =>
529 call(
530 "events/subscribe",
531 subscribeParams({ delivery: { mode: "webhook", url, secret } }),
532 ).pipe(Effect.forkChild);
533 const wrongUrl = `${subscribeParams().delivery.url}?wrong`;
534 const failing = yield* at(wrongUrl);
535 const wrong = yield* Queue.take(deliveries);
536 yield* answer(wrong, 200, JSON.stringify({ challenge: "not-it" }));
537 expect((yield* Fiber.join(failing)).error).toMatchObject({
538 code: -32027,
539 data: { reason: "challenge_failed" },
540 });
541 // A failure is remembered, so subscribing again answers without another POST.
542 const again = yield* at(wrongUrl);
543 const repeated = yield* Effect.raceFirst(
544 Effect.map(Fiber.join(again), (response) => ({ cached: response.error })),
545 Effect.map(Queue.take(deliveries), (delivery) => ({ posted: delivery.body })),
546 );
547 expect(repeated).toMatchObject({
548 cached: { code: -32027, data: { reason: "challenge_failed" } },
549 });
550​
551 // At most 8 KiB of the answer is read: exactly that passes, and one byte more fails at
552 // once, even from an endpoint that never ends its answer.
553 const echoOfLength = (challenge: string, length: number) => {
554 const bare = JSON.stringify({ challenge, padding: "" });
555 return JSON.stringify({ challenge, padding: "x".repeat(length - bare.length) });
556 };
557 const exact = yield* at(`${subscribeParams().delivery.url}?exact`);
558 const fits = yield* Queue.take(deliveries);
559 yield* answer(fits, 200, echoOfLength(fits.body.challenge, 8_192));
560 expect((yield* Fiber.join(exact)).error).toBeUndefined();
561 const long = yield* at(`${subscribeParams().delivery.url}?long`);
562 const padded = yield* Queue.take(deliveries);
563 yield* answer(padded, 200, echoOfLength(padded.body.challenge, 8_193), true);
564 expect((yield* Fiber.join(long)).error).toMatchObject({
565 code: -32027,
566 data: { reason: "challenge_failed" },
567 });
568​
569 const { verification, response } = yield* subscribe();
570 expect(verification.headers["webhook-id"]).toMatch(/^msg_verification_[\w-]+$/);
571 expect(verification.headers["x-mcp-subscription-id"]).toBe(response.result!.id);
572 expect(response.result).toMatchObject({
573 id: expect.stringMatching(/^sub_[0-9a-f]{32}$/),
574 truncated: false,
575 });
576 }).pipe(Effect.scoped, Effect.provide(layerTest)),
577);
578​
579it.effect("delivers one signed event at a time and advances the cursor once each resolves", () =>
580 Effect.gen(function* () {
581 const hub = yield* MilestoneHub.MilestoneHub;
582 const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve;
583 const { response } = yield* subscribe({ ttlMs: 600_000 });
584 const subscribed = response.result!;
585 const refresh = (params: Record<string, unknown> = {}) =>
586 call("events/subscribe", subscribeParams({ ttlMs: 600_000, ...params })).pipe(
587 Effect.map((refreshed) => refreshed.result!),
588 );
589​
590 yield* hub.publish(settled("a"));
591 yield* hub.publish(settled("b"));
592 const first = yield* Queue.take(deliveries);
593 expect(first.body).toMatchObject({ data: { id: "a" }, name: "thread.run_settled" });
594 // TODO(#41158): drop with the bridge for clients predating SEP-3415. An event's webhook-id is its eventId.
595 expect(first.body.eventId).toMatch(/^[A-Za-z0-9_-]+$/);
596 expect(first.headers["webhook-id"]).toBe(first.body.eventId);
597 expect(first.headers["x-mcp-subscription-id"]).toBe(subscribed.id);
598 expect(yield* signedBy(secret, first.headers, first.raw)).toBe(true);
599 yield* answer(first, 500);
600 // Unresolved, so the refresh still reports where the subscription started.
601 expect(yield* refresh()).toMatchObject({
602 id: subscribed.id,
603 cursor: subscribed.cursor,
604 deliveryStatus: { active: true, lastError: "http_5xx" },
605 });
606​
607 // "b" waits for "a": the next POST is its retry, which keeps its webhook-id with a fresh
608 // timestamp and signature.
609 yield* TestClock.adjust("30 seconds");
610 const retry = yield* Queue.take(deliveries);
611 expect(retry.body.data.id).toBe("a");
612 expect(retry.headers["webhook-id"]).toBe(first.headers["webhook-id"]);
613 expect(retry.headers["webhook-timestamp"]).not.toBe(first.headers["webhook-timestamp"]);
614 expect(yield* signedBy(secret, retry.headers, retry.raw)).toBe(true);
615 yield* answer(retry, 200);
616​
617 // Only after "a" resolved does "b" go out; a 410 gives it up without a retry.
618 const second = yield* Queue.take(deliveries);
619 expect(second.body.data.id).toBe("b");
620 expect(yield* refresh()).toMatchObject({
621 cursor: first.body.cursor,
622 deliveryStatus: { lastError: null, lastDeliveryAt: expect.any(String) },
623 });
624 yield* answer(second, 410);
625 // A new secret signs alongside the old one for a grace period.
626 const rotated = "whsec_" + Buffer.alloc(32, 7).toString("base64");
627 yield* refresh({
628 delivery: { mode: "webhook", url: subscribeParams().delivery.url, secret: rotated },
629 });
630 yield* hub.publish(settled("c"));
631 const third = yield* Queue.take(deliveries);
632 expect(third.body.data.id).toBe("c");
633 expect(yield* signedBy(secret, third.headers, third.raw)).toBe(true);
634 expect(yield* signedBy(rotated, third.headers, third.raw)).toBe(true);
635 expect(
636 (yield* refresh({
637 delivery: { mode: "webhook", url: subscribeParams().delivery.url, secret: rotated },
638 })).cursor,
639 ).toBe(second.body.cursor);
640 yield* answer(third, 200);
641 }).pipe(Effect.scoped, Effect.provide(layerTest)),
642);
643​
644it.effect("reports a gap the endpoint never took on the next refresh", () =>
645 Effect.gen(function* () {
646 const hub = yield* MilestoneHub.MilestoneHub;
647 const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve;
648 const filter = { arguments: { projectIds: ["project:a"] } };
649 yield* subscribe(filter);
650 yield* hub.publish(settled("a"));
651 const first = yield* Queue.take(deliveries);
652 // While "a" is out, more milestones than the subscription's backlog go by elsewhere.
653 for (let index = 0; index < 300; index++) {
654 yield* hub.publish(settled(`elsewhere-${index}`, { project: "project:b" }));
655 }
656 yield* answer(first, 200);
657 const gap = yield* Queue.take(deliveries);
658 expect(gap.body).toMatchObject({ type: "gap" });
659 yield* answer(gap, 410);
660 // "c" goes out only after the gap was given up on.
661 yield* hub.publish(settled("c"));
662 const next = yield* Queue.take(deliveries);
663 expect(next.body.data.id).toBe("c");
664 const refresh = (cursor: string) =>
665 call("events/subscribe", subscribeParams({ ...filter, cursor })).pipe(
666 Effect.map(({ result }) => result!),
667 );
668 // Until the client shows a cursor from past the gap, as if each answer were lost.
669 const refreshed = yield* refresh(first.body.cursor);
670 expect(refreshed.truncated).toBe(true);
671 expect(refreshed.cursor).not.toBe(first.body.cursor);
672 expect((yield* refresh(first.body.cursor)).truncated).toBe(true);
673 expect((yield* refresh(refreshed.cursor)).truncated).toBe(false);
674 yield* answer(next, 200);
675 }).pipe(Effect.scoped, Effect.provide(layerTest)),
676);
677​
678it.effect("gives each subscription to one URL its own delivery id for an event", () =>
679 Effect.gen(function* () {
680 const hub = yield* MilestoneHub.MilestoneHub;
681 const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve;
682 yield* subscribe();
683 yield* call("events/subscribe", subscribeParams({ arguments: { projectIds: ["project:a"] } }));
684 yield* hub.publish(settled("a"));
685 const both = [yield* Queue.take(deliveries), yield* Queue.take(deliveries)];
686 for (const delivery of both) {
687 expect(delivery.body.data.id).toBe("a");
688 expect(delivery.headers["webhook-id"]).toBe(delivery.body.eventId);
689 yield* answer(delivery, 200);
690 }
691 expect(both[0]!.headers["webhook-id"]).not.toBe(both[1]!.headers["webhook-id"]);
692 }).pipe(Effect.scoped, Effect.provide(layerTest)),
693);
694​
695it.effect("gives an event up after five attempts", () =>
696 Effect.gen(function* () {
697 const hub = yield* MilestoneHub.MilestoneHub;
698 const { deliveries, answer, subscribe } = yield* serve;
699 yield* subscribe();
700 yield* hub.publish(settled("a"));
701 for (const wait of ["30 seconds", "1 minute", "2 minutes", "4 minutes"] as const) {
702 yield* answer(yield* Queue.take(deliveries), 503);
703 yield* TestClock.adjust(wait);
704 }
705 const last = yield* Queue.take(deliveries);
706 expect(last.body.data.id).toBe("a");
707 yield* answer(last, 503);
708 yield* hub.publish(settled("b"));
709 const next = yield* Queue.take(deliveries);
710 expect(next.body.data.id).toBe("b");
711 yield* answer(next, 200);
712 }).pipe(Effect.scoped, Effect.provide(layerTest)),
713);
714​
715it.effect("grants a finite TTL and keeps one id for the same subscription", () =>
716 Effect.gen(function* () {
717 const { call, subscribe, subscribeParams } = yield* serve;
718 const { response } = yield* subscribe({ ttlMs: 1_000 });
719 // The test clock starts at the epoch; a grant is clamped to between a minute and an hour.
720 const hour = "1970-01-01T01:00:00.000Z";
721 expect(response.result!.refreshBefore).toBe("1970-01-01T00:01:00.000Z");
722 const grant = (params: Record<string, unknown>) =>
723 call("events/subscribe", subscribeParams(params)).pipe(Effect.map(({ result }) => result!));
724 expect((yield* grant({ ttlMs: null })).refreshBefore).toBe(hour);
725 expect((yield* grant({ ttlMs: 86_400_000 })).refreshBefore).toBe(hour);
726 expect((yield* grant({})).refreshBefore).toBe("1970-01-01T00:15:00.000Z");
727​
728 // Arguments compare as canonical JSON; a different filter is another subscription.
729 const ordered = yield* grant({
730 arguments: { projectIds: ["project:a"], includeSubagentChildren: true },
731 });
732 const reordered = yield* grant({
733 arguments: { includeSubagentChildren: true, projectIds: ["project:a"] },
734 });
735 expect(reordered.id).toBe(ordered.id);
736 expect(reordered.deliveryStatus).toBeDefined();
737 expect(ordered.id).not.toBe(response.result!.id);
738 }).pipe(Effect.scoped, Effect.provide(layerTest)),
739);
740​
741it.effect("ends a subscription at a deadline a refresh brought forward", () =>
742 Effect.gen(function* () {
743 const { call, subscribe, subscribeParams } = yield* serve;
744 yield* subscribe({ ttlMs: 3_600_000 });
745 const grant = (ttlMs: number) =>
746 call("events/subscribe", subscribeParams({ ttlMs })).pipe(
747 Effect.map(({ result }) => result!),
748 );
749 expect(yield* grant(60_000)).toMatchObject({
750 refreshBefore: "1970-01-01T00:01:00.000Z",
751 deliveryStatus: { active: true },
752 });
753 yield* TestClock.adjust("1 minute");
754 // Gone, so subscribing again starts a new subscription rather than refreshing a live one.
755 expect((yield* grant(3_600_000)).deliveryStatus).toBeUndefined();
756 }).pipe(Effect.scoped, Effect.provide(layerTest)),
757);
758​
759it.effect("refuses subscribes past the per-client cap even when they arrive together", () =>
760 Effect.gen(function* () {
761 const { call, deliveries, answer, subscribeParams } = yield* serve;
762 const fibers = yield* Effect.forEach(
763 Array.from({ length: 101 }, (_, index) => index),
764 (index) =>
765 call(
766 "events/subscribe",
767 subscribeParams({ arguments: { threadIds: [`thread:${index}`] } }),
768 ).pipe(Effect.forkChild),
769 );
770 // They share one verification; while it is pending each holds a slot, so one is refused now.
771 const verification = yield* Queue.take(deliveries);
772 const refused = yield* Effect.raceAll(fibers.map(Fiber.join));
773 expect(refused.error).toMatchObject({
774 code: -32025,
775 data: { limit: "subscriptions", max: 100 },
776 });
777 yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge }));
778 const responses = yield* Effect.forEach(fibers, Fiber.join);
779 expect(responses.filter((response) => response.result !== undefined)).toHaveLength(100);
780 }).pipe(Effect.scoped, Effect.provide(layerTest)),
781);
782​
783it.effect("ends a webhook subscription with terminated when the client's session is revoked", () =>
784 Effect.gen(function* () {
785 const { deliveries, answer, subscribe, revoke } = yield* serve;
786 yield* subscribe();
787 yield* revoke;
788 const terminated = yield* Queue.take(deliveries);
789 expect(terminated.headers["webhook-id"]).toMatch(/^msg_terminated_/);
790 expect(terminated.body).toMatchObject({ type: "terminated", error: { code: -32024 } });
791 yield* answer(terminated, 200);
792 }).pipe(Effect.scoped, Effect.provide(layerTest)),
793);