-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent-script.js
More file actions
5788 lines (5229 loc) · 230 KB
/
Copy pathcontent-script.js
File metadata and controls
5788 lines (5229 loc) · 230 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
// Goby - AI 浏览器助手 | Content Script — 消息监听 + 面板注入 + 设置模态框
// Plan 01-03: 面板浮层注入、消息转发、设置模态框(PANEL-07)
// Plan 03-01: 流式 LLM 调用、安全渲染管道、回退机制(AGENT-02/03/04/06)
// Plan 03-02: Agent 主循环、工具执行引擎、限制保护(AGENT-01/05)
// 依赖: storage.js, panel.js(通过 manifest content_scripts 顺序注入)
(function () {
'use strict';
// i18n 翻译函数引用
var t = window.GobyI18n ? window.GobyI18n.t : function (k, p) { return k; };
console.log('Goby content script loaded on:', window.location.hostname);
// ---- Message Listener ----
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
// T-01-07: 验证消息来源为扩展自身
if (sender.id !== chrome.runtime.id) {
return false;
}
if (message.action === 'toggle-panel') {
if (message.visible) {
GobyPanel.show();
} else {
GobyPanel.hide();
}
return false;
}
if (message.action === 'get-panel-state') {
sendResponse(GobyPanel.getState());
return true; // 异步响应
}
// Plan 03-01: stream-chunk 事件 — 从 SW 接收 LLM 流式响应
if (message.action === 'stream-chunk') {
if (window.GobyAgent && typeof window.GobyAgent.handleStreamChunk === 'function') {
window.GobyAgent.handleStreamChunk(message.data);
}
return false;
}
// Phase 12 / Plan 12-01 Task 2: watcher-event — SW 转发的 watcher 通知(来自 ISOLATED/MAIN world watcher)
// 入 _watcherEventQueue,由下一次 agent 工具调用结果末尾附带(_attachWatcherEvents)
if (message.action === 'watcher-event') {
try {
var notice = '[watcher ' + message.watcherId + '] ' +
(message.type === 'applied' ? 'applied action to ' + message.matchedCount + ' nodes'
: 'detected ' + message.matchedCount + ' nodes matching ' + (message.selector || '?') +
(message.sample ? ': ' + message.sample : ''));
if (!Array.isArray(_watcherEventQueue)) _watcherEventQueue = [];
_watcherEventQueue.push({ watcherId: message.watcherId, notice: notice, at: Date.now() });
// 队列上限:保留最近 50 条(旧事件被丢弃)
if (_watcherEventQueue.length > 50) _watcherEventQueue.shift();
} catch (e) { /* 静默 — watcher 通知失败不应阻断页面 */ }
return false; // fire-and-forget,不需要 sendResponse
}
// Phase 8 / NAV-08 / D-10: workflow-init — SW 注入工作 Tab 角色 + inherited 上下文
// 工作 Tab 是全新页面,没有 interrupted session 需要恢复;isWorkflowInit=true 等价
// 新 session 的第一次 processAgentMessage 调用(不复用 resume 标记,避免误触发续跑)
if (message.action === 'workflow-init') {
window.__gobyWorkflowId = message.workflow_id;
// Phase 8 fix (260621-gKz): 重置 messages 数组,避免同一 worker Tab 多次
// workflow 启动(如用户连续 page_open_tab)时累积旧 messages 导致顺序错位
// 触发 HTTP 400(tool message 在 assistant.tool_calls 之前)
_agentState.messages = [];
// push inherited messages(chat Tab 最后 5 条,让工作 Tab 有上下文)
if (Array.isArray(message.inherited_messages)) {
for (var ii = 0; ii < message.inherited_messages.length; ii++) {
_agentState.messages.push(message.inherited_messages[ii]);
}
}
// push initial user message(D-10:让 LLM 知道自己在工作 Tab 角色 + 任务目标)
if (message.initial_user_message) {
_agentState.messages.push({ role: 'user', content: message.initial_user_message });
}
// 自动启动 Agent 循环 — isWorkflowInit 路径不复用 resume(避免误触发 initSession resume)
// processAgentMessage 内识别 isWorkflowInit=true 时 push 角色 user message 路径
if (window.GobyAgent && typeof window.GobyAgent.processAgentMessage === 'function') {
window.GobyAgent.processAgentMessage(null, { isWorkflowInit: true });
}
return false;
}
// Phase 8 / NAV-08 / D-11: workflow_progress — 工作 Tab Agent 增量转发回 chat Tab
// Claude's Discretion 锁定:复用 GobyPanel.appendMessage('bot', ...) + badge 前缀
// 不引入新 panel.js 方法(保持轻量);workflow_id badge 通过文本前缀 [W-xxxx] 实现
if (message.action === 'workflow_progress') {
var wfShort = (message.workflow_id || 'wf').slice(0, 8);
var progressContent = (message.data && message.data.content) || '';
if (window.GobyPanel && typeof window.GobyPanel.appendMessage === 'function') {
window.GobyPanel.appendMessage('bot', '[W-' + wfShort + '] ' + progressContent);
}
return false;
}
// Phase 8 / NAV-08 / D-15: workflow_complete — 工作 Tab 调 page_finish_workflow 后 SW 转发 summary
// chat Tab 把 summary 作为 user message 追加 + 以 resume 模式调 processAgentMessage 续跑
if (message.action === 'workflow_complete') {
var wcWfId = message.workflow_id;
var wcSummary = (message.data && message.data.summary) || '';
var fromWorkflowText = '[From workflow ' + wcWfId + '] ' + wcSummary;
_agentState.messages.push({ role: 'user', content: fromWorkflowText });
if (window.GobyPanel && typeof window.GobyPanel.appendMessage === 'function') {
window.GobyPanel.appendMessage('user', fromWorkflowText);
}
if (window.GobyAgent && typeof window.GobyAgent.processAgentMessage === 'function') {
window.GobyAgent.processAgentMessage(null, { resume: true, fromWorkflow: wcWfId });
}
return false;
}
// Phase 8 / NAV-08: workflow_error — 工作 Tab 报错或被关闭
// chat Tab push assistant 错误消息 + 恢复输入框(isProcessing=false)
if (message.action === 'workflow_error') {
var weWfId = message.workflow_id;
var weReason = (message.data && message.data.reason) || '未知错误';
var errMsg = '工作流 ' + weWfId + ' 失败: ' + weReason;
_agentState.messages.push({ role: 'assistant', content: errMsg });
if (window.GobyPanel && typeof window.GobyPanel.appendMessage === 'function') {
window.GobyPanel.appendMessage('bot', errMsg);
}
_agentState.isProcessing = false;
if (window.GobyPanel && typeof window.GobyPanel.setAgentRunning === 'function') {
window.GobyPanel.setAgentRunning(false);
}
if (window.GobyPanel && window.GobyPanel._inputEl) window.GobyPanel._inputEl.disabled = false;
if (window.GobyPanel && window.GobyPanel._sendBtn) window.GobyPanel._sendBtn.disabled = false;
return false;
}
// Phase 8 fix: sessions-deleted — SW 广播,通知所有 tab 重置本地状态
// deleteAllSessions 委托 SW 执行后,SW 广播此消息给所有 tab。
// 每个 content-script 重置 _agentState 并创建新 session,
// 而不是只靠发起清除的 tab 自己做。
if (message.action === 'sessions-deleted') {
_agentState.messages = [];
_agentState.isProcessing = false;
_agentState.roundCount = 0;
GobyPanel.updateRoundCount(0);
if (window.GobyPanel && typeof window.GobyPanel.refreshSessionSidebar === 'function') {
window.GobyPanel.refreshSessionSidebar();
}
return false;
}
return false;
});
// ---- Init — 面板默认隐藏,autoStart 控制自动展开 ----
// Phase 03 UAT 测试 5:先 await GobyPanel.init(),再 initSession(),避免渲染时序竞争
// (否则 loadSession 完成时面板未就绪,renderWelcome + appendMessage(历史) 被静默跳过)
// Plan 09-03: 首次运行预装内置技能(gobySkills 为空时自动注入 5 个技能)
// Plan 10-02: MCP 工具拉取不阻塞 session 初始化(initSession 之后 fire-and-forget)
GobyPanel.init().then(function () {
// 先预装内置技能(异步),再初始化会话
return _preloadBuiltinSkills().then(function () {
// 面板就绪 + 技能就绪后再初始化会话
initSession();
// MCP 工具拉取 fire-and-forget — 不阻塞 session 初始化
_loadMcpTools();
return chrome.storage.local.get(['gobyPanelState']).then(function (result) {
var panelState = result.gobyPanelState || {};
if (panelState.autoStart) {
return GobyPanel.show();
}
});
});
}).catch(function () {
// 初始化失败 — 退化到立即初始化会话(无面板渲染)
// 仍尝试预装技能
_preloadBuiltinSkills().then(function () {
initSession();
_loadMcpTools();
});
});
// ==================================================================
// 设置模态框(PANEL-07) — 复用 GobyStorage API 进行 Profile CRUD
// 可被 Phase 2 复用
// ==================================================================
/**
* 创建模态框表单组(不含眼睛切换)
*/
function createFormGroup(labelText, inputId, inputType, placeholder) {
var group = document.createElement('div');
group.className = 'form-group';
var label = document.createElement('label');
label.htmlFor = inputId;
label.textContent = labelText;
var wrapper = document.createElement('div');
wrapper.className = 'input-wrapper';
var input = document.createElement('input');
input.type = inputType;
input.id = inputId;
input.placeholder = placeholder;
input.autocomplete = 'off';
wrapper.appendChild(input);
group.appendChild(label);
group.appendChild(wrapper);
return group;
}
/**
* 创建模态框 API Key 表单组(带眼睛切换)
* T-01-09: API Key 默认 password 类型,仅用户主动操作显示明文
*/
function createFormGroupWithEye(labelText, inputId, placeholder) {
var group = document.createElement('div');
group.className = 'form-group';
var label = document.createElement('label');
label.htmlFor = inputId;
label.textContent = labelText;
var wrapper = document.createElement('div');
wrapper.className = 'input-wrapper';
var input = document.createElement('input');
input.type = 'password';
input.id = inputId;
input.placeholder = placeholder;
input.autocomplete = 'off';
var eyeBtn = document.createElement('button');
eyeBtn.className = 'eye-toggle';
eyeBtn.type = 'button';
eyeBtn.id = 'modal-eyeToggle';
eyeBtn.textContent = '\u{1F441}'; // 👁
eyeBtn.title = '显示/隐藏 API Key';
eyeBtn.addEventListener('click', function () {
if (input.type === 'password') {
input.type = 'text';
eyeBtn.textContent = '\u{1F648}'; // 🙈
} else {
input.type = 'password';
eyeBtn.textContent = '\u{1F441}'; // 👁
}
});
wrapper.appendChild(input);
wrapper.appendChild(eyeBtn);
group.appendChild(label);
group.appendChild(wrapper);
return group;
}
/**
* 加载 profiles 并填充模态框下拉框
*/
function loadModalProfiles() {
GobyStorage.getProfiles().then(function (profiles) {
GobyStorage.getActiveProfile().then(function (active) {
var select = document.getElementById('modal-profile-select');
if (!select) return;
select.innerHTML = '';
var names = Object.keys(profiles);
names.forEach(function (name) {
var opt = document.createElement('option');
opt.value = name;
opt.textContent = name;
select.appendChild(opt);
});
var target = active && profiles[active] ? active : (names.length > 0 ? names[0] : '');
if (target) {
select.value = target;
}
loadModalProfileForm(target, profiles);
});
}).catch(function () {
// 读取失败 — 保持空状态
});
}
/**
* 将指定 Profile 加载到模态框表单
*/
function loadModalProfileForm(name, profiles) {
if (!name) return;
var baseUrlInput = document.getElementById('modal-baseUrl');
var apiKeyInput = document.getElementById('modal-apiKey');
var modelInput = document.getElementById('modal-model');
if (!baseUrlInput) return;
if (!profiles) {
GobyStorage.getProfiles().then(function (p) {
var profile = p[name] || {};
baseUrlInput.value = profile.baseUrl || '';
apiKeyInput.value = profile.apiKey || '';
modelInput.value = profile.model || '';
updateHttpsWarning();
});
return;
}
var profile = profiles[name] || {};
baseUrlInput.value = profile.baseUrl || '';
apiKeyInput.value = profile.apiKey || '';
modelInput.value = profile.model || '';
updateHttpsWarning();
// 加载 autoStart 状态
chrome.storage.local.get(['gobyPanelState'], function (result) {
var panelState = result.gobyPanelState || {};
var autoCheck = document.getElementById('modal-autoStart');
if (autoCheck) {
autoCheck.checked = panelState.autoStart === true;
}
});
}
/**
* 更新 HTTPS 警告显示 — 仅 baseUrl 不以 https 开头时显示
*/
function updateHttpsWarning() {
var baseUrl = document.getElementById('modal-baseUrl');
var warning = document.getElementById('modal-https-warning');
if (!baseUrl || !warning) return;
var value = baseUrl.value.trim();
if (value && !value.startsWith('https://')) {
warning.classList.remove('hidden');
} else {
warning.classList.add('hidden');
}
}
/**
* 表单验证 — 检查所有字段非空
* @returns {boolean} 验证是否通过
*/
function validateModalForm() {
var fields = [
{ id: 'modal-baseUrl', name: 'API Base URL' },
{ id: 'modal-apiKey', name: 'API Key' },
{ id: 'modal-model', name: 'Model Name' }
];
// 清除旧错误提示
document.querySelectorAll('.goby-field-error').forEach(function (el) {
el.remove();
});
var valid = true;
fields.forEach(function (field) {
var input = document.getElementById(field.id);
if (!input) return;
// 清除输入框的错误样式
var wrapper = input.parentElement;
if (wrapper) {
wrapper.style.border = '';
}
if (!input.value.trim()) {
valid = false;
var error = document.createElement('span');
error.className = 'goby-field-error';
error.textContent = '此项为必填';
var wrapper2 = input.parentElement;
if (wrapper2 && wrapper2.parentElement) {
wrapper2.parentElement.appendChild(error);
}
}
});
return valid;
}
/**
* 保存当前模态框表单到 Profile(由保存按钮触发)
*/
function saveModalProfile() {
if (!validateModalForm()) {
return;
}
var select = document.getElementById('modal-profile-select');
if (!select || !select.value) return;
var name = select.value;
var config = GobyFormHelpers.buildProfileConfigFromForm(
document.getElementById('modal-baseUrl').value,
document.getElementById('modal-apiKey').value,
document.getElementById('modal-model').value
);
var v = GobyFormHelpers.validateProfileConfig(config);
if (!v.ok) {
showModalFeedback(v.message, 'error', 3000);
if (v.field === 'baseUrl') {
var bEl = document.getElementById('modal-baseUrl');
if (bEl) bEl.focus();
} else if (v.field === 'apiKey') {
var kEl = document.getElementById('modal-apiKey');
if (kEl) kEl.focus();
}
return;
}
GobyStorage.saveProfile(name, config).then(function () {
showModalFeedback(t('modal.save_success'), 'success');
}).catch(function (err) {
showModalFeedback(t('modal.save_fail', { msg: err.message || '未知错误' }), 'error');
});
}
/**
* 编辑当前选中的 Profile(对标 popup.js btnEditProfile 行为)
* 重新加载表单 + 聚焦 + 全选 Base URL + 显示编辑模式提示
*/
function editModalProfile() {
var select = document.getElementById('modal-profile-select');
if (!select || !select.value) return;
var name = select.value;
loadModalProfileForm(name);
var baseUrlInput = document.getElementById('modal-baseUrl');
if (baseUrlInput) {
baseUrlInput.focus();
baseUrlInput.select();
}
showModalFeedback(t('modal.edit_hint', { name: name }), 'success', 1500);
}
/**
* 添加新 Profile
*/
function addModalProfile() {
var name = prompt(t('modal.add_prompt'));
if (!name || name.trim() === '') return;
name = name.trim();
// 检查名称是否已存在
GobyStorage.getProfiles().then(function (profiles) {
if (profiles[name]) {
alert(t('modal.add_duplicate'));
return;
}
GobyStorage.saveProfile(name, { baseUrl: '', apiKey: '', model: '' }).then(function () {
loadModalProfiles();
// 选中新创建的 profile
var select = document.getElementById('modal-profile-select');
if (select) {
select.value = name;
}
// 聚焦 Base URL
var baseUrlInput = document.getElementById('modal-baseUrl');
if (baseUrlInput) baseUrlInput.focus();
}).catch(function (err) {
showModalFeedback(t('modal.add_fail', { msg: err.message || '未知错误' }), 'error');
});
});
}
/**
* 删除选中的 Profile
*/
function deleteModalProfile() {
var select = document.getElementById('modal-profile-select');
if (!select || !select.value) return;
var name = select.value;
if (!confirm(t('modal.delete_confirm', { name: name }))) {
return;
}
GobyStorage.deleteProfile(name).then(function () {
loadModalProfiles();
showModalFeedback(t('modal.delete_success', { name: name }), 'error', 1500);
}).catch(function (err) {
showModalFeedback(t('modal.delete_fail', { msg: err.message || '未知错误' }), 'error');
});
}
/**
* 在模态框内显示反馈消息
*/
function showModalFeedback(message, type, duration) {
duration = duration || 2000;
var statusEl = document.getElementById('modal-save-status');
if (!statusEl) return;
statusEl.textContent = message;
statusEl.className = 'goby-modal-save-status visible ' + type;
statusEl.style.opacity = '1';
// 清除之前的定时器
if (statusEl._feedbackTimer) {
clearTimeout(statusEl._feedbackTimer);
}
statusEl._feedbackTimer = setTimeout(function () {
statusEl.style.opacity = '0';
setTimeout(function () {
statusEl.className = 'goby-modal-save-status';
statusEl.style.opacity = '';
}, 300);
}, duration);
}
/**
* 打开设置模态框 — 构建 DOM 并挂载到页面
*/
function openSettingsModal() {
// T-01-11: 防止重复打开
if (document.querySelector('.goby-modal-backdrop')) return;
// ---- Backdrop ----
var backdrop = document.createElement('div');
backdrop.className = 'goby-modal-backdrop';
backdrop.addEventListener('click', function (e) {
if (e.target === backdrop) {
closeSettingsModal();
}
});
// ---- Modal Container ----
var modal = document.createElement('div');
modal.className = 'goby-modal';
// ---- Header ----
var header = document.createElement('div');
header.className = 'goby-modal-header';
var title = document.createElement('span');
title.className = 'goby-modal-header-title';
title.textContent = t('modal.title');
var closeBtn = document.createElement('button');
closeBtn.className = 'goby-modal-close-btn';
closeBtn.textContent = '×'; // ×
closeBtn.addEventListener('click', closeSettingsModal);
header.appendChild(title);
header.appendChild(closeBtn);
modal.appendChild(header);
// ---- Body ----
var body = document.createElement('div');
body.className = 'goby-modal-body';
// Profile selector row
var profileRow = document.createElement('div');
profileRow.className = 'goby-modal-profile-row';
var profileLabel = document.createElement('span');
profileLabel.className = 'profile-label';
profileLabel.textContent = t('modal.api_config_label');
var profileSelect = document.createElement('select');
profileSelect.className = 'goby-modal-profile-select';
profileSelect.id = 'modal-profile-select';
var btnGroup = document.createElement('div');
btnGroup.className = 'goby-modal-btn-group';
var addBtn = document.createElement('button');
addBtn.className = 'goby-modal-btn';
addBtn.textContent = '+'; // +
addBtn.title = t('modal.add_btn_title');
var editBtn = document.createElement('button');
editBtn.className = 'goby-modal-btn';
editBtn.textContent = '✎'; // ✎
editBtn.title = t('modal.edit_btn_title');
var deleteBtn = document.createElement('button');
deleteBtn.className = 'goby-modal-btn delete-btn';
deleteBtn.textContent = '✕'; // ✕
deleteBtn.title = t('modal.delete_btn_title');
btnGroup.appendChild(addBtn);
btnGroup.appendChild(editBtn);
btnGroup.appendChild(deleteBtn);
profileRow.appendChild(profileLabel);
profileRow.appendChild(profileSelect);
profileRow.appendChild(btnGroup);
body.appendChild(profileRow);
// Form fields
body.appendChild(createFormGroup('API Base URL', 'modal-baseUrl', 'text', 'http://127.0.0.1:8765/v1'));
body.appendChild(createFormGroupWithEye('API Key', 'modal-apiKey', ''));
body.appendChild(createFormGroup('Model Name', 'modal-model', 'text', '例如: Qwen3.6-35B-A3B'));
// Auto-start toggle (与 popup 共享 lib/toggle.css 样式)
var autoCheckRow = document.createElement('div');
autoCheckRow.className = 'panel-toggle-row';
var autoCheckLabel = document.createElement('span');
autoCheckLabel.className = 'panel-toggle-label';
autoCheckLabel.textContent = t('modal.autostart_label');
var autoCheckSwitch = document.createElement('label');
autoCheckSwitch.className = 'toggle-switch';
var autoCheckInput = document.createElement('input');
autoCheckInput.type = 'checkbox';
autoCheckInput.id = 'modal-autoStart';
var autoCheckSlider = document.createElement('span');
autoCheckSlider.className = 'toggle-slider';
autoCheckSwitch.appendChild(autoCheckInput);
autoCheckSwitch.appendChild(autoCheckSlider);
autoCheckRow.appendChild(autoCheckLabel);
autoCheckRow.appendChild(autoCheckSwitch);
body.appendChild(autoCheckRow);
// HTTPS warning
var httpsWarning = document.createElement('div');
httpsWarning.className = 'goby-https-warning hidden';
httpsWarning.id = 'modal-https-warning';
httpsWarning.textContent = t('modal.https_warning');
body.appendChild(httpsWarning);
// ---- 语言选择行 ----
var langRow = document.createElement('div');
langRow.className = 'panel-toggle-row';
var langLabel = document.createElement('span');
langLabel.className = 'panel-toggle-label';
langLabel.textContent = t('modal.language_label');
var langSelect = document.createElement('select');
langSelect.id = 'goby-lang-select';
langSelect.style.cssText = 'padding:4px 8px;border:1px solid #d1d5db;border-radius:4px;font-size:13px;';
var optZh = document.createElement('option');
optZh.value = 'zh'; optZh.textContent = t('modal.lang_zh');
var optEn = document.createElement('option');
optEn.value = 'en'; optEn.textContent = t('modal.lang_en');
optZh.selected = window.GobyI18n.getLocale() === 'zh';
optEn.selected = window.GobyI18n.getLocale() === 'en';
langSelect.appendChild(optZh);
langSelect.appendChild(optEn);
langRow.appendChild(langLabel);
langRow.appendChild(langSelect);
body.appendChild(langRow);
// 切换事件
langSelect.addEventListener('change', function () {
window.GobyI18n.setLocale(this.value);
showModalFeedback(t('modal.lang_switch_msg'), 'success', 3000);
});
// ---- Plan 09-04: 技能管理区域 ----
var skillsSection = document.createElement('div');
skillsSection.className = 'goby-skills-section';
// 节标题 + 导入按钮
var skillsTitleRow = document.createElement('div');
skillsTitleRow.className = 'goby-skills-section-title';
var skillsTitleText = document.createElement('span');
skillsTitleText.textContent = t('modal.skills_title') || '技能管理';
var skillsImportBtn = document.createElement('button');
skillsImportBtn.className = 'goby-skills-import-btn';
skillsImportBtn.id = 'goby-skills-import-btn';
skillsImportBtn.textContent = t('modal.skills_import_btn') || '+ 导入技能';
skillsTitleRow.appendChild(skillsTitleText);
skillsTitleRow.appendChild(skillsImportBtn);
skillsSection.appendChild(skillsTitleRow);
// 导入行(默认隐藏)
var importRow = document.createElement('div');
importRow.className = 'goby-skill-import-row';
importRow.id = 'goby-skill-import-row';
importRow.style.display = 'none';
var importInput = document.createElement('input');
importInput.type = 'text';
importInput.className = 'goby-skill-import-input';
importInput.id = 'goby-skill-import-input';
importInput.placeholder = 'https://raw.githubusercontent.com/.../SKILL.md';
var importConfirm = document.createElement('button');
importConfirm.className = 'goby-skill-import-confirm-btn';
importConfirm.id = 'goby-skill-import-confirm-btn';
importConfirm.textContent = t('modal.skills_import_confirm') || '确认导入';
var importCancel = document.createElement('button');
importCancel.className = 'goby-skill-import-cancel-btn';
importCancel.id = 'goby-skill-import-cancel-btn';
importCancel.textContent = t('modal.skills_cancel') || '取消';
importRow.appendChild(importInput);
importRow.appendChild(importConfirm);
importRow.appendChild(importCancel);
// 文件上传按钮
var fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.md,.SKILL.md,.txt';
fileInput.id = 'goby-skill-file-input';
fileInput.style.display = 'none';
var fileBtn = document.createElement('button');
fileBtn.className = 'goby-skill-import-file-btn';
var uploadText = t('modal.skills_upload');
fileBtn.textContent = (uploadText && uploadText !== 'modal.skills_upload') ? uploadText : '📁 上传文件';
fileBtn.addEventListener('click', function () { fileInput.click(); });
importRow.appendChild(fileBtn);
importRow.appendChild(fileInput);
skillsSection.appendChild(importRow);
// 反馈信息
var skillFeedback = document.createElement('div');
skillFeedback.className = 'goby-skill-feedback';
skillFeedback.id = 'goby-skill-feedback';
skillsSection.appendChild(skillFeedback);
// 已安装技能列表
var skillsListContainer = document.createElement('div');
skillsListContainer.className = 'goby-skills-list';
skillsListContainer.id = 'goby-skills-list';
skillsSection.appendChild(skillsListContainer);
// 推荐技能区域
var recommendedSection = document.createElement('div');
recommendedSection.className = 'goby-recommended-section';
recommendedSection.id = 'goby-recommended-section';
var recommendedTitle = document.createElement('div');
recommendedTitle.className = 'goby-recommended-title';
recommendedTitle.textContent = t('modal.skills_recommended') || '推荐安装';
recommendedSection.appendChild(recommendedTitle);
var recommendedList = document.createElement('div');
recommendedList.id = 'goby-recommended-list';
recommendedSection.appendChild(recommendedList);
skillsSection.appendChild(recommendedSection);
body.appendChild(skillsSection);
// ---- Phase 10-03: MCP Servers 管理区域 ----
var mcpSection = document.createElement('div');
mcpSection.className = 'goby-mcp-section';
// 节标题 + 添加按钮
var mcpTitleRow = document.createElement('div');
mcpTitleRow.className = 'goby-mcp-section-title';
var mcpTitleText = document.createElement('span');
mcpTitleText.textContent = t('modal.mcp_title');
var mcpAddBtn = document.createElement('button');
mcpAddBtn.className = 'goby-mcp-add-btn';
mcpAddBtn.id = 'goby-mcp-add-btn';
mcpAddBtn.textContent = t('modal.mcp_add_btn');
mcpTitleRow.appendChild(mcpTitleText);
mcpTitleRow.appendChild(mcpAddBtn);
mcpSection.appendChild(mcpTitleRow);
// 反馈信息容器
var mcpFeedback = document.createElement('div');
mcpFeedback.className = 'goby-mcp-feedback';
mcpFeedback.id = 'goby-mcp-feedback';
mcpSection.appendChild(mcpFeedback);
// 空状态提示
var mcpNoServers = document.createElement('div');
mcpNoServers.className = 'goby-mcp-no-servers';
mcpNoServers.id = 'goby-mcp-no-servers';
mcpNoServers.textContent = t('modal.mcp_no_servers');
mcpSection.appendChild(mcpNoServers);
// Server 列表容器
var mcpList = document.createElement('div');
mcpList.className = 'goby-mcp-list';
mcpList.id = 'goby-mcp-list';
mcpSection.appendChild(mcpList);
body.appendChild(mcpSection);
// ---- 技能管理事件绑定 ----
// 显示/隐藏导入 URL 输入行
skillsImportBtn.addEventListener('click', function () {
var row = document.getElementById('goby-skill-import-row');
if (row) {
var isVisible = row.style.display !== 'none';
row.style.display = isVisible ? 'none' : 'flex';
if (!isVisible && importInput) {
importInput.value = '';
importInput.focus();
}
}
});
// 取消导入
importCancel.addEventListener('click', function () {
importRow.style.display = 'none';
importInput.value = '';
hideSkillFeedback();
});
// 文件上传导入
fileInput.addEventListener('change', function () {
var file = fileInput.files && fileInput.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function (e) {
var markdown = e.target.result;
if (!markdown || typeof markdown !== 'string') {
showSkillFeedback('文件内容为空', 'error');
return;
}
// 直接走 parse + validate + save(不需要 SW 下载)
var parseResult;
try {
parseResult = SkillLoader.parseSkillMarkdown(markdown);
} catch (err) {
showSkillFeedback('解析失败: ' + (err.message || String(err)), 'error');
return;
}
var validation = SkillLoader.validateSkill(parseResult);
if (!validation.valid) {
showSkillFeedback((t('modal.skills_import_failed') || '导入失败') + ': ' + validation.errors.join('; '), 'error');
return;
}
GobyStorage.saveSkill(validation.skillManifest.domain, {
name: validation.skillManifest.name,
description: validation.skillManifest.description,
domain: validation.skillManifest.domain,
actions: validation.skillManifest.actions,
source: 'imported'
}).then(function () {
showSkillFeedback((t('modal.skills_import_success') || '已安装') + ': ' + validation.skillManifest.domain, 'success');
refreshSkillsList();
refreshRecommendedList();
importRow.style.display = 'none';
importInput.value = '';
// 如果新技能匹配当前 hostname,立即注册到当前会话工具列表
// (否则要刷新页面才会生效)
if (window.GobyAgent && typeof window.GobyAgent._refreshActiveSkills === 'function') {
window.GobyAgent._refreshActiveSkills();
}
}).catch(function (e) {
showSkillFeedback('保存失败: ' + (e.message || String(e)), 'error');
});
};
reader.readAsText(file);
});
// 确认导入
importConfirm.addEventListener('click', function () {
var url = (importInput.value || '').trim();
if (!url) {
showSkillFeedback(t('modal.skills_url_required') || '请输入 URL', 'error');
return;
}
if (url.indexOf('https://') !== 0) {
// D-01: 只允许 https:// URLs,阻止 http:// 和 file://
showSkillFeedback(t('modal.skills_https_only') || '仅支持 https:// URL', 'error');
return;
}
importConfirm.disabled = true;
importConfirm.textContent = t('modal.skills_importing') || '导入中...';
window.GobyAgent.importSkill(url).then(function (result) {
importConfirm.disabled = false;
importConfirm.textContent = t('modal.skills_import_confirm') || '确认导入';
if (result && result.ok) {
showSkillFeedback(
(t('modal.skills_import_success') || '技能已安装:') + (result.domain || ''),
'success'
);
importRow.style.display = 'none';
importInput.value = '';
refreshSkillsList();
refreshRecommendedList();
// 如果新技能匹配当前 hostname,立即注册到当前会话工具列表
if (window.GobyAgent && typeof window.GobyAgent._refreshActiveSkills === 'function') {
window.GobyAgent._refreshActiveSkills();
}
} else {
var errMsg = result && result.error ? result.error : (t('modal.skills_import_failed') || '导入失败');
showSkillFeedback(errMsg, 'error');
}
}).catch(function (e) {
importConfirm.disabled = false;
importConfirm.textContent = t('modal.skills_import_confirm') || '确认导入';
showSkillFeedback((t('modal.skills_import_failed') || '导入失败') + ': ' + (e.message || String(e)), 'error');
});
});
// ---- 技能反馈辅助函数 ----
var _skillFeedbackTimer = null;
function showSkillFeedback(msg, type) {
if (_skillFeedbackTimer) clearTimeout(_skillFeedbackTimer);
var fb = document.getElementById('goby-skill-feedback');
if (fb) {
fb.textContent = msg;
fb.className = 'goby-skill-feedback visible ' + type;
_skillFeedbackTimer = setTimeout(function () {
fb.className = 'goby-skill-feedback';
}, 5000);
}
}
function hideSkillFeedback() {
if (_skillFeedbackTimer) clearTimeout(_skillFeedbackTimer);
var fb = document.getElementById('goby-skill-feedback');
if (fb) {
fb.className = 'goby-skill-feedback';
}
}
// ---- 技能列表渲染函数 ----
/**
* 渲染已安装技能列表
*/
function refreshSkillsList() {
var listEl = document.getElementById('goby-skills-list');
if (!listEl) return;
window.GobyAgent.listSkills().then(function (skills) {
listEl.innerHTML = '';
var domains = Object.keys(skills);
if (domains.length === 0) {
var emptyDiv = document.createElement('div');
emptyDiv.className = 'goby-skills-empty';
emptyDiv.textContent = t('modal.skills_empty') || '暂无已安装技能';
listEl.appendChild(emptyDiv);
return;
}
for (var i = 0; i < domains.length; i++) {
var domain = domains[i];
var skill = skills[domain];
renderSkillItem(listEl, domain, skill);
}
}).catch(function () {
// 静默降级
});
}
/**
* 渲染单个技能项
*/
function renderSkillItem(container, domain, skill) {
var item = document.createElement('div');
item.className = 'goby-skill-item';
item.id = 'goby-skill-' + domain.replace(/\./g, '-');
if (skill.enabled === false) {
item.classList.add('disabled');
}
// 技能信息
var info = document.createElement('div');
info.className = 'goby-skill-info';
var nameEl = document.createElement('div');
nameEl.className = 'goby-skill-name';
nameEl.textContent = skill.name || domain;
var meta = document.createElement('div');
meta.className = 'goby-skill-meta';
var domainEl = document.createElement('span');
domainEl.className = 'goby-skill-domain';
domainEl.textContent = domain;
var actionCountEl = document.createElement('span');
actionCountEl.className = 'goby-skill-action-count';
actionCountEl.textContent = (skill.actions ? skill.actions.length : 0) + ' ' + (t('modal.skills_actions') || '个操作');
var sourceEl = document.createElement('span');
sourceEl.className = 'goby-skill-source ' + (skill.source === 'builtin' ? 'builtin' : 'imported');
sourceEl.textContent = skill.source === 'builtin' ? (t('modal.skills_builtin') || '内置') : (t('modal.skills_imported') || '导入');
meta.appendChild(domainEl);
meta.appendChild(actionCountEl);
meta.appendChild(sourceEl);
info.appendChild(nameEl);
info.appendChild(meta);
// 启用/禁用 toggle
var toggleRow = document.createElement('div');
toggleRow.className = 'goby-skill-toggle-row';
var toggleLabel = document.createElement('span');
toggleLabel.style.cssText = 'font-size:11px;color:#6b7280;white-space:nowrap;';
toggleLabel.textContent = (skill.enabled !== false) ? (t('modal.skills_enabled') || '启用') : (t('modal.skills_disabled') || '禁用');