summaryrefslogtreecommitdiffhomepage
path: root/packages/transport-ws/src/router.test.ts
blob: 6d0182309e1a4e475095dcfae6ed5133dd23d6ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import type { SurfaceContext, SurfaceProvider, SurfaceRegistry } from "@dispatch/surface-registry";
import type { WsClientMessage } from "@dispatch/transport-contract";
import type { SurfaceCatalogEntry, SurfaceSpec } from "@dispatch/ui-contract";
import { describe, expect, it } from "vitest";
import { catalogMessage, type RouteResult, routeClientMessage, subKey } from "./router.js";

// ── Fake in-memory registry (no mocks — just a plain implementation) ────────

interface FakeProviderOpts {
	readonly id: string;
	readonly title?: string;
	readonly actions?: readonly string[];
	/** Called with the context that getSpec receives — for test assertions. */
	readonly onGetSpec?: (context: SurfaceContext | undefined) => void;
	/** Called with the context that invoke receives — for test assertions. */
	readonly onInvoke?: (
		actionId: string,
		payload: unknown,
		context: SurfaceContext | undefined,
	) => void;
}

function fakeProvider(
	idOrOpts: string | FakeProviderOpts,
	title?: string,
	actions?: readonly string[],
): SurfaceProvider {
	const opts: FakeProviderOpts =
		typeof idOrOpts === "string"
			? {
					id: idOrOpts,
					...(title !== undefined ? { title } : {}),
					...(actions !== undefined ? { actions } : {}),
				}
			: idOrOpts;
	const catalogEntry: SurfaceCatalogEntry = {
		id: opts.id,
		region: "default",
		title: opts.title ?? `Surface ${opts.id}`,
	};
	return {
		catalogEntry,
		getSpec(context?: SurfaceContext): SurfaceSpec {
			opts.onGetSpec?.(context);
			return {
				id: opts.id,
				region: "default",
				title: catalogEntry.title,
				fields:
					opts.actions?.map((a) => ({
						kind: "button" as const,
						label: a,
						action: { actionId: a },
					})) ?? [],
			};
		},
		invoke(actionId: string, _payload?: unknown, context?: SurfaceContext) {
			opts.onInvoke?.(actionId, _payload, context);
		},
	};
}

function fakeRegistry(providers: readonly SurfaceProvider[]): SurfaceRegistry {
	const map = new Map(providers.map((p) => [p.catalogEntry.id, p]));
	return {
		register(_provider: SurfaceProvider) {
			return () => {};
		},
		getCatalog() {
			return [...map.values()].map((p) => p.catalogEntry);
		},
		getSurface(id: string) {
			return map.get(id);
		},
	};
}

// ── Tests ───────────────────────────────────────────────────────────────────

describe("routeClientMessage", () => {
	describe("subscribe", () => {
		it("replies with `surface` and tracks the subscription", () => {
			const provider = fakeProvider("a", "Surface A");
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "subscribe",
				surfaceId: "a",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(1);
			expect(result.replies[0]).toEqual({
				type: "surface",
				spec: {
					id: "a",
					region: "default",
					title: "Surface A",
					fields: [],
				},
			});
			expect(result.subChange).toEqual({ op: "add", surfaceId: "a" });
		});

		it("is idempotent — subscribing twice does not duplicate the subChange", () => {
			const provider = fakeProvider("a");
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>([subKey("a")]); // already subscribed (global)

			const result = routeClientMessage(registry, connSubs, {
				type: "subscribe",
				surfaceId: "a",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(1);
			expect(result.replies[0]?.type).toBe("surface");
			expect(result.subChange).toBeUndefined();
		});

		it("returns `error` for an unknown surface id", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "subscribe",
				surfaceId: "nonexistent",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(1);
			expect(result.replies[0]).toEqual({
				type: "error",
				surfaceId: "nonexistent",
				message: "Unknown surface: nonexistent",
			});
			expect(result.subChange).toBeUndefined();
		});

		it("subscribe with conversationId fetches the provider spec for that conversation and tags the reply", () => {
			let receivedContext: SurfaceContext | undefined;
			const provider = fakeProvider({
				id: "cache-warm",
				title: "Cache Warming",
				onGetSpec(ctx) {
					receivedContext = ctx;
				},
			});
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "subscribe",
				surfaceId: "cache-warm",
				conversationId: "conv-42",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(receivedContext).toEqual({ conversationId: "conv-42" });
			expect(result.replies).toHaveLength(1);
			const reply = result.replies[0];
			if (reply?.type !== "surface") throw new Error("expected surface reply");
			expect(reply.conversationId).toBe("conv-42");
			expect(reply.spec.id).toBe("cache-warm");
			expect(result.subChange).toEqual({
				op: "add",
				surfaceId: "cache-warm",
				conversationId: "conv-42",
			});
		});

		it("subscribe without conversationId behaves as before (global surface unaffected)", () => {
			let receivedContext: SurfaceContext | undefined;
			const provider = fakeProvider({
				id: "global-surf",
				title: "Global Surface",
				onGetSpec(ctx) {
					receivedContext = ctx;
				},
			});
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "subscribe",
				surfaceId: "global-surf",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(receivedContext).toBeUndefined();
			const reply = result.replies[0];
			if (reply?.type !== "surface") throw new Error("expected surface reply");
			expect(reply.conversationId).toBeUndefined();
			expect(result.subChange).toEqual({ op: "add", surfaceId: "global-surf" });
		});
	});

	describe("unsubscribe", () => {
		it("emits a remove subChange and no replies", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>([subKey("a")]);

			const result = routeClientMessage(registry, connSubs, {
				type: "unsubscribe",
				surfaceId: "a",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(0);
			expect(result.subChange).toEqual({ op: "remove", surfaceId: "a" });
		});

		it("emits remove even if not currently subscribed (idempotent)", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "unsubscribe",
				surfaceId: "a",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(0);
			expect(result.subChange).toEqual({ op: "remove", surfaceId: "a" });
		});
	});

	describe("invoke", () => {
		it("signals the invoke effect for a known surface", () => {
			const provider = fakeProvider("a", "Surface A", ["toggle"]);
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "invoke",
				surfaceId: "a",
				actionId: "toggle",
				payload: true,
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(0);
			expect(result.invoke).toEqual({
				surfaceId: "a",
				actionId: "toggle",
				payload: true,
			});
		});

		it("returns `error` for an unknown surface id", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "invoke",
				surfaceId: "nonexistent",
				actionId: "toggle",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.replies).toHaveLength(1);
			expect(result.replies[0]).toEqual({
				type: "error",
				surfaceId: "nonexistent",
				message: "Unknown surface: nonexistent",
			});
			expect(result.invoke).toBeUndefined();
		});

		it("invoke forwards the conversationId to the provider", () => {
			let _receivedContext: SurfaceContext | undefined;
			const provider = fakeProvider({
				id: "cache-warm",
				title: "Cache Warming",
				actions: ["warm"],
				onInvoke(_actionId, _payload, ctx) {
					_receivedContext = ctx;
				},
			});
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "invoke",
				surfaceId: "cache-warm",
				actionId: "warm",
				payload: { force: true },
				conversationId: "conv-99",
			});

			expect(result.kind).toBe("surface");
			if (result.kind !== "surface") throw new Error("expected surface");
			expect(result.invoke).toEqual({
				surfaceId: "cache-warm",
				actionId: "warm",
				payload: { force: true },
				conversationId: "conv-99",
			});
		});
	});

	describe("chat.send", () => {
		it("classifies a chat.send message", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: "hello",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			expect(result.message).toBe("hello");
			expect(result.conversationId).toBeUndefined();
			expect(result.model).toBeUndefined();
			expect(result.cwd).toBeUndefined();
		});

		it("passes through optional fields", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				conversationId: "conv-123",
				message: "follow up",
				model: "gpt-4",
				cwd: "/tmp",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			expect(result.conversationId).toBe("conv-123");
			expect(result.message).toBe("follow up");
			expect(result.model).toBe("gpt-4");
			expect(result.cwd).toBe("/tmp");
		});

		it("chat.send threads workspaceId", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				conversationId: "conv-ws",
				message: "hello workspace",
				workspaceId: "my-workspace",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			expect(result.workspaceId).toBe("my-workspace");
		});

		it("chat.send defaults workspaceId when omitted", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: "hello no workspace",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			// workspaceId is absent (undefined) — the orchestrator receives no
			// workspaceId and applies its own "default" resolution.
			expect(result).not.toHaveProperty("workspaceId");
		});

		it("chat.send threads computerId", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				conversationId: "conv-cid",
				message: "hello computer",
				computerId: "dev-box",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			expect(result.computerId).toBe("dev-box");
		});

		it("chat.send omits computerId (absent/undefined) when not sent — backward compatible", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: "hello no computer",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			// computerId is absent (undefined) — the orchestrator receives no
			// computerId and resolves the inherited chain (conversation →
			// workspace defaultComputerId → local). Mirrors workspaceId.
			expect(result).not.toHaveProperty("computerId");
		});

		it("rejects a malformed chat.send (empty message)", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: "",
			});

			expect(result.kind).toBe("chat-error");
			if (result.kind !== "chat-error") throw new Error("expected chat-error");
			expect(result.errorMessage).toContain("non-empty string");
		});

		it("rejects a malformed chat.send (missing message)", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: undefined as unknown as string,
			});

			expect(result.kind).toBe("chat-error");
			if (result.kind !== "chat-error") throw new Error("expected chat-error");
			expect(result.errorMessage).toContain("non-empty string");
		});

		it("threads each valid reasoningEffort level through to the result", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();
			const levels = ["low", "medium", "high", "xhigh", "max"] as const;

			for (const level of levels) {
				const result = routeClientMessage(registry, connSubs, {
					type: "chat.send",
					message: "hello",
					reasoningEffort: level,
				});

				expect(result.kind).toBe("chat");
				if (result.kind !== "chat") throw new Error("expected chat");
				expect(result.reasoningEffort).toBe(level);
			}
		});

		it("omits reasoningEffort from result when not provided by client", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: "hello",
			});

			expect(result.kind).toBe("chat");
			if (result.kind !== "chat") throw new Error("expected chat");
			expect(result).not.toHaveProperty("reasoningEffort");
		});

		it("rejects an invalid reasoningEffort value with a chat-error", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.send",
				message: "hello",
				reasoningEffort: "turbo" as unknown as "low",
			});

			expect(result.kind).toBe("chat-error");
			if (result.kind !== "chat-error") throw new Error("expected chat-error");
			expect(result.errorMessage).toContain("invalid reasoningEffort");
			expect(result.errorMessage).toContain("turbo");
		});
	});

	describe("chat.subscribe", () => {
		it("routes chat.subscribe → { kind: 'chat-subscribe', conversationId }", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.subscribe",
				conversationId: "conv-abc",
			});

			expect(result).toEqual({ kind: "chat-subscribe", conversationId: "conv-abc" });
		});
	});

	describe("chat.unsubscribe", () => {
		it("routes chat.unsubscribe → { kind: 'chat-unsubscribe', conversationId }", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.unsubscribe",
				conversationId: "conv-abc",
			});

			expect(result).toEqual({ kind: "chat-unsubscribe", conversationId: "conv-abc" });
		});
	});

	describe("chat.queue", () => {
		it("routes a valid chat.queue → { kind: 'chat-queue', conversationId, text } (what the shell passes to orchestrator.enqueue)", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.queue",
				conversationId: "conv-1",
				text: "steer here",
			});

			expect(result).toEqual({
				kind: "chat-queue",
				conversationId: "conv-1",
				text: "steer here",
			});
		});

		it("chat.queue threads workspaceId", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.queue",
				conversationId: "conv-ws",
				text: "steer here",
				workspaceId: "my-workspace",
			});

			expect(result.kind).toBe("chat-queue");
			if (result.kind !== "chat-queue") throw new Error("expected chat-queue");
			expect(result.workspaceId).toBe("my-workspace");
		});

		it("rejects empty/whitespace text → chat-error (no enqueue signal)", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			for (const text of ["", "   ", "\t\n"]) {
				const result = routeClientMessage(registry, connSubs, {
					type: "chat.queue",
					conversationId: "conv-1",
					text,
				});

				expect(result.kind).toBe("chat-error");
				if (result.kind !== "chat-error") throw new Error("expected chat-error");
				expect(result.conversationId).toBe("conv-1");
				expect(result.errorMessage).toContain("non-empty string");
				expect(result.errorMessage).toContain("text");
			}
		});

		it("rejects missing text → chat-error (no enqueue signal)", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			const result = routeClientMessage(registry, connSubs, {
				type: "chat.queue",
				conversationId: "conv-1",
				text: undefined as unknown as string,
			});

			expect(result.kind).toBe("chat-error");
			if (result.kind !== "chat-error") throw new Error("expected chat-error");
			expect(result.errorMessage).toContain("non-empty string");
		});

		it("does not trim the stored text — passes the original through to the shell", () => {
			const registry = fakeRegistry([]);
			const connSubs = new Set<string>();

			// Non-empty after trim (so valid), but the value carries surrounding
			// whitespace: the router passes it through unchanged (validation uses
			// trim; the orchestrator receives the original text).
			const result = routeClientMessage(registry, connSubs, {
				type: "chat.queue",
				conversationId: "conv-1",
				text: "  steer  ",
			});

			expect(result.kind).toBe("chat-queue");
			if (result.kind !== "chat-queue") throw new Error("expected chat-queue");
			expect(result.text).toBe("  steer  ");
		});
	});

	describe("exhaustive switch (regression guard for Wave-0 fan-out)", () => {
		// Every WsClientMessage variant must route to a defined result with a
		// known kind — no fall-through / undefined return. If the union is
		// widened again, `tsc` catches the missing case (the switch is
		// exhaustive); this test guards the runtime side of that contract.
		it("routes every WsClientMessage variant to a defined RouteResult", () => {
			const provider = fakeProvider("a", "Surface A", ["toggle"]);
			const registry = fakeRegistry([provider]);
			const connSubs = new Set<string>();

			const samples: WsClientMessage[] = [
				{ type: "subscribe", surfaceId: "a" },
				{ type: "unsubscribe", surfaceId: "a" },
				{ type: "invoke", surfaceId: "a", actionId: "toggle", payload: true },
				{ type: "chat.send", message: "hi" },
				{ type: "chat.subscribe", conversationId: "c1" },
				{ type: "chat.unsubscribe", conversationId: "c1" },
				{ type: "chat.queue", conversationId: "c1", text: "steer" },
			];

			const validKinds = new Set<RouteResult["kind"]>([
				"surface",
				"chat",
				"chat-error",
				"chat-subscribe",
				"chat-unsubscribe",
				"chat-queue",
			]);

			for (const msg of samples) {
				const result = routeClientMessage(registry, connSubs, msg);
				expect(result).toBeDefined();
				expect(validKinds.has(result.kind)).toBe(true);
			}
		});
	});
});

describe("catalogMessage", () => {
	it("returns the catalog from the registry", () => {
		const providerA = fakeProvider("a", "Surface A");
		const providerB = fakeProvider("b", "Surface B");
		const registry = fakeRegistry([providerA, providerB]);

		const msg = catalogMessage(registry);

		expect(msg).toEqual({
			type: "catalog",
			catalog: [
				{ id: "a", region: "default", title: "Surface A" },
				{ id: "b", region: "default", title: "Surface B" },
			],
		});
	});

	it("returns an empty catalog when no providers are registered", () => {
		const registry = fakeRegistry([]);

		const msg = catalogMessage(registry);

		expect(msg).toEqual({ type: "catalog", catalog: [] });
	});
});

describe("subKey", () => {
	it("builds a global key when conversationId is undefined", () => {
		expect(subKey("surf-a")).toBe("surf-a::");
	});

	it("builds a conversation-scoped key when conversationId is provided", () => {
		expect(subKey("surf-a", "conv-42")).toBe("surf-a::conv-42");
	});

	it("global and conversation-scoped keys are distinct", () => {
		expect(subKey("surf-a")).not.toBe(subKey("surf-a", "conv-42"));
	});
});