File size: 25,370 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
  AgentTerminateMode,
  SubagentActivityErrorType,
  SUBAGENT_REJECTED_ERROR_PREFIX,
  SUBAGENT_CANCELLED_ERROR_MESSAGE,
  type SubagentProgress,
  type LocalAgentDefinition,
  type AgentInputs,
  type SubagentActivityEvent,
} from './types.js';
import { LocalSessionInvocation } from './local-session-invocation.js';
import { LocalSubagentSession } from './local-subagent-protocol.js';
import { makeFakeConfig } from '../test-utils/config.js';
import { createMockMessageBus } from '../test-utils/mock-message-bus.js';
import { MessageBusType } from '../confirmation-bus/types.js';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';

vi.mock('./local-subagent-protocol.js');

const MockLocalSubagentSession = vi.mocked(LocalSubagentSession);

let capturedActivityCallback:
  | ((activity: SubagentActivityEvent) => void)
  | undefined;

const testDefinition: LocalAgentDefinition = {
  kind: 'local',
  name: 'MockAgent',
  description: 'A mock agent for testing.',
  inputConfig: {
    inputSchema: {
      type: 'object',
      properties: { task: { type: 'string' } },
    },
  },
  modelConfig: { model: 'test-model', generateContentConfig: {} },
  runConfig: { maxTimeMinutes: 1 },
  promptConfig: { systemPrompt: 'test' },
};

function setupMockSession(config: {
  output?: { result: string; terminate_reason: AgentTerminateMode };
  error?: Error;
}) {
  const mockSession = {
    send: vi.fn().mockResolvedValue({ streamId: 'stream-1' }),
    getResult: config.error
      ? vi.fn().mockRejectedValue(config.error)
      : vi.fn().mockResolvedValue(
          config.output ?? {
            result: 'done',
            terminate_reason: AgentTerminateMode.GOAL,
          },
        ),
    abort: vi.fn(),
    subscribe: vi.fn().mockReturnValue(vi.fn()),
  };
  MockLocalSubagentSession.mockImplementation(
    (
      _def: LocalAgentDefinition,
      _ctx: AgentLoopContext,
      _bus: MessageBus,
      rawCallback?: (activity: SubagentActivityEvent) => void,
    ) => {
      capturedActivityCallback = rawCallback;
      return mockSession as unknown as LocalSubagentSession;
    },
  );
  return mockSession;
}

describe('LocalSessionInvocation', () => {
  let mockContext: AgentLoopContext;
  let mockMessageBus: MessageBus;

  beforeEach(() => {
    vi.clearAllMocks();
    capturedActivityCallback = undefined;
    mockContext = makeFakeConfig() as unknown as AgentLoopContext;
    mockMessageBus = createMockMessageBus();
  });

  it('should pass the messageBus to the parent constructor', () => {
    setupMockSession({});
    const params = { task: 'Analyze data' };
    const invocation = new LocalSessionInvocation(
      testDefinition,
      mockContext,
      params,
      mockMessageBus,
    );
    expect(
      (invocation as unknown as { messageBus: MessageBus }).messageBus,
    ).toBe(mockMessageBus);
  });

  describe('getDescription', () => {
    it('should format the description with inputs', () => {
      setupMockSession({});
      const params = { task: 'Analyze data', priority: 5 };
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );
      const description = invocation.getDescription();
      expect(description).toBe(
        "Running subagent 'MockAgent' with inputs: { task: Analyze data, priority: 5 }",
      );
    });

    it('should not truncate long input values', () => {
      setupMockSession({});
      const longTask = 'A'.repeat(100);
      const params = { task: longTask };
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );
      const description = invocation.getDescription();
      expect(description).toBe(
        `Running subagent 'MockAgent' with inputs: { task: ${'A'.repeat(100)} }`,
      );
    });

    it('should not truncate the overall description', () => {
      setupMockSession({});
      const longNameDef: LocalAgentDefinition = {
        ...testDefinition,
        name: 'VeryLongAgentNameThatTakesUpSpace',
      };
      const params: AgentInputs = {};
      for (let i = 0; i < 20; i++) {
        params[`input${i}`] = `value${i}`;
      }
      const invocation = new LocalSessionInvocation(
        longNameDef,
        mockContext,
        params,
        mockMessageBus,
      );
      const description = invocation.getDescription();
      expect(description.length).toBeGreaterThan(300);
    });
  });

  describe('execute', () => {
    it('should create session and run successfully', async () => {
      const mockOutput = {
        result: 'Analysis complete.',
        terminate_reason: AgentTerminateMode.GOAL,
      };
      const mockSession = setupMockSession({ output: mockOutput });
      const params = { query: 'Execute task' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const result = await invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      expect(MockLocalSubagentSession).toHaveBeenCalledWith(
        testDefinition,
        mockContext,
        mockMessageBus,
        expect.any(Function),
      );
      expect(mockSession.send).toHaveBeenCalledWith({
        message: { content: [{ type: 'text', text: 'Execute task' }] },
      });
      expect(result.llmContent).toEqual([
        {
          text: expect.stringContaining(
            "Subagent 'MockAgent' finished.\nTermination Reason: GOAL\nResult:\nAnalysis complete.",
          ),
        },
      ]);
      const display = result.returnDisplay as SubagentProgress;
      expect(display.isSubagentProgress).toBe(true);
      expect(display.state).toBe('completed');
      expect(display.result).toBe('Analysis complete.');
      expect(display.terminateReason).toBe(AgentTerminateMode.GOAL);
    });

    it('should stream THOUGHT_CHUNK activity', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'think' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      // Wait for send to be called so the activity callback is wired
      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      // Emit a thought chunk via captured callback
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'THOUGHT_CHUNK',
        data: { text: 'Analyzing...' },
      });

      await executePromise;

      // Find an updateOutput call containing the thought
      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      const hasThought = progressCalls.some(
        (p) =>
          p.recentActivity &&
          p.recentActivity.some(
            (a) => a.type === 'thought' && a.content === 'Analyzing...',
          ),
      );
      expect(hasThought).toBe(true);
    });

    it('should stream TOOL_CALL_START and TOOL_CALL_END', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'run tool' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'ls', args: {}, callId: 'call-123' },
      });
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_END',
        data: { name: 'ls', data: {}, id: 'call-123' },
      });

      await executePromise;

      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );

      // After TOOL_CALL_START, the immediate updateOutput call should show running
      const runningCalls = progressCalls.filter((p) => p.state === 'running');
      // The first running call with a tool_call should show 'running'
      const firstToolCall = runningCalls.find((p) =>
        p.recentActivity?.some(
          (a) => a.type === 'tool_call' && a.content === 'ls',
        ),
      );
      expect(firstToolCall).toBeDefined();

      // After TOOL_CALL_END, the tool should be completed
      const hasCompleted = progressCalls.some((p) =>
        p.recentActivity?.some(
          (a) =>
            a.type === 'tool_call' &&
            a.content === 'ls' &&
            a.status === 'completed',
        ),
      );
      expect(hasCompleted).toBe(true);
    });

    it('should handle ERROR activity', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'fail' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'ERROR',
        data: { error: 'Something broke' },
      });

      await executePromise;

      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      const hasError = progressCalls.some((p) =>
        p.recentActivity?.some(
          (a) =>
            a.type === 'thought' &&
            a.content === 'Error: Something broke' &&
            a.status === 'error',
        ),
      );
      expect(hasError).toBe(true);
    });

    it('should handle cancelled errors', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'cancel' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'ERROR',
        data: {
          error: SUBAGENT_CANCELLED_ERROR_MESSAGE,
          errorType: SubagentActivityErrorType.CANCELLED,
        },
      });

      await executePromise;

      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      const hasCancelled = progressCalls.some((p) =>
        p.recentActivity?.some(
          (a) => a.type === 'thought' && a.status === 'cancelled',
        ),
      );
      expect(hasCancelled).toBe(true);
    });

    it('should handle rejected errors', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'reject' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'dangerous_tool', args: {}, callId: 'call-rej' },
      });
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'ERROR',
        data: {
          name: 'dangerous_tool',
          error: `${SUBAGENT_REJECTED_ERROR_PREFIX} Rethink approach.`,
          errorType: SubagentActivityErrorType.REJECTED,
          callId: 'call-rej',
        },
      });

      await executePromise;

      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      // Tool call should be marked cancelled
      const hasToolCancelled = progressCalls.some((p) =>
        p.recentActivity?.some(
          (a) =>
            a.type === 'tool_call' &&
            a.content === 'dangerous_tool' &&
            a.status === 'cancelled',
        ),
      );
      expect(hasToolCancelled).toBe(true);
    });

    it('should trim recentActivity to MAX_RECENT_ACTIVITY', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'trim' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      // Emit 4+ activities to exceed MAX_RECENT_ACTIVITY (3)
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'tool1', args: {} },
      });
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'tool2', args: {} },
      });
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'tool3', args: {} },
      });
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'tool4', args: {} },
      });

      await executePromise;

      // After the 4th activity, the last updateOutput call before completion
      // should have only 3 items in recentActivity
      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      // Find the call right after the 4th activity (before completion)
      const afterFourthActivity = progressCalls.filter(
        (p) => p.state === 'running' && p.recentActivity.length > 0,
      );
      const lastRunning = afterFourthActivity[afterFourthActivity.length - 1];
      expect(lastRunning.recentActivity.length).toBeLessThanOrEqual(3);
      // Should contain tool4 (the latest)
      expect(
        lastRunning.recentActivity.some((a) => a.content === 'tool4'),
      ).toBe(true);
      // Should NOT contain tool1 (trimmed away)
      expect(
        lastRunning.recentActivity.some((a) => a.content === 'tool1'),
      ).toBe(false);
    });

    it('should handle executor errors', async () => {
      const error = new Error('Model failed during execution.');
      setupMockSession({ error });
      const params = { query: 'fail hard' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const result = await invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      expect(result.llmContent).toBe(
        `Subagent 'MockAgent' failed. Error: ${error.message}`,
      );
      const display = result.returnDisplay as SubagentProgress;
      expect(display.isSubagentProgress).toBe(true);
      expect(display.state).toBe('error');
      expect(display.recentActivity).toContainEqual(
        expect.objectContaining({
          type: 'thought',
          content: `Error: ${error.message}`,
          status: 'error',
        }),
      );
    });

    it('should handle abort', async () => {
      const mockOutput = {
        result: '',
        terminate_reason: AgentTerminateMode.ABORTED,
      };
      setupMockSession({ output: mockOutput });
      const params = { query: 'abort me' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      await expect(
        invocation.execute({ abortSignal: signal, updateOutput }),
      ).rejects.toThrow('Operation cancelled by user');

      // Verify cancelled state was published
      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      const hasCancelledState = progressCalls.some(
        (p) => p.state === 'cancelled',
      );
      expect(hasCancelledState).toBe(true);
    });

    it('should wire abort signal to session.abort', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'abort wire' };
      const controller = new AbortController();
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: controller.signal,
        updateOutput,
      });

      // Trigger abort
      controller.abort();

      // The execute should complete (getResult returned GOAL by default)
      await executePromise.catch(() => {
        /* abort may throw */
      });

      expect(mockSession.abort).toHaveBeenCalled();
    });

    it('should send non-query params as config update before query', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'Do something', extra_config: 'value123' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      await invocation.execute({ abortSignal: signal, updateOutput });

      // First send: config update with non-query params
      expect(mockSession.send).toHaveBeenCalledWith({
        update: { config: { extra_config: 'value123' } },
      });
      // Second send: message with query
      expect(mockSession.send).toHaveBeenCalledWith({
        message: { content: [{ type: 'text', text: 'Do something' }] },
      });
      // Config update should come before message
      const sendCalls = mockSession.send.mock.calls;
      const configIdx = sendCalls.findIndex((c) => c[0]?.update?.config);
      const messageIdx = sendCalls.findIndex((c) => c[0]?.message);
      expect(configIdx).toBeLessThan(messageIdx);
    });

    it('should publish SUBAGENT_ACTIVITY on messageBus', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'publish test' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'THOUGHT_CHUNK',
        data: { text: 'Thinking...' },
      });

      await executePromise;

      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({
          type: MessageBusType.SUBAGENT_ACTIVITY,
          subagentName: 'MockAgent',
          activity: expect.objectContaining({
            type: 'thought',
            content: 'Thinking...',
          }),
        }),
      );
    });

    it('should clean up abort listener in finally', async () => {
      setupMockSession({});
      const params = { query: 'cleanup' };
      const controller = new AbortController();
      const removeEventListenerSpy = vi.spyOn(
        controller.signal,
        'removeEventListener',
      );
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      await invocation.execute({
        abortSignal: controller.signal,
        updateOutput,
      });

      expect(removeEventListenerSpy).toHaveBeenCalledWith(
        'abort',
        expect.any(Function),
      );
    });

    it('should unsubscribe parent observer in finally', async () => {
      const unsubscribeFn = vi.fn();
      const mockSession = setupMockSession({});
      mockSession.subscribe.mockReturnValue(unsubscribeFn);

      const params = { query: 'unsub test' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const onAgentEvent = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
        { onAgentEvent },
      );

      await invocation.execute({ abortSignal: signal, updateOutput });

      expect(mockSession.subscribe).toHaveBeenCalledWith(onAgentEvent);
      expect(unsubscribeFn).toHaveBeenCalled();
    });

    it('should handle TOOL_CALL_END with error data', async () => {
      const mockSession = setupMockSession({});
      const params = { query: 'tool error' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'failing_tool', args: {}, callId: 'call-err' },
      });
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_END',
        data: { name: 'failing_tool', data: { isError: true }, id: 'call-err' },
      });

      await executePromise;

      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      const hasToolError = progressCalls.some((p) =>
        p.recentActivity?.some(
          (a) =>
            a.type === 'tool_call' &&
            a.content === 'failing_tool' &&
            a.status === 'error',
        ),
      );
      expect(hasToolError).toBe(true);
    });

    it('should mark running items as cancelled on abort', async () => {
      const abortError = new Error('Aborted');
      abortError.name = 'AbortError';
      const mockSession = setupMockSession({ error: abortError });
      const params = { query: 'mark cancelled' };
      const signal = new AbortController().signal;
      const updateOutput = vi.fn();
      const invocation = new LocalSessionInvocation(
        testDefinition,
        mockContext,
        params,
        mockMessageBus,
      );

      const executePromise = invocation.execute({
        abortSignal: signal,
        updateOutput,
      });

      await vi.waitFor(() => expect(mockSession.send).toHaveBeenCalled());

      // Emit a running tool call before the abort
      capturedActivityCallback!({
        isSubagentActivityEvent: true,
        agentName: 'MockAgent',
        type: 'TOOL_CALL_START',
        data: { name: 'running_tool', args: {} },
      });

      await expect(executePromise).rejects.toThrow('Aborted');

      const progressCalls = updateOutput.mock.calls.map(
        (c) => c[0] as SubagentProgress,
      );
      // The final progress should show the tool as cancelled
      const lastProgress = progressCalls[progressCalls.length - 1];
      expect(lastProgress.state).toBe('cancelled');
      expect(lastProgress.recentActivity).toContainEqual(
        expect.objectContaining({
          type: 'tool_call',
          content: 'running_tool',
          status: 'cancelled',
        }),
      );
    });
  });
});