summaryrefslogtreecommitdiffhomepage
path: root/packages/session-orchestrator/src/queue.test.ts
blob: adf5d9ae1d32830b5da5c1688406d4fc2001a701 (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
import type { ConversationStore } from "@dispatch/conversation-store";
import type {
	AgentEvent,
	ChatMessage,
	ProviderContract,
	ProviderEvent,
	ReasoningEffort,
	RunTurnInput,
	RunTurnResult,
	StoredChunk,
	ToolContract,
	TurnMetrics,
} from "@dispatch/kernel";
import { runTurn } from "@dispatch/kernel";
import { createMessageQueueService } from "@dispatch/message-queue";
import { describe, expect, it } from "vitest";
import { createSessionOrchestrator } from "./orchestrator.js";
import type { ToolAssembly } from "./tools-filter.js";

// --- Shared test helpers (duplicated from orchestrator.test.ts per isolation-over-dRY;
//     a shared test-helper module wired between test files is a coupling smell) ---

function createInMemoryStore(): ConversationStore & {
	readonly data: Map<string, ChatMessage[]>;
	readonly metricsData: Map<string, TurnMetrics[]>;
	readonly cwdData: Map<string, string>;
	readonly effortData: Map<string, ReasoningEffort>;
	readonly modelData: Map<string, string>;
} {
	const data = new Map<string, ChatMessage[]>();
	const metricsData = new Map<string, TurnMetrics[]>();
	const cwdData = new Map<string, string>();
	const effortData = new Map<string, ReasoningEffort>();
	const modelData = new Map<string, string>();
	return {
		data,
		metricsData,
		cwdData,
		effortData,
		modelData,
		async append(conversationId, messages) {
			const existing = data.get(conversationId) ?? [];
			data.set(conversationId, [...existing, ...messages]);
		},
		async load(conversationId) {
			return [...(data.get(conversationId) ?? [])];
		},
		async loadSince(conversationId, sinceSeq) {
			const messages = data.get(conversationId) ?? [];
			const result: StoredChunk[] = [];
			let seq = 1;
			for (const msg of messages) {
				for (const chunk of msg.chunks) {
					if (sinceSeq === undefined || seq > sinceSeq) {
						result.push({ seq, role: msg.role, chunk });
					}
					seq++;
				}
			}
			return result;
		},
		async appendMetrics(conversationId, metrics) {
			const existing = metricsData.get(conversationId) ?? [];
			metricsData.set(conversationId, [...existing, metrics]);
		},
		async loadMetrics(conversationId) {
			return [...(metricsData.get(conversationId) ?? [])];
		},
		async getCwd(conversationId) {
			return cwdData.get(conversationId) ?? null;
		},
		async setCwd(conversationId, cwd) {
			cwdData.set(conversationId, cwd);
		},
		async clearCwd(conversationId) {
			cwdData.delete(conversationId);
		},
		async getComputerId() {
			return null;
		},
		async setComputerId() {},
		async clearComputerId() {},
		async getReasoningEffort(conversationId) {
			return effortData.get(conversationId) ?? null;
		},
		async setReasoningEffort(conversationId, effort) {
			effortData.set(conversationId, effort);
		},
		async getModel(conversationId) {
			return modelData.get(conversationId) ?? null;
		},
		async setModel(conversationId, model) {
			if (model === "") {
				modelData.delete(conversationId);
			} else {
				modelData.set(conversationId, model);
			}
		},
		async listConversations() {
			return [];
		},
		async getConversationMeta() {
			return null;
		},
		async setConversationTitle() {},
		async getConversationStatus() {
			return null;
		},
		async setConversationStatus() {},
		async replaceHistory() {},
		async getCompactPercent() {
			return null;
		},
		async setCompactPercent() {},
		async forkHistory() {},
		async setCompactedFrom() {},
		async getWorkspace() {
			return null;
		},
		async ensureWorkspace(id) {
			return {
				id,
				title: id,
				defaultCwd: null,
				defaultComputerId: null,
				createdAt: 0,
				lastActivityAt: 0,
			};
		},
		async setWorkspaceTitle(id, title) {
			return {
				id,
				title,
				defaultCwd: null,
				defaultComputerId: null,
				createdAt: 0,
				lastActivityAt: 0,
			};
		},
		async setWorkspaceDefaultCwd(id, defaultCwd) {
			return {
				id,
				title: id,
				defaultCwd,
				defaultComputerId: null,
				createdAt: 0,
				lastActivityAt: 0,
			};
		},
		async setWorkspaceDefaultComputerId(id, defaultComputerId) {
			return {
				id,
				title: id,
				defaultCwd: null,
				defaultComputerId,
				createdAt: 0,
				lastActivityAt: 0,
			};
		},
		async deleteWorkspace() {
			return { closedCount: 0 };
		},
		async listWorkspaces() {
			return [];
		},
		async getWorkspaceId() {
			return "default";
		},
		async setWorkspaceId() {},
		async getEffectiveCwd(conversationId) {
			return cwdData.get(conversationId) ?? null;
		},
		async getEffectiveComputer() {
			return null;
		},
	};
}

function identityApplyToolsFilter(assembly: ToolAssembly): Promise<ToolAssembly> {
	return Promise.resolve(assembly);
}

function noTools(): readonly ToolContract[] {
	return [];
}

function simpleProvider(): ProviderContract {
	return {
		id: "fake",
		stream: async function* () {
			yield { type: "text-delta", delta: "ok" } as ProviderEvent;
			yield { type: "finish", reason: "stop" } as ProviderEvent;
		},
	};
}

/**
 * A capturing runTurn that simulates the kernel calling `drainSteering` at the
 * tool-result boundary. It records the RunTurnInput (so the test can assert
 * drainSteering was wired) and collects what drainSteering returned. NOT a mock
 * of @dispatch/* — it's a plain fake of the outermost runTurn edge.
 */
function createDrainingCaptureRunTurn(): {
	captured: RunTurnInput[];
	drainedMessages: ChatMessage[];
	wasDrainCalled: () => boolean;
	runTurn: (input: RunTurnInput) => Promise<RunTurnResult>;
} {
	const captured: RunTurnInput[] = [];
	const drainedMessages: ChatMessage[] = [];
	let drainCalled = false;
	return {
		captured,
		drainedMessages,
		wasDrainCalled: () => drainCalled,
		runTurn: async (input) => {
			captured.push(input);
			if (input.drainSteering !== undefined) {
				drainCalled = true;
				const drained = input.drainSteering();
				drainedMessages.push(...drained);
			}
			return {
				messages: [{ role: "assistant", chunks: [{ type: "text", text: "ok" }] }],
				usage: { inputTokens: 1, outputTokens: 1 },
				finishReason: "stop",
			};
		},
	};
}

function waitForSealed(
	orchestrator: ReturnType<typeof createSessionOrchestrator>["orchestrator"],
	conversationId: string,
): Promise<void> {
	return new Promise((resolve) => {
		const unsub = orchestrator.subscribe(conversationId, (e) => {
			if (e.type === "turn-sealed") {
				unsub();
				resolve();
			}
		});
	});
}

function waitForSealedCount(
	orchestrator: ReturnType<typeof createSessionOrchestrator>["orchestrator"],
	conversationId: string,
	count: number,
): Promise<void> {
	return new Promise((resolve) => {
		let seen = 0;
		const unsub = orchestrator.subscribe(conversationId, (e) => {
			if (e.type === "turn-sealed") {
				seen++;
				if (seen >= count) {
					unsub();
					resolve();
				}
			}
		});
	});
}

function isSteering(e: AgentEvent): e is Extract<AgentEvent, { type: "steering" }> {
	return e.type === "steering";
}

function isUserMessage(e: AgentEvent): e is Extract<AgentEvent, { type: "user-message" }> {
	return e.type === "user-message";
}

function createTestQueue() {
	return createMessageQueueService({
		id: () => `q-${Math.random().toString(36).slice(2, 8)}`,
		now: () => 1000,
		notify: () => {},
	});
}

// --- drainSteering (mid-turn, at the tool-result boundary) ---

describe("drainSteering", () => {
	it("drainSteering drains the queue + emits a steering event + returns one combined user message", async () => {
		const store = createInMemoryStore();
		const queue = createTestQueue();
		queue.enqueue("conv-drain", "first");
		queue.enqueue("conv-drain", "second");

		const { captured, drainedMessages, runTurn: captureRunTurn } = createDrainingCaptureRunTurn();

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => ({ id: "p", stream: async function* () {} }),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn: captureRunTurn,
			resolveQueue: () => queue,
		});

		const events: AgentEvent[] = [];
		const unsub = orchestrator.subscribe("conv-drain", (e) => events.push(e));

		orchestrator.startTurn({ conversationId: "conv-drain", text: "go" });
		await waitForSealed(orchestrator, "conv-drain");
		unsub();

		// drainSteering was wired on the RunTurnInput
		expect(captured).toHaveLength(1);
		expect(captured[0]?.drainSteering).toBeDefined();
		expect(typeof captured[0]?.drainSteering).toBe("function");

		// The fake runTurn called drainSteering → returned one combined user message
		expect(drainedMessages).toHaveLength(1);
		const steerMsg = drainedMessages[0];
		if (steerMsg === undefined) throw new Error("expected drained message");
		expect(steerMsg.role).toBe("user");
		expect(steerMsg.chunks).toHaveLength(1);
		const chunk = steerMsg.chunks[0];
		if (chunk === undefined) throw new Error("expected chunk");
		expect(chunk.type).toBe("text");
		if (chunk.type === "text") {
			expect(chunk.text).toBe("first\n\nsecond");
		}

		// The queue was drained (cleared)
		expect(queue.getQueue("conv-drain")).toHaveLength(0);

		// A steering event was emitted into the hub with the combined text
		const steering = events.find(isSteering);
		expect(steering).toBeDefined();
		expect(steering?.conversationId).toBe("conv-drain");
		expect(steering?.text).toBe("first\n\nsecond");
		expect(steering?.turnId).toMatch(/^turn-/);
	});

	it("drainSteering on an empty queue returns [] and emits nothing", async () => {
		const store = createInMemoryStore();
		const queue = createTestQueue();

		const {
			drainedMessages,
			wasDrainCalled,
			runTurn: captureRunTurn,
		} = createDrainingCaptureRunTurn();

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => ({ id: "p", stream: async function* () {} }),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn: captureRunTurn,
			resolveQueue: () => queue,
		});

		const events: AgentEvent[] = [];
		const unsub = orchestrator.subscribe("conv-empty", (e) => events.push(e));

		orchestrator.startTurn({ conversationId: "conv-empty", text: "go" });
		await waitForSealed(orchestrator, "conv-empty");
		unsub();

		// drainSteering was wired and called, but returned []
		expect(wasDrainCalled()).toBe(true);
		expect(drainedMessages).toHaveLength(0);

		// No steering event was emitted
		expect(events.filter(isSteering)).toHaveLength(0);
	});

	it("no queue ext (resolveQueue undefined) → drainSteering omitted; turn unchanged", async () => {
		const store = createInMemoryStore();

		const { captured, wasDrainCalled, runTurn: captureRunTurn } = createDrainingCaptureRunTurn();

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => ({ id: "p", stream: async function* () {} }),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn: captureRunTurn,
			// resolveQueue intentionally omitted — feature degrades off
		});

		const events: AgentEvent[] = [];
		const unsub = orchestrator.subscribe("conv-noqueue", (e) => events.push(e));

		orchestrator.startTurn({ conversationId: "conv-noqueue", text: "go" });
		await waitForSealed(orchestrator, "conv-noqueue");
		unsub();

		// drainSteering is absent from the RunTurnInput (not undefined — omitted)
		expect(captured).toHaveLength(1);
		expect(captured[0]?.drainSteering).toBeUndefined();
		expect(wasDrainCalled()).toBe(false);

		// No steering event; turn sealed normally
		expect(events.filter(isSteering)).toHaveLength(0);
		expect(events.filter((e) => e.type === "turn-sealed")).toHaveLength(1);
	});
});

// --- Post-seal carry (turn ended with a non-empty queue → new turn) ---

describe("post-seal carry", () => {
	it("post-seal: non-empty queue → a new turn starts with the combined message", async () => {
		const store = createInMemoryStore();
		const queue = createTestQueue();
		queue.enqueue("conv-carry", "queued-a");
		queue.enqueue("conv-carry", "queued-b");

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => simpleProvider(),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn,
			resolveQueue: () => queue,
		});

		const events: AgentEvent[] = [];
		const unsub = orchestrator.subscribe("conv-carry", (e) => events.push(e));

		orchestrator.startTurn({ conversationId: "conv-carry", text: "original" });
		// Wait for the original turn + the carried turn to both seal.
		await waitForSealedCount(orchestrator, "conv-carry", 2);
		unsub();

		// Two user-message events: the original prompt + the carried combined text.
		const userMessages = events.filter(isUserMessage);
		expect(userMessages).toHaveLength(2);
		expect(userMessages[0]?.text).toBe("original");
		expect(userMessages[1]?.text).toBe("queued-a\n\nqueued-b");

		// No steering event — the carry case emits user-message, not steering.
		expect(events.filter(isSteering)).toHaveLength(0);

		// The queue was drained by the carry.
		expect(queue.getQueue("conv-carry")).toHaveLength(0);

		// Both turns persisted (original + carry).
		expect(store.data.get("conv-carry")?.length).toBeGreaterThanOrEqual(4);
	});

	it("post-seal: empty queue → no new turn", async () => {
		const store = createInMemoryStore();
		const queue = createTestQueue();

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => simpleProvider(),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn,
			resolveQueue: () => queue,
		});

		const events: AgentEvent[] = [];
		const unsub = orchestrator.subscribe("conv-no-carry", (e) => events.push(e));

		orchestrator.startTurn({ conversationId: "conv-no-carry", text: "original" });
		await waitForSealed(orchestrator, "conv-no-carry");
		// Give the carry check a chance to run (it's in the finally, synchronous
		// after turn-sealed, but await yields first).
		await new Promise<void>((resolve) => setTimeout(resolve, 10));
		unsub();

		// Only one user-message (the original) — no carry turn.
		expect(events.filter(isUserMessage)).toHaveLength(1);
		expect(events.filter((e) => e.type === "turn-sealed")).toHaveLength(1);
	});
});

// --- enqueue facade (the single entry transports call) ---

describe("enqueue", () => {
	it("enqueue when idle → starts a turn (startedTurn:true)", async () => {
		const store = createInMemoryStore();
		const queue = createTestQueue();

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => simpleProvider(),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn,
			resolveQueue: () => queue,
		});

		const result = orchestrator.enqueue({ conversationId: "conv-idle", text: "hello" });
		expect(result.startedTurn).toBe(true);
		expect(result.queue).toHaveLength(0);

		await waitForSealed(orchestrator, "conv-idle");

		// The turn ran and persisted.
		expect(store.data.get("conv-idle")).toBeDefined();
		expect(store.data.get("conv-idle")?.length).toBeGreaterThanOrEqual(2);
	});

	it("enqueue when active → queues (startedTurn:false, snapshot with the message)", async () => {
		const store = createInMemoryStore();
		const queue = createTestQueue();

		let resolveFirst: (() => void) | undefined;
		const firstBlocker = new Promise<void>((resolve) => {
			resolveFirst = resolve;
		});
		let callCount = 0;
		const blockingFirstRunTurn = async (_input: RunTurnInput): Promise<RunTurnResult> => {
			callCount++;
			if (callCount === 1) {
				await firstBlocker;
			}
			return {
				messages: [{ role: "assistant", chunks: [{ type: "text", text: "done" }] }],
				usage: { inputTokens: 1, outputTokens: 1 },
				finishReason: "stop",
			};
		};

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => simpleProvider(),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn: blockingFirstRunTurn,
			resolveQueue: () => queue,
		});

		// Start the original turn (it blocks in runTurn).
		orchestrator.startTurn({ conversationId: "conv-active", text: "first" });
		// Let the turn reach the blocked runTurn call.
		await new Promise<void>((resolve) => setTimeout(resolve, 10));

		// Enqueue while active.
		const result = orchestrator.enqueue({ conversationId: "conv-active", text: "second" });
		expect(result.startedTurn).toBe(false);
		expect(result.queue).toHaveLength(1);
		expect(result.queue[0]?.text).toBe("second");

		// The queue holds the enqueued message.
		expect(queue.getQueue("conv-active")).toHaveLength(1);

		// Release the original turn → it seals → post-seal carry starts a new
		// turn with the enqueued message. Subscribe before releasing to catch
		// both turn-sealed events.
		const sealed = waitForSealedCount(orchestrator, "conv-active", 2);
		resolveFirst?.();
		await sealed;
	});

	it("enqueue when active + no queue ext → startedTurn:false, empty queue (degraded)", async () => {
		const store = createInMemoryStore();

		let resolveFirst: (() => void) | undefined;
		const firstBlocker = new Promise<void>((resolve) => {
			resolveFirst = resolve;
		});
		let callCount = 0;
		const blockingFirstRunTurn = async (_input: RunTurnInput): Promise<RunTurnResult> => {
			callCount++;
			if (callCount === 1) {
				await firstBlocker;
			}
			return {
				messages: [{ role: "assistant", chunks: [{ type: "text", text: "done" }] }],
				usage: { inputTokens: 1, outputTokens: 1 },
				finishReason: "stop",
			};
		};

		const { orchestrator } = createSessionOrchestrator({
			conversationStore: store,
			resolveProvider: () => simpleProvider(),
			resolveTools: noTools,
			applyToolsFilter: identityApplyToolsFilter,
			runTurn: blockingFirstRunTurn,
			// resolveQueue omitted — no queue extension loaded (degraded)
		});

		orchestrator.startTurn({ conversationId: "conv-degraded", text: "first" });
		await new Promise<void>((resolve) => setTimeout(resolve, 10));

		// Enqueue while active, but no queue ext → message dropped, empty snapshot.
		const result = orchestrator.enqueue({ conversationId: "conv-degraded", text: "second" });
		expect(result.startedTurn).toBe(false);
		expect(result.queue).toHaveLength(0);

		// Release the original turn; no carry (no queue ext).
		const sealed = waitForSealed(orchestrator, "conv-degraded");
		resolveFirst?.();
		await sealed;
	});
});