@seekskyworld/open-browser 0.1.0 → 0.3.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 (68) hide show
  1. package/Docs/open-browser-api.d.ts +32 -10
  2. 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 +51 -3
  3. package/README.md +14 -5
  4. package/README.zh-CN.md +16 -5
  5. package/access-registry.mjs +13 -3
  6. package/action-execution.mjs +60 -24
  7. package/api-contract.mjs +19 -7
  8. package/browser-extension/manifest.json +1 -4
  9. package/browser-extension/newtab.css +6 -0
  10. package/browser-extension/newtab.js +54 -2
  11. package/browser-extension/phase-labels.js +1 -1
  12. package/browser-extension/popup.css +1 -1
  13. package/browser-extension/popup.html +16 -4
  14. package/browser-extension/popup.js +122 -21
  15. package/browser-extension/tab-action.js +4 -2
  16. package/browser-extension/worker.js +102 -9
  17. package/build-profile.mjs +23 -0
  18. package/capability-matrix.mjs +4 -4
  19. package/chromium-host.mjs +81 -25
  20. package/chromium-shell.mjs +78 -49
  21. package/cli.mjs +63 -5
  22. package/contract-validation.mjs +1 -1
  23. package/desktop/Info.plist +2 -2
  24. package/desktop/OBControlBar.m +7 -3
  25. package/desktop/WorkspacePanel.m +4 -2
  26. package/desktop/brand-keychain.py +20 -4
  27. package/desktop/build-macos.mjs +31 -12
  28. package/desktop/build-managed-input.mjs +37 -0
  29. package/desktop/build-profile.mjs +6 -0
  30. package/desktop/build.mjs +8 -0
  31. package/desktop/macos-entitlements.plist +12 -0
  32. package/desktop/notarize-macos.mjs +189 -0
  33. package/desktop/package-macos.mjs +54 -0
  34. package/desktop/patches/chromium-managed-input.patch +144 -0
  35. package/desktop/sign.mjs +63 -4
  36. package/desktop/start-profile.mjs +5 -0
  37. package/desktop/start.mjs +25 -3
  38. package/desktop/verify-macos-release.mjs +69 -0
  39. package/desktop/verify-version.mjs +22 -2
  40. package/diagnostics.mjs +9 -0
  41. package/engine-service.mjs +244 -29
  42. package/managed-input.mjs +155 -0
  43. package/mcp-http.mjs +84 -0
  44. package/mcp-server.mjs +57 -0
  45. package/mcp.mjs +3 -40
  46. package/package.json +24 -3
  47. package/page-activity.mjs +97 -29
  48. package/page-observation.mjs +44 -3
  49. package/paths.mjs +5 -3
  50. package/receipt-store.mjs +24 -7
  51. package/runtime.mjs +10 -1
  52. package/sdk.mjs +53 -26
  53. package/service.mjs +45 -10
  54. package/skill-links.mjs +144 -0
  55. package/skills/open-browser/SKILL.md +8 -76
  56. package/skills/open-browser/references/macos.md +3 -0
  57. package/skills/open-browser/references/operations.md +59 -0
  58. package/skills/open-browser/references/recovery.md +36 -0
  59. package/skills/open-browser/references/windows.md +3 -0
  60. package/skills/open-browser/scripts/bootstrap.mjs +112 -45
  61. package/skills/open-browser/scripts/guide.mjs +17 -0
  62. package/studio/studio.js +2 -2
  63. package/tab-adoption.mjs +83 -0
  64. package/tab-recovery.mjs +100 -0
  65. package/uploads.mjs +4 -4
  66. package/visual-page.mjs +17 -7
  67. package/workspace-lifecycle.mjs +92 -8
  68. package/workspace-state.mjs +65 -12
package/api-contract.mjs CHANGED
@@ -56,7 +56,7 @@ const definitions = {
56
56
  },['workspaceId','pageId','documentId','controlGeneration','operationId','workflow']],
57
57
 
58
58
  capabilities: ['Discover service version, enabled inputs, limits and privacy mode before using optional features.',{}],
59
- captureVisual: ['Capture approved masked viewport pixels. Coordinates use viewport CSS pixels.',{...page,region,ref:id},Object.keys(page)],
59
+ captureVisual: ['Capture approved masked viewport pixels. Coordinates use viewport CSS pixels. For an animated game set liveCanvas to bind input to its sole canvas across repaints.',{...page,region,ref:id,liveCanvas:{type:'boolean'}},Object.keys(page)],
60
60
  listWorkspaces: ['List the workspaces available to this agent.', {}],
61
61
  createWorkspace: ['Create a browser workspace. Every task must provide a clear non-empty name. Each subagent should pass its own display name in agentName.', {
62
62
  profileId:{type:'string',pattern:'^[a-z0-9][a-z0-9_-]{0,47}$'},
@@ -77,13 +77,25 @@ const definitions = {
77
77
  ...workspace, controlGeneration: id, origin: { type:'string', format:'uri' },
78
78
  scope: { enum:['navigation','resource'], type:'string' },
79
79
  }, ['workspaceId','controlGeneration','origin','scope']],
80
- getWorkspace: ['Read the state of a workspace and its pages.', workspace],
80
+ canvasSnapshot: ['Read visible React Flow nodes and edges, chat turns and download labels. Compare snapshotVersion after an action. Unsupported markup is reported explicitly.',page],
81
+ adoptCurrentTab: ['Redeem the two-minute token issued by the user for this empty named workspace. The original tab stays open at finish.', {...workspace,adoptionToken:{type:'string',pattern:'^[0-9a-f]{64}$'}}],
82
+ reattachPage: ['Refresh the exact managed page after the user returns control. Returns a fresh observation. Set waitMs to wait for human control to return.',{...page,waitMs:{type:'integer',minimum:1,maximum:30000}},Object.keys(page)],
83
+ previewFinish: ['Preview which pages will stay open and which will close. Pass previewId to finishWorkspace to require this plan.',{...workspace,keepPageIds:{type:'array',uniqueItems:true,items:id}}],
84
+ getWorkspace: ['Read workspace control, page availability and extension synchronization. Supply profileId to verify the expected profile.', {...workspace,profileId:id},['workspaceId']],
81
85
  openPage: ['Open a page in the workspace.', { ...workspace, url: { type: 'string', format: 'uri' } }],
82
86
  observe: ['Read visible controls. Continue a truncated observation with nextCursor or filter by name or viewport region. After stale_ref, stale_document or user handoff, observe again before acting.', {
83
87
  ...page, includeFrames:{type:'boolean'}, frameControls:{type:'boolean'},
84
88
  locator:object({role:id,name:id,within:object({role:id,name:id})},['role','name']),
85
89
  cursor:id, limit:{type:'integer',minimum:1,maximum:180}, name:id, region,
86
90
  }, Object.keys(page)],
91
+ observeAndAct: ['Observe the current page and submit an ordered action batch through one service request. The service binds the actions to the returned document and control generation before queueing them.', {
92
+ ...page, includeFrames:{type:'boolean'}, frameControls:{type:'boolean'},
93
+ locator:object({role:id,name:id,within:object({role:id,name:id})},['role','name']),
94
+ cursor:id, limit:{type:'integer',minimum:1,maximum:180}, name:id, region,
95
+ operationId:id, waitMs:{type:'integer',minimum:1,maximum:10000}, timeoutMs:{type:'integer',minimum:1,maximum:60000},
96
+ observeAfter:{enum:['full','delta']},
97
+ actions:{type:'array',minItems:1,maxItems:32,items:action},
98
+ }, ['workspaceId','pageId','operationId','actions']],
87
99
  act: ['Submit ordered actions for the observed document and control generation. Use fillCredential for login secrets. Supply a unique operationId. The optional timeout is a wall-clock budget shared by queueing and execution. After a timeout or outcome_unknown, query the receipt and verify the site before retrying.', {
88
100
  ...page, operationId: id, documentId: id, controlGeneration: id,
89
101
  timeoutMs:{type:'integer',minimum:1,maximum:60000},
@@ -97,15 +109,15 @@ const definitions = {
97
109
  readOutput:['Read one locally delivered output in bounded base64 chunks. Use nextOffset to continue.',{...workspace,outputId:id,partName:{type:'string',maxLength:180},offset:{type:'integer',minimum:0},limit:{type:'integer',minimum:1,maximum:65536}},['workspaceId','outputId']],
98
110
  cancelDownload:['Cancel a download belonging to this workspace.',{...workspace,downloadId:id}],
99
111
  eventCursor:['Get the current workspace event cursor before triggering an action.',workspace],
100
- waitForEvent:['Wait for a matching page event. Reuse the same cursor to read it after reconnecting.',
101
- {...page,kind:{enum:['dialog','download','popup']},after:{type:'integer',minimum:0},operationId:id,
102
- timeoutMs:{type:'integer',minimum:1,maximum:10000}},[...Object.keys(page),'kind','after']],
112
+ waitForEvent:['Wait for a matching page event. Omit pageId for a workspace page_bound event after tab approval. Other kinds require pageId. Reuse the same cursor to read it after reconnecting.',
113
+ {...page,kind:{enum:['dialog','download','popup','page_bound']},after:{type:'integer',minimum:0},operationId:id,
114
+ timeoutMs:{type:'integer',minimum:1,maximum:10000}},['workspaceId','kind','after']],
103
115
  listEvents:['Poll redacted changes since a sequence number.',history,['workspaceId']],
104
116
  getRecoverySummary:['Read task recovery steps, delivered objects and page availability. Observe or verify before resuming.',{...history,objectsAfter:{type:'integer',minimum:0}},['workspaceId']],
105
117
  listOperations:['Read redacted receipt history.',history,['workspaceId']],
106
- finishWorkspace:['Call when the overall task is complete, before reporting success. Keep selected result tabs as ordinary tabs and remove the task group. Use an empty list when there are no results to keep.',{...operation,keepPageIds:{type:'array',uniqueItems:true,items:id}}],
118
+ finishWorkspace:['Call when the overall task is complete, before reporting success. Keep selected result tabs as ordinary tabs and remove the task group. Use an empty list when there are no results to keep.',{...operation,keepPageIds:{type:'array',uniqueItems:true,items:id},previewId:id},['workspaceId','operationId','keepPageIds']],
107
119
  diagnoseOperation: ['Preview a redacted diagnostic with the next safe action. Use it after a timeout, disconnect or outcome_unknown.', operation],
108
- getOperation: ['Read an operation receipt, including its completed step count.', operation],
120
+ getOperation: ['Read an operation receipt, including its completed step count. Set waitMs to wait briefly for a pending action.', {...operation,waitMs:{type:'integer',minimum:1,maximum:10000}},Object.keys(operation)],
109
121
  cancelOperation: ['Cancel the remaining steps of an operation.', operation],
110
122
  handOff: ['Hand control of the workspace to its user.', workspace],
111
123
  closeWorkspace: ['Close the workspace and its managed pages.', workspace],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "open-browser",
4
- "version": "0.1.0",
4
+ "version": "0.3.0",
5
5
  "description": "管理本机 Agent 工作区与 Chromium 标签组",
6
6
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhZVSXIA/vfzO0jj4ebn25I3lbL//y8FbZUeQ8Q9shwfMWTbl3bsjcHzIITSGg5+NqVTAEB1AgjFZDi/Idoj+tgsvwQxXbMBzgdZA1tQMASXcbFRdVNTxWbRBSd4JXtsFfD7H6QeBwXuIHNqUeyQYD0sYn8Ot0c4KJCzsYshYPLU56+Lzdoy+7l6ydmmw31T4tpanZHJvUgyzATOjEekFJii+9IEI/G4BUGQhKdPqR/MBYiqzxgPB5WIr3w25z6bH5KC6wnUxblLQM0RAHa4hot38NOFul5JCW6BOLHEes7Pz3DOUpWFP+DFSkY42r0dt1Kh/5CFKr6ED3agcc+tB1wIDAQAB",
7
7
  "permissions": [
@@ -23,9 +23,6 @@
23
23
  "128": "icons/open-browser-128.png"
24
24
  }
25
25
  },
26
- "chrome_url_overrides": {
27
- "newtab": "newtab.html"
28
- },
29
26
  "content_security_policy": {
30
27
  "extension_pages": "script-src 'self'; object-src 'none'; connect-src 'none'; frame-ancestors 'none'; base-uri 'none'"
31
28
  },
@@ -16,5 +16,11 @@ section { margin-top: 34px; } .section-title { margin-bottom: 12px; }
16
16
  .history-list { display: grid; gap: 2px; border-top: 1px solid color-mix(in srgb, CanvasText 12%, transparent); }
17
17
  .history-row { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 12px 2px; border-bottom: 1px solid color-mix(in srgb, CanvasText 10%, transparent); }
18
18
  .history-title { display: block; font-size: 14px; font-weight: 600; } .history-meta { display: grid; justify-items: end; gap: 4px; white-space: nowrap; } .history-state { font-size: 12px; font-weight: 600; color: #28734c; } .history-state.failed, .history-state.outcome_unknown { color: #a44b2b; }
19
+ .record-button { margin-top: 10px; font-size: 12px; }
20
+ .timeline { display: grid; gap: 4px; margin-top: 10px; padding: 8px 10px; border-left: 2px solid color-mix(in srgb, CanvasText 20%, transparent); }
21
+ .timeline-row { display: block; color: color-mix(in srgb, CanvasText 70%, Canvas); font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
22
+ .history-actions { display: flex; align-items: center; }
23
+ .history-row { flex-wrap: wrap; }
24
+ .history-row .timeline { flex-basis: 100%; }
19
25
  .empty { padding: 22px 0; } .quiet { cursor: pointer; color: color-mix(in srgb, CanvasText 68%, Canvas); background: none; border: 0; text-decoration: none; padding: 4px 0; font: inherit; } #notice.error { color: #a44b2b; } [hidden] { display: none !important; }
20
26
  @media (max-width: 700px) { body { min-width: 0; } header { padding: 0 20px; } main { width: calc(100% - 40px); margin-top: 28px; } }
@@ -18,11 +18,17 @@ function notify(message) {
18
18
 
19
19
  function friendlyError(error) {
20
20
  const code = error?.message || '';
21
- if (code === 'host_unavailable' || code === 'host_timeout') return 'open-browser 服务未连接,请先启动应用后点击刷新。';
21
+ if (code === 'host_unavailable' || code === 'host_timeout') return code === 'host_timeout'
22
+ ? 'open-browser 已收到请求,但服务响应超时,请检查应用后重试。'
23
+ : 'open-browser 服务未连接,请先启动应用后点击刷新。';
24
+ if (code === 'extension_worker_timeout') return 'open-browser 扩展响应超时,请重新加载扩展或重启应用。';
25
+ if (code === 'extension_unavailable') return 'open-browser 工作区扩展未运行,请重新启动应用。';
22
26
  return code || '暂时无法读取 Agent 状态,请点击刷新重试。';
23
27
  }
24
28
 
25
29
  function stateLabel(workspace) {
30
+ if (workspace.activity?.needsHumanVerification) return '需要人工验证';
31
+ if (workspace.activity?.needsVisualPermission) return '需要授权截图';
26
32
  if (workspace.activity?.needsCredential) return '等待凭据';
27
33
  return modes[workspace.mode] || phases[workspace.activity?.current?.phase] || phases[workspace.activity?.phase] || '待命';
28
34
  }
@@ -37,6 +43,42 @@ function line(text, className = '') {
37
43
  return node;
38
44
  }
39
45
 
46
+ function eventLabel(event) {
47
+ const state = event.state || 'unknown';
48
+ const steps = Number.isInteger(event.completedSteps) ? ` · ${event.completedSteps} 步` : '';
49
+ const operation = event.operationId ? ` · ${event.operationId.slice(0, 8)}` : '';
50
+ return `${event.kind || '事件'} · ${phases[state] || state}${steps}${operation}`;
51
+ }
52
+
53
+ async function showEvents(workspaceId, host) {
54
+ const timeline = host.querySelector('.timeline');
55
+ if (!timeline) return;
56
+ if (!timeline.hidden) {
57
+ timeline.hidden = true;
58
+ return;
59
+ }
60
+ timeline.hidden = false;
61
+ timeline.replaceChildren(line('正在读取记录…', 'detail'));
62
+ try {
63
+ const result = await call('listEvents', { workspaceId, after: 0, limit: 24 });
64
+ const events = result?.events || [];
65
+ timeline.replaceChildren(...(events.length
66
+ ? events.map(event => line(eventLabel(event), 'timeline-row'))
67
+ : [line('暂无可显示的脱敏事件。', 'detail')]));
68
+ } catch (error) {
69
+ timeline.replaceChildren(line(friendlyError(error), 'detail'));
70
+ }
71
+ }
72
+
73
+ function recordButton(workspaceId, host) {
74
+ const button = document.createElement('button');
75
+ button.type = 'button';
76
+ button.className = 'quiet record-button';
77
+ button.textContent = '查看记录';
78
+ button.onclick = () => void showEvents(workspaceId, host);
79
+ return button;
80
+ }
81
+
40
82
  function renderWorkspaces(items) {
41
83
  el('workspace-count').textContent = items.length ? `${items.length} 个` : '';
42
84
  el('empty').hidden = items.length > 0;
@@ -53,6 +95,10 @@ function renderWorkspaces(items) {
53
95
  const agent = line(workspace.agentName || 'Agent', 'agent-name');
54
96
  card.append(title, agent, status, detail);
55
97
  if (needsTaskName(workspace)) card.append(line('请为此任务命名', 'name-hint'));
98
+ const timeline = document.createElement('div');
99
+ timeline.className = 'timeline';
100
+ timeline.hidden = true;
101
+ card.append(recordButton(workspace.workspaceId, card), timeline);
56
102
  return card;
57
103
  }));
58
104
  }
@@ -83,7 +129,13 @@ function renderHistory(items) {
83
129
  meta.append(line(phases[item.state] || item.state || '已完成', `history-state ${item.state || ''}`));
84
130
  const time = formatTime(item.updatedAt || item.createdAt);
85
131
  if (time) meta.append(line(time, 'detail'));
86
- row.append(main, meta);
132
+ const timeline = document.createElement('div');
133
+ timeline.className = 'timeline';
134
+ timeline.hidden = true;
135
+ const actions = document.createElement('div');
136
+ actions.className = 'history-actions';
137
+ actions.append(recordButton(item.workspaceId, row));
138
+ row.append(main, meta, actions, timeline);
87
139
  return row;
88
140
  }));
89
141
  }
@@ -3,7 +3,7 @@
3
3
  globalThis.openBrowserPhaseLabels = Object.freeze({
4
4
  idle: '等待指令', queued: '已排队', running: '执行中', actionability: '检查目标',
5
5
  dispatching: '正在派发', waiting: '等待页面', verifying: '核对结果',
6
- needs_credential: '等待凭据', completed: '已完成', failed: '失败',
6
+ needs_credential: '等待凭据', needs_human_verification: '需要人工验证', needs_visual_permission: '需要授权截图', completed: '已完成', failed: '失败',
7
7
  cancelled: '已取消', outcome_unknown: '结果待核实',
8
8
  });
9
9
  globalThis.openBrowserModeLabels = Object.freeze({ agent: 'Agent 控制', human: '人工接管', transferring: '交接中' });
@@ -8,7 +8,7 @@ strong { font-size: 17px; letter-spacing: -.3px; }
8
8
  main { padding: 0 16px 14px; } section, form, details { margin-top: 14px; }
9
9
  h2 { font-size: 14px; margin: 0 0 3px; } p { margin: 8px 0; overflow-wrap: anywhere; }
10
10
  label { display: block; margin: 8px 0 3px; }
11
- select, input[type=password] { width: 100%; height: 30px; font: inherit; }
11
+ select, #adoption input, input[type=password] { width: 100%; height: 30px; font: inherit; }
12
12
  input[type=password] { padding: 3px 6px; }
13
13
  button { font: inherit; border: 1px solid transparent; border-radius: 5px; padding: 4px 10px; background: #176244; color: white; cursor: pointer; }
14
14
  button.secondary { background: ButtonFace; color: ButtonText; border-color: color-mix(in srgb, ButtonText 25%, transparent); }
@@ -14,20 +14,32 @@
14
14
  <header><strong><img src="icons/open-browser-48.png" width="24" height="24" alt="">open-browser</strong><span id="status" role="status">正在连接…</span></header>
15
15
  <main>
16
16
  <p id="empty" hidden>当前没有活动任务。新标签页会显示 Agent 控制台。</p>
17
+ <section id="adoption" hidden>
18
+ <p id="adopt-site"></p>
19
+ <label for="adopt-task">授权给哪个 Agent 任务</label><select id="adopt-task"></select>
20
+ <label for="adopt-alias">账号别名(选填)</label><input id="adopt-alias" maxlength="48" placeholder="例如:工作账号">
21
+ <label><input type="checkbox" id="resume-tab">重启时恢复上次浏览会话,并继续此页任务</label>
22
+ <div class="action"><button id="adopt" type="button">让 Agent 操作此页</button><button class="secondary" id="adopt-manual" type="button">生成备用授权码</button></div>
23
+ <label id="adopt-result" hidden>将以下授权交给所选 Agent,两分钟内有效<input id="adopt-token" readonly></label>
24
+ </section>
17
25
  <section id="workspace" hidden>
26
+ <div id="context-selection" hidden>
18
27
  <label for="workspaces">工作区</label><select id="workspaces"></select>
19
28
  <label for="pages">标签页</label><select id="pages"></select>
29
+ </div>
30
+ <p id="page-details"></p>
20
31
  <div class="action"><button id="control" type="button"></button></div>
21
32
  <div id="dialogs"></div>
22
33
  <div id="blocked"></div>
23
34
  <details id="uploads"><summary>授权上传文件</summary><p id="upload-origin"></p>
24
35
  <input id="upload-file" type="file"><div id="upload-list"></div></details>
25
36
  <details id="downloads" hidden><summary>任务下载</summary><div id="download-list"></div></details>
37
+ <button id="pixel-permission" type="button" class="secondary" hidden></button>
26
38
  <p id="visual-status" hidden></p>
27
- <details><summary>操作诊断</summary>
28
- <label for="diagnostic-operation">操作 ID</label><input id="diagnostic-operation" autocomplete="off">
29
- <button id="diagnostic-preview" type="button" class="secondary">预览脱敏报告</button>
30
- <pre id="diagnostic-data"></pre><a id="diagnostic-export" download="open-browser-diagnostic.json" hidden>保存预览内容</a>
39
+ <details><summary>导出错误日志</summary>
40
+ <p>导出当前任务的脱敏失败记录,便于排查问题。</p>
41
+ <button id="diagnostic-export-button" type="button" class="secondary">导出错误日志</button>
42
+ <a id="diagnostic-export" download="open-browser-error-log.json" hidden>下载错误日志</a>
31
43
  </details>
32
44
  <details id="delivery"><summary>结束任务</summary>
33
45
  <p>勾选要留给自己的标签,其余任务标签将关闭。</p>
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const el = id => document.getElementById(id);
4
- let selected = '', detail, request, selectedTab = '', revision = 0, busy = false, refreshing = false;
4
+ let selected = '', detail, request, selectedTab = '', revision = 0, busy = false, refreshing = false, contextTab = false;
5
5
  const phases = globalThis.openBrowserPhaseLabels;
6
6
 
7
7
  async function call(method, params = {}) {
@@ -16,9 +16,11 @@ function notify(text = '') {
16
16
  }
17
17
 
18
18
  function describe(w) {
19
+ if (w.activity?.needsHumanVerification) return '需要人工验证';
19
20
  if (w.mode === 'human') return '人工接管';
20
21
  if (w.mode === 'transferring') return '交接中';
21
22
  if (w.activity?.needsCredential) return '等待凭据';
23
+ if (w.activity?.needsVisualPermission) return '需要授权截图';
22
24
  const current = w.activity?.current;
23
25
  const stage = current?.dispatchState;
24
26
  if (stage) return stage === 'dispatched' ? '已派发' : '等待页面';
@@ -44,6 +46,32 @@ function showCredential(next) {
44
46
  el('save').textContent = '绑定凭据';
45
47
  }
46
48
 
49
+ let popupTabId, ordinaryTarget, tokenTimer, standalone = false;
50
+ function clearToken() {
51
+ clearTimeout(tokenTimer);
52
+ el('adopt-token').value = '';
53
+ el('adopt-result').hidden = true;
54
+ }
55
+ el('adopt-task').onchange = () => { clearToken(); el('adopt-manual').disabled = el('adopt').disabled = !el('adopt-task').value; };
56
+ function authorizeTab(bindOnApproval) {
57
+ return perform(async () => {
58
+ clearToken();
59
+ const {id:targetId, origin} = ordinaryTarget;
60
+ const reply = await call('offerCurrentTab',{workspaceId:el('adopt-task').value, tabId:popupTabId,
61
+ targetId, origin, bindOnApproval, resumeOnRestart:el('resume-tab').checked, accountAlias:el('adopt-alias').value.trim()});
62
+ if (bindOnApproval && reply.pageId) {
63
+ notify('已将此页交给所选任务');
64
+ return;
65
+ }
66
+ el('adopt-token').value = JSON.stringify({workspaceId:reply.workspaceId,adoptionToken:reply.adoptionToken});
67
+ el('adopt-result').hidden = false;
68
+ el('adopt-token').select();
69
+ tokenTimer = setTimeout(clearToken, Math.max(0, reply.expiresAt - Date.now()));
70
+ });
71
+ }
72
+ el('adopt').onclick = () => authorizeTab(true);
73
+ el('adopt-manual').onclick = () => authorizeTab(false);
74
+
47
75
  let deliveryKey = '', finishId;
48
76
  function renderDelivery(w) {
49
77
  const originLabels = {resource:'加载静态资源',navigation:'允许导航与页面操作'};
@@ -66,6 +94,7 @@ function renderDelivery(w) {
66
94
  const label = document.createElement('label'), input = document.createElement('input');
67
95
  input.type = 'checkbox';
68
96
  input.checked = true;
97
+ input.disabled = p.ownership === 'user';
69
98
  input.value = p.pageId;
70
99
  input.onchange = () => { finishId = crypto.randomUUID(); };
71
100
  label.append(input, ' ' + (p.title || p.origin || '页面'));
@@ -86,39 +115,54 @@ function clearDiagnostic() {
86
115
  if (link.hasAttribute('href')) URL.revokeObjectURL(link.href);
87
116
  link.removeAttribute('href');
88
117
  link.hidden = true;
89
- el('diagnostic-data').textContent = '';
90
118
  }
91
- el('diagnostic-operation').oninput = clearDiagnostic;
92
- el('diagnostic-preview').onclick = () => perform(async () => {
119
+ el('diagnostic-export-button').onclick = () => perform(async () => {
93
120
  clearDiagnostic();
94
- const workspaceId = selected, operationId = el('diagnostic-operation').value;
95
- const data = await call('diagnoseOperation', {workspaceId, operationId});
96
- if (workspaceId !== selected || operationId !== el('diagnostic-operation').value) return;
97
- const text = JSON.stringify(data, null, 2);
98
- el('diagnostic-data').textContent = text;
121
+ const workspaceId = selected;
122
+ const [operations, events] = await Promise.all([
123
+ call('listOperations', {workspaceId, after: 0, limit: 100}),
124
+ call('listEvents', {workspaceId, after: 0, limit: 100}),
125
+ ]);
126
+ const text = JSON.stringify({ version: 1, workspaceId, exportedAt: new Date().toISOString(),
127
+ operations: (operations.operations || []).filter(item => item.error || ['failed', 'outcome_unknown', 'cancelled'].includes(item.state)),
128
+ events: events.events || [] }, null, 2) + '\n';
99
129
  const link = el('diagnostic-export');
100
130
  link.href = URL.createObjectURL(new Blob([text], {type:'application/json'}));
101
131
  link.hidden = false;
132
+ link.textContent = '下载错误日志';
133
+ link.click();
102
134
  });
103
135
 
104
136
  function render(w) {
105
137
  if (detail?.workspaceId !== w?.workspaceId) {
106
138
  clearDiagnostic();
107
- el('diagnostic-operation').value = '';
108
139
  }
109
140
 
110
141
  detail = w;
111
142
  el('workspace').hidden = !w;
112
143
  el('empty').hidden = !!w;
144
+ el('context-selection').hidden = contextTab || !w;
113
145
  el('status').textContent = w ? describe(w) + ' · 资料 ' + w.profileId : '暂无工作区';
114
146
  if (!w) { showCredential(null); return; }
115
147
  renderDialogs(w);
116
148
  renderDelivery(w);
117
149
  const pages = w.pages || [];
118
- if (!pages.some(p => p.pageId === selectedTab)) selectedTab = pages.at(-1)?.pageId || '';
150
+ if (standalone && !selectedTab) selectedTab = pages[0]?.pageId || '';
151
+ const page = pages.find(p => p.pageId === selectedTab);
119
152
  options(el('pages'), pages.map((p, i) => [p.pageId, (i+1) + ' · ' + (p.title || p.origin || '页面')]), selectedTab);
120
- el('control').textContent = w.mode === 'human' ? '交回 Agent' : '接管此页';
121
- el('control').disabled = busy || w.mode === 'transferring' || (!selectedTab && w.mode !== 'human');
153
+ if (!page) {
154
+ el('workspace').hidden = !standalone;
155
+ el('control').disabled = true;
156
+ el('uploads').hidden = true;
157
+ el('page-details').textContent = '';
158
+ el('status').textContent = '原标签页已关闭或解绑';
159
+ showCredential(null);
160
+ return;
161
+ }
162
+ const sync = page.lastSyncedAt ? '上次同步 ' + new Date(page.lastSyncedAt).toLocaleTimeString() : '';
163
+ el('page-details').textContent = [page.origin, w.accountAlias, page.syncState === 'sync_pending' ? '同步中' : sync].filter(Boolean).join(' · ');
164
+ el('control').textContent = w.unlockPending ? '重试人工接管' : w.mode === 'human' ? '交回 Agent' : w.scope === 'single_tab' ? '接管此页' : '接管工作区';
165
+ el('control').disabled = busy || (w.mode === 'transferring' && !w.unlockPending) || (!selectedTab && w.mode !== 'human');
122
166
  el('uploads').hidden = w.mode!=='agent' || !selectedTab;
123
167
  el('upload-origin').textContent = pages.find(p=>p.pageId===selectedTab)?.origin || '';
124
168
  showCredential(w.mode === 'agent' ? w.activity?.credentialRequest || null : null);
@@ -129,9 +173,42 @@ async function sync() {
129
173
  refreshing = true;
130
174
  const serial = revision;
131
175
  try {
132
- const list = await call('listWorkspaces');
176
+ if (Number.isInteger(popupTabId)) {
177
+ const key = 'tab:' + popupTabId;
178
+ const mapping = (await chrome.storage.session.get(key))[key];
179
+ if (!contextTab && mapping) {
180
+ contextTab = true;
181
+ selected = mapping.workspaceId;
182
+ selectedTab = mapping.pageId;
183
+ clearToken();
184
+ }
185
+ }
186
+ el('adoption').hidden = true;
187
+ if (!contextTab && !standalone) {
188
+ const list = await call('listWorkspaces');
189
+ const target = (await chrome.debugger.getTargets()).find(t => t.type === 'page' && t.tabId === popupTabId);
190
+ const origin = URL.parse(target?.url);
191
+ if (serial !== revision) return;
192
+ render(null);
193
+ if (!origin || !['http:', 'https:'].includes(origin.protocol)) return;
194
+ if (ordinaryTarget?.id !== target.id || ordinaryTarget?.origin !== origin.origin) clearToken();
195
+ ordinaryTarget = {id:target.id, origin:origin.origin};
196
+ const tasks = list.filter(w => w.pageAvailability === 'unregistered' && w.mode === 'agent');
197
+ el('adoption').hidden = false;
198
+ el('empty').hidden = true;
199
+ el('status').textContent = '普通标签页';
200
+ el('adopt-site').textContent = origin.origin + (tasks.length ? '' : ' · 请让 Agent 先创建一个命名工作区');
201
+ const chooser = el('adopt-task');
202
+ options(chooser, tasks.map(w => [w.workspaceId, workspaceTitle(w) + ' · ' + w.workspaceId.slice(0,8)]),
203
+ tasks.some(w => w.workspaceId === chooser.value) ? chooser.value : tasks.length === 1 ? tasks[0].workspaceId : '');
204
+ el('adopt-manual').disabled = el('adopt').disabled = !chooser.value;
205
+ return;
206
+ }
207
+ const list = contextTab ? (selected ? [await call('getWorkspace', {workspaceId: selected })] : []) : await call('listWorkspaces');
133
208
  if (serial !== revision) return;
209
+ if (contextTab && !list.some(w => w.workspaceId === selected)) { render(null); return; }
134
210
  if (!list.some(w => w.workspaceId === selected)) {
211
+ selectedTab = '';
135
212
  selected = (list.find(w => w.activity?.needsCredential) || list[0])?.workspaceId || '';
136
213
  }
137
214
  const titles = list.map(workspaceTitle);
@@ -142,9 +219,9 @@ async function sync() {
142
219
  return [w.workspaceId, title + suffix + ' · ' + describe(w)];
143
220
  });
144
221
  options(el('workspaces'), entries, selected);
145
- const w = selected ? await call('getWorkspace', { workspaceId: selected }) : null;
222
+ const w = contextTab ? list[0] || null : selected ? await call('getWorkspace', { workspaceId: selected }) : null;
146
223
  const [captureReply, downloads, uploads] = w ? await Promise.all([
147
- call('visualStatus',{workspaceId:selected}).catch(()=>({})),
224
+ call('visualStatus',{workspaceId:selected,pageId:selectedTab}).catch(()=>({})),
148
225
  call('listDownloads',{workspaceId:selected}),
149
226
  call('listUploads',{workspaceId:selected}),
150
227
  ]) : [{}, [], []];
@@ -158,13 +235,33 @@ async function sync() {
158
235
  return button;
159
236
  }));
160
237
  renderDownloads(downloads);
238
+ const permission = captureReply.pagePermission;
239
+ const button = el('pixel-permission');
240
+ const pageId = selectedTab;
241
+ button.hidden = !permission;
242
+ if (permission) {
243
+ button.textContent = (permission.allow ? '撤销本任务截图授权 · ' : '允许本任务截图 · ') + permission.origin;
244
+ button.onclick = () => perform(() => call('setPagePixelPermission',{
245
+ workspaceId:w.workspaceId, pageId, documentId:permission.documentId, controlGeneration:w.controlGeneration,
246
+ origin:permission.origin, allow:!permission.allow
247
+ }));
248
+ }
161
249
  const status=el('visual-status');
162
250
  status.hidden=!capture;
163
251
  if(capture) status.textContent='最近画面采集 · '+capture.principalId+' · '+capture.origin+' · ('+
164
252
  capture.clip.x+', '+capture.clip.y+') '+capture.clip.width+' × '+capture.clip.height;
165
253
  }
166
254
  } catch (error) {
167
- if (serial === revision) { render(null); el('status').textContent = '连接失败'; notify(error.message); }
255
+ if (serial === revision) {
256
+ render(null);
257
+ if (contextTab && error.message === 'workspace_not_found') {
258
+ el('status').textContent = '原任务已结束或服务已重启';
259
+ notify('请在需要授权的标签页重新打开扩展。');
260
+ } else {
261
+ el('status').textContent = '连接失败';
262
+ notify(error.message);
263
+ }
264
+ }
168
265
  } finally {
169
266
  refreshing = false;
170
267
  if (!busy && serial !== revision) void sync();
@@ -230,11 +327,12 @@ async function perform(action) {
230
327
  busy = true;
231
328
  revision++;
232
329
  notify();
233
- for (const element of document.querySelectorAll('button, select, input')) element.disabled = true;
330
+ const enabled = [...document.querySelectorAll('button:enabled, select:enabled, input:enabled')];
331
+ for (const element of enabled) element.disabled = true;
234
332
  try { await action(); } catch (error) { notify(error.message); }
235
333
  finally {
236
334
  busy = false;
237
- for (const element of document.querySelectorAll('button, select, input')) element.disabled = false;
335
+ for (const element of enabled) element.disabled = false;
238
336
  render(detail);
239
337
  void sync();
240
338
  }
@@ -283,7 +381,8 @@ el('upload-file').onchange = event => {
283
381
  });
284
382
  };
285
383
  el('control').onclick = () => perform(async () => {
286
- if (detail.mode === 'human') await call('returnToAgent', { workspaceId: selected, controlGeneration: detail.controlGeneration });
384
+ if (!detail?.pages.some(p => p.pageId === selectedTab)) return;
385
+ if (detail.mode === 'human') await call('returnToAgent', { workspaceId: selected, pageId:selectedTab, controlGeneration: detail.controlGeneration });
287
386
  else await call('takeControl', { workspaceId: selected, pageId: selectedTab, controlGeneration: detail.controlGeneration });
288
387
  });
289
388
  el('credential').onsubmit = event => {
@@ -304,10 +403,12 @@ el('credential').onsubmit = event => {
304
403
 
305
404
  async function open() {
306
405
  const explicit = /^#tab-(\d+)(-delivery)?$/.exec(location.hash);
307
- const tabId = explicit ? Number(explicit[1]) : (await chrome.tabs.query({ active: true, lastFocusedWindow: true }))[0]?.id;
406
+ standalone = !explicit && !!(await chrome.tabs.getCurrent());
407
+ const tabId = popupTabId = standalone ? undefined : explicit ? Number(explicit[1]) : (await chrome.tabs.query({ active: true, lastFocusedWindow: true }))[0]?.id;
308
408
  if (Number.isInteger(tabId)) {
309
409
  const key = 'tab:' + tabId;
310
410
  const owned = (await chrome.storage.session.get(key))[key];
411
+ contextTab = Boolean(owned);
311
412
  if (owned) { selected = owned.workspaceId; selectedTab = owned.pageId; }
312
413
  }
313
414
  await sync();
@@ -28,6 +28,8 @@ const actionStates = {
28
28
  waiting: ['…', '#6757a4', '等待页面'],
29
29
  verifying: ['✓', '#526675', '核对结果'],
30
30
  needs_credential: ['!', '#a72f24', '等待凭据'],
31
+ needs_human_verification: ['!', '#a75d08', '需要人工验证'],
32
+ needs_visual_permission: ['!', '#a75d08', '需要授权截图'],
31
33
  completed: ['✓', '#526675', '已完成'],
32
34
  failed: ['!', '#a72f24', '执行失败'],
33
35
  outcome_unknown: ['?', '#a75d08', '结果待核实'],
@@ -51,10 +53,10 @@ async function writeAction(tabId, record) {
51
53
  return;
52
54
  }
53
55
  await chrome.storage.session.set({ [key]: record });
54
- const phase = record.mode !== 'agent' ? record.mode : record.needsCredential ? 'needs_credential' : record.phase;
56
+ const phase = record.mode !== 'agent' ? record.mode : record.needsHumanVerification ? 'needs_human_verification' : record.needsVisualPermission ? 'needs_visual_permission' : record.needsCredential ? 'needs_credential' : record.phase;
55
57
  showRunning(tabId, ['running', 'actionability', 'dispatching', 'waiting', 'verifying'].includes(phase));
56
58
  const [text, color, status] = actionStates[phase] || actionStates.idle;
57
- const panel = phase === 'needs_credential' || phase === 'transferring' || !record.controlGeneration;
59
+ const panel = phase === 'needs_credential' || phase === 'needs_human_verification' || phase === 'needs_visual_permission' || phase === 'transferring' || !record.controlGeneration;
58
60
  const steps = { click: '点击', fill: '填写', fillCredential: '填写凭据' };
59
61
  const step = phase === 'running' && record.dispatchState ? (record.dispatchState === 'dispatched' ? '已派发' : '等待页面') : phase === 'running' ? steps[record.stepKind] : '';
60
62
  const hint = record.mode === 'human' ? '点击交回 Agent' : panel ? '点击打开工作区面板' : '点击接管';