@seekskyworld/open-browser 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +291 -0
  5. package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
  6. package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
  7. package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
  8. package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +84 -0
  9. package/LICENSE +200 -0
  10. package/README.md +159 -2
  11. package/README.zh-CN.md +166 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +156 -0
  14. package/action-execution.mjs +385 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +134 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +35 -0
  23. package/browser-extension/newtab.css +26 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +174 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +56 -0
  29. package/browser-extension/popup.js +405 -0
  30. package/browser-extension/tab-action.js +138 -0
  31. package/browser-extension/worker.js +281 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/build-profile.mjs +23 -0
  34. package/capability-matrix.mjs +21 -0
  35. package/chromium-host.mjs +209 -0
  36. package/chromium-shell.mjs +179 -0
  37. package/cli.mjs +141 -0
  38. package/contract-validation.mjs +27 -0
  39. package/control.mjs +107 -0
  40. package/desktop/Info.plist +13 -0
  41. package/desktop/Launcher.m +117 -0
  42. package/desktop/OBControlBar.h +7 -0
  43. package/desktop/OBControlBar.m +217 -0
  44. package/desktop/OBPageView.h +6 -0
  45. package/desktop/OBPageView.m +348 -0
  46. package/desktop/WorkspacePanel.h +16 -0
  47. package/desktop/WorkspacePanel.m +916 -0
  48. package/desktop/archive-release.py +129 -0
  49. package/desktop/brand-keychain.py +111 -0
  50. package/desktop/brand-locales.py +93 -0
  51. package/desktop/brand-macos-icons.py +24 -0
  52. package/desktop/brand-windows-icons.mjs +48 -0
  53. package/desktop/build-macos.mjs +112 -0
  54. package/desktop/build-managed-input.mjs +37 -0
  55. package/desktop/build-portable.mjs +95 -0
  56. package/desktop/build-profile.mjs +6 -0
  57. package/desktop/build.mjs +13 -0
  58. package/desktop/create-shortcut.ps1 +9 -0
  59. package/desktop/generate-icons.py +39 -0
  60. package/desktop/icons/open-browser.icns +0 -0
  61. package/desktop/icons/open-browser.ico +0 -0
  62. package/desktop/install-menu-entry.mjs +24 -0
  63. package/desktop/macos-entitlements.plist +12 -0
  64. package/desktop/notarize-macos.mjs +145 -0
  65. package/desktop/package-assets.mjs +34 -0
  66. package/desktop/package-macos.mjs +54 -0
  67. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  68. package/desktop/patches/chromium-managed-input.patch +144 -0
  69. package/desktop/portable-archive.py +22 -0
  70. package/desktop/sign.mjs +77 -0
  71. package/desktop/smoke-portable.mjs +65 -0
  72. package/desktop/start-profile.mjs +5 -0
  73. package/desktop/start.mjs +34 -0
  74. package/desktop/verify-macos-release.mjs +61 -0
  75. package/desktop/verify-upgrade.mjs +74 -0
  76. package/desktop/verify-version.mjs +12 -0
  77. package/desktop-page.mjs +211 -0
  78. package/diagnostics.mjs +37 -0
  79. package/downloads.mjs +110 -0
  80. package/engine-service.mjs +1158 -0
  81. package/hosted/README.md +74 -0
  82. package/hosted/cli.mjs +17 -0
  83. package/hosted/directory.mjs +261 -0
  84. package/hosted/init.mjs +37 -0
  85. package/hosted/server.mjs +129 -0
  86. package/managed-input.mjs +138 -0
  87. package/managed-popup.mjs +54 -0
  88. package/mcp-http.mjs +84 -0
  89. package/mcp-server.mjs +41 -0
  90. package/mcp.mjs +5 -0
  91. package/network-policy.mjs +107 -0
  92. package/output-store.mjs +96 -0
  93. package/package.json +77 -4
  94. package/page-activity.mjs +188 -0
  95. package/page-dialogs.mjs +53 -0
  96. package/page-observation.mjs +318 -0
  97. package/paths.mjs +22 -0
  98. package/privacy-config.mjs +95 -0
  99. package/receipt-store.mjs +198 -0
  100. package/runtime.mjs +53 -0
  101. package/scheduler.mjs +70 -0
  102. package/sdk.mjs +193 -0
  103. package/service.mjs +290 -0
  104. package/site-workflow.mjs +115 -0
  105. package/skill-links.mjs +90 -0
  106. package/skills/open-browser/SKILL.macos.md +112 -0
  107. package/skills/open-browser/SKILL.md +107 -0
  108. package/skills/open-browser/SKILL.windows.md +112 -0
  109. package/skills/open-browser/scripts/bootstrap.mjs +213 -0
  110. package/skills/open-browser/scripts/open-browser +21 -0
  111. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  112. package/skills/open-browser/workflows/login-export.json +10 -0
  113. package/skills/open-browser/workflows/upload-verify.json +8 -0
  114. package/studio/demo-site.mjs +111 -0
  115. package/studio/demo.css +1 -0
  116. package/studio/index.html +66 -0
  117. package/studio/index.mjs +57 -0
  118. package/studio/native-demo.mjs +124 -0
  119. package/studio/studio.css +119 -0
  120. package/studio/studio.js +438 -0
  121. package/tab-adoption.mjs +77 -0
  122. package/uploads.mjs +63 -0
  123. package/visual-page.mjs +306 -0
  124. package/workspace-lifecycle.mjs +238 -0
  125. package/workspace-state.mjs +107 -0
@@ -0,0 +1,405 @@
1
+ 'use strict';
2
+
3
+ const el = id => document.getElementById(id);
4
+ let selected = '', detail, request, selectedTab = '', revision = 0, busy = false, refreshing = false, contextTab = false;
5
+ const phases = globalThis.openBrowserPhaseLabels;
6
+
7
+ async function call(method, params = {}) {
8
+ const reply = await chrome.runtime.sendMessage({ method, params });
9
+ if (!reply || reply.error) throw new Error(reply?.error || 'host_unavailable');
10
+ return reply.result;
11
+ }
12
+
13
+ function notify(text = '') {
14
+ el('notice').textContent = text;
15
+ el('notice').hidden = !text;
16
+ }
17
+
18
+ function describe(w) {
19
+ if (w.activity?.needsHumanVerification) return '需要人工验证';
20
+ if (w.mode === 'human') return '人工接管';
21
+ if (w.mode === 'transferring') return '交接中';
22
+ if (w.activity?.needsCredential) return '等待凭据';
23
+ const current = w.activity?.current;
24
+ const stage = current?.dispatchState;
25
+ if (stage) return stage === 'dispatched' ? '已派发' : '等待页面';
26
+ return phases[current?.phase] || phases[w.activity?.phase] || 'Agent 控制';
27
+ }
28
+
29
+ function options(node, entries, value) {
30
+ const signature = JSON.stringify(entries);
31
+ if (node.dataset.signature !== signature) {
32
+ node.replaceChildren(...entries.map(([id, title]) => new Option(title, id)));
33
+ node.dataset.signature = signature;
34
+ }
35
+ node.value = value;
36
+ }
37
+
38
+ function showCredential(next) {
39
+ const previous = JSON.stringify(request);
40
+ request = next;
41
+ if (previous !== JSON.stringify(next)) el('secret').value = '';
42
+ el('credential').hidden = !next;
43
+ if (!next) return;
44
+ el('credential-target').textContent = next.origin + ' · ' + next.credentialRef;
45
+ el('save').textContent = '绑定凭据';
46
+ }
47
+
48
+ let popupTabId, ordinaryTarget, tokenTimer, standalone = false;
49
+ function clearToken() {
50
+ clearTimeout(tokenTimer);
51
+ el('adopt-token').value = '';
52
+ el('adopt-result').hidden = true;
53
+ }
54
+ el('adopt-task').onchange = () => { clearToken(); el('adopt').disabled = !el('adopt-task').value; };
55
+ el('adopt').onclick = () => perform(async () => {
56
+ clearToken();
57
+ const {id:targetId, origin} = ordinaryTarget;
58
+ const reply = await call('offerCurrentTab',{workspaceId:el('adopt-task').value, tabId:popupTabId,
59
+ targetId, origin, accountAlias:el('adopt-alias').value.trim()});
60
+ el('adopt-token').value = JSON.stringify({workspaceId:reply.workspaceId,adoptionToken:reply.adoptionToken});
61
+ el('adopt-result').hidden = false;
62
+ el('adopt-token').select();
63
+ tokenTimer = setTimeout(clearToken, Math.max(0, reply.expiresAt - Date.now()));
64
+ });
65
+
66
+ let deliveryKey = '', finishId;
67
+ function renderDelivery(w) {
68
+ const originLabels = {resource:'加载静态资源',navigation:'允许导航与页面操作'};
69
+ const blocks = (w.blockedOrigins || []).filter(item => originLabels[item.scope]);
70
+ el('blocked').replaceChildren(...blocks.map(item => {
71
+ const button = document.createElement('button');
72
+ button.type = 'button';
73
+ button.className = 'secondary';
74
+ button.textContent = '本次' + originLabels[item.scope] + ' · ' + item.origin;
75
+ button.onclick = () => perform(() => call('grantOrigin',{workspaceId:w.workspaceId,
76
+ controlGeneration:w.controlGeneration,origin:item.origin,scope:item.scope}));
77
+ return button;
78
+ }));
79
+ const key = JSON.stringify([w.workspaceId, w.controlGeneration, w.pages.map(p => p.pageId)]);
80
+ if (deliveryKey === key) return;
81
+ deliveryKey = key;
82
+ finishId = crypto.randomUUID();
83
+ el('delivery').open = false;
84
+ el('keep').replaceChildren(...w.pages.map(p => {
85
+ const label = document.createElement('label'), input = document.createElement('input');
86
+ input.type = 'checkbox';
87
+ input.checked = true;
88
+ input.disabled = p.ownership === 'user';
89
+ input.value = p.pageId;
90
+ input.onchange = () => { finishId = crypto.randomUUID(); };
91
+ label.append(input, ' ' + (p.title || p.origin || '页面'));
92
+ return label;
93
+ }));
94
+ }
95
+ el('finish').onclick = () => perform(async () => {
96
+ const keepPageIds = [...el('keep').querySelectorAll('input:checked')].map(input => input.value);
97
+ const receipt = await call('finishWorkspace',{workspaceId:selected,keepPageIds,operationId:finishId,
98
+ controlGeneration:detail.controlGeneration});
99
+ if (receipt.state !== 'completed') { notify('交付待核实 · ' + receipt.operationId); return; }
100
+ notify('已保留 ' + receipt.keptPageIds.length + ' 页,已关闭 ' + receipt.closedPageIds.length + ' 页。');
101
+ render(null);
102
+ });
103
+
104
+ function clearDiagnostic() {
105
+ const link = el('diagnostic-export');
106
+ if (link.hasAttribute('href')) URL.revokeObjectURL(link.href);
107
+ link.removeAttribute('href');
108
+ link.hidden = true;
109
+ }
110
+ el('diagnostic-export-button').onclick = () => perform(async () => {
111
+ clearDiagnostic();
112
+ const workspaceId = selected;
113
+ const [operations, events] = await Promise.all([
114
+ call('listOperations', {workspaceId, after: 0, limit: 100}),
115
+ call('listEvents', {workspaceId, after: 0, limit: 100}),
116
+ ]);
117
+ const text = JSON.stringify({ version: 1, workspaceId, exportedAt: new Date().toISOString(),
118
+ operations: (operations.operations || []).filter(item => item.error || ['failed', 'outcome_unknown', 'cancelled'].includes(item.state)),
119
+ events: events.events || [] }, null, 2) + '\n';
120
+ const link = el('diagnostic-export');
121
+ link.href = URL.createObjectURL(new Blob([text], {type:'application/json'}));
122
+ link.hidden = false;
123
+ link.textContent = '下载错误日志';
124
+ link.click();
125
+ });
126
+
127
+ function render(w) {
128
+ if (detail?.workspaceId !== w?.workspaceId) {
129
+ clearDiagnostic();
130
+ }
131
+
132
+ detail = w;
133
+ el('workspace').hidden = !w;
134
+ el('empty').hidden = !!w;
135
+ el('context-selection').hidden = contextTab || !w;
136
+ el('status').textContent = w ? describe(w) + ' · 资料 ' + w.profileId : '暂无工作区';
137
+ if (!w) { showCredential(null); return; }
138
+ renderDialogs(w);
139
+ renderDelivery(w);
140
+ const pages = w.pages || [];
141
+ if (standalone && !selectedTab) selectedTab = pages[0]?.pageId || '';
142
+ const page = pages.find(p => p.pageId === selectedTab);
143
+ options(el('pages'), pages.map((p, i) => [p.pageId, (i+1) + ' · ' + (p.title || p.origin || '页面')]), selectedTab);
144
+ if (!page) {
145
+ el('workspace').hidden = !standalone;
146
+ el('control').disabled = true;
147
+ el('uploads').hidden = true;
148
+ el('page-details').textContent = '';
149
+ el('status').textContent = '原标签页已关闭或解绑';
150
+ showCredential(null);
151
+ return;
152
+ }
153
+ const sync = page.lastSyncedAt ? '上次同步 ' + new Date(page.lastSyncedAt).toLocaleTimeString() : '';
154
+ el('page-details').textContent = [page.origin, w.accountAlias, page.syncState === 'sync_pending' ? '同步中' : sync].filter(Boolean).join(' · ');
155
+ el('control').textContent = w.unlockPending ? '重试人工接管' : w.mode === 'human' ? '交回 Agent' : w.scope === 'single_tab' ? '接管此页' : '接管工作区';
156
+ el('control').disabled = busy || (w.mode === 'transferring' && !w.unlockPending) || (!selectedTab && w.mode !== 'human');
157
+ el('uploads').hidden = w.mode!=='agent' || !selectedTab;
158
+ el('upload-origin').textContent = pages.find(p=>p.pageId===selectedTab)?.origin || '';
159
+ showCredential(w.mode === 'agent' ? w.activity?.credentialRequest || null : null);
160
+ }
161
+
162
+ async function sync() {
163
+ if (refreshing || busy) return;
164
+ refreshing = true;
165
+ const serial = revision;
166
+ try {
167
+ if (Number.isInteger(popupTabId)) {
168
+ const key = 'tab:' + popupTabId;
169
+ const mapping = (await chrome.storage.session.get(key))[key];
170
+ if (!contextTab && mapping) {
171
+ contextTab = true;
172
+ selected = mapping.workspaceId;
173
+ selectedTab = mapping.pageId;
174
+ clearToken();
175
+ }
176
+ }
177
+ el('adoption').hidden = true;
178
+ if (!contextTab && !standalone) {
179
+ const list = await call('listWorkspaces');
180
+ const target = (await chrome.debugger.getTargets()).find(t => t.type === 'page' && t.tabId === popupTabId);
181
+ const origin = URL.parse(target?.url);
182
+ if (serial !== revision) return;
183
+ render(null);
184
+ if (!origin || !['http:', 'https:'].includes(origin.protocol)) return;
185
+ if (ordinaryTarget?.id !== target.id || ordinaryTarget?.origin !== origin.origin) clearToken();
186
+ ordinaryTarget = {id:target.id, origin:origin.origin};
187
+ const tasks = list.filter(w => w.pageAvailability === 'unregistered' && w.mode === 'agent');
188
+ el('adoption').hidden = false;
189
+ el('empty').hidden = true;
190
+ el('status').textContent = '普通标签页';
191
+ el('adopt-site').textContent = origin.origin + (tasks.length ? '' : ' · 请让 Agent 先创建一个命名工作区');
192
+ const chooser = el('adopt-task');
193
+ options(chooser, tasks.map(w => [w.workspaceId, workspaceTitle(w) + ' · ' + w.workspaceId.slice(0,8)]),
194
+ tasks.some(w => w.workspaceId === chooser.value) ? chooser.value : tasks.length === 1 ? tasks[0].workspaceId : '');
195
+ el('adopt').disabled = !chooser.value;
196
+ return;
197
+ }
198
+ const list = contextTab ? (selected ? [await call('getWorkspace', {workspaceId: selected })] : []) : await call('listWorkspaces');
199
+ if (serial !== revision) return;
200
+ if (contextTab && !list.some(w => w.workspaceId === selected)) { render(null); return; }
201
+ if (!list.some(w => w.workspaceId === selected)) {
202
+ selectedTab = '';
203
+ selected = (list.find(w => w.activity?.needsCredential) || list[0])?.workspaceId || '';
204
+ }
205
+ const titles = list.map(workspaceTitle);
206
+ const entries = list.map((w, index) => {
207
+ const title = titles[index];
208
+ const duplicate = titles.indexOf(title) !== titles.lastIndexOf(title);
209
+ const suffix = duplicate ? ' · ' + w.workspaceId.slice(0, 8) : '';
210
+ return [w.workspaceId, title + suffix + ' · ' + describe(w)];
211
+ });
212
+ options(el('workspaces'), entries, selected);
213
+ const w = contextTab ? list[0] || null : selected ? await call('getWorkspace', { workspaceId: selected }) : null;
214
+ const [captureReply, downloads, uploads] = w ? await Promise.all([
215
+ call('visualStatus',{workspaceId:selected}).catch(()=>({})),
216
+ call('listDownloads',{workspaceId:selected}),
217
+ call('listUploads',{workspaceId:selected}),
218
+ ]) : [{}, [], []];
219
+ const capture = captureReply.lastCapture;
220
+ if (serial === revision) {
221
+ render(w);
222
+ el('upload-list').replaceChildren(...uploads.map(file=>{
223
+ const button=document.createElement('button');
224
+ button.textContent='撤销 '+file.name+' · '+file.origin;
225
+ button.onclick=()=>perform(()=>call('revokeUpload',{workspaceId:w.workspaceId,fileId:file.fileId}));
226
+ return button;
227
+ }));
228
+ renderDownloads(downloads);
229
+ const status=el('visual-status');
230
+ status.hidden=!capture;
231
+ if(capture) status.textContent='最近画面采集 · '+capture.principalId+' · '+capture.origin+' · ('+
232
+ capture.clip.x+', '+capture.clip.y+') '+capture.clip.width+' × '+capture.clip.height;
233
+ }
234
+ } catch (error) {
235
+ if (serial === revision) {
236
+ render(null);
237
+ if (contextTab && error.message === 'workspace_not_found') {
238
+ el('status').textContent = '原任务已结束或服务已重启';
239
+ notify('请在需要授权的标签页重新打开扩展。');
240
+ } else {
241
+ el('status').textContent = '连接失败';
242
+ notify(error.message);
243
+ }
244
+ }
245
+ } finally {
246
+ refreshing = false;
247
+ if (!busy && serial !== revision) void sync();
248
+ }
249
+ }
250
+
251
+ function renderDialogs(w) {
252
+ const panel = el('dialogs'), items = w.pendingDialogs || [];
253
+ const signature = JSON.stringify([w.workspaceId,w.mode,w.controlGeneration,items]);
254
+ if (panel.dataset.signature === signature) return;
255
+ panel.dataset.signature = signature;
256
+ panel.replaceChildren(...items.map(item => {
257
+ const row = document.createElement('div');
258
+ row.textContent = item.origin + ' · ' + item.type + ' · ' + item.message;
259
+ if (w.mode === 'agent') {
260
+ const take = document.createElement('button');
261
+ take.textContent = '接管并处理';
262
+ take.onclick = () => {
263
+ take.disabled = true;
264
+ void call('takeControl',{workspaceId:w.workspaceId,pageId:item.pageId,controlGeneration:w.controlGeneration})
265
+ .catch(error=>notify(error.message)).finally(()=>void sync());
266
+ };
267
+ row.append(take);
268
+ return row;
269
+ }
270
+ const input = document.createElement('input');
271
+ if (item.type === 'prompt') { input.placeholder = '回复'; input.maxLength = 2048; row.append(input); }
272
+ for (const accept of [true,false]) {
273
+ const button = document.createElement('button');
274
+ button.textContent = accept ? '确定' : '取消';
275
+ button.onclick = () => perform(() => call('respondDialog',{workspaceId:w.workspaceId,pageId:item.pageId,
276
+ dialogId:item.dialogId,controlGeneration:w.controlGeneration,accept,
277
+ ...(accept && item.type === 'prompt' && {text:input.value})}));
278
+ row.append(button);
279
+ }
280
+ return row;
281
+ }));
282
+ }
283
+
284
+ function renderDownloads(items) {
285
+ el('downloads').hidden = !items.length;
286
+ const labels = {receiving:'下载中',ready:'待保留',failed:'失败',cancelled:'已取消',kept:'已保留'};
287
+ el('download-list').replaceChildren(...items.map(item => {
288
+ const row = document.createElement('p');
289
+ row.textContent = item.filename + ' · ' + labels[item.state] + ' ';
290
+ function button(label, handler) {
291
+ const action = document.createElement('button');
292
+ action.type = 'button';
293
+ action.textContent = label;
294
+ action.onclick = () => perform(handler);
295
+ row.append(action);
296
+ }
297
+ const params = {workspaceId:item.workspaceId,downloadId:item.downloadId};
298
+ if (item.state === 'ready' || item.state === 'kept')
299
+ button(item.state === 'kept' ? '查看保存位置' : '保留文件', async () => notify((await call('keepDownload',params)).path));
300
+ if (item.state === 'receiving' || item.state === 'ready') button('取消', () => call('cancelDownload',params));
301
+ return row;
302
+ }));
303
+ }
304
+
305
+ async function perform(action) {
306
+ if (busy) return;
307
+ busy = true;
308
+ revision++;
309
+ notify();
310
+ const enabled = [...document.querySelectorAll('button:enabled, select:enabled, input:enabled')];
311
+ for (const element of enabled) element.disabled = true;
312
+ try { await action(); } catch (error) { notify(error.message); }
313
+ finally {
314
+ busy = false;
315
+ for (const element of enabled) element.disabled = false;
316
+ render(detail);
317
+ void sync();
318
+ }
319
+ }
320
+
321
+ el('workspaces').onchange = event => {
322
+ selected = event.target.value;
323
+ selectedTab = '';
324
+ revision++;
325
+ render(null);
326
+ void sync();
327
+ };
328
+ el('pages').onchange = event => { selectedTab = event.target.value; render(detail); };
329
+ let uploadTarget;
330
+ function selectedUploadTarget() {
331
+ const target = detail?.pages.find(page=>page.pageId===selectedTab);
332
+ if (!target || detail.mode!=='agent' || detail.workspaceId!==selected || target.origin==='null') return null;
333
+ return {workspaceId:detail.workspaceId,pageId:target.pageId,controlGeneration:detail.controlGeneration,
334
+ documentId:target.documentId,origin:target.origin};
335
+ }
336
+ el('upload-file').onclick = event => {
337
+ uploadTarget = selectedUploadTarget();
338
+ if (!uploadTarget) event.preventDefault();
339
+ };
340
+ el('upload-file').onchange = event => {
341
+ const file=event.target.files[0];
342
+ event.target.value='';
343
+ if (!file) return;
344
+ const target=uploadTarget, current=selectedUploadTarget();
345
+ uploadTarget=null;
346
+ if (!target || !current || Object.keys(target).some(key=>target[key]!==current[key])) {
347
+ notify('页面或控制权已变更,请重新选择文件。');
348
+ return;
349
+ }
350
+ const params={...target,name:file.name,mimeType:file.type};
351
+ void perform(async()=>{
352
+ if (file.size>8*1024*1024) throw Error('单文件上限 8 MiB');
353
+ const data=await new Promise((resolve,reject)=>{
354
+ const reader=new FileReader();
355
+ reader.onload=()=>resolve(reader.result.split(',')[1]);
356
+ reader.onerror=()=>reject(Error('文件读取失败'));
357
+ reader.readAsDataURL(file);
358
+ });
359
+ await call('grantUpload',{...params,data});
360
+ notify('已向 '+params.origin+' 授权 '+file.name+',有效期五分钟。');
361
+ });
362
+ };
363
+ el('control').onclick = () => perform(async () => {
364
+ if (!detail?.pages.some(p => p.pageId === selectedTab)) return;
365
+ if (detail.mode === 'human') await call('returnToAgent', { workspaceId: selected, pageId:selectedTab, controlGeneration: detail.controlGeneration });
366
+ else await call('takeControl', { workspaceId: selected, pageId: selectedTab, controlGeneration: detail.controlGeneration });
367
+ });
368
+ el('credential').onsubmit = event => {
369
+ event.preventDefault();
370
+ const value = el('secret').value;
371
+ el('secret').value = '';
372
+ if (!value || !request) return;
373
+ const pending = request, workspaceId = selected, generation = detail.controlGeneration;
374
+ void perform(async () => {
375
+ const w = await call('getWorkspace', { workspaceId });
376
+ const fresh = w.activity?.credentialRequest;
377
+ if (w.mode !== 'agent' || generation !== w.controlGeneration || !fresh ||
378
+ ['pageId', 'origin', 'credentialRef', 'operationId'].some(k => fresh[k] !== pending[k])) throw new Error('凭据请求已变化');
379
+ await call('resolveCredential', { workspaceId, ...pending, value });
380
+ notify('已绑定凭据,调用方可以重试。');
381
+ });
382
+ };
383
+
384
+ async function open() {
385
+ const explicit = /^#tab-(\d+)(-delivery)?$/.exec(location.hash);
386
+ standalone = !explicit && !!(await chrome.tabs.getCurrent());
387
+ const tabId = popupTabId = standalone ? undefined : explicit ? Number(explicit[1]) : (await chrome.tabs.query({ active: true, lastFocusedWindow: true }))[0]?.id;
388
+ if (Number.isInteger(tabId)) {
389
+ const key = 'tab:' + tabId;
390
+ const owned = (await chrome.storage.session.get(key))[key];
391
+ contextTab = Boolean(owned);
392
+ if (owned) { selected = owned.workspaceId; selectedTab = owned.pageId; }
393
+ }
394
+ await sync();
395
+ if (explicit?.[2] && detail) el('delivery').open = true;
396
+ }
397
+ void open().catch(() => sync());
398
+ chrome.runtime.onMessage.addListener((message, sender) => {
399
+ if (sender.id === chrome.runtime.id && message?.event === 'workspaceChanged') {
400
+ if (refreshing) revision++;
401
+ else void sync();
402
+ }
403
+ });
404
+ // Recover after a worker restart and refresh ancillary details such as file grants.
405
+ setInterval(sync, 5000);
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ const defaultPopup = 'popup.html';
4
+ const tabKey = tabId => 'tab:' + tabId;
5
+ const runningTabs = new Set();
6
+ const activityFrames = ['▶', '▸', '▹', '▸'];
7
+ let animation, frame = 0;
8
+
9
+ function showRunning(tabId, running) {
10
+ if (running) runningTabs.add(tabId);
11
+ else runningTabs.delete(tabId);
12
+ if (runningTabs.size && !animation) {
13
+ animation = setInterval(() => {
14
+ frame = (frame + 1) % activityFrames.length;
15
+ for (const id of runningTabs) {
16
+ chrome.action.setBadgeText({ tabId: id, text: activityFrames[frame] }).catch(() => showRunning(id, false));
17
+ }
18
+ }, 480);
19
+ }
20
+ if (!runningTabs.size && animation) { clearInterval(animation); animation = undefined; }
21
+ }
22
+
23
+ const actionStates = {
24
+ running: ['▶', '#1556b0', '执行中'],
25
+ queued: ['…', '#6757a4', '排队中'],
26
+ actionability: ['⌁', '#1556b0', '检查目标'],
27
+ dispatching: ['▶', '#1556b0', '正在派发'],
28
+ waiting: ['…', '#6757a4', '等待页面'],
29
+ verifying: ['✓', '#526675', '核对结果'],
30
+ needs_credential: ['!', '#a72f24', '等待凭据'],
31
+ needs_human_verification: ['!', '#a75d08', '需要人工验证'],
32
+ completed: ['✓', '#526675', '已完成'],
33
+ failed: ['!', '#a72f24', '执行失败'],
34
+ outcome_unknown: ['?', '#a75d08', '结果待核实'],
35
+ cancelled: ['−', '#626977', '已取消'],
36
+ idle: ['·', '#626977', '等待指令'],
37
+ human: ['人', '#176344', '人工控制'],
38
+ transferring: ['↔', '#926407', '交接中'],
39
+ };
40
+
41
+ async function writeAction(tabId, record) {
42
+ const key = tabKey(tabId);
43
+ if (!record) {
44
+ showRunning(tabId, false);
45
+ await chrome.storage.session.remove(key);
46
+ if (!await chrome.tabs.get(tabId).catch(() => null)) return;
47
+ await Promise.all([
48
+ chrome.action.setPopup({ tabId, popup: defaultPopup }),
49
+ chrome.action.setTitle({ tabId, title: 'open-browser 工作区' }),
50
+ chrome.action.setBadgeText({ tabId, text: '' }),
51
+ ]);
52
+ return;
53
+ }
54
+ await chrome.storage.session.set({ [key]: record });
55
+ const phase = record.mode !== 'agent' ? record.mode : record.needsHumanVerification ? 'needs_human_verification' : record.needsCredential ? 'needs_credential' : record.phase;
56
+ showRunning(tabId, ['running', 'actionability', 'dispatching', 'waiting', 'verifying'].includes(phase));
57
+ const [text, color, status] = actionStates[phase] || actionStates.idle;
58
+ const panel = phase === 'needs_credential' || phase === 'needs_human_verification' || phase === 'transferring' || !record.controlGeneration;
59
+ const steps = { click: '点击', fill: '填写', fillCredential: '填写凭据' };
60
+ const step = phase === 'running' && record.dispatchState ? (record.dispatchState === 'dispatched' ? '已派发' : '等待页面') : phase === 'running' ? steps[record.stepKind] : '';
61
+ const hint = record.mode === 'human' ? '点击交回 Agent' : panel ? '点击打开工作区面板' : '点击接管';
62
+ await Promise.all([
63
+ chrome.action.setBadgeText({ tabId, text }),
64
+ chrome.action.setBadgeBackgroundColor({ tabId, color }),
65
+ chrome.action.setTitle({ tabId, title: (record.agentName || 'Agent') + ' · ' + (step || status) + ' · ' + hint }),
66
+ chrome.action.setPopup({ tabId, popup: panel ? defaultPopup : '' }),
67
+ ]);
68
+ }
69
+
70
+ async function registerAction(tabId, state) {
71
+ if (!state.pageId) return;
72
+ const key = tabKey(tabId);
73
+ const existing = (await chrome.storage.session.get(key))[key];
74
+ const same = existing?.targetId === state.targetId && existing?.workspaceId === state.workspaceId && existing?.pageId === state.pageId;
75
+ const record = { ...(same ? existing : {}), ...state, tabId };
76
+ if (same && existing.mode !== state.mode && !state.controlGeneration) delete record.controlGeneration;
77
+ await writeAction(tabId, record);
78
+ }
79
+
80
+ // Reconcile only records registered by the host, independent of user tab-group edits.
81
+ async function syncTabActions(byId, slots) {
82
+ await Promise.all(Object.entries(slots).filter(([key]) => key.startsWith('tab:')).map(([key, previous]) =>
83
+ forWorkspace(previous.workspaceId, async () => {
84
+ const current = (await chrome.storage.session.get(key))[key];
85
+ if (!current || current.targetId !== previous.targetId) return;
86
+ const state = byId.get(current.workspaceId);
87
+ const pageIds = state?.pageIds || state?.pages?.map(p => typeof p === 'string' ? p : p.pageId);
88
+ if (!state || (pageIds && !pageIds.includes(current.pageId))) return writeAction(current.tabId, null);
89
+ const working = ['running', 'queued'].includes(state.phase);
90
+ const running = state.running?.find(job => job.pageId === current.pageId);
91
+ const phase = running ? (running.phase || 'running') : working && current.pageId !== state.currentPageId ? 'idle' : state.phase;
92
+ const record = { ...current, mode: state.mode, agentName: state.agentName, phase,
93
+ stepKind: running ? (running.stepKind || state.stepKind) : null,
94
+ dispatchState: running ? (running.dispatchState || state.dispatchState) : null,
95
+ needsCredential: state.needsCredential, controlGeneration: state.controlGeneration };
96
+ if (JSON.stringify(record) !== JSON.stringify(current)) await writeAction(current.tabId, record);
97
+ })));
98
+ }
99
+
100
+ chrome.tabs.onRemoved.addListener(tabId => {
101
+ showRunning(tabId, false);
102
+ void chrome.storage.session.remove(tabKey(tabId));
103
+ });
104
+
105
+ async function openWorkspacePanel(tabId, delivery = false) {
106
+ const url = chrome.runtime.getURL(defaultPopup) + (Number.isInteger(tabId) ? '#tab-' + tabId + (delivery ? '-delivery' : '') : '');
107
+ await chrome.windows.create({ url, type: 'popup', width: 380, height: 510, focused: true });
108
+ }
109
+
110
+ const toggling = new Set();
111
+
112
+ async function clickTabAction(tab) {
113
+ const key = tabKey(tab.id);
114
+ const record = (await chrome.storage.session.get(key))[key];
115
+ if (!record) return openWorkspacePanel(tab.id);
116
+ if (toggling.has(record.workspaceId)) return;
117
+ toggling.add(record.workspaceId);
118
+ try {
119
+ const workspace = await hostRequest('getWorkspace', { workspaceId: record.workspaceId });
120
+ if (!workspace.pages.some(p => p.pageId === record.pageId) || workspace.mode !== record.mode ||
121
+ workspace.controlGeneration !== record.controlGeneration || workspace.mode === 'transferring' ||
122
+ (workspace.mode === 'agent' && workspace.activity?.needsCredential)) return openWorkspacePanel(tab.id);
123
+ const target = { workspaceId: record.workspaceId, pageId: record.pageId, controlGeneration: record.controlGeneration };
124
+ await hostRequest(workspace.mode === 'human' ? 'returnToAgent' : 'takeControl', target);
125
+ } catch {
126
+ await openWorkspacePanel(tab.id);
127
+ } finally {
128
+ toggling.delete(record.workspaceId);
129
+ }
130
+ }
131
+
132
+ chrome.action.onClicked.addListener(clickTabAction);
133
+ chrome.runtime.onInstalled.addListener(() => {
134
+ chrome.contextMenus.create({ id: 'workspace-panel', title: '工作区面板', contexts: ['action'] });
135
+ });
136
+ chrome.contextMenus.onClicked.addListener((info, tab) => {
137
+ if (info.menuItemId === 'workspace-panel') void openWorkspacePanel(tab?.id);
138
+ });