-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathagent_browser_host.cpp
More file actions
2733 lines (2604 loc) · 113 KB
/
Copy pathagent_browser_host.cpp
File metadata and controls
2733 lines (2604 loc) · 113 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
#include "agent_browser_host.hpp"
#include "agent_browser_navigation_state.hpp"
#include "agent_browser_runtime.hpp"
#include "daemon/platform.hpp"
#include "utils/encoding.hpp"
#include "utils/logger.hpp"
#include "utils/token.hpp"
#include "utils/utf8_path.hpp"
#include <atomic>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include <nlohmann/json.hpp>
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
# include <shellapi.h>
# include <wrl.h>
# include <WebView2.h>
# include <WebView2EnvironmentOptions.h>
# include <webview/webview.h>
#endif
namespace acecode::desktop {
namespace {
std::int64_t now_unix_ms() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
}
void assign_error(std::string* target, const std::string& value) {
if (target) *target = value;
}
std::string agent_browser_title_or_default(std::string title) {
return title.find_first_not_of(" \t\r\n") == std::string::npos
? std::string(kAgentBrowserDefaultTitle)
: std::move(title);
}
#ifdef _WIN32
constexpr std::size_t kAgentBrowserMaxConsoleEntries = 1000;
constexpr std::size_t kAgentBrowserMaxConsoleEntryBytes = 16 * 1024;
constexpr std::size_t kAgentBrowserMaxFaviconBytes = 256 * 1024;
constexpr char kAgentBrowserElementPickerKey[] =
"__acecodeAgentBrowserElementPickerV1";
bool valid_agent_browser_favicon(const std::string& value) {
if (value.empty() || value.size() > kAgentBrowserMaxFaviconBytes) {
return false;
}
return value.rfind("https://", 0) == 0 ||
value.rfind("http://", 0) == 0 ||
value.rfind("data:image/", 0) == 0;
}
const char* agent_browser_favicon_expression() {
return R"JS((async () => {
const maxDataUrlLength = 256 * 1024;
const links = [...document.querySelectorAll('link[rel][href]')];
const icon = links.find((link) => String(link.rel || '').toLowerCase().split(/\s+/).includes('icon'));
let href = icon?.href || '';
if (!href && (location.protocol === 'http:' || location.protocol === 'https:')) {
href = new URL('/favicon.ico', location.href).href;
}
if (!href) return '';
try {
const parsed = new URL(href, location.href);
if (!['http:', 'https:', 'data:'].includes(parsed.protocol)) return '';
href = parsed.href;
} catch (_) {
return '';
}
if (href.startsWith('data:')) {
return href.startsWith('data:image/') && href.length <= maxDataUrlLength ? href : '';
}
if (new URL(href).origin !== location.origin) {
return href.length <= 4096 ? href : '';
}
try {
const response = await fetch(href, { credentials: 'include', cache: 'force-cache' });
if (!response.ok) return href.length <= 4096 ? href : '';
const declaredLength = Number(response.headers.get('content-length') || 0);
if (declaredLength > 128 * 1024) return href.length <= 4096 ? href : '';
const blob = await response.blob();
if (!String(blob.type || '').toLowerCase().startsWith('image/') || blob.size > 128 * 1024) {
return href.length <= 4096 ? href : '';
}
const dataUrl = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
reader.onerror = () => resolve('');
reader.readAsDataURL(blob);
});
return dataUrl.length <= maxDataUrlLength ? dataUrl : (href.length <= 4096 ? href : '');
} catch (_) {
return href.length <= 4096 ? href : '';
}
})())JS";
}
// 可以交给操作系统打开的外部 scheme。http/https/file/about 由 WebView 自己承载;
// javascript/data/blob 不代表外部应用,edge/devtools 是引擎内部页面。
bool agent_browser_external_handoff_candidate(const std::string& uri) {
const auto colon = uri.find(':');
if (colon == std::string::npos || colon == 0) return false;
std::string scheme = uri.substr(0, colon);
std::transform(scheme.begin(), scheme.end(), scheme.begin(),
[](unsigned char ch) {
return static_cast<char>(std::tolower(ch));
});
if (std::isalpha(static_cast<unsigned char>(scheme.front())) == 0) {
return false;
}
static const char* const blocked[] = {
"http", "https", "file", "about", "javascript", "data", "blob",
"edge", "devtools", "ws", "wss",
};
for (const char* name : blocked) {
if (scheme == name) return false;
}
return true;
}
const char* agent_browser_web_error_kind(
COREWEBVIEW2_WEB_ERROR_STATUS status) {
switch (status) {
case COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT:
case COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED:
case COREWEBVIEW2_WEB_ERROR_STATUS_CLIENT_CERTIFICATE_CONTAINS_ERRORS:
case COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_REVOKED:
case COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_IS_INVALID:
return "certificate";
case COREWEBVIEW2_WEB_ERROR_STATUS_SERVER_UNREACHABLE:
return "server_unreachable";
case COREWEBVIEW2_WEB_ERROR_STATUS_TIMEOUT:
return "timeout";
case COREWEBVIEW2_WEB_ERROR_STATUS_ERROR_HTTP_INVALID_SERVER_RESPONSE:
return "invalid_response";
case COREWEBVIEW2_WEB_ERROR_STATUS_CONNECTION_ABORTED:
return "connection_aborted";
case COREWEBVIEW2_WEB_ERROR_STATUS_CONNECTION_RESET:
return "connection_reset";
case COREWEBVIEW2_WEB_ERROR_STATUS_DISCONNECTED:
return "disconnected";
case COREWEBVIEW2_WEB_ERROR_STATUS_CANNOT_CONNECT:
return "cannot_connect";
case COREWEBVIEW2_WEB_ERROR_STATUS_HOST_NAME_NOT_RESOLVED:
return "name_not_resolved";
case COREWEBVIEW2_WEB_ERROR_STATUS_OPERATION_CANCELED:
return "cancelled";
case COREWEBVIEW2_WEB_ERROR_STATUS_REDIRECT_FAILED:
return "redirect_failed";
case COREWEBVIEW2_WEB_ERROR_STATUS_VALID_AUTHENTICATION_CREDENTIALS_REQUIRED:
return "authentication_required";
case COREWEBVIEW2_WEB_ERROR_STATUS_VALID_PROXY_AUTHENTICATION_REQUIRED:
return "proxy_authentication_required";
case COREWEBVIEW2_WEB_ERROR_STATUS_UNEXPECTED_ERROR:
case COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN:
default:
return "unexpected";
}
}
const char* agent_browser_process_failure_kind(
COREWEBVIEW2_PROCESS_FAILED_KIND kind,
COREWEBVIEW2_PROCESS_FAILED_REASON reason) {
const bool top_level_failure =
kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED ||
kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED ||
kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE;
if (!top_level_failure) return "";
if (reason == COREWEBVIEW2_PROCESS_FAILED_REASON_OUT_OF_MEMORY) {
return "out_of_memory";
}
if (kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE ||
reason == COREWEBVIEW2_PROCESS_FAILED_REASON_UNRESPONSIVE) {
return "unresponsive";
}
if (kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED) {
return "browser_process_exited";
}
if (kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED) {
return "render_process_exited";
}
return "";
}
std::string clip_agent_browser_text(std::string value,
std::size_t max_bytes) {
if (value.size() <= max_bytes) return value;
value.resize(max_bytes);
value += "\n[truncated]";
return value;
}
std::string cdp_remote_object_text(const nlohmann::json& object) {
if (!object.is_object()) return object.dump();
if (object.contains("value") && !object["value"].is_null()) {
return object["value"].is_string()
? object["value"].get<std::string>()
: object["value"].dump();
}
if (object.contains("unserializableValue") &&
object["unserializableValue"].is_string()) {
return object["unserializableValue"].get<std::string>();
}
if (object.contains("description") && object["description"].is_string()) {
return object["description"].get<std::string>();
}
return object.value("type", std::string("value"));
}
const char* agent_browser_element_picker_expression() {
return R"JS((() => {
const key = '__acecodeAgentBrowserElementPickerV1';
const previous = globalThis[key];
if (previous && typeof previous.cancel === 'function') previous.cancel();
return new Promise((resolve) => {
const root = document.documentElement || document.body;
if (!root) { resolve({ cancelled: true }); return; }
let finished = false;
let commitPending = false;
let dragStart = null;
let dragTarget = null;
let highlighted = null;
const host = document.createElement('div');
host.setAttribute('data-acecode-element-picker', '');
host.style.cssText = 'position:fixed;inset:0;width:0;height:0;z-index:2147483647;pointer-events:none';
const shadow = host.attachShadow({ mode: 'closed' });
const styleNode = document.createElement('style');
styleNode.textContent = `
.box{display:none;position:fixed;box-sizing:border-box;border:2px solid #0e70c0;background:rgba(14,112,192,.14);pointer-events:none;z-index:2}
.label{display:none;position:fixed;max-width:70vw;padding:3px 6px;border-radius:3px;background:#0e70c0;color:#fff;font:11px/16px "Segoe UI",sans-serif;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none;z-index:3;box-shadow:0 2px 8px rgba(0,0,0,.22)}
.drag{display:none;position:fixed;box-sizing:border-box;border:1px dashed #0e70c0;background:rgba(14,112,192,.08);pointer-events:none;z-index:1}
`;
const box = document.createElement('div'); box.className = 'box';
const label = document.createElement('div'); label.className = 'label';
const drag = document.createElement('div'); drag.className = 'drag';
shadow.append(styleNode, box, drag, label);
root.appendChild(host);
const cursor = document.createElement('style');
cursor.setAttribute('data-acecode-element-picker-cursor', '');
cursor.textContent = '*{cursor:default!important}';
(document.head || root).appendChild(cursor);
const clip = (value, limit) => {
const text = String(value == null ? '' : value);
return text.length > limit ? `${text.slice(0, limit)}\n[truncated]` : text;
};
const elementAt = (x, y) => {
const values = document.elementsFromPoint(x, y);
return values.find((value) => value !== host && !host.contains(value));
};
const commonAncestor = (values) => {
const unique = [...new Set(values.filter(Boolean))];
if (!unique.length) return null;
let chain = [];
for (let node = unique[0]; node; node = node.parentElement) chain.unshift(node);
for (let i = 1; i < unique.length && chain.length; i += 1) {
const other = [];
for (let node = unique[i]; node; node = node.parentElement) other.unshift(node);
let index = 0;
while (index < chain.length && index < other.length && chain[index] === other[index]) index += 1;
chain = chain.slice(0, index);
}
return chain[chain.length - 1] || null;
};
const regionTarget = (left, top, width, height) => {
const right = left + width;
const bottom = top + height;
const centerX = left + width / 2;
const centerY = top + height / 2;
return commonAncestor([
elementAt(left, top), elementAt(right, top), elementAt(left, bottom),
elementAt(right, bottom), elementAt(centerX, top), elementAt(centerX, bottom),
elementAt(left, centerY), elementAt(right, centerY), elementAt(centerX, centerY),
]);
};
const selectorName = (element) => {
if (!element) return '';
const tag = String(element.tagName || 'element').toLowerCase();
const id = element.id ? `#${element.id}` : '';
const classes = [...element.classList].slice(0, 4).map((name) => `.${name}`).join('');
return `${tag}${id}${classes}`;
};
const render = (element) => {
highlighted = element || null;
if (!element) { box.style.display = 'none'; label.style.display = 'none'; return; }
const rect = element.getBoundingClientRect();
box.style.display = 'block';
box.style.left = `${rect.left}px`; box.style.top = `${rect.top}px`;
box.style.width = `${Math.max(0, rect.width)}px`; box.style.height = `${Math.max(0, rect.height)}px`;
label.textContent = `${selectorName(element)} ${Math.round(rect.width)} × ${Math.round(rect.height)}`;
label.style.display = 'block';
label.style.left = `${Math.max(2, Math.min(rect.left, innerWidth - 180))}px`;
label.style.top = `${Math.max(2, rect.top >= 24 ? rect.top - 22 : rect.bottom + 2)}px`;
};
const collect = (element) => {
const rect = element.getBoundingClientRect();
const attributes = {};
[...element.attributes].slice(0, 100).forEach((attr) => { attributes[attr.name] = clip(attr.value, 2048); });
const computed = getComputedStyle(element);
const computedStyles = {};
const cssLines = [];
for (let i = 0; i < computed.length && i < 200; i += 1) {
const name = computed[i];
const value = clip(computed.getPropertyValue(name), 512);
computedStyles[name] = value;
cssLines.push(`${name}: ${value};`);
}
const ancestors = [];
for (let node = element; node && ancestors.length < 16; node = node.parentElement) {
ancestors.unshift({
tagName: String(node.tagName || '').toLowerCase(),
id: clip(node.id || '', 512),
classNames: [...node.classList].slice(0, 12).map((name) => clip(name, 256)),
});
}
return {
url: location.href,
title: document.title,
name: selectorName(element),
tagName: String(element.tagName || '').toLowerCase(),
outerHTML: clip(element.outerHTML || '', 40000),
innerText: clip(element.innerText || element.textContent || '', 20000),
attributes,
computedStyle: clip(cssLines.join('\n'), 40000),
computedStyles,
ancestors,
bounds: { x: rect.left, y: rect.top, width: rect.width, height: rect.height },
dimensions: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
};
};
const listeners = [
['pointermove', onPointerMove], ['pointerdown', onPointerDown],
['pointerup', onPointerUp], ['click', suppress], ['contextmenu', suppress],
['keydown', onKeyDown], ['scroll', onViewportChange], ['resize', onViewportChange],
];
function cleanup() {
listeners.forEach(([name, handler]) => window.removeEventListener(name, handler, true));
cursor.remove(); host.remove();
try { delete globalThis[key]; } catch (_) { globalThis[key] = undefined; }
}
function finish(value) {
if (finished) return;
finished = true; cleanup(); resolve(value);
}
function suppress(event) {
event.preventDefault(); event.stopImmediatePropagation();
}
function onPointerMove(event) {
suppress(event);
if (commitPending) return;
if (!dragStart) { render(elementAt(event.clientX, event.clientY)); return; }
const left = Math.min(dragStart.x, event.clientX);
const top = Math.min(dragStart.y, event.clientY);
const width = Math.abs(event.clientX - dragStart.x);
const height = Math.abs(event.clientY - dragStart.y);
if (width < 4 && height < 4) return;
drag.style.display = 'block'; drag.style.left = `${left}px`; drag.style.top = `${top}px`;
drag.style.width = `${width}px`; drag.style.height = `${height}px`;
render(regionTarget(left, top, width, height));
}
function onPointerDown(event) {
if (commitPending) { suppress(event); return; }
if (event.button !== 0) { suppress(event); return; }
dragStart = { x: event.clientX, y: event.clientY };
dragTarget = elementAt(event.clientX, event.clientY);
cursor.textContent = '*{cursor:crosshair!important}';
suppress(event);
}
function onPointerUp(event) {
if (!dragStart) { suppress(event); return; }
const start = dragStart; dragStart = null;
const width = Math.abs(event.clientX - start.x);
const height = Math.abs(event.clientY - start.y);
const target = width < 4 && height < 4
? (dragTarget || elementAt(event.clientX, event.clientY))
: regionTarget(Math.min(start.x, event.clientX), Math.min(start.y, event.clientY), width, height);
dragTarget = null; suppress(event);
if (target) {
const selection = { cancelled: false, element: collect(target) };
commitPending = true;
requestAnimationFrame(() => finish(selection));
}
}
function onKeyDown(event) {
if (event.key === 'Escape') { suppress(event); finish({ cancelled: true }); }
}
function onViewportChange() { if (highlighted) render(highlighted); }
listeners.forEach(([name, handler]) => window.addEventListener(name, handler, true));
const controller = { cancel: () => finish({ cancelled: true }) };
try { Object.defineProperty(globalThis, key, { configurable: true, value: controller }); }
catch (_) { globalThis[key] = controller; }
});
})())JS";
}
constexpr wchar_t kAgentBrowserWidgetClassName[] =
L"ACECodeAgentBrowserWidget";
HWND create_agent_browser_widget(HWND parent) {
const HINSTANCE instance = ::GetModuleHandleW(nullptr);
WNDCLASSEXW window_class{};
window_class.cbSize = sizeof(window_class);
window_class.hInstance = instance;
window_class.lpfnWndProc = ::DefWindowProcW;
window_class.lpszClassName = kAgentBrowserWidgetClassName;
window_class.hCursor =
::LoadCursorW(nullptr, reinterpret_cast<LPCWSTR>(IDC_ARROW));
window_class.hbrBackground =
reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
if (!::RegisterClassExW(&window_class) &&
::GetLastError() != ERROR_CLASS_ALREADY_EXISTS) {
return nullptr;
}
// Keep the parent HWND visible while WebView2 creates controllers. A
// hidden parent can leave a controller permanently unpainted on some
// WebView2 runtimes. The parked 1x1 child is outside the client area and
// therefore cannot cover the main ACECode WebView.
return ::CreateWindowExW(
WS_EX_CONTROLPARENT | WS_EX_NOPARENTNOTIFY,
kAgentBrowserWidgetClassName,
L"",
WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
-1,
-1,
1,
1,
parent,
nullptr,
instance,
nullptr);
}
void park_agent_browser_widget(HWND widget) {
if (!widget || !::IsWindow(widget)) return;
::SetWindowPos(widget,
HWND_TOP,
-1,
-1,
1,
1,
SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
void hide_agent_browser_widget(HWND widget) {
if (!widget || !::IsWindow(widget)) return;
::SetWindowPos(widget,
nullptr,
0,
0,
0,
0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE |
SWP_NOZORDER | SWP_HIDEWINDOW);
}
bool apply_agent_browser_widget_region(
HWND widget,
int width,
int height,
const std::vector<AgentBrowserOcclusionRect>& occlusions) {
if (!widget || !::IsWindow(widget)) return false;
if (occlusions.empty()) {
return ::SetWindowRgn(widget, nullptr, TRUE) != 0;
}
HRGN visible_region = ::CreateRectRgn(0, 0, width, height);
if (!visible_region) return false;
for (const auto& occlusion : occlusions) {
const int left = (std::max)(0, (std::min)(width, occlusion.x));
const int top = (std::max)(0, (std::min)(height, occlusion.y));
const int right = (std::max)(left, (std::min)(
width, occlusion.x + occlusion.width));
const int bottom = (std::max)(top, (std::min)(
height, occlusion.y + occlusion.height));
if (right <= left || bottom <= top) continue;
HRGN hole = ::CreateRectRgn(left, top, right, bottom);
if (!hole) {
::DeleteObject(visible_region);
return false;
}
const int combine_result =
::CombineRgn(visible_region, visible_region, hole, RGN_DIFF);
::DeleteObject(hole);
if (combine_result == ERROR) {
::DeleteObject(visible_region);
return false;
}
}
// SetWindowRgn takes ownership only on success.
if (::SetWindowRgn(widget, visible_region, TRUE) == 0) {
::DeleteObject(visible_region);
return false;
}
return true;
}
std::string hresult_text(HRESULT result) {
return "HRESULT 0x" + [] (unsigned long value) {
constexpr char digits[] = "0123456789ABCDEF";
std::string output(8, '0');
for (int index = 7; index >= 0; --index) {
output[static_cast<std::size_t>(index)] = digits[value & 0xF];
value >>= 4;
}
return output;
}(static_cast<unsigned long>(result));
}
bool proxy_aborted(const std::atomic<bool>& stopping,
std::chrono::steady_clock::time_point deadline) {
return stopping.load() || std::chrono::steady_clock::now() >= deadline;
}
bool pipe_transfer(HANDLE pipe,
void* buffer,
std::size_t size,
bool write,
const std::atomic<bool>& stopping,
std::chrono::steady_clock::time_point deadline) {
std::size_t offset = 0;
while (offset < size && !proxy_aborted(stopping, deadline)) {
OVERLAPPED operation{};
operation.hEvent = ::CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!operation.hEvent) return false;
const DWORD chunk = static_cast<DWORD>((std::min)(
size - offset, static_cast<std::size_t>(1024u * 1024u)));
DWORD transferred = 0;
BOOL started = write
? ::WriteFile(pipe,
static_cast<const char*>(buffer) + offset,
chunk, &transferred, &operation)
: ::ReadFile(pipe,
static_cast<char*>(buffer) + offset,
chunk, &transferred, &operation);
DWORD operation_error = started ? ERROR_SUCCESS : ::GetLastError();
bool pending_io = false;
if (!started && operation_error == ERROR_IO_PENDING) {
pending_io = true;
while (!proxy_aborted(stopping, deadline)) {
const DWORD wait = ::WaitForSingleObject(operation.hEvent, 50);
if (wait == WAIT_OBJECT_0) {
started = ::GetOverlappedResult(
pipe, &operation, &transferred, FALSE);
operation_error = started ? ERROR_SUCCESS : ::GetLastError();
break;
}
if (wait == WAIT_FAILED) {
operation_error = ::GetLastError();
break;
}
}
}
if (!started || proxy_aborted(stopping, deadline)) {
if (pending_io) {
::CancelIoEx(pipe, &operation);
::WaitForSingleObject(operation.hEvent, INFINITE);
}
::CloseHandle(operation.hEvent);
if (!stopping.load() &&
std::chrono::steady_clock::now() < deadline) {
LOG_WARN(
std::string("[agent-browser] proxy pipe ") +
(write ? "write" : "read") + " failed (Windows error " +
std::to_string(operation_error) + ")");
}
return false;
}
::CloseHandle(operation.hEvent);
if (transferred == 0) return false;
offset += transferred;
}
return offset == size;
}
bool connect_pipe(HANDLE pipe,
const std::atomic<bool>& stopping) {
OVERLAPPED operation{};
operation.hEvent = ::CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!operation.hEvent) return false;
BOOL connected = ::ConnectNamedPipe(pipe, &operation);
const DWORD error = connected ? ERROR_SUCCESS : ::GetLastError();
bool pending_io = false;
if (!connected && error == ERROR_PIPE_CONNECTED) connected = TRUE;
if (!connected && error == ERROR_IO_PENDING) {
pending_io = true;
while (!stopping.load()) {
const DWORD wait = ::WaitForSingleObject(operation.hEvent, 50);
if (wait == WAIT_OBJECT_0) {
DWORD transferred = 0;
connected = ::GetOverlappedResult(
pipe, &operation, &transferred, FALSE);
break;
}
if (wait == WAIT_FAILED) break;
}
}
if (!connected) {
if (pending_io) {
::CancelIoEx(pipe, &operation);
::WaitForSingleObject(operation.hEvent, INFINITE);
}
}
::CloseHandle(operation.hEvent);
return connected != FALSE && !stopping.load();
}
#endif
} // namespace
struct AgentBrowserHost::Impl
: public std::enable_shared_from_this<AgentBrowserHost::Impl> {
struct PendingProxyCall {
std::mutex mutex;
std::condition_variable ready;
bool completed = false;
nlohmann::json response;
};
void* parent_window = nullptr;
std::int64_t desktop_pid = 0;
std::string desktop_instance_id;
std::string acecode_dir;
StateHandler state_handler;
DispatchHandler dispatch_handler;
mutable std::mutex state_mutex;
AgentBrowserState host_state;
bool parent_surface_visible = true;
#ifdef _WIN32
struct QueuedCdpCall {
std::string method;
nlohmann::json params;
std::shared_ptr<PendingProxyCall> pending;
};
struct Page {
std::string id;
AgentBrowserState state;
AgentBrowserBounds requested_bounds;
bool creation_started = false;
bool closing = false;
Microsoft::WRL::ComPtr<ICoreWebView2Controller> controller;
Microsoft::WRL::ComPtr<ICoreWebView2> webview;
Microsoft::WRL::ComPtr<ICoreWebView2DevToolsProtocolEventReceiver>
runtime_console_receiver;
Microsoft::WRL::ComPtr<ICoreWebView2DevToolsProtocolEventReceiver>
runtime_exception_receiver;
Microsoft::WRL::ComPtr<ICoreWebView2DevToolsProtocolEventReceiver>
log_entry_receiver;
EventRegistrationToken navigation_starting_token{};
EventRegistrationToken navigation_completed_token{};
EventRegistrationToken source_changed_token{};
EventRegistrationToken history_changed_token{};
EventRegistrationToken title_changed_token{};
EventRegistrationToken new_window_token{};
EventRegistrationToken process_failed_token{};
EventRegistrationToken runtime_console_token{};
EventRegistrationToken runtime_exception_token{};
EventRegistrationToken log_entry_token{};
EventRegistrationToken server_certificate_error_token{};
EventRegistrationToken launching_external_uri_token{};
Microsoft::WRL::ComPtr<ICoreWebView2_14> permissive_certificates;
Microsoft::WRL::ComPtr<ICoreWebView2_18> external_uri_schemes;
AgentBrowserNavigationTracker navigation;
// 已经交给系统 shell 打开的外部 URI。NavigationStarting 与
// LaunchingExternalUriScheme 谁先到都可能触发交接,用它去重防止启动两次。
std::string external_handoff_uri;
// 证书放行后需要重新发起的顶层地址。
std::string current_navigation_uri;
std::vector<std::string> console_logs;
std::uint64_t element_selection_generation = 0;
std::uint64_t favicon_generation = 0;
std::uint64_t current_navigation_id = 0;
std::string content_state_before_navigation =
kAgentBrowserContentStateEmpty;
std::string favicon_before_navigation;
std::vector<QueuedCdpCall> queued_cdp;
};
Microsoft::WRL::ComPtr<ICoreWebView2Environment> environment;
webview::detail::mswebview2::loader loader;
HWND browser_widget = nullptr;
std::unordered_map<std::string, std::shared_ptr<Page>> pages;
std::vector<std::string> page_order;
std::string active_page;
std::uint64_t next_page_sequence = 0;
std::string proxy_pipe_name;
std::string proxy_auth_token;
std::atomic<bool> proxy_stopping{false};
std::thread proxy_thread;
#endif
Impl(void* parent,
std::int64_t pid,
std::string instance_id,
StateHandler handler,
DispatchHandler dispatcher,
std::string data_dir)
: parent_window(parent),
desktop_pid(pid),
desktop_instance_id(std::move(instance_id)),
acecode_dir(std::move(data_dir)),
state_handler(std::move(handler)),
dispatch_handler(std::move(dispatcher)) {
#ifdef _WIN32
host_state.supported = parent_window != nullptr;
#else
host_state.error =
"Agent Browser is available on Windows and macOS 14+ Desktop only";
#endif
}
~Impl() {
#ifdef _WIN32
proxy_stopping.store(true);
if (proxy_thread.joinable()) proxy_thread.join();
std::vector<std::shared_ptr<Page>> remaining;
{
std::lock_guard<std::mutex> lock(state_mutex);
for (const auto& [id, page] : pages) remaining.push_back(page);
pages.clear();
page_order.clear();
active_page.clear();
}
for (const auto& page : remaining) teardown_page(page);
environment.Reset();
if (browser_widget && ::IsWindow(browser_widget)) {
::DestroyWindow(browser_widget);
}
browser_widget = nullptr;
#endif
cleanup_agent_browser_runtime_manifest(desktop_instance_id, acecode_dir);
}
void emit_state(const AgentBrowserState& state) const {
if (state_handler) state_handler(state);
}
AgentBrowserState state(const std::string& requested_page = {}) const {
std::lock_guard<std::mutex> lock(state_mutex);
#ifdef _WIN32
const std::string id = requested_page.empty() ? active_page : requested_page;
const auto found = pages.find(id);
if (found != pages.end()) return found->second->state;
#else
(void)requested_page;
#endif
return host_state;
}
std::vector<AgentBrowserState> states() const {
std::vector<AgentBrowserState> result;
std::lock_guard<std::mutex> lock(state_mutex);
#ifdef _WIN32
result.reserve(page_order.size());
for (const std::string& id : page_order) {
const auto found = pages.find(id);
if (found != pages.end()) result.push_back(found->second->state);
}
#endif
return result;
}
std::string active_page_id() const {
std::lock_guard<std::mutex> lock(state_mutex);
#ifdef _WIN32
return active_page;
#else
return {};
#endif
}
void update_host_state(
const std::function<void(AgentBrowserState&)>& update) {
AgentBrowserState snapshot;
{
std::lock_guard<std::mutex> lock(state_mutex);
update(host_state);
snapshot = host_state;
}
emit_state(snapshot);
}
#ifdef _WIN32
std::shared_ptr<Page> find_page(const std::string& requested_page) const {
std::lock_guard<std::mutex> lock(state_mutex);
const std::string id = requested_page.empty() ? active_page : requested_page;
const auto found = pages.find(id);
return found == pages.end() ? nullptr : found->second;
}
bool page_shared_with_agent(const std::shared_ptr<Page>& page) const {
if (!page) return false;
std::lock_guard<std::mutex> lock(state_mutex);
return !page->closing && page->state.shared_with_agent;
}
bool require_agent_shared_page(
const std::shared_ptr<Page>& page,
const std::string& page_id,
const std::shared_ptr<PendingProxyCall>& pending) const {
if (page_shared_with_agent(page)) return true;
finish_proxy_call(
pending,
{{"ok", false},
{"page_id", page_id},
{"error", "page_not_shared_with_agent"}});
return false;
}
void update_page(
const std::shared_ptr<Page>& page,
const std::function<void(AgentBrowserState&)>& update) {
if (!page) return;
AgentBrowserState snapshot;
{
std::lock_guard<std::mutex> lock(state_mutex);
if (page->closing && !page->state.closed) return;
update(page->state);
snapshot = page->state;
}
emit_state(snapshot);
}
#endif
void fail(const std::string& message) {
LOG_ERROR("[agent-browser] " + message);
update_host_state([&](AgentBrowserState& state) {
state.ready = false;
state.loading = false;
state.error = message;
});
#ifdef _WIN32
for (const auto& page_state : states()) {
if (auto page = find_page(page_state.page_id)) {
update_page(page, [&](AgentBrowserState& state) {
state.ready = false;
state.loading = false;
state.error = message;
});
}
}
#endif
}
static void finish_proxy_call(
const std::shared_ptr<PendingProxyCall>& pending,
nlohmann::json response) {
{
std::lock_guard<std::mutex> lock(pending->mutex);
if (pending->completed) return;
pending->completed = true;
pending->response = std::move(response);
}
pending->ready.notify_all();
}
#ifdef _WIN32
void start() {
if (!parent_window || !::IsWindow(static_cast<HWND>(parent_window))) {
fail("Agent Browser parent window is unavailable");
return;
}
browser_widget = create_agent_browser_widget(
static_cast<HWND>(parent_window));
if (!browser_widget) {
fail("failed to create Agent Browser native child host (Windows error " +
std::to_string(::GetLastError()) + ")");
return;
}
const auto user_data_path = agent_browser_user_data_path(acecode_dir);
std::error_code ec;
std::filesystem::create_directories(user_data_path, ec);
if (ec) {
fail("failed to create Agent Browser profile: " + ec.message());
return;
}
auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
const HRESULT browser_arguments_result =
options->put_AdditionalBrowserArguments(
L"--allow-file-access-from-files");
if (FAILED(browser_arguments_result)) {
fail("failed to enable Agent Browser local-file access (" +
hresult_text(browser_arguments_result) + ")");
return;
}
const auto weak = weak_from_this();
auto completed = Microsoft::WRL::Callback<
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[weak](HRESULT result, ICoreWebView2Environment* value) -> HRESULT {
if (const auto self = weak.lock()) {
self->environment_created(result, value);
}
return S_OK;
});
const HRESULT result = loader.create_environment_with_options(
nullptr, user_data_path.wstring().c_str(), options.Get(),
completed.Get());
if (FAILED(result)) {
fail("failed to start Agent Browser WebView2 environment (" +
hresult_text(result) + ")");
}
}
bool publish_proxy() {
if (!dispatch_handler) {
fail("Agent Browser UI dispatcher is unavailable");
return false;
}
proxy_pipe_name = "\\\\.\\pipe\\ACECode-AgentBrowser-" +
std::to_string(desktop_pid) + "-" +
desktop_instance_id;
try {
proxy_auth_token = acecode::generate_auth_token();
proxy_thread = std::thread([this] { proxy_loop(); });
} catch (const std::exception& error) {
fail(std::string("failed to start Agent Browser proxy: ") +
error.what());
return false;
}
AgentBrowserRuntimeManifest manifest;
manifest.desktop_pid = desktop_pid;
manifest.desktop_instance_id = desktop_instance_id;
manifest.user_data_dir = acecode::path_to_utf8(
agent_browser_user_data_path(acecode_dir));
manifest.pipe_name = proxy_pipe_name;
manifest.auth_token = proxy_auth_token;
manifest.ready_at_ms = now_unix_ms();
if (!write_agent_browser_runtime_manifest(manifest, acecode_dir)) {
fail("failed to publish Agent Browser runtime endpoint");
return false;
}
return true;
}
void environment_created(HRESULT result, ICoreWebView2Environment* value) {
if (FAILED(result) || !value) {
fail("Agent Browser WebView2 environment initialization failed (" +
hresult_text(result) + ")");
return;
}
environment = value;
if (!publish_proxy()) return;
update_host_state([](AgentBrowserState& state) {
state.ready = true;
state.error.clear();
});
std::vector<std::shared_ptr<Page>> pending_pages;
{
std::lock_guard<std::mutex> lock(state_mutex);
for (const auto& [id, page] : pages) pending_pages.push_back(page);
}
for (const auto& page : pending_pages) begin_create_controller(page);
LOG_INFO("[agent-browser] WebView2 environment ready; Desktop proxy published");
}
std::string create_page_on_ui(bool shared_with_agent) {
auto page = std::make_shared<Page>();
page->id = "browser-" + std::to_string(desktop_pid) + "-" +
std::to_string(++next_page_sequence);
page->state.page_id = page->id;
page->state.supported = true;
page->state.shared_with_agent = shared_with_agent;
{
std::lock_guard<std::mutex> lock(state_mutex);
pages.emplace(page->id, page);
page_order.push_back(page->id);
}
emit_state(page->state);