-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathturn_flow.test.ts
More file actions
679 lines (592 loc) · 26.6 KB
/
Copy pathturn_flow.test.ts
File metadata and controls
679 lines (592 loc) · 26.6 KB
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
import { RunTurnUseCase, buildResumeValue } from '../application/runTurnUseCase.js';
import { SteerBuffer } from '../domain/steerBuffer.js';
import type { AgentStreamChunk, PendingInterrupt } from '../domain/turnTypes.js';
// Characterization tests for the turn-orchestration flow (the layer between the HTTP
// endpoint and the LLM). We drive the REAL RunTurnUseCase, faking only the two true
// boundaries: the LlmPort (a scripted typed stream) and the session repository. This
// freezes the emitted AgentEvent sequence, persistence, error/abort handling, and the
// HITL approve -> resume path without a real LLM or database.
async function* streamOf(...chunks: AgentStreamChunk[]) {
for (const chunk of chunks) {
yield chunk;
}
}
const text = (delta: string): AgentStreamChunk => ({ kind: 'text', delta });
const reasoning = (delta: string): AgentStreamChunk => ({ kind: 'reasoning', delta });
const interrupt = (
value: unknown,
descriptors: PendingInterrupt[] = [{ id: 'int-1', count: 1, requests: [] }],
): AgentStreamChunk => ({ kind: 'interrupt', interrupt: value, descriptors });
function fakeLlm(
opts: {
streamFor?: (call: number, input: any) => AsyncIterable<AgentStreamChunk>;
pendingInterrupts?: PendingInterrupt[];
pendingInterruptsError?: Error;
latestCheckpointId?: string | null;
detectedLanguage?: any;
} = {},
) {
const calls: any[] = [];
const detectLanguageCalls: any[] = [];
const getPendingInterruptsCalls: any[] = [];
const getLatestCheckpointIdCalls: any[] = [];
const resetThreadCalls: any[] = [];
return {
calls,
detectLanguageCalls,
getPendingInterruptsCalls,
getLatestCheckpointIdCalls,
resetThreadCalls,
async streamTurn(input: any) {
calls.push(input);
const factory = opts.streamFor ?? (() => streamOf());
return factory(calls.length, input);
},
async detectLanguage(input: any) {
detectLanguageCalls.push(input);
return opts.detectedLanguage ?? null;
},
async getPendingInterrupts(input: any) {
getPendingInterruptsCalls.push(input);
if (opts.pendingInterruptsError) {
throw opts.pendingInterruptsError;
}
return opts.pendingInterrupts ?? [];
},
async getLatestCheckpointId(input: any) {
getLatestCheckpointIdCalls.push(input);
return opts.latestCheckpointId ?? 'cp-latest';
},
async resetThreadCheckpoints(input: any) {
resetThreadCalls.push(input);
},
};
}
function fakeSessions(opts: { initialResponse?: string; agentTurns?: any[] } = {}) {
const calls = {
createNewTurn: [] as any[],
touchSession: [] as string[],
saveTurnResponse: [] as any[],
getResumeState: 0,
editTurnAndTruncateAfter: [] as any[],
};
return {
calls,
async getPreviousUserMessages() {
return [];
},
async createNewTurn(sessionId: string, prompt: string) {
calls.createNewTurn.push({ sessionId, prompt });
return 'turn-1';
},
async touchSession(sessionId: string) {
calls.touchSession.push(sessionId);
},
async getResumeState() {
calls.getResumeState += 1;
return { turnId: 'turn-1', initialResponse: opts.initialResponse ?? '' };
},
async saveTurnResponse(payload: any) {
calls.saveTurnResponse.push(payload);
},
async getAgentTurns() {
return opts.agentTurns ?? [];
},
async editTurnAndTruncateAfter(payload: any) {
calls.editTurnAndTruncateAfter.push(payload);
},
};
}
const SESSION_RESOURCE = {
resourceId: 'sessions',
idField: 'id',
titleField: 'title',
askerIdField: 'asker_id',
createdAtField: 'created_at',
} as any;
function buildUseCase(opts: {
streamFor?: (call: number, input: any) => AsyncIterable<AgentStreamChunk>;
initialResponse?: string;
pendingInterrupts?: PendingInterrupt[];
pendingInterruptsError?: Error;
hasPersistentCheckpointer?: boolean;
turnCheckpointsEnabled?: boolean;
agentTurns?: any[];
latestCheckpointId?: string | null;
sessionOwnerPk?: string | null;
detectedLanguage?: any;
} = {}) {
const llm = fakeLlm({
streamFor: opts.streamFor,
pendingInterrupts: opts.pendingInterrupts,
pendingInterruptsError: opts.pendingInterruptsError,
latestCheckpointId: opts.latestCheckpointId,
detectedLanguage: opts.detectedLanguage,
});
const sessions = fakeSessions({ initialResponse: opts.initialResponse, agentTurns: opts.agentTurns });
const steerBuffer = new SteerBuffer();
const getAdminforth = () => ({
config: { auth: { usernameField: 'email' }, baseUrlSlashed: '/admin/' },
resource: () => ({
async get() {
// Session owned by 'u1' unless overridden (null => session missing).
if (opts.sessionOwnerPk === null) return null;
return { id: 's1', asker_id: opts.sessionOwnerPk ?? 'u1' };
},
}),
}) as any;
const useCase = new RunTurnUseCase({
llm: llm as any,
sessions: sessions as any,
steerBuffer,
modes: [{ name: 'default', completionAdapter: {} as any }],
getAdminforth,
getAgentSystemPrompt: async () => 'SYS',
hasPersistentCheckpointer: opts.hasPersistentCheckpointer ?? false,
turnCheckpointsEnabled: opts.turnCheckpointsEnabled ?? false,
sessionResource: SESSION_RESOURCE,
createDebugSink: () => ({ flush() {}, getHistory: () => [] }),
});
return { useCase, llm, sessions, steerBuffer };
}
function makeInput(overrides: Record<string, unknown> = {}) {
const events: any[] = [];
const input = {
prompt: 'hi',
sessionId: 's1',
modeName: null,
userTimeZone: 'UTC',
adminUser: { pk: 'u1', username: 'admin', dbUser: { email: 'admin@x.io' } },
emit: async (event: any) => {
events.push(event);
},
failureLogMessage: 'fail',
abortLogMessage: 'abort',
...overrides,
};
return { input, events };
}
describe('RunTurnUseCase.handleTurn', () => {
it('streams a text turn, emits response/finish, and persists the assembled text', async () => {
const { useCase, llm, sessions } = buildUseCase({
streamFor: () => streamOf(text('Hello'), text(' world')),
});
const { input, events } = makeInput();
const result = await useCase.handleTurn(input as any);
expect(events.map((e) => e.type)).toEqual([
'turn-started',
'turn-persisted',
'text-delta',
'text-delta',
'response',
'finish',
]);
expect(events.filter((e) => e.type === 'text-delta').map((e) => e.delta).join('')).toBe('Hello world');
expect(events.find((e) => e.type === 'response')).toMatchObject({
text: 'Hello world',
sessionId: 's1',
turnId: 'turn-1',
});
expect(result).toMatchObject({ text: 'Hello world', turnId: 'turn-1', aborted: false, failed: false });
expect(sessions.calls.saveTurnResponse[0]).toMatchObject({ turnId: 'turn-1', responseText: 'Hello world' });
expect(sessions.calls.touchSession).toEqual(['s1']);
expect(llm.calls).toHaveLength(1);
expect('messages' in llm.calls[0].input).toBe(true);
});
it('sends only the user message, passing the system prompt and language out-of-band', async () => {
// The system prompt must never enter the message history: it used to be prepended
// as a SystemMessage per turn, which piled up one copy per turn in the checkpoint.
const { useCase, llm } = buildUseCase({
streamFor: () => streamOf(text('ok')),
detectedLanguage: { language: 'Ukrainian', code: 'UK', ambiguous: false },
});
await useCase.handleTurn(makeInput().input as any);
expect(llm.calls[0].input.messages).toEqual([{ role: 'user', content: 'hi' }]);
expect(llm.calls[0].systemPrompt).toBe('SYS');
// The per-turn half travels in the context, to be rebuilt on every model call.
expect(llm.calls[0].context.userLanguage).toEqual({
language: 'Ukrainian',
code: 'UK',
ambiguous: false,
});
});
it('reuses the detected language on a HITL resume, which has no message to detect from', async () => {
const { useCase, llm } = buildUseCase({
detectedLanguage: { language: 'Ukrainian', code: 'UK', ambiguous: false },
streamFor: (call) =>
call === 1
? streamOf(interrupt([{ id: 'int-1', value: {} }]))
: streamOf(text('Done')),
});
await useCase.handleTurn(makeInput().input as any);
await useCase.handleTurn(makeInput({ prompt: '', approvalDecision: 'approve' }).input as any);
// Detection ran once, for the original message — not again for the approval.
expect(llm.detectLanguageCalls).toHaveLength(1);
expect(llm.calls[1].context.userLanguage).toEqual({
language: 'Ukrainian',
code: 'UK',
ambiguous: false,
});
});
it('re-detects the language on the next turn (a user may switch languages mid-session)', async () => {
const { useCase, llm } = buildUseCase({ streamFor: () => streamOf(text('ok')) });
await useCase.handleTurn(makeInput().input as any);
await useCase.handleTurn(makeInput({ prompt: 'now in english' }).input as any);
expect(llm.detectLanguageCalls).toHaveLength(2);
});
it('emits reasoning deltas but excludes reasoning from the persisted response', async () => {
const { useCase, sessions } = buildUseCase({
streamFor: () => streamOf(reasoning('thinking...'), text('Answer')),
});
const { input, events } = makeInput();
await useCase.handleTurn(input as any);
expect(events.some((e) => e.type === 'reasoning-delta' && e.delta === 'thinking...')).toBe(true);
expect(events.find((e) => e.type === 'response').text).toBe('Answer');
expect(sessions.calls.saveTurnResponse[0].responseText).toBe('Answer');
});
it('turns an LLM failure into an error event and persists the message as the response (current behavior)', async () => {
const { useCase, sessions } = buildUseCase({
streamFor: () => {
throw new Error('llm exploded');
},
});
const { input, events } = makeInput();
const result = await useCase.handleTurn(input as any);
expect(events.map((e) => e.type)).toEqual(['turn-started', 'turn-persisted', 'error', 'finish']);
expect(result.failed).toBe(true);
expect(result.aborted).toBe(false);
expect(result.text).toContain('llm exploded');
expect(events.find((e) => e.type === 'error').error).toContain('llm exploded');
expect(sessions.calls.saveTurnResponse[0].responseText).toContain('llm exploded');
});
it('handles a client abort without emitting response/error and still finalizes the turn', async () => {
const controller = new AbortController();
controller.abort();
const { useCase, sessions } = buildUseCase({
streamFor: () => streamOf(text('partial')),
});
const { input, events } = makeInput({ abortSignal: controller.signal });
const result = await useCase.handleTurn(input as any);
expect(result.aborted).toBe(true);
expect(result.failed).toBe(false);
expect(events.map((e) => e.type)).toEqual(['turn-started', 'turn-persisted', 'finish']);
expect(sessions.calls.saveTurnResponse).toHaveLength(1);
});
it('emits a HITL interrupt and resumes via a provider-agnostic resume payload on approval', async () => {
const { useCase, llm, sessions } = buildUseCase({
initialResponse: 'prev ',
streamFor: (call) =>
call === 1
? streamOf(
interrupt([
{ id: 'int-1', value: { actionRequests: [{ name: 'delete_record', description: 'Delete row' }] } },
]),
)
: streamOf(text('Done')),
});
const first = makeInput();
await useCase.handleTurn(first.input as any);
expect(first.events.map((e) => e.type)).toEqual(['turn-started', 'turn-persisted', 'interrupt', 'response', 'finish']);
expect(first.events.find((e) => e.type === 'interrupt').sessionId).toBe('s1');
const second = makeInput({ prompt: '', approvalDecision: 'approve' });
const result = await useCase.handleTurn(second.input as any);
expect(sessions.calls.getResumeState).toBe(1);
expect(llm.calls).toHaveLength(2);
expect('messages' in llm.calls[1].input).toBe(false);
expect('resume' in llm.calls[1].input).toBe(true);
// initialResponse ('prev ') is prepended to the resumed streamed text.
expect(result.text).toBe('prev Done');
expect(second.events.find((e) => e.type === 'response').text).toBe('prev Done');
});
it('clears unconsumed steers when a turn completes (they must not leak into the next turn)', async () => {
const { useCase, steerBuffer } = buildUseCase({
streamFor: () => streamOf(text('done')),
});
// Steer enqueued but the (faked) LLM stream never drains it — e.g. it arrived after the
// last model call. On turn completion the leftover must be discarded.
steerBuffer.add('s1', 'too late');
expect(steerBuffer.size('s1')).toBe(1);
await useCase.handleTurn(makeInput().input as any);
expect(steerBuffer.size('s1')).toBe(0);
});
it('preserves steers across a HITL interrupt and clears them after the resumed turn ends', async () => {
const { useCase, steerBuffer } = buildUseCase({
streamFor: (call) =>
call === 1
? streamOf(interrupt([{ id: 'int-1', value: {} }]))
: streamOf(text('done')),
});
// A steer sent while the turn is paused for approval must survive the interrupted turn...
steerBuffer.add('s1', 'while waiting for approval');
await useCase.handleTurn(makeInput().input as any);
expect(steerBuffer.size('s1')).toBe(1);
// ...and be cleared once the resumed turn finishes.
await useCase.handleTurn(makeInput({ prompt: '', approvalDecision: 'approve' }).input as any);
expect(steerBuffer.size('s1')).toBe(0);
});
it('with a persistent checkpointer, resumes from checkpoint state (ignoring the local cache)', async () => {
const { useCase, llm } = buildUseCase({
hasPersistentCheckpointer: true,
initialResponse: 'prev ',
pendingInterrupts: [{ id: 'int-1', count: 1, requests: [] }],
streamFor: () => streamOf(text('Resumed')),
});
// No interrupt cached in this process (restart / other instance); the checkpoint is authoritative.
const { input } = makeInput({ prompt: '', approvalDecision: 'approve' });
const result = await useCase.handleTurn(input as any);
expect(llm.getPendingInterruptsCalls).toHaveLength(1);
expect(llm.calls).toHaveLength(1);
expect('resume' in llm.calls[0].input).toBe(true);
expect(result.text).toBe('prev Resumed');
});
it('surfaces a checkpoint read failure as a real error, not "no pending approval"', async () => {
const { useCase } = buildUseCase({
hasPersistentCheckpointer: true,
pendingInterruptsError: new Error('checkpoint DB unavailable'),
});
const { input } = makeInput({ prompt: '', approvalDecision: 'approve' });
// The infra error must propagate, NOT be masked as a missing interrupt.
await expect(useCase.handleTurn(input as any)).rejects.toThrow('checkpoint DB unavailable');
await expect(useCase.handleTurn(input as any)).rejects.not.toThrow('No pending approval');
});
it('rejects a normal turn on a session the user does not own, before creating a turn', async () => {
const { useCase, sessions, llm } = buildUseCase({
sessionOwnerPk: 'someone-else',
streamFor: () => streamOf(text('secret')),
});
const { input } = makeInput();
await expect(useCase.handleTurn(input as any)).rejects.toThrow(/does not belong/);
// Nothing about the victim's session may be touched or streamed back.
expect(sessions.calls.createNewTurn).toHaveLength(0);
expect(llm.calls).toHaveLength(0);
});
it('rejects a turn on a session that does not exist', async () => {
const { useCase } = buildUseCase({ sessionOwnerPk: null });
const { input } = makeInput();
await expect(useCase.handleTurn(input as any)).rejects.toThrow(/not found/);
});
it('rejects an approval resume on a session the user does not own, before resolving interrupts', async () => {
const { useCase, llm } = buildUseCase({
sessionOwnerPk: 'someone-else',
hasPersistentCheckpointer: true,
pendingInterrupts: [{ id: 'int-1', count: 1, requests: [] }],
});
const { input } = makeInput({ prompt: '', approvalDecision: 'approve' });
// An attacker must not be able to approve a dangerous tool call pending in
// someone else's session.
await expect(useCase.handleTurn(input as any)).rejects.toThrow(/does not belong/);
expect(llm.getPendingInterruptsCalls).toHaveLength(0);
expect(llm.calls).toHaveLength(0);
});
it('allows a chat-surface turn whose session is shared with other linked users', async () => {
const { useCase, llm } = buildUseCase({
sessionOwnerPk: 'someone-else',
streamFor: () => streamOf(text('ok')),
});
const { input } = makeInput({ chatSurface: 'telegram' });
const result = await useCase.handleTurn(input as any);
expect(result.text).toBe('ok');
expect(llm.calls).toHaveLength(1);
});
it('rejects (does not swallow) an approval with no pending interrupt, after emitting turn-started', async () => {
const { useCase } = buildUseCase();
const { input, events } = makeInput({ prompt: '', approvalDecision: 'approve' });
// prepareTurn() runs BEFORE the try/catch in runAndPersistAgentResponse, so — unlike an
// LLM failure during streaming — this error propagates out of handleTurn instead of
// becoming a `failed` result. turn-started has already been emitted by then.
await expect(useCase.handleTurn(input as any)).rejects.toThrow('No pending approval interrupt');
expect(events.map((e) => e.type)).toEqual(['turn-started']);
});
});
describe('RunTurnUseCase.handleEditTurn', () => {
it('edits a non-first message: forks from the previous turn, truncates, and persists to the same turn', async () => {
const { useCase, llm, sessions } = buildUseCase({
turnCheckpointsEnabled: true,
latestCheckpointId: 'cp-new',
agentTurns: [
{ id: 't1', prompt: 'p1', response: 'r1', checkpointId: 'cp1' },
{ id: 't2', prompt: 'p2', response: 'r2', checkpointId: 'cp2' },
],
streamFor: () => streamOf(text('New answer')),
});
const { input, events } = makeInput({ turnId: 't2', prompt: 'edited prompt' });
const result = await useCase.handleEditTurn(input as any);
expect(events.map((e) => e.type)).toEqual(['turn-started', 'turn-persisted', 'text-delta', 'response', 'finish']);
// Forks from the PREVIOUS turn's checkpoint, not the edited one.
expect(llm.calls).toHaveLength(1);
expect(llm.calls[0].branchFromCheckpointId).toBe('cp1');
expect('messages' in llm.calls[0].input).toBe(true);
expect(llm.resetThreadCalls).toHaveLength(0);
// Truncates + rewrites the edited turn (reusing its id, no new turn created).
expect(sessions.calls.editTurnAndTruncateAfter).toEqual([
{ sessionId: 's1', turnId: 't2', newPrompt: 'edited prompt' },
]);
expect(sessions.calls.createNewTurn).toHaveLength(0);
expect(result).toMatchObject({ turnId: 't2', text: 'New answer', aborted: false, failed: false });
// Records the new tip checkpoint on the edited turn.
expect(sessions.calls.saveTurnResponse[0]).toMatchObject({
turnId: 't2',
responseText: 'New answer',
checkpointId: 'cp-new',
});
});
it('editing the first message resets the thread instead of forking', async () => {
const { useCase, llm, sessions } = buildUseCase({
turnCheckpointsEnabled: true,
agentTurns: [{ id: 't1', prompt: 'p1', response: 'r1', checkpointId: 'cp1' }],
streamFor: () => streamOf(text('Fresh')),
});
const { input } = makeInput({ turnId: 't1', prompt: 'edited first' });
await useCase.handleEditTurn(input as any);
expect(llm.resetThreadCalls).toHaveLength(1);
expect(llm.calls[0].branchFromCheckpointId).toBeUndefined();
expect(sessions.calls.editTurnAndTruncateAfter[0].turnId).toBe('t1');
});
it('rejects an edit when the previous turn has no stored checkpoint', async () => {
const { useCase } = buildUseCase({
turnCheckpointsEnabled: true,
agentTurns: [
{ id: 't1', prompt: 'p1', response: 'r1', checkpointId: null },
{ id: 't2', prompt: 'p2', response: 'r2', checkpointId: 'cp2' },
],
});
const { input, events } = makeInput({ turnId: 't2', prompt: 'x' });
await expect(useCase.handleEditTurn(input as any)).rejects.toThrow(/no stored checkpoint/i);
expect(events.map((e) => e.type)).toEqual(['turn-started']);
});
it('rejects an edit when checkpointIdField is not configured', async () => {
const { useCase } = buildUseCase({
turnCheckpointsEnabled: false,
agentTurns: [
{ id: 't1', prompt: 'p1', response: 'r1', checkpointId: null },
{ id: 't2', prompt: 'p2', response: 'r2', checkpointId: null },
],
});
const { input } = makeInput({ turnId: 't2', prompt: 'x' });
await expect(useCase.handleEditTurn(input as any)).rejects.toThrow(/checkpointIdField/);
});
it('rejects an edit on a session the user does not own', async () => {
const { useCase } = buildUseCase({
turnCheckpointsEnabled: true,
sessionOwnerPk: 'someone-else',
agentTurns: [
{ id: 't1', prompt: 'p1', response: 'r1', checkpointId: 'cp1' },
{ id: 't2', prompt: 'p2', response: 'r2', checkpointId: 'cp2' },
],
});
const { input } = makeInput({ turnId: 't2', prompt: 'x' });
await expect(useCase.handleEditTurn(input as any)).rejects.toThrow(/does not belong/);
});
});
describe('buildResumeValue', () => {
it('fans a single approval across the recorded interrupt count', () => {
expect(buildResumeValue({ decision: 'approve', interrupts: [{ id: 'a', count: 2 }] })).toEqual({
decisions: [{ type: 'approve' }, { type: 'approve' }],
});
});
it('keys resume payloads by interrupt id when there are multiple', () => {
const value = buildResumeValue({
decision: 'reject',
interrupts: [{ id: 'a', count: 1 }, { id: 'b', count: 1 }],
prompt: 'do this instead',
}) as Record<string, any>;
expect(Object.keys(value)).toEqual(['a', 'b']);
expect(value.a.decisions[0]).toMatchObject({ type: 'reject' });
expect(value.a.decisions[0].message).toContain('do this instead');
});
it('throws when there is no interrupt to resume', () => {
expect(() => buildResumeValue({ decision: 'approve', interrupts: [] })).toThrow('No pending approval interrupt');
});
});
// A pending approval leaves the provider thread holding a tool call with no result. If a
// new message were simply appended, the provider would reject the whole thread ("No tool
// output found for function call ..."), which is unrecoverable for the session. Sending a
// message means the user moved on, so the pending call must be rejected with it.
describe('RunTurnUseCase — a new message while an approval is pending', () => {
it('rejects the pending call and carries the new prompt in the rejection', async () => {
const { useCase, llm, sessions } = buildUseCase({
streamFor: (call) =>
call === 1
? streamOf(interrupt([{ id: 'int-1', value: {} }]))
: streamOf(text('ok')),
});
await useCase.handleTurn(makeInput().input as any);
await useCase.handleTurn(makeInput({ prompt: 'never mind, do X instead' }).input as any);
expect(llm.calls[1].input.resume).toEqual({
decisions: [{
type: 'reject',
message: expect.stringContaining('never mind, do X instead'),
}],
});
// The prompt still gets its own turn, so the conversation history stays complete.
expect(sessions.calls.createNewTurn).toHaveLength(2);
expect(sessions.calls.createNewTurn[1]).toEqual({ sessionId: 's1', prompt: 'never mind, do X instead' });
expect(sessions.calls.getResumeState).toBe(0);
});
it('reads the pending call from the checkpoint (page reloaded, or another instance)', async () => {
const { useCase, llm, sessions } = buildUseCase({
hasPersistentCheckpointer: true,
pendingInterrupts: [{ id: 'int-1', count: 2, requests: [] }],
streamFor: () => streamOf(text('ok')),
});
await useCase.handleTurn(makeInput({ prompt: 'forget it' }).input as any);
// Nothing is cached in this process, yet the orphan tool call must still be answered —
// one decision per pending call.
expect(llm.calls[0].input.resume.decisions).toHaveLength(2);
expect(sessions.calls.createNewTurn).toHaveLength(1);
});
it('detects the language of the new prompt (it is a real user message, not a resume)', async () => {
const { useCase, llm } = buildUseCase({
hasPersistentCheckpointer: true,
pendingInterrupts: [{ id: 'int-1', count: 1, requests: [] }],
detectedLanguage: { language: 'Ukrainian', code: 'UK', ambiguous: false },
streamFor: () => streamOf(text('ok')),
});
await useCase.handleTurn(makeInput({ prompt: 'забудь' }).input as any);
expect(llm.detectLanguageCalls).toHaveLength(1);
expect(llm.calls[0].context.userLanguage).toEqual({
language: 'Ukrainian',
code: 'UK',
ambiguous: false,
});
});
it('starts an ordinary turn when nothing is pending', async () => {
const { useCase, llm } = buildUseCase({
hasPersistentCheckpointer: true,
pendingInterrupts: [],
streamFor: () => streamOf(text('ok')),
});
await useCase.handleTurn(makeInput().input as any);
expect('messages' in llm.calls[0].input).toBe(true);
});
});
// The approval prompt lives only in the browser, so a client that (re)loads a conversation
// has to be able to rebuild it from the agent's persisted state.
describe('RunTurnUseCase.getPendingApprovals', () => {
it('describes the pending tool calls in plain language', async () => {
const { useCase } = buildUseCase({
hasPersistentCheckpointer: true,
pendingInterrupts: [{
id: 'int-1',
count: 1,
requests: [{ toolName: 'delete_record', args: { resourceId: 'cars', primaryKey: '10' } }],
}],
});
expect(await useCase.getPendingApprovals('s1')).toEqual([
'Delete record with id:10 from cars — this cannot be undone',
]);
});
it('is empty when nothing is pending', async () => {
const { useCase } = buildUseCase({ hasPersistentCheckpointer: true, pendingInterrupts: [] });
expect(await useCase.getPendingApprovals('s1')).toEqual([]);
});
it('does not fail the conversation load when the checkpoint store is unavailable', async () => {
const { useCase } = buildUseCase({
hasPersistentCheckpointer: true,
pendingInterruptsError: new Error('checkpoint DB unavailable'),
});
// Unlike a resume, this is a read for display: the user still gets their history, and
// the implicit reject in `prepareTurn` keeps the session recoverable.
expect(await useCase.getPendingApprovals('s1')).toEqual([]);
});
});