File size: 9,192 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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { createAnalyzeScreenshotTool } from './analyzeScreenshot.js';
import type { BrowserManager, McpToolCallResult } from './browserManager.js';
import type { Config } from '../../config/config.js';
import type { MessageBus } from '../../confirmation-bus/message-bus.js';
import { Environment } from '@google/genai';

const mockMessageBus = {
  waitForConfirmation: vi.fn().mockResolvedValue({ approved: true }),
} as unknown as MessageBus;

function createMockBrowserManager(
  callToolResult?: McpToolCallResult,
): BrowserManager {
  return {
    callTool: vi.fn().mockResolvedValue(
      callToolResult ?? {
        content: [
          { type: 'text', text: 'Screenshot captured' },
          {
            type: 'image',
            data: 'base64encodeddata',
            mimeType: 'image/png',
          },
        ],
      },
    ),
  } as unknown as BrowserManager;
}

function createMockConfig(
  generateContentResult?: unknown,
  generateContentError?: Error,
  modelName: string = 'gemini-2.5-computer-use-preview-10-2025',
): Config {
  const generateContent = generateContentError
    ? vi.fn().mockRejectedValue(generateContentError)
    : vi.fn().mockResolvedValue(
        generateContentResult ?? {
          candidates: [
            {
              content: {
                parts: [
                  {
                    text: 'The blue submit button is at coordinates (250, 400).',
                  },
                ],
              },
            },
          ],
        },
      );

  return {
    getBrowserAgentConfig: vi.fn().mockReturnValue({
      customConfig: { visualModel: modelName },
    }),
    getContentGenerator: vi.fn().mockReturnValue({
      generateContent,
    }),
  } as unknown as Config;
}

describe('analyzeScreenshot', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('createAnalyzeScreenshotTool', () => {
    it('creates a tool with the correct name and schema', () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig();
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      expect(tool.name).toBe('analyze_screenshot');
    });
  });

  describe('AnalyzeScreenshotInvocation', () => {
    it('captures a screenshot and returns visual analysis', async () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig();
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Find the blue submit button',
      });
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      // Verify screenshot was captured
      expect(browserManager.callTool).toHaveBeenCalledWith(
        'take_screenshot',
        {},
      );

      // Verify the visual model was called
      const contentGenerator = config.getContentGenerator();
      expect(contentGenerator.generateContent).toHaveBeenCalledWith(
        expect.objectContaining({
          model: 'gemini-2.5-computer-use-preview-10-2025',
          config: expect.objectContaining({
            tools: [
              {
                computerUse: {
                  environment: Environment.ENVIRONMENT_BROWSER,
                  excludedPredefinedFunctions: [
                    'open_web_browser',
                    'click_at',
                    'key_combination',
                    'drag_and_drop',
                  ],
                },
              },
            ],
          }),
          contents: expect.arrayContaining([
            expect.objectContaining({
              role: 'user',
              parts: expect.arrayContaining([
                expect.objectContaining({
                  inlineData: {
                    mimeType: 'image/png',
                    data: 'base64encodeddata',
                  },
                }),
              ]),
            }),
          ]),
        }),
        'visual-analysis',
        'utility_tool',
      );

      // Verify result
      expect(result.llmContent).toContain('Visual Analysis Result');
      expect(result.llmContent).toContain(
        'The blue submit button is at coordinates (250, 400).',
      );
      expect(result.error).toBeUndefined();
    });

    it('omits computerUse tools for non-computer-use models', async () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig(undefined, undefined, 'gemini-2.0-flash');
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Find the search bar',
      });
      await invocation.execute({ abortSignal: new AbortController().signal });

      const contentGenerator = config.getContentGenerator();
      expect(contentGenerator.generateContent).toHaveBeenCalledWith(
        expect.objectContaining({
          model: 'gemini-2.0-flash',
          config: expect.not.objectContaining({
            tools: expect.anything(),
          }),
        }),
        'visual-analysis',
        'utility_tool',
      );
    });

    it('returns an error when screenshot capture fails (no image)', async () => {
      const browserManager = createMockBrowserManager({
        content: [{ type: 'text', text: 'No screenshot available' }],
      });
      const config = createMockConfig();
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Find the button',
      });
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.error).toBeDefined();
      expect(result.llmContent).toContain('Failed to capture screenshot');
      // Should NOT call the visual model
      const contentGenerator = config.getContentGenerator();
      expect(contentGenerator.generateContent).not.toHaveBeenCalled();
    });

    it('returns an error when visual model returns empty response', async () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig({
        candidates: [{ content: { parts: [] } }],
      });
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Check the layout',
      });
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.error).toBeDefined();
      expect(result.llmContent).toContain('Visual model returned no analysis');
    });

    it('returns a model-unavailability fallback for 404 errors', async () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig(
        undefined,
        new Error('Model not found: 404'),
      );
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Find the red error',
      });
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.error).toBeDefined();
      expect(result.llmContent).toContain(
        'Visual analysis model is not available',
      );
    });

    it('returns a model-unavailability fallback for 403 errors', async () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig(
        undefined,
        new Error('permission denied: 403'),
      );
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Identify the element',
      });
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.error).toBeDefined();
      expect(result.llmContent).toContain(
        'Visual analysis model is not available',
      );
    });

    it('returns a generic error for non-model errors', async () => {
      const browserManager = createMockBrowserManager();
      const config = createMockConfig(undefined, new Error('Network timeout'));
      const tool = createAnalyzeScreenshotTool(
        browserManager,
        config,
        mockMessageBus,
      );

      const invocation = tool.build({
        instruction: 'Find something',
      });
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.error).toBeDefined();
      expect(result.llmContent).toContain('Visual analysis failed');
      expect(result.llmContent).toContain('Network timeout');
    });
  });
});