File size: 10,431 Bytes
739fc44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * Integration tests for the browser agent.
 *
 * These tests verify the complete end-to-end flow from CLI prompt through
 * browser_agent delegation to MCP/Chrome DevTools and back. Unlike the unit
 * tests in packages/core/src/agents/browser/ which mock all MCP components,
 * these tests launch real Chrome instances in headless mode.
 *
 * Tests are skipped on systems without Chrome/Chromium installed.
 */

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { TestRig, assertModelHasOutput } from './test-helper.js';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execSync } from 'node:child_process';
import { existsSync } from 'node:fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const chromeAvailable = (() => {
  try {
    if (process.platform === 'darwin') {
      execSync(
        'test -d "/Applications/Google Chrome.app"  || test -d "/Applications/Chromium.app"',
        {
          stdio: 'ignore',
        },
      );
    } else if (process.platform === 'linux') {
      execSync(
        'which google-chrome || which chromium-browser || which chromium',
        { stdio: 'ignore' },
      );
    } else if (process.platform === 'win32') {
      // Check standard Windows installation paths using Node.js fs
      const chromePaths = [
        'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
        `${process.env['LOCALAPPDATA'] ?? ''}\\Google\\Chrome\\Application\\chrome.exe`,
      ];
      const found = chromePaths.some((p) => existsSync(p));
      if (!found) {
        // Fall back to PATH check
        execSync('where chrome || where chromium', { stdio: 'ignore' });
      }
    } else {
      return false;
    }
    return true;
  } catch {
    return false;
  }
})();

describe.skipIf(!chromeAvailable)('browser-agent', () => {
  let rig: TestRig;

  beforeEach(() => {
    rig = new TestRig();
  });

  afterEach(async () => await rig.cleanup());

  it('should navigate to a page and capture accessibility tree', async () => {
    rig.setup('browser-navigate-and-snapshot', {
      fakeResponsesPath: join(
        __dirname,
        'browser-agent.navigate-snapshot.responses',
      ),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
          },
        },
      },
    });

    const result = await rig.run({
      args: 'Open https://example.com in the browser and tell me the page title and main content.',
    });

    assertModelHasOutput(result);

    const toolLogs = rig.readToolLogs();
    const browserAgentCall = toolLogs.find(
      (t) =>
        t.toolRequest.name === 'invoke_agent' &&
        JSON.parse(t.toolRequest.args).agent_name === 'browser_agent',
    );
    expect(
      browserAgentCall,
      'Expected browser_agent to be called',
    ).toBeDefined();
  });

  it('should take screenshots of web pages', async () => {
    rig.setup('browser-screenshot', {
      fakeResponsesPath: join(__dirname, 'browser-agent.screenshot.responses'),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
          },
        },
      },
    });

    const result = await rig.run({
      args: 'Navigate to https://example.com and take a screenshot.',
    });

    const toolLogs = rig.readToolLogs();
    const browserCalls = toolLogs.filter(
      (t) =>
        t.toolRequest.name === 'invoke_agent' &&
        JSON.parse(t.toolRequest.args).agent_name === 'browser_agent',
    );
    expect(browserCalls.length).toBeGreaterThan(0);

    assertModelHasOutput(result);
  });

  it('should interact with page elements', async () => {
    rig.setup('browser-interaction', {
      fakeResponsesPath: join(__dirname, 'browser-agent.interaction.responses'),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
          },
        },
      },
    });

    const result = await rig.run({
      args: 'Go to https://example.com, find any links on the page, and describe them.',
    });

    const toolLogs = rig.readToolLogs();
    const browserAgentCall = toolLogs.find(
      (t) =>
        t.toolRequest.name === 'invoke_agent' &&
        JSON.parse(t.toolRequest.args).agent_name === 'browser_agent',
    );
    expect(
      browserAgentCall,
      'Expected browser_agent to be called',
    ).toBeDefined();

    assertModelHasOutput(result);
  });

  it('should clean up browser processes after completion', async () => {
    rig.setup('browser-cleanup', {
      fakeResponsesPath: join(__dirname, 'browser-agent.cleanup.responses'),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
          },
        },
      },
    });

    await rig.run({
      args: 'Open https://example.com in the browser and check the page title.',
    });

    // Test passes if we reach here, relying on Vitest's timeout mechanism
    // to detect hanging browser processes.
  });

  it('should handle multiple browser operations in sequence', async () => {
    rig.setup('browser-sequential', {
      fakeResponsesPath: join(__dirname, 'browser-agent.sequential.responses'),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
          },
        },
      },
    });

    const result = await rig.run({
      args: 'Navigate to https://example.com, take a snapshot of the accessibility tree, then take a screenshot.',
    });

    const toolLogs = rig.readToolLogs();
    const browserCalls = toolLogs.filter(
      (t) =>
        t.toolRequest.name === 'invoke_agent' &&
        JSON.parse(t.toolRequest.args).agent_name === 'browser_agent',
    );
    expect(browserCalls.length).toBeGreaterThan(0);

    // Should successfully complete all operations
    assertModelHasOutput(result);
  });

  it('should keep browser open across multiple browser_agent invocations', async () => {
    rig.setup('browser-persistent-session', {
      fakeResponsesPath: join(
        __dirname,
        'browser-agent.persistent-session.responses',
      ),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
            allowedDomains: ['example.com'],
          },
        },
      },
    });

    const result = await rig.run({
      args: 'First, ask the browser agent to get the page title of example.com. After you receive that response, you MUST invoke the browser agent a second time to check for links on the page.',
    });

    const toolLogs = rig.readToolLogs();
    const browserCalls = toolLogs.filter(
      (t) =>
        t.toolRequest.name === 'invoke_agent' &&
        JSON.parse(t.toolRequest.args).agent_name === 'browser_agent',
    );

    // Both browser_agent invocations must succeed — if the browser was
    // incorrectly closed after the first call (regression #24210),
    // the second call would fail.
    expect(
      browserCalls.length,
      'Expected browser_agent to be called twice',
    ).toBe(2);
    expect(
      browserCalls.every((c) => c.toolRequest.success),
      'Both browser_agent calls should succeed',
    ).toBe(true);

    assertModelHasOutput(result);
  });

  it('should handle tool confirmation for write_file without crashing', async () => {
    rig.setup('tool-confirmation', {
      fakeResponsesPath: join(
        __dirname,
        'browser-agent.confirmation.responses',
      ),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            sessionMode: 'isolated',
          },
        },
      },
    });

    const run = await rig.runInteractive({ approvalMode: 'default' });

    await run.type('Write hello to test.txt');
    await run.type('\r');

    await run.expectText('Allow', 15000);

    await run.type('y');
    await run.type('\r');

    await run.expectText('successfully written', 15000);
  });

  it('should handle concurrent browser agents with isolated session mode', async () => {
    rig.setup('browser-concurrent', {
      fakeResponsesPath: join(__dirname, 'browser-agent.concurrent.responses'),
      settings: {
        agents: {
          overrides: {
            browser_agent: {
              enabled: true,
            },
          },
          browser: {
            headless: true,
            // Isolated mode supports concurrent browser agents.
            // Persistent/existing modes reject concurrent calls to prevent
            // Chrome profile lock conflicts.
            sessionMode: 'isolated',
          },
        },
      },
    });

    const result = await rig.run({
      args: 'Launch two browser agents concurrently to check example.com',
    });

    assertModelHasOutput(result);

    const toolLogs = rig.readToolLogs();
    const browserCalls = toolLogs.filter(
      (t) =>
        t.toolRequest.name === 'invoke_agent' &&
        JSON.parse(t.toolRequest.args).agent_name === 'browser_agent',
    );

    // Both browser_agent invocations should have been called
    expect(browserCalls.length).toBe(2);

    // Both should complete successfully (no errors)
    for (const call of browserCalls) {
      expect(
        call.toolRequest.success,
        `browser_agent call failed: ${JSON.stringify(call.toolRequest)}`,
      ).toBe(true);
    }
  });
});