File size: 24,726 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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { BrowserAgentInvocation } from './browserAgentInvocation.js';
import { makeFakeConfig } from '../../test-utils/config.js';
import type { Config } from '../../config/config.js';
import type { MessageBus } from '../../confirmation-bus/message-bus.js';
import {
  type AgentInputs,
  type SubagentProgress,
  type SubagentActivityEvent,
} from '../types.js';

// Mock dependencies before imports
vi.mock('../../utils/debugLogger.js', () => ({
  debugLogger: {
    log: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
  },
}));

vi.mock('./browserAgentFactory.js', () => ({
  createBrowserAgentDefinition: vi.fn(),
  cleanupBrowserAgent: vi.fn(),
}));

vi.mock('./inputBlocker.js', () => ({
  removeInputBlocker: vi.fn(),
}));

vi.mock('./automationOverlay.js', () => ({
  removeAutomationOverlay: vi.fn(),
}));

vi.mock('../../telemetry/metrics.js', () => ({
  recordBrowserAgentTaskOutcome: vi.fn(),
}));

vi.mock('../local-executor.js', () => ({
  LocalAgentExecutor: {
    create: vi.fn(),
  },
}));

import {
  createBrowserAgentDefinition,
  cleanupBrowserAgent,
} from './browserAgentFactory.js';
import { removeInputBlocker } from './inputBlocker.js';
import { removeAutomationOverlay } from './automationOverlay.js';
import { LocalAgentExecutor } from '../local-executor.js';
import { recordBrowserAgentTaskOutcome } from '../../telemetry/metrics.js';
import type { ToolLiveOutput } from '../../tools/tools.js';

describe('BrowserAgentInvocation', () => {
  let mockConfig: Config;
  let mockMessageBus: MessageBus;
  let mockParams: AgentInputs;

  beforeEach(() => {
    vi.clearAllMocks();

    mockConfig = makeFakeConfig({
      agents: {
        overrides: {
          browser_agent: {
            enabled: true,
          },
        },
        browser: {
          headless: false,
          sessionMode: 'isolated',
        },
      },
    });

    mockMessageBus = {
      publish: vi.fn().mockResolvedValue(undefined),
      subscribe: vi.fn(),
      unsubscribe: vi.fn(),
    } as unknown as MessageBus;

    mockParams = {
      task: 'Navigate to example.com and click the button',
    };
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe('constructor', () => {
    it('should create invocation with params', () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

      expect(invocation.params).toEqual(mockParams);
    });

    it('should use browser_agent as default tool name', () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

      expect(invocation['_toolName']).toBe('browser_agent');
    });

    it('should use custom tool name if provided', () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
        'custom_name',
        'Custom Display Name',
      );

      expect(invocation['_toolName']).toBe('custom_name');
      expect(invocation['_toolDisplayName']).toBe('Custom Display Name');
    });
  });

  describe('getDescription', () => {
    it('should return description with input summary', () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

      const description = invocation.getDescription();

      expect(description).toContain('browser agent');
      expect(description).toContain('task');
    });

    it('should truncate long input values', () => {
      const longParams = {
        task: 'A'.repeat(100),
      };

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        longParams,
        mockMessageBus,
      );

      const description = invocation.getDescription();

      // Should be truncated to max length
      expect(description.length).toBeLessThanOrEqual(200);
    });
  });

  describe('toolLocations', () => {
    it('should return empty array by default', () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

      const locations = invocation.toolLocations();

      expect(locations).toEqual([]);
    });
  });

  describe('execute', () => {
    let mockExecutor: { run: ReturnType<typeof vi.fn> };

    beforeEach(() => {
      vi.mocked(createBrowserAgentDefinition).mockResolvedValue({
        definition: {
          name: 'browser_agent',
          description: 'mock definition',
          kind: 'local',
          inputConfig: {} as never,
          outputConfig: {} as never,
          processOutput: () => '',
          modelConfig: { model: 'test' },
          runConfig: {},
          promptConfig: { query: '', systemPrompt: '' },
          toolConfig: { tools: ['analyze_screenshot', 'click'] },
        },
        browserManager: {
          release: vi.fn(),
          callTool: vi.fn().mockResolvedValue({ content: [] }),
        } as never,
        visionEnabled: true,
        sessionMode: 'persistent',
      });

      mockExecutor = {
        run: vi.fn().mockResolvedValue({
          result: JSON.stringify({ success: true }),
          terminate_reason: 'GOAL',
        }),
      };

      vi.mocked(LocalAgentExecutor.create).mockResolvedValue(
        mockExecutor as never,
      );
      vi.mocked(removeInputBlocker).mockClear();
    });

    it('should return result text and call cleanup on success', async () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

      const controller = new AbortController();
      const updateOutput: (output: ToolLiveOutput) => void = vi.fn();

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

      expect(Array.isArray(result.llmContent)).toBe(true);
      expect((result.llmContent as Array<{ text: string }>)[0].text).toContain(
        'Browser agent finished',
      );
      expect(removeInputBlocker).toHaveBeenCalled();
    });

    it('should work without updateOutput (fire-and-forget)', async () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

      const controller = new AbortController();
      // Should not throw even with no updateOutput
      await expect(
        invocation.execute({ abortSignal: controller.signal }),
      ).resolves.toBeDefined();
    });

    it('should return error result when executor throws', async () => {
      mockExecutor.run.mockRejectedValue(new Error('Unexpected crash'));

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      expect(result.error).toBeDefined();
      expect(removeInputBlocker).toHaveBeenCalled();
    });

    // ─── Structured SubagentProgress emission tests ───────────────────────

    /**
     * Helper: sets up LocalAgentExecutor.create to capture the onActivity
     * callback so tests can fire synthetic activity events.
     */
    function setupActivityCapture(): {
      capturedOnActivity: () => SubagentActivityEvent | undefined;
      fireActivity: (event: SubagentActivityEvent) => void;
    } {
      let onActivityFn: ((e: SubagentActivityEvent) => void) | undefined;

      vi.mocked(LocalAgentExecutor.create).mockImplementation(
        async (_def, _config, onActivity) => {
          onActivityFn = onActivity;
          return mockExecutor as never;
        },
      );

      return {
        capturedOnActivity: () => undefined,
        fireActivity: (event: SubagentActivityEvent) => {
          onActivityFn?.(event);
        },
      };
    }

    it('should emit initial SubagentProgress with running state', async () => {
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      const firstCall = updateOutput.mock.calls[0]?.[0] as SubagentProgress;
      expect(firstCall.isSubagentProgress).toBe(true);
      expect(firstCall.state).toBe('running');
      expect(firstCall.recentActivity).toEqual([]);
    });

    it('should emit completed SubagentProgress on success', async () => {
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      const lastCall = updateOutput.mock.calls[
        updateOutput.mock.calls.length - 1
      ]?.[0] as SubagentProgress;
      expect(lastCall.isSubagentProgress).toBe(true);
      expect(lastCall.state).toBe('completed');
    });

    it('should handle THOUGHT_CHUNK and emit structured progress', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      // Allow createBrowserAgentDefinition to resolve and onActivity to be registered
      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'THOUGHT_CHUNK',
        data: { text: 'Navigating to the page...' },
      });

      await executePromise;

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

      const thoughtProgress = progressCalls.find((p) =>
        p.recentActivity.some(
          (a) =>
            a.type === 'thought' &&
            a.content.includes('Navigating to the page...'),
        ),
      );

      expect(thoughtProgress).toBeDefined();
    });

    it('should overwrite the thought content with new THOUGHT_CHUNK activity', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      // Allow createBrowserAgentDefinition to resolve and onActivity to be registered
      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'THOUGHT_CHUNK',
        data: { text: 'I am thinking.' },
      });
      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'THOUGHT_CHUNK',
        data: { text: 'Now I will act.' },
      });

      await executePromise;

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

      const lastCall = progressCalls[progressCalls.length - 1];
      expect(lastCall.recentActivity).toContainEqual(
        expect.objectContaining({
          type: 'thought',
          content: 'Now I will act.',
        }),
      );
    });

    it('should handle TOOL_CALL_START and TOOL_CALL_END with callId tracking', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'TOOL_CALL_START',
        data: {
          name: 'navigate_browser',
          callId: 'call-1',
          args: { url: 'https://example.com' },
        },
      });

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'TOOL_CALL_END',
        data: { name: 'navigate_browser', id: 'call-1' },
      });

      await executePromise;

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

      // After TOOL_CALL_END, the tool should be completed
      const finalProgress = progressCalls[progressCalls.length - 1];
      const toolItem = finalProgress?.recentActivity.find(
        (a) => a.type === 'tool_call' && a.content === 'navigate_browser',
      );
      expect(toolItem).toBeDefined();
      expect(toolItem?.status).toBe('completed');
    });

    it('should sanitize sensitive data in tool call args', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'TOOL_CALL_START',
        data: {
          name: 'fill_form',
          callId: 'call-2',
          args: { password: 'supersecret123', url: 'https://example.com' },
        },
      });

      await executePromise;

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

      const toolItem = progressCalls
        .flatMap((p) => p.recentActivity)
        .find((a) => a.type === 'tool_call' && a.content === 'fill_form');

      expect(toolItem).toBeDefined();
      expect(toolItem?.args).not.toContain('supersecret123');
      expect(toolItem?.args).toContain('[REDACTED]');
    });

    it('should handle ERROR event with callId and mark tool as errored', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'TOOL_CALL_START',
        data: { name: 'click_element', callId: 'call-3', args: {} },
      });

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'ERROR',
        data: { error: 'Element not found', callId: 'call-3' },
      });

      await executePromise;

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

      const allItems = progressCalls.flatMap((p) => p.recentActivity);
      const toolItem = allItems.find(
        (a) => a.type === 'tool_call' && a.content === 'click_element',
      );
      expect(toolItem?.status).toBe('error');
    });

    it('should sanitize sensitive data in ERROR event messages', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'ERROR',
        data: { error: 'Auth failed: api_key=sk-secret-abc1234567890' },
      });

      await executePromise;

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

      const errorItem = progressCalls
        .flatMap((p) => p.recentActivity)
        .find((a) => a.type === 'thought' && a.status === 'error');

      expect(errorItem).toBeDefined();
      expect(errorItem?.content).not.toContain('sk-secret-abc1234567890');
      expect(errorItem?.content).toContain('[REDACTED]');
    });

    it('should sanitize inline PEM content in error messages', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'ERROR',
        data: {
          error:
            'Failed to authenticate:\n-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA12345...\n-----END RSA PRIVATE KEY-----\nPlease check credentials.',
        },
      });

      await executePromise;

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

      const errorItem = progressCalls
        .flatMap((p) => p.recentActivity)
        .find((a) => a.type === 'thought' && a.status === 'error');

      expect(errorItem).toBeDefined();
      expect(errorItem?.content).toContain('[REDACTED_PEM]');
      expect(errorItem?.content).not.toContain('-----BEGIN');
    });

    it('should mark all running tools as errored when ERROR has no callId', async () => {
      const { fireActivity } = setupActivityCapture();
      const updateOutput = vi.fn();

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      await Promise.resolve();
      await Promise.resolve();

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'TOOL_CALL_START',
        data: { name: 'tool_a', callId: 'c1', args: {} },
      });

      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'TOOL_CALL_START',
        data: { name: 'tool_b', callId: 'c2', args: {} },
      });

      // ERROR with no callId should mark ALL running tools as error
      fireActivity({
        isSubagentActivityEvent: true,
        agentName: 'browser_agent',
        type: 'ERROR',
        data: { error: 'Agent crashed' },
      });

      await executePromise;

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

      const finalActivity =
        progressCalls[progressCalls.length - 1].recentActivity;
      const toolA = finalActivity.find(
        (a) => a.type === 'tool_call' && a.content === 'tool_a',
      );
      const toolB = finalActivity.find(
        (a) => a.type === 'tool_call' && a.content === 'tool_b',
      );

      // Both should be error since no callId was specified
      expect(toolA?.status).toBe('error');
      expect(toolB?.status).toBe('error');
    });

    it('should record successful task outcome metrics', async () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );
      await invocation.execute({
        abortSignal: new AbortController().signal,
        updateOutput: vi.fn(),
      });

      expect(recordBrowserAgentTaskOutcome).toHaveBeenCalledWith(
        mockConfig,
        expect.objectContaining({
          success: true,
          session_mode: 'persistent',
          vision_enabled: true,
          headless: false,
          duration_ms: expect.any(Number),
        }),
      );
    });

    it('should record failed task outcome metrics', async () => {
      vi.mocked(LocalAgentExecutor.create).mockResolvedValue({
        run: vi.fn().mockResolvedValue({
          result: JSON.stringify({ success: false, foo: 'bar' }),
        }),
      } as never);

      const updateOutput = vi.fn();
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );

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

      expect(recordBrowserAgentTaskOutcome).toHaveBeenCalledWith(
        mockConfig,
        expect.objectContaining({
          success: false,
          session_mode: 'persistent',
          vision_enabled: true,
          headless: false,
          duration_ms: expect.any(Number),
        }),
      );
    });

    it('should not call cleanupBrowserAgent (cleanup is handled by BrowserManager.resetAll)', async () => {
      const invocation = new BrowserAgentInvocation(
        mockConfig,
        mockParams,
        mockMessageBus,
      );
      await invocation.execute({
        abortSignal: new AbortController().signal,
        updateOutput: vi.fn(),
      });

      expect(cleanupBrowserAgent).not.toHaveBeenCalled();
    });
  });

  describe('cleanup', () => {
    it('should clean up all pages on finally', async () => {
      const mockBrowserManager = {
        callTool: vi.fn().mockImplementation(async (toolName: string) => {
          if (toolName === 'list_pages') {
            return {
              content: [{ type: 'text', text: '0: Page 1\n1: Page 2\n' }],
              isError: false,
            };
          }
          return { isError: false };
        }),
        release: vi.fn(),
      };

      vi.mocked(createBrowserAgentDefinition).mockResolvedValue({
        definition: {
          name: 'browser_agent',
          description: 'mock definition',
          kind: 'local',
          inputConfig: {} as never,
          outputConfig: {} as never,
          processOutput: () => '',
          modelConfig: { model: 'test' },
          runConfig: {},
          promptConfig: { query: '', systemPrompt: '' },
          toolConfig: { tools: [] },
        },
        browserManager: mockBrowserManager as never,
        visionEnabled: true,
        sessionMode: 'persistent',
      });

      const mockExecutor = {
        run: vi.fn().mockResolvedValue({
          result: JSON.stringify({ success: true }),
          terminate_reason: 'GOAL',
        }),
      };

      vi.mocked(LocalAgentExecutor.create).mockResolvedValue(
        mockExecutor as never,
      );

      const invocation = new BrowserAgentInvocation(
        mockConfig,
        { task: 'test' },
        mockMessageBus,
      );

      await invocation.execute({ abortSignal: new AbortController().signal });

      // Verify list_pages was called
      expect(mockBrowserManager.callTool).toHaveBeenCalledWith(
        'list_pages',
        expect.anything(),
        expect.anything(),
        true,
      );

      // Verify select_page was called for each page
      expect(mockBrowserManager.callTool).toHaveBeenCalledWith(
        'select_page',
        { pageId: 0, bringToFront: false },
        expect.anything(),
        true,
      );
      expect(mockBrowserManager.callTool).toHaveBeenCalledWith(
        'select_page',
        { pageId: 1, bringToFront: false },
        expect.anything(),
        true,
      );

      // Verify removeInputBlocker and removeAutomationOverlay were called for each page + initial cleanup
      expect(removeInputBlocker).toHaveBeenCalledTimes(3);
      expect(removeAutomationOverlay).toHaveBeenCalledTimes(3);
    });
  });
});