-
Notifications
You must be signed in to change notification settings - Fork 14k
Expand file tree
/
Copy pathweb-fetch.test.ts
More file actions
1098 lines (952 loc) · 37.3 KB
/
web-fetch.test.ts
File metadata and controls
1098 lines (952 loc) · 37.3 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
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import {
WebFetchTool,
parsePrompt,
convertGithubUrlToRaw,
normalizeUrl,
} from './web-fetch.js';
import type { Config } from '../config/config.js';
import { ApprovalMode } from '../policy/types.js';
import { ToolConfirmationOutcome } from './tools.js';
import { ToolErrorType } from './tool-error.js';
import {
createMockMessageBus,
getMockMessageBusInstance,
} from '../test-utils/mock-message-bus.js';
import * as fetchUtils from '../utils/fetch.js';
import { MessageBus } from '../confirmation-bus/message-bus.js';
import { PolicyEngine } from '../policy/policy-engine.js';
import {
MessageBusType,
type ToolConfirmationResponse,
} from '../confirmation-bus/types.js';
import { randomUUID } from 'node:crypto';
import {
logWebFetchFallbackAttempt,
WebFetchFallbackAttemptEvent,
} from '../telemetry/index.js';
import { convert } from 'html-to-text';
const mockGenerateContent = vi.fn();
const mockGetGeminiClient = vi.fn(() => ({
generateContent: mockGenerateContent,
}));
vi.mock('html-to-text', () => ({
convert: vi.fn((text) => `Converted: ${text}`),
}));
vi.mock('../telemetry/index.js', () => ({
logWebFetchFallbackAttempt: vi.fn(),
WebFetchFallbackAttemptEvent: vi.fn((reason) => ({ reason })),
}));
vi.mock('../utils/fetch.js', async (importOriginal) => {
const actual = await importOriginal<typeof fetchUtils>();
return {
...actual,
fetchWithTimeout: vi.fn(),
isPrivateIp: vi.fn(),
};
});
vi.mock('node:crypto', () => ({
randomUUID: vi.fn(),
}));
/**
* Helper to mock fetchWithTimeout with URL matching.
*/
const mockFetch = (url: string, response: Partial<Response> | Error) =>
vi
.spyOn(fetchUtils, 'fetchWithTimeout')
.mockImplementation(async (actualUrl) => {
if (actualUrl !== url) {
throw new Error(
`Unexpected fetch URL: expected "${url}", got "${actualUrl}"`,
);
}
if (response instanceof Error) {
throw response;
}
const headers = response.headers || new Headers();
// If we have text/arrayBuffer but no body, create a body mock
let body = response.body;
if (!body) {
let content: Uint8Array | undefined;
if (response.text) {
const text = await response.text();
content = new TextEncoder().encode(text);
} else if (response.arrayBuffer) {
const ab = await response.arrayBuffer();
content = new Uint8Array(ab);
}
if (content) {
body = {
getReader: () => {
let sent = false;
return {
read: async () => {
if (sent) return { done: true, value: undefined };
sent = true;
return { done: false, value: content };
},
releaseLock: () => {},
cancel: async () => {},
};
},
} as unknown as ReadableStream;
}
}
return {
ok: response.status ? response.status < 400 : true,
status: 200,
headers,
text: response.text || (() => Promise.resolve('')),
arrayBuffer:
response.arrayBuffer || (() => Promise.resolve(new ArrayBuffer(0))),
body: body || {
getReader: () => ({
read: async () => ({ done: true, value: undefined }),
releaseLock: () => {},
cancel: async () => {},
}),
},
...response,
} as unknown as Response;
});
describe('normalizeUrl', () => {
it('should lowercase hostname', () => {
expect(normalizeUrl('https://EXAMPLE.com/Path')).toBe(
'https://example.com/Path',
);
});
it('should remove trailing slash except for root', () => {
expect(normalizeUrl('https://example.com/path/')).toBe(
'https://example.com/path',
);
expect(normalizeUrl('https://example.com/')).toBe('https://example.com/');
});
it('should remove default ports', () => {
expect(normalizeUrl('http://example.com:80/')).toBe('http://example.com/');
expect(normalizeUrl('https://example.com:443/')).toBe(
'https://example.com/',
);
expect(normalizeUrl('https://example.com:8443/')).toBe(
'https://example.com:8443/',
);
});
it('should handle invalid URLs gracefully', () => {
expect(normalizeUrl('not-a-url')).toBe('not-a-url');
});
});
describe('parsePrompt', () => {
it('should extract valid URLs separated by whitespace', () => {
const prompt = 'Go to https://example.com and http://google.com';
const { validUrls, errors } = parsePrompt(prompt);
expect(errors).toHaveLength(0);
expect(validUrls).toHaveLength(2);
expect(validUrls[0]).toBe('https://example.com/');
expect(validUrls[1]).toBe('http://google.com/');
});
it('should accept URLs with trailing punctuation', () => {
const prompt = 'Check https://example.com.';
const { validUrls, errors } = parsePrompt(prompt);
expect(errors).toHaveLength(0);
expect(validUrls).toHaveLength(1);
expect(validUrls[0]).toBe('https://example.com./');
});
it.each([
{
name: 'URLs wrapped in punctuation',
prompt: 'Read (https://example.com)',
expectedErrorContent: ['Malformed URL detected', '(https://example.com)'],
},
{
name: 'unsupported protocols (httpshttps://)',
prompt: 'Summarize httpshttps://github.com/JuliaLang/julia/issues/58346',
expectedErrorContent: [
'Unsupported protocol',
'httpshttps://github.com/JuliaLang/julia/issues/58346',
],
},
{
name: 'unsupported protocols (ftp://)',
prompt: 'ftp://example.com/file.txt',
expectedErrorContent: ['Unsupported protocol'],
},
{
name: 'malformed URLs (http://)',
prompt: 'http://',
expectedErrorContent: ['Malformed URL detected'],
},
])('should detect $name as errors', ({ prompt, expectedErrorContent }) => {
const { validUrls, errors } = parsePrompt(prompt);
expect(validUrls).toHaveLength(0);
expect(errors).toHaveLength(1);
expectedErrorContent.forEach((content) => {
expect(errors[0]).toContain(content);
});
});
it('should handle prompts with no URLs', () => {
const prompt = 'hello world';
const { validUrls, errors } = parsePrompt(prompt);
expect(validUrls).toHaveLength(0);
expect(errors).toHaveLength(0);
});
it('should handle mixed valid and invalid URLs', () => {
const prompt = 'Valid: https://google.com, Invalid: ftp://bad.com';
const { validUrls, errors } = parsePrompt(prompt);
expect(validUrls).toHaveLength(1);
expect(validUrls[0]).toBe('https://google.com,/');
expect(errors).toHaveLength(1);
expect(errors[0]).toContain('ftp://bad.com');
});
});
describe('convertGithubUrlToRaw', () => {
it('should convert valid github blob urls', () => {
expect(
convertGithubUrlToRaw('https://github.com/user/repo/blob/main/README.md'),
).toBe('https://raw.githubusercontent.com/user/repo/main/README.md');
});
it('should not convert non-blob github urls', () => {
expect(convertGithubUrlToRaw('https://github.com/user/repo')).toBe(
'https://github.com/user/repo',
);
});
it('should not convert urls with similar domain names', () => {
expect(
convertGithubUrlToRaw('https://mygithub.com/user/repo/blob/main'),
).toBe('https://mygithub.com/user/repo/blob/main');
});
it('should only replace the /blob/ that separates repo from branch', () => {
expect(
convertGithubUrlToRaw('https://github.com/blob/repo/blob/main/test.ts'),
).toBe('https://raw.githubusercontent.com/blob/repo/main/test.ts');
});
it('should not convert urls if blob is not in path', () => {
expect(
convertGithubUrlToRaw('https://github.com/user/repo/tree/main'),
).toBe('https://github.com/user/repo/tree/main');
});
it('should handle invalid urls gracefully', () => {
expect(convertGithubUrlToRaw('not-a-url')).toBe('not-a-url');
});
});
describe('WebFetchTool', () => {
let mockConfig: Config;
let bus: MessageBus;
beforeEach(() => {
vi.resetAllMocks();
bus = createMockMessageBus();
getMockMessageBusInstance(bus).defaultToolDecision = 'ask_user';
mockConfig = {
getApprovalMode: vi.fn(),
setApprovalMode: vi.fn(),
getProxy: vi.fn(),
getGeminiClient: mockGetGeminiClient,
getRetryFetchErrors: vi.fn().mockReturnValue(false),
getMaxAttempts: vi.fn().mockReturnValue(3),
getDirectWebFetch: vi.fn().mockReturnValue(false),
modelConfigService: {
getResolvedConfig: vi.fn().mockImplementation(({ model }) => ({
model,
generateContentConfig: {},
})),
},
isInteractive: () => false,
} as unknown as Config;
});
describe('validateToolParamValues', () => {
describe('standard mode', () => {
it.each([
{
name: 'empty prompt',
prompt: '',
expectedError: "The 'prompt' parameter cannot be empty",
},
{
name: 'prompt with no URLs',
prompt: 'hello world',
expectedError: "The 'prompt' must contain at least one valid URL",
},
{
name: 'prompt with malformed URLs',
prompt: 'fetch httpshttps://example.com',
expectedError: 'Error(s) in prompt URLs:',
},
])('should throw if $name', ({ prompt, expectedError }) => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ prompt })).toThrow(expectedError);
});
it('should pass if prompt contains at least one valid URL', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() =>
tool.build({ prompt: 'fetch https://example.com' }),
).not.toThrow();
});
});
describe('experimental mode', () => {
beforeEach(() => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
});
it('should throw if url is missing', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ prompt: 'foo' })).toThrow(
"params must have required property 'url'",
);
});
it('should throw if url is invalid', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ url: 'not-a-url' })).toThrow(
'Invalid URL: "not-a-url"',
);
});
it('should pass if url is valid', () => {
const tool = new WebFetchTool(mockConfig, bus);
expect(() => tool.build({ url: 'https://example.com' })).not.toThrow();
});
});
});
describe('getSchema', () => {
it('should return standard schema by default', () => {
const tool = new WebFetchTool(mockConfig, bus);
const schema = tool.getSchema();
expect(schema.parametersJsonSchema).toHaveProperty('properties.prompt');
expect(schema.parametersJsonSchema).not.toHaveProperty('properties.url');
});
it('should return experimental schema when enabled', () => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
const tool = new WebFetchTool(mockConfig, bus);
const schema = tool.getSchema();
expect(schema.parametersJsonSchema).toHaveProperty('properties.url');
expect(schema.parametersJsonSchema).not.toHaveProperty(
'properties.prompt',
);
expect(schema.parametersJsonSchema).toHaveProperty('required', ['url']);
});
});
describe('execute', () => {
it('should return WEB_FETCH_PROCESSING_ERROR on rate limit exceeded', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
mockGenerateContent.mockResolvedValue({
candidates: [{ content: { parts: [{ text: 'response' }] } }],
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://ratelimit.example.com' };
const invocation = tool.build(params);
// Execute 10 times to hit the limit
for (let i = 0; i < 10; i++) {
await invocation.execute(new AbortController().signal);
}
// The 11th time should fail due to rate limit
const result = await invocation.execute(new AbortController().signal);
expect(result.error?.type).toBe(ToolErrorType.WEB_FETCH_PROCESSING_ERROR);
expect(result.error?.message).toContain(
'All requested URLs were skipped',
);
});
it('should skip rate-limited URLs but fetch others', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
const tool = new WebFetchTool(mockConfig, bus);
const params = {
prompt: 'fetch https://ratelimit-multi.com and https://healthy.com',
};
const invocation = tool.build(params);
// Hit rate limit for one host
for (let i = 0; i < 10; i++) {
mockGenerateContent.mockResolvedValueOnce({
candidates: [{ content: { parts: [{ text: 'response' }] } }],
});
await tool
.build({ prompt: 'fetch https://ratelimit-multi.com' })
.execute(new AbortController().signal);
}
// 11th call - should be rate limited and not use a mock
await tool
.build({ prompt: 'fetch https://ratelimit-multi.com' })
.execute(new AbortController().signal);
mockGenerateContent.mockResolvedValueOnce({
candidates: [{ content: { parts: [{ text: 'healthy response' }] } }],
});
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toContain('healthy response');
expect(result.llmContent).toContain(
'[Warning] The following URLs were skipped:',
);
expect(result.llmContent).toContain(
'[Rate limit exceeded] https://ratelimit-multi.com/',
);
});
it('should skip private or local URLs but fetch others and log telemetry', async () => {
vi.mocked(fetchUtils.isPrivateIp).mockImplementation(
(url) => url === 'https://private.com/',
);
const tool = new WebFetchTool(mockConfig, bus);
const params = {
prompt:
'fetch https://private.com and https://healthy.com and http://localhost',
};
const invocation = tool.build(params);
mockGenerateContent.mockResolvedValueOnce({
candidates: [{ content: { parts: [{ text: 'healthy response' }] } }],
});
const result = await invocation.execute(new AbortController().signal);
expect(logWebFetchFallbackAttempt).toHaveBeenCalledTimes(2);
expect(logWebFetchFallbackAttempt).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ reason: 'private_ip_skipped' }),
);
expect(result.llmContent).toContain('healthy response');
expect(result.llmContent).toContain(
'[Warning] The following URLs were skipped:',
);
expect(result.llmContent).toContain(
'[Blocked Host] https://private.com/',
);
expect(result.llmContent).toContain('[Blocked Host] http://localhost');
});
it('should fallback to all public URLs if primary fails', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
// Primary fetch fails
mockGenerateContent.mockRejectedValueOnce(new Error('primary fail'));
// Mock fallback fetch for BOTH URLs
mockFetch('https://url1.com/', {
text: () => Promise.resolve('content 1'),
});
mockFetch('https://url2.com/', {
text: () => Promise.resolve('content 2'),
});
// Mock fallback LLM call
mockGenerateContent.mockResolvedValueOnce({
candidates: [
{ content: { parts: [{ text: 'fallback processed response' }] } },
],
});
const tool = new WebFetchTool(mockConfig, bus);
const params = {
prompt: 'fetch https://url1.com and https://url2.com/',
};
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toBe('fallback processed response');
expect(result.returnDisplay).toContain(
'2 URL(s) processed using fallback fetch',
);
});
it('should NOT include private URLs in fallback', async () => {
vi.mocked(fetchUtils.isPrivateIp).mockImplementation(
(url) => url === 'https://private.com/',
);
// Primary fetch fails
mockGenerateContent.mockRejectedValueOnce(new Error('primary fail'));
// Mock fallback fetch only for public URL
mockFetch('https://public.com/', {
text: () => Promise.resolve('public content'),
});
// Mock fallback LLM call
mockGenerateContent.mockResolvedValueOnce({
candidates: [{ content: { parts: [{ text: 'fallback response' }] } }],
});
const tool = new WebFetchTool(mockConfig, bus);
const params = {
prompt: 'fetch https://public.com/ and https://private.com',
};
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toBe('fallback response');
// Verify private URL was NOT fetched (mockFetch would throw if it was called for private.com)
});
it('should return WEB_FETCH_FALLBACK_FAILED on fallback fetch failure', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
mockGenerateContent.mockRejectedValue(new Error('primary fail'));
mockFetch('https://public.ip/', new Error('fallback fetch failed'));
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://public.ip' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.error?.type).toBe(ToolErrorType.WEB_FETCH_FALLBACK_FAILED);
});
it('should return WEB_FETCH_FALLBACK_FAILED on general processing failure (when fallback also fails)', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
mockGenerateContent.mockRejectedValue(new Error('API error'));
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://public.ip' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.error?.type).toBe(ToolErrorType.WEB_FETCH_FALLBACK_FAILED);
});
it('should log telemetry when falling back due to primary fetch failure', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
// Mock primary fetch to return empty response, triggering fallback
mockGenerateContent.mockResolvedValueOnce({
candidates: [],
});
// Mock fetchWithTimeout to succeed so fallback proceeds
mockFetch('https://public.ip/', {
text: () => Promise.resolve('some content'),
});
// Mock fallback LLM call
mockGenerateContent.mockResolvedValueOnce({
candidates: [{ content: { parts: [{ text: 'fallback response' }] } }],
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://public.ip' };
const invocation = tool.build(params);
await invocation.execute(new AbortController().signal);
expect(logWebFetchFallbackAttempt).toHaveBeenCalledWith(
mockConfig,
expect.objectContaining({ reason: 'primary_failed' }),
);
expect(WebFetchFallbackAttemptEvent).toHaveBeenCalledWith(
'primary_failed',
);
});
});
describe('execute (fallback)', () => {
beforeEach(() => {
// Force fallback by mocking primary fetch to fail
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
mockGenerateContent.mockResolvedValueOnce({
candidates: [],
});
});
it.each([
{
name: 'HTML content using html-to-text',
content: '<html><body><h1>Hello</h1></body></html>',
contentType: 'text/html; charset=utf-8',
shouldConvert: true,
},
{
name: 'raw text for JSON content',
content: '{"key": "value"}',
contentType: 'application/json',
shouldConvert: false,
},
{
name: 'raw text for plain text content',
content: 'Just some text.',
contentType: 'text/plain',
shouldConvert: false,
},
{
name: 'content with no Content-Type header as HTML',
content: '<p>No header</p>',
contentType: null,
shouldConvert: true,
},
])(
'should handle $name',
async ({ content, contentType, shouldConvert }) => {
const headers = contentType
? new Headers({ 'content-type': contentType })
: new Headers();
mockFetch('https://example.com/', {
headers,
text: () => Promise.resolve(content),
});
// Mock fallback LLM call to return the content passed to it
mockGenerateContent.mockImplementationOnce(async (_, req) => ({
candidates: [
{ content: { parts: [{ text: req[0].parts[0].text }] } },
],
}));
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://example.com' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
if (shouldConvert) {
expect(convert).toHaveBeenCalledWith(content, {
wordwrap: false,
selectors: [
{ selector: 'a', options: { ignoreHref: true } },
{ selector: 'img', format: 'skip' },
],
});
expect(result.llmContent).toContain(`Converted: ${content}`);
} else {
expect(convert).not.toHaveBeenCalled();
expect(result.llmContent).toContain(content);
}
},
);
});
describe('shouldConfirmExecute', () => {
it('should return confirmation details with the correct prompt and parsed urls', async () => {
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://example.com' };
const invocation = tool.build(params);
const confirmationDetails = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(confirmationDetails).toEqual({
type: 'info',
title: 'Confirm Web Fetch',
prompt: 'fetch https://example.com',
urls: ['https://example.com/'],
onConfirm: expect.any(Function),
});
});
it('should handle URL param in confirmation details', async () => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com' };
const invocation = tool.build(params);
const confirmationDetails = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(confirmationDetails).toEqual({
type: 'info',
title: 'Confirm Web Fetch',
prompt: 'Fetch https://example.com',
urls: ['https://example.com'],
onConfirm: expect.any(Function),
});
});
it('should convert github urls to raw format', async () => {
const tool = new WebFetchTool(mockConfig, bus);
const params = {
prompt:
'fetch https://github.com/google/gemini-react/blob/main/README.md',
};
const invocation = tool.build(params);
const confirmationDetails = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(confirmationDetails).toEqual({
type: 'info',
title: 'Confirm Web Fetch',
prompt:
'fetch https://github.com/google/gemini-react/blob/main/README.md',
urls: [
'https://raw.githubusercontent.com/google/gemini-react/main/README.md',
],
onConfirm: expect.any(Function),
});
});
it('should return false if approval mode is AUTO_EDIT', async () => {
vi.spyOn(mockConfig, 'getApprovalMode').mockReturnValue(
ApprovalMode.AUTO_EDIT,
);
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://example.com' };
const invocation = tool.build(params);
const confirmationDetails = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(confirmationDetails).toBe(false);
});
it('should NOT call setApprovalMode when onConfirm is called with ProceedAlways (now handled by scheduler)', async () => {
const tool = new WebFetchTool(mockConfig, bus);
const params = { prompt: 'fetch https://example.com' };
const invocation = tool.build(params);
const confirmationDetails = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
if (
confirmationDetails &&
typeof confirmationDetails === 'object' &&
'onConfirm' in confirmationDetails
) {
await confirmationDetails.onConfirm(
ToolConfirmationOutcome.ProceedAlways,
);
}
// Schedulers are now responsible for mode transitions via updatePolicy
expect(mockConfig.setApprovalMode).not.toHaveBeenCalled();
});
});
describe('Message Bus Integration', () => {
let policyEngine: PolicyEngine;
let messageBus: MessageBus;
let mockUUID: Mock;
const createToolWithMessageBus = (customBus?: MessageBus) => {
const tool = new WebFetchTool(mockConfig, customBus ?? bus);
const params = { prompt: 'fetch https://example.com' };
return { tool, invocation: tool.build(params) };
};
const simulateMessageBusResponse = (
subscribeSpy: ReturnType<typeof vi.spyOn>,
confirmed: boolean,
correlationId = 'test-correlation-id',
) => {
const responseHandler = subscribeSpy.mock.calls[0][1] as (
response: ToolConfirmationResponse,
) => void;
const response: ToolConfirmationResponse = {
type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
correlationId,
confirmed,
};
responseHandler(response);
};
beforeEach(() => {
policyEngine = new PolicyEngine();
messageBus = new MessageBus(policyEngine);
mockUUID = vi.mocked(randomUUID);
mockUUID.mockReturnValue('test-correlation-id');
});
it('should use message bus for confirmation when available', async () => {
const { invocation } = createToolWithMessageBus(messageBus);
const publishSpy = vi.spyOn(messageBus, 'publish');
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const unsubscribeSpy = vi.spyOn(messageBus, 'unsubscribe');
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(publishSpy).toHaveBeenCalledWith({
type: MessageBusType.TOOL_CONFIRMATION_REQUEST,
toolCall: {
name: 'web_fetch',
args: { prompt: 'fetch https://example.com' },
},
correlationId: 'test-correlation-id',
});
expect(subscribeSpy).toHaveBeenCalledWith(
MessageBusType.TOOL_CONFIRMATION_RESPONSE,
expect.any(Function),
);
simulateMessageBusResponse(subscribeSpy, true);
const result = await confirmationPromise;
expect(result).toBe(false);
expect(unsubscribeSpy).toHaveBeenCalled();
});
it('should reject promise when confirmation is denied via message bus', async () => {
const { invocation } = createToolWithMessageBus(messageBus);
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
simulateMessageBusResponse(subscribeSpy, false);
await expect(confirmationPromise).rejects.toThrow(
'Tool execution for "WebFetch" denied by policy.',
);
});
it('should handle timeout gracefully', async () => {
vi.useFakeTimers();
const { invocation } = createToolWithMessageBus(messageBus);
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
await vi.advanceTimersByTimeAsync(30000);
const result = await confirmationPromise;
expect(result).not.toBe(false);
expect(result).toHaveProperty('type', 'info');
vi.useRealTimers();
});
it('should handle abort signal during confirmation', async () => {
const { invocation } = createToolWithMessageBus(messageBus);
const abortController = new AbortController();
const confirmationPromise = invocation.shouldConfirmExecute(
abortController.signal,
);
abortController.abort();
await expect(confirmationPromise).rejects.toThrow(
'Tool execution for "WebFetch" denied by policy.',
);
});
it('should ignore responses with wrong correlation ID', async () => {
vi.useFakeTimers();
const { invocation } = createToolWithMessageBus(messageBus);
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
simulateMessageBusResponse(subscribeSpy, true, 'wrong-id');
await vi.advanceTimersByTimeAsync(30000);
const result = await confirmationPromise;
expect(result).not.toBe(false);
expect(result).toHaveProperty('type', 'info');
vi.useRealTimers();
});
it('should handle message bus publish errors gracefully', async () => {
const { invocation } = createToolWithMessageBus(messageBus);
vi.spyOn(messageBus, 'publish').mockImplementation(() => {
throw new Error('Message bus error');
});
const result = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(result).toBe(false);
});
it('should execute normally after confirmation approval', async () => {
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
mockGenerateContent.mockResolvedValue({
candidates: [
{
content: {
parts: [{ text: 'Fetched content from https://example.com' }],
role: 'model',
},
},
],
});
const { invocation } = createToolWithMessageBus(messageBus);
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
simulateMessageBusResponse(subscribeSpy, true);
await confirmationPromise;
const result = await invocation.execute(new AbortController().signal);
expect(result.error).toBeUndefined();
expect(result.llmContent).toContain('Fetched content');
});
});
describe('execute (experimental)', () => {
beforeEach(() => {
vi.spyOn(mockConfig, 'getDirectWebFetch').mockReturnValue(true);
vi.spyOn(fetchUtils, 'isPrivateIp').mockReturnValue(false);
});
it('should perform direct fetch and return text for plain text content', async () => {
const content = 'Plain text content';
mockFetch('https://example.com/', {
status: 200,
headers: new Headers({ 'content-type': 'text/plain' }),
text: () => Promise.resolve(content),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toBe(content);
expect(result.returnDisplay).toContain('Fetched text/plain content');
expect(fetchUtils.fetchWithTimeout).toHaveBeenCalledWith(
'https://example.com/',
expect.any(Number),
expect.objectContaining({
headers: expect.objectContaining({
Accept: expect.stringContaining('text/plain'),
}),
}),
);
});
it('should use html-to-text and preserve links for HTML content', async () => {
const content =
'<html><body><a href="https://link.com">Link</a></body></html>';
mockFetch('https://example.com/', {
status: 200,
headers: new Headers({ 'content-type': 'text/html' }),
text: () => Promise.resolve(content),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com' };
const invocation = tool.build(params);
await invocation.execute(new AbortController().signal);
expect(convert).toHaveBeenCalledWith(
content,
expect.objectContaining({
selectors: [
expect.objectContaining({
selector: 'a',
options: { ignoreHref: false, baseUrl: 'https://example.com/' },
}),
],
}),
);
});
it('should return base64 for image content', async () => {
const buffer = Buffer.from('fake-image-data');
mockFetch('https://example.com/image.png', {
status: 200,
headers: new Headers({ 'content-type': 'image/png' }),
arrayBuffer: () =>
Promise.resolve(
buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength,
),
),
});
const tool = new WebFetchTool(mockConfig, bus);
const params = { url: 'https://example.com/image.png' };
const invocation = tool.build(params);
const result = await invocation.execute(new AbortController().signal);
expect(result.llmContent).toEqual({
inlineData: {
data: buffer.toString('base64'),
mimeType: 'image/png',
},