@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
@@ -0,0 +1,100 @@
1
+ import {createHash} from 'node:crypto';
2
+
3
+ // Read the browser-generated navigation entry in a fresh isolated world.
4
+ // Page scripts cannot substitute a value for this getter.
5
+ async function identify(page) {
6
+ const cdp = await page.context().newCDPSession(page);
7
+ try {
8
+ const {frameTree} = await cdp.send('Page.getFrameTree');
9
+ const {executionContextId} = await cdp.send('Page.createIsolatedWorld',{frameId:frameTree.frame.id,worldName:'open-browser-resume'});
10
+ const {result} = await cdp.send('Runtime.evaluate',{contextId:executionContextId,
11
+ expression:'window.navigation?.currentEntry?.key'});
12
+ if (typeof result.value !== 'string' || !/^[a-f0-9-]{36}$/i.test(result.value)) return null;
13
+ const {targetInfo} = await cdp.send('Target.getTargetInfo');
14
+ return {page, targetId:targetInfo.targetId, origin:URL.parse(targetInfo.url)?.origin,
15
+ entry:createHash('sha256').update(result.value).digest('hex')};
16
+ } finally { await cdp.detach().catch(() => {}); }
17
+ }
18
+
19
+ // Only the hash of the browser's own history entry is durable. Keep the
20
+ // checkpoint in step with ownership and pending writes, before input dispatch.
21
+ export class TabRecovery {
22
+ constructor(registry) {
23
+ this.save = registry.db.prepare('INSERT OR REPLACE INTO resumable_tabs(task,page,origin,entry,expires) VALUES(?,?,?,?,?)');
24
+ this.remove = registry.db.prepare('DELETE FROM resumable_tabs WHERE task=?');
25
+ this.entries = new WeakMap();
26
+ }
27
+
28
+ refresh(ws) {
29
+ if (this.closed || !ws.resumeOnRestart) return;
30
+ let state = this.entries.get(ws);
31
+ if (!state) {
32
+ state = {};
33
+ this.entries.set(ws,state);
34
+ }
35
+ const [tab] = ws.pages.values();
36
+ const eligible = ws.mode === 'agent' && !ws.finishing && !ws.securityChallenge && !ws.guardLost &&
37
+ tab && !tab.dialog && !tab.needsSubmissionReview && !tab.page.isClosed() &&
38
+ ws.origins.has(URL.parse(tab.page.url())?.origin) && ![...ws.jobs].some(job => job.kind === 'act');
39
+ if (state.saved && (!eligible || state.documentId !== tab.documentId)) {
40
+ this.remove.run(ws.id);
41
+ state.saved = false;
42
+ }
43
+ if (!eligible) return;
44
+ if (state.documentId !== tab.documentId || !state.identity) {
45
+ if (state.documentId === tab.documentId && state.pending) return state.pending;
46
+ const documentId = tab.documentId;
47
+ state.documentId = documentId;
48
+ state.identity = null;
49
+ state.pending = identify(tab.page).catch(() => null).then(identity => {
50
+ if (state.documentId !== documentId) return;
51
+ state.pending = null;
52
+ if (!this.closed && identity && tab.documentId === documentId && ws.pages.get(tab.id) === tab &&
53
+ identity.origin === URL.parse(tab.page.url())?.origin && ws.origins.has(identity.origin)) {
54
+ state.identity = identity;
55
+ this.refresh(ws);
56
+ }
57
+ });
58
+ return state.pending;
59
+ }
60
+ if (!state.saved || Date.now() >= state.renewAt) {
61
+ const now = Date.now();
62
+ this.save.run(ws.id,tab.id,state.identity.origin,state.identity.entry,now+86400000);
63
+ state.saved = true;
64
+ state.renewAt = now + 60000;
65
+ }
66
+ }
67
+ }
68
+
69
+ export async function restoreApprovedTabs(engine, registry) {
70
+ const rows = registry.db.prepare(`SELECT r.*, t.name, t.owner, t.agentName FROM resumable_tabs r
71
+ JOIN tasks t ON r.task=t.id WHERE r.expires>? AND (t.owner='local' OR t.owner IN (SELECT id FROM clients))`).all(Date.now());
72
+ registry.db.prepare(`DELETE FROM resumable_tabs WHERE expires<=? OR task IN
73
+ (SELECT id FROM tasks WHERE owner!='local' AND owner NOT IN (SELECT id FROM clients))`).run(Date.now());
74
+ const consume = registry.db.prepare('DELETE FROM resumable_tabs WHERE task=?');
75
+ if (!rows.length) return;
76
+ const origins = new Set(rows.map(row => row.origin));
77
+ const candidates = await Promise.all(engine.sharedContext.pages()
78
+ .filter(page => origins.has(URL.parse(page.url())?.origin)).map(page => identify(page).catch(() => null)));
79
+ for (const row of rows) {
80
+ const matches = candidates.filter(item => item?.origin === row.origin && item.entry === row.entry);
81
+ if (matches.length !== 1 || registry.hasDelegates(row.task)) {
82
+ consume.run(row.task);
83
+ continue;
84
+ }
85
+ const [match] = matches;
86
+ let ws;
87
+ try {
88
+ await engine.create({name:row.name,agentName:row.agentName},row.owner,row.task);
89
+ ws = engine.workspaces.get(row.task);
90
+ const offer = await engine.call('offerCurrentTab',{workspaceId:row.task,targetId:match.targetId,
91
+ origin:row.origin,resumeOnRestart:true},row.owner,'desktop');
92
+ if ((await identify(match.page))?.entry !== row.entry || !ws.offer) throw Error('navigation_changed');
93
+ ws.offer.restoredPageId = row.page;
94
+ await registry.call(engine,row.owner,'adoptCurrentTab',{workspaceId:row.task,adoptionToken:offer.adoptionToken});
95
+ } catch {
96
+ consume.run(row.task);
97
+ if (ws) await engine.call('closeWorkspace',{workspaceId:row.task},row.owner);
98
+ }
99
+ }
100
+ }
package/uploads.mjs CHANGED
@@ -38,7 +38,7 @@ export class UploadGrants {
38
38
  }
39
39
  }
40
40
 
41
- export async function chooseGrantedFile(ws,tab,el,id,beforeDispatch,check) {
41
+ export async function chooseGrantedFile(ws,tab,el,id,beforeDispatch,dispatch,check) {
42
42
  ws.uploads.get(ws,tab,id);
43
43
  // Register the chooser before dispatch. Many pages create a detached input during click.
44
44
  let receive, timer;
@@ -49,13 +49,13 @@ export async function chooseGrantedFile(ws,tab,el,id,beforeDispatch,check) {
49
49
  });
50
50
  try {
51
51
  beforeDispatch();
52
- const [chooser]=await Promise.all([chosen,el.click({timeout:5000})]);
52
+ const [chooser]=await Promise.all([chosen,dispatch(() => el.click({timeout:5000}))]);
53
53
  const frame=await chooser.element().ownerFrame();
54
54
  if (frame!==tab.page.mainFrame()) fail('file_origin_mismatch');
55
- check();
55
+ (check || (() => {}))();
56
56
  const {payload}=ws.uploads.get(ws,tab,id);
57
57
  ws.uploads.remove(id);
58
- await chooser.setFiles(payload,{timeout:5000});
58
+ await dispatch(() => chooser.setFiles(payload,{timeout:5000}));
59
59
  } finally {
60
60
  clearTimeout(timer);
61
61
  tab.page.off('filechooser',receive);
package/visual-page.mjs CHANGED
@@ -51,12 +51,15 @@ async function measure(session, contextId, guarded=false) {
51
51
  }
52
52
  if(privateNode || sensitive.has(doc.nodes.parentIndex[i])) sensitive.add(i);
53
53
  }
54
- const masks=[],layout=[],hiddenNodes=new Set();
54
+ const masks=[],layout=[],hiddenNodes=new Set(), canvases=[];
55
55
  let complexPaint=false;
56
56
  for(let j=0;j<doc.layout.nodeIndex.length;j++) {
57
57
  const node = doc.layout.nodeIndex[j], b = doc.layout.bounds[j];
58
58
  const [visibility,filter,reflection,backdrop,opacity] = doc.layout.styles[j].map(k=>strings[k]);
59
59
  if(opacity==='0') hiddenNodes.add(node);
60
+ if (strings[doc.nodes.nodeName[node]] === 'CANVAS' && b[2] > 0 && b[3] > 0 &&
61
+ visibility === 'visible' && opacity !== '0' && !sensitive.has(node))
62
+ canvases.push(doc.nodes.backendNodeId[node]);
60
63
  layout.push([doc.nodes.backendNodeId[node],b,doc.layout.paintOrders[j],visibility]);
61
64
  if ([filter,reflection,backdrop].some(v=>v && v!=='none')) complexPaint=true;
62
65
  if(sensitive.has(node)) masks.push({x:b[0]/viewport.zoom-viewport.scrollX-2,y:b[1]/viewport.zoom-viewport.scrollY-2,
@@ -73,7 +76,7 @@ async function measure(session, contextId, guarded=false) {
73
76
  if(masks.length && complexPaint) fail('visual_redaction_unavailable');
74
77
  const protectedNodes=new Set([...sensitive].map(i=>doc.nodes.backendNodeId[i]));
75
78
  const hosts=[...new Set([...shadowHosts].map(i=>strings[doc.nodes.nodeName[i]].toLowerCase()))];
76
- return {viewport,masks,protectedNodes,hosts,signature:hash(JSON.stringify([viewport,layout,masks]))};
79
+ return {viewport,masks,protectedNodes,hosts,canvases,signature:hash(JSON.stringify([viewport,layout,masks]))};
77
80
  }
78
81
 
79
82
  // Read the current compositor surface. CDP's screenshot clip can temporarily
@@ -182,6 +185,10 @@ export class VisualPages {
182
185
  return {principalId,origin,allow};
183
186
  }
184
187
 
188
+ hasPermission(ws, principalId, origin) {
189
+ return this.permissions.get(ws)?.has(JSON.stringify([principalId,origin])) ?? false;
190
+ }
191
+
185
192
  authority(ws,tab,actor,mode) {
186
193
  if(!this.enabled) fail('visual_disabled');
187
194
  if(ws.mode!==mode || ws.finishing) fail('stale_control');
@@ -204,6 +211,7 @@ export class VisualPages {
204
211
  const contextId=await isolatedContext(session);
205
212
  const initial=await measure(session,contextId);
206
213
  const v=initial.viewport;
214
+ if (params.liveCanvas && initial.canvases.length !== 1) fail('visual_canvas_ambiguous');
207
215
  let region=params.region;
208
216
  if(params.ref!==undefined) {
209
217
  const handle=tab.refs.get(params.ref);
@@ -222,7 +230,7 @@ export class VisualPages {
222
230
  const frameId=randomUUID();
223
231
  this.frames.set(tab,{...auth,actor,mode,clip,frameId,expires:Date.now()+frameLifetime,signature:initial.signature,
224
232
  // Retain only a digest, so changed paint on canvas is detected without saving its pixels.
225
- pixelDigest:hash(pixels)});
233
+ pixelDigest:hash(pixels), canvasId:params.liveCanvas ? initial.canvases[0] : null});
226
234
  return {workspaceId:ws.id,pageId:tab.id,frameId,documentId:auth.documentId,controlGeneration:auth.controlGeneration,
227
235
  origin:auth.origin,mimeType:'image/png',data:pixels.toString('base64'),clip,viewport:{width:v.width,height:v.height},
228
236
  pixelWidth:clip.width,pixelHeight:clip.height,scale:v.scale,zoom:v.zoom,deviceScaleFactor:v.deviceScaleFactor};
@@ -252,9 +260,11 @@ export class VisualPages {
252
260
  const executionContextId=await isolatedContext(session);
253
261
  const layout=await measure(session,executionContextId);
254
262
  if(layout.signature!==frame.signature) fail('stale_visual_frame');
255
- const pixels=await maskedCapture(session,executionContextId,frame.clip,layout);
256
- if(hash(pixels)!==frame.pixelDigest || (await measure(session,executionContextId)).signature!==layout.signature)
257
- fail('stale_visual_frame');
263
+ if (!frame.canvasId) {
264
+ const pixels=await maskedCapture(session,executionContextId,frame.clip,layout);
265
+ if(hash(pixels)!==frame.pixelDigest || (await measure(session,executionContextId)).signature!==layout.signature)
266
+ fail('stale_visual_frame');
267
+ }
258
268
  async function point(x,y,verifyFocus=false) {
259
269
  check();
260
270
  if(!inRect(x,y,frame.clip) || layout.masks.some(m=>inRect(x,y,m))) fail('visual_target_denied');
@@ -269,7 +279,7 @@ export class VisualPages {
269
279
  const {result}=await session.send('Runtime.evaluate',{expression,contextId:executionContextId});
270
280
  if(!result.objectId) fail('visual_target_denied');
271
281
  const {node}=await session.send('DOM.describeNode',{objectId:result.objectId});
272
- if(!node.backendNodeId || layout.protectedNodes.has(node.backendNodeId)) fail('visual_target_denied');
282
+ if(!node.backendNodeId || (frame.canvasId && frame.canvasId !== node.backendNodeId) || layout.protectedNodes.has(node.backendNodeId)) fail('visual_target_denied');
273
283
  check();
274
284
  }
275
285
  await point(action.x,action.y,['key','text'].includes(action.type));
@@ -9,6 +9,16 @@ export function finishDigest(keepPageIds) {
9
9
  return createHash('sha256').update(JSON.stringify(['finish', [...keepPageIds].sort()])).digest('hex');
10
10
  }
11
11
 
12
+ export function previewFinish(service, ws, keepPageIds) {
13
+ const digest = finishDigest(keepPageIds);
14
+ for (const id of keepPageIds) service.tab(ws, id);
15
+ const keptPageIds = [], closedPageIds = [];
16
+ for (const tab of ws.pages.values())
17
+ (keepPageIds.includes(tab.id) || !tab.createdByAgent ? keptPageIds : closedPageIds).push(tab.id);
18
+ const previewId = createHash('sha256').update(JSON.stringify([ws.id, ws.generation, digest, keptPageIds, closedPageIds])).digest('hex');
19
+ return {previewId, keptPageIds, closedPageIds};
20
+ }
21
+
12
22
  function stopOperations(ws, controlTransferred = false) {
13
23
  ws.uploads?.clear();
14
24
  ws.control.abort();
@@ -19,7 +29,7 @@ function stopOperations(ws, controlTransferred = false) {
19
29
  }
20
30
  }
21
31
 
22
- export async function finish(service, ws, {operationId, keepPageIds, controlGeneration}, trusted = false) {
32
+ export async function finish(service, ws, {operationId, keepPageIds, controlGeneration, previewId}, trusted = false) {
23
33
  stringParam(operationId, 160);
24
34
  const digest = finishDigest(keepPageIds);
25
35
  const past = service.store.get(ws.owner, ws.id, operationId);
@@ -29,13 +39,17 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
29
39
  }
30
40
  if (controlGeneration !== undefined && controlGeneration !== ws.generation) fail('stale_control');
31
41
  if (ws.finishing) fail('workspace_finishing');
42
+ if (previewId !== undefined && (ws.pending || ws.inputPending || ws.popupTasks.size ||
43
+ previewFinish(service, ws, keepPageIds).previewId !== previewId)) fail('finish_preview_changed');
32
44
  if (!trusted || ws.mode !== 'human') service.requireControl(ws, ws.generation);
33
45
  for (const id of keepPageIds) service.tab(ws, id);
46
+ ws.offer?.revoke();
34
47
  const keep = new Set(keepPageIds);
35
48
  const receipt = { operationId, state:'running', phase:'running', totalSteps:ws.pages.size, completedSteps:0, keptPageIds:[], closedPageIds:[] };
36
49
  service.store.save(ws.owner, ws.id, digest, receipt);
37
50
  const pending = { operationId };
38
51
  ws.finishing = pending;
52
+ service.notify(ws);
39
53
  for (const tab of ws.pages.values()) discardDialog(tab);
40
54
  ws.generation = randomUUID();
41
55
  stopOperations(ws);
@@ -51,6 +65,7 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
51
65
  service.store.save(ws.owner, ws.id, digest, receipt, true);
52
66
  if (keep.has(tab.id) || !tab.createdByAgent) {
53
67
  await releaseInput(tab);
68
+ await service.setInputGuard?.(ws, tab, false);
54
69
  await service.releaseTab?.(tab.page, ws.id, tab.id);
55
70
  await tab.releasePopups?.();
56
71
  await tab.networkRelease?.();
@@ -69,6 +84,7 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
69
84
  service.store.save(ws.owner, ws.id, digest, receipt);
70
85
  }
71
86
  if (!service.sharedContext && !receipt.keptPageIds.length) await ws.context.close();
87
+ service.store.event(ws.owner, ws.id, 'workspace_end', 'finished');
72
88
  ws.mode = 'closed';
73
89
  ws.credentials.clear();
74
90
  ws.credentialRequests.clear();
@@ -83,7 +99,13 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
83
99
  receipt.state = 'outcome_unknown';
84
100
  receipt.phase = 'outcome_unknown';
85
101
  receipt.error = 'inspect_before_retry';
86
- ws.mode = 'human';
102
+ ws.mode = 'transferring';
103
+ try {
104
+ await setWorkspaceGuard(service, ws, false);
105
+ ws.mode = 'human';
106
+ } catch {
107
+ ws.unlockPending = true;
108
+ }
87
109
  ws.generation = randomUUID();
88
110
  service.notify(ws);
89
111
  } finally {
@@ -98,7 +120,8 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
98
120
  export async function handOff(service, ws, pageId, focus = true, expectedGeneration) {
99
121
  if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
100
122
  if (ws.returning) fail('control_transition');
101
- if (ws.handoff) return ws.handoff;
123
+ const hasDialog = () => [...ws.pages.values()].some(page => page.dialog);
124
+ if (ws.handoff) return hasDialog() ? workspaceView(ws) : ws.handoff;
102
125
  if (ws.mode === 'human') return workspaceView(ws);
103
126
  const tab = pageId ? service.tab(ws, pageId) : [...ws.pages.values()].at(-1);
104
127
  ws.mode = 'transferring';
@@ -110,6 +133,14 @@ export async function handOff(service, ws, pageId, focus = true, expectedGenerat
110
133
  ws.handoff = (async () => {
111
134
  await Promise.allSettled([ws.tail,...ws.popupTasks]);
112
135
  for (const candidate of ws.pages.values()) clearRefs(candidate);
136
+ try {
137
+ await setWorkspaceGuard(service, ws, false);
138
+ } catch (error) {
139
+ ws.unlockPending = true;
140
+ service.notify(ws);
141
+ throw error;
142
+ }
143
+ ws.unlockPending = false;
113
144
  if (ws.mode !== 'transferring') fail('workspace_closed');
114
145
  ws.mode = 'human';
115
146
  service.store.event(ws.owner, ws.id, 'control', ws.mode);
@@ -119,27 +150,70 @@ export async function handOff(service, ws, pageId, focus = true, expectedGenerat
119
150
  await refreshControlGroups(service, ws);
120
151
  return workspaceView(ws);
121
152
  })().finally(() => { ws.handoff = null; });
153
+ // A native dialog suspends the dispatched action. Let the desktop answer it
154
+ // while ownership is transferring, then finish draining before enabling input.
155
+ if (hasDialog()) {
156
+ ws.handoff.catch(() => {});
157
+ return workspaceView(ws);
158
+ }
122
159
  return ws.handoff;
123
160
  }
124
161
 
162
+ async function setWorkspaceGuard(service, ws, enabled) {
163
+ if (!service.setInputGuard) return;
164
+ const results = await Promise.allSettled([...ws.pages.values()].map(async tab => {
165
+ try { await service.setInputGuard(ws, tab, enabled); }
166
+ catch (error) { if (!tab.page.isClosed()) throw error; }
167
+ }));
168
+ const failed = results.find(result => result.status === 'rejected');
169
+ if (failed) throw failed.reason;
170
+ }
171
+
125
172
  async function refreshControlGroups(service, ws) {
126
173
  if (!service.groupTab) return;
127
174
  await Promise.allSettled([...ws.pages.values()].filter(tab => !tab.dialog && !tab.page.isClosed())
128
- .map(async tab => service.groupTab(tab.page, ws.id, ws.name, ws.mode, ws.agentName, tab.id)));
175
+ .map(async tab => service.syncTab(ws, tab)));
129
176
  }
130
177
 
131
178
  export async function returnToAgent(service, ws, expectedGeneration) {
132
179
  if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
133
180
  if (ws.returning) return ws.returning;
181
+ if (ws.handoff && ws.mode === 'transferring') {
182
+ if ([...ws.pages.values()].some(tab => tab.dialog)) fail('control_transition');
183
+ await ws.handoff;
184
+ if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
185
+ if (ws.returning) return ws.returning;
186
+ }
134
187
  if (ws.mode !== 'human') fail('not_in_human_control');
135
188
  ws.mode = 'transferring';
136
189
  service.store.event(ws.owner, ws.id, 'control', ws.mode);
137
190
  ws.generation = randomUUID();
138
191
  service.notify(ws);
139
192
  ws.returning = (async () => {
140
- await ws.inputTail;
141
- await Promise.all([...ws.pages.values()].map(releaseInput));
193
+ try {
194
+ await ws.inputTail;
195
+ await Promise.all([...ws.pages.values()].map(releaseInput));
196
+ ws.guardLost = false;
197
+ await setWorkspaceGuard(service, ws, true);
198
+ if (ws.guardLost) fail('input_guard_unavailable');
199
+ } catch (error) {
200
+ try { await setWorkspaceGuard(service, ws, false); }
201
+ catch (rollbackError) {
202
+ ws.unlockPending = true;
203
+ service.notify(ws);
204
+ throw rollbackError;
205
+ }
206
+ if (ws.mode === 'transferring') {
207
+ ws.mode = 'human';
208
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
209
+ service.notify(ws);
210
+ }
211
+ throw error;
212
+ }
142
213
  if (ws.mode !== 'transferring') fail('workspace_closed');
214
+ // Returning control acknowledges that the user handled the visible site
215
+ // verification. A later navigation or response can raise it again.
216
+ ws.securityChallenge = null;
143
217
  ws.control = new AbortController();
144
218
  ws.mode = 'agent';
145
219
  service.store.event(ws.owner, ws.id, 'control', ws.mode);
@@ -150,7 +224,9 @@ export async function returnToAgent(service, ws, expectedGeneration) {
150
224
  return ws.returning;
151
225
  }
152
226
 
153
- export async function close(service, ws) {
227
+ export async function close(service, ws, reason = 'explicit_close') {
228
+ service.store.event(ws.owner, ws.id, 'workspace_end', reason);
229
+ ws.offer?.revoke();
154
230
  for (const tab of ws.pages.values()) discardDialog(tab);
155
231
  ws.mode = 'closed';
156
232
  service.store.event(ws.owner, ws.id, 'control', ws.mode);
@@ -160,7 +236,15 @@ export async function close(service, ws) {
160
236
  await ws.downloads?.close();
161
237
  if (service.sharedContext) {
162
238
  await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
163
- await Promise.all([...ws.pages.values()].map(async ({page,id}) => {
239
+ await Promise.all([...ws.pages.values()].map(async tab => {
240
+ const {page, id} = tab;
241
+ if (ws.singleTab) {
242
+ await releaseInput(tab);
243
+ await service.setInputGuard?.(ws, tab, false);
244
+ try { await service.releaseTab?.(page, ws.id, id); }
245
+ finally { tab.unregister(); }
246
+ return;
247
+ }
164
248
  if (!page.isClosed() && service.releaseTab) await service.releaseTab(page,ws.id,id).catch(() => {});
165
249
  await page.close().catch(() => {});
166
250
  }));
@@ -30,6 +30,7 @@ export function requirePageOrigin(ws, tab) {
30
30
 
31
31
  export function publicError(error) {
32
32
  if (error instanceof ServiceError) return error.code;
33
+ if (typeof error?.code === 'string' && /^[a-z_]{1,64}$/.test(error.code)) return error.code;
33
34
  return error.name === 'TimeoutError' ? 'timeout' : 'browser_action_failed';
34
35
  }
35
36
 
@@ -67,13 +68,7 @@ function operationView(job) {
67
68
  ...(job.stepKind && { stepKind: job.stepKind }), ...(error && { error }) };
68
69
  }
69
70
 
70
- export function workspaceView(ws, includeCredentialRequest = false) {
71
- const pages = [...ws.pages.values()].map(tab => {
72
- const origin = allowedPageOrigin(ws, tab);
73
- return { workspaceId: ws.id, pageId: tab.id, documentId:tab.documentId, origin: origin || 'null',
74
- ...(tab.openerPageId && {openerPageId:tab.openerPageId,openedByOperationId:tab.openedByOperationId}),
75
- title: origin ? redact(ws, tab.title) : '' };
76
- });
71
+ function workspaceActivity(ws, includeCredentialRequest = false) {
77
72
  const pending = [...ws.jobs];
78
73
  const queued = pending.filter(job => job.receipt.state === 'queued');
79
74
  const running = pending.filter(job => job.receipt.state === 'running');
@@ -83,13 +78,71 @@ export function workspaceView(ws, includeCredentialRequest = false) {
83
78
  const request = ws.credentialRequests.values().next().value;
84
79
  const recent = operationView(ws.recent);
85
80
  let phase = 'idle';
86
- if (current) phase = current.state;
81
+ const needsVisualPermission = recent?.error === 'pixel_permission_required';
82
+ if (ws.securityChallenge) phase = 'needs_human_verification';
83
+ else if (current) phase = current.state;
84
+ else if (needsVisualPermission) phase = 'needs_visual_permission';
87
85
  else if (request) phase = 'needs_credential';
88
86
  else if (recent && recent.error !== 'credential_required') phase = recent.state;
89
- return { workspaceId: ws.id, profileId: serviceProfileId, name: ws.name, agentName: ws.agentName, mode: ws.mode, controlGeneration: ws.generation, pages,
87
+ return { phase, queued: queued.length, needsCredential: !!request, needsVisualPermission,
88
+ needsHumanVerification: !!ws.securityChallenge,
89
+ ...(ws.securityChallenge && { securityChallenge: { ...ws.securityChallenge } }), current, recent,
90
+ running: running.map(job => ({ ...operationView(job), ...(ws.pages.has(job.pageId) && {pageId:job.pageId}) })),
91
+ credentialRequest: request && includeCredentialRequest ? { ...request } : null };
92
+ }
93
+
94
+ function workspaceIdentity(ws) {
95
+ return { workspaceId: ws.id, agentName: ws.agentName, name: ws.name, mode: ws.mode, controlGeneration: ws.generation };
96
+ }
97
+
98
+ export function workspaceView(ws, includeCredentialRequest = false) {
99
+ const pages = [...ws.pages.values()].map(tab => {
100
+ const origin = allowedPageOrigin(ws, tab);
101
+ const synced = !tab.extensionSync || tab.syncedGeneration === ws.generation;
102
+ const readyForAgent = ws.mode === 'agent' && !ws.finishing && !ws.securityChallenge && !ws.guardLost &&
103
+ !!origin && synced && !tab.page.isClosed() && !tab.dialog;
104
+ return { workspaceId: ws.id, pageId: tab.id, readyForAgent, documentId:tab.documentId, origin: origin || 'null',
105
+ ...(tab.openerPageId && {openerPageId:tab.openerPageId,openedByOperationId:tab.openedByOperationId}),
106
+ ownership:ws.singleTab ? 'user' : tab.createdByAgent ? 'agent' : 'user',
107
+ syncState:!tab.extensionSync ? 'not_required' : tab.syncedGeneration === ws.generation ? 'synced' : 'sync_pending',
108
+ syncRevision:tab.syncRevision || 0, lastSyncedAt:tab.lastSyncedAt || null,
109
+ title: origin ? redact(ws, tab.title) : '' };
110
+ });
111
+ const activity = workspaceActivity(ws, includeCredentialRequest);
112
+ const { current } = activity;
113
+ return { ...workspaceIdentity(ws), profileId: serviceProfileId, pages,
114
+ pageAvailability:pages.length ? 'managed' : current?.kind === 'openPage' ? 'sync_pending' : ws.everRegistered ? 'closed' : 'unregistered',
115
+ scope:ws.singleTab ? 'single_tab' : 'workspace',
116
+ nextAction:pages.length ? (ws.mode === 'agent' ? 'reattachPage' : 'wait_for_agent_control') : current?.kind === 'openPage' ? 'wait_for_sync' : 'request_tab_selection',
117
+ ...(ws.accountAlias && {accountAlias:ws.accountAlias}),
90
118
  ...(includeCredentialRequest && {pendingDialogs: [...ws.pages.values()].flatMap(tab=>tab.dialog ? [tab.dialog.info] : [])}),
91
119
  ...(includeCredentialRequest && { blockedOrigins: [...ws.blockedOrigins.values()] }),
92
- activity: { phase, queued: queued.length, needsCredential: !!request, current, recent,
93
- running: running.map(job => ({ ...operationView(job), ...(ws.pages.has(job.pageId) && {pageId:job.pageId}) })),
94
- credentialRequest: request && includeCredentialRequest ? { ...request } : null } };
120
+ ...(ws.mode === 'transferring' && ws.unlockPending && {unlockPending:true}),
121
+ security: { inputGuard: ws.inputGuardMode || 'unavailable' },
122
+ activity };
123
+ }
124
+
125
+ // Both paths send the same fields to the extension. The service supplies page IDs
126
+ // directly from its map, without inspecting URLs, titles or credentials on each tick.
127
+ export function extensionWorkspace({ workspaceId, agentName, name, mode, controlGeneration, activity, pages },
128
+ pageIds = pages.map(({pageId}) => ({pageId}))) {
129
+ return { workspaceId, agentName, name, mode, controlGeneration, pages: pageIds,
130
+ running: activity.running, currentPageId: activity.current?.pageId, stepKind: activity.current?.stepKind,
131
+ dispatchState: activity.current?.dispatchState, phase: activity.phase, needsCredential: activity.needsCredential,
132
+ needsHumanVerification: activity.needsHumanVerification };
133
+ }
134
+
135
+ export function workspaceSyncView(ws) {
136
+ return extensionWorkspace({ ...workspaceIdentity(ws), activity: workspaceActivity(ws) },
137
+ Array.from(ws.pages.keys(), pageId => ({pageId})));
138
+ }
139
+
140
+ // Only the trusted desktop sees all owners, grouped in first-seen order.
141
+ export function desktopWorkspaces(workspaces, view = workspaceView) {
142
+ const groups = new Map();
143
+ for (const ws of workspaces.values()) {
144
+ if (!groups.has(ws.owner)) groups.set(ws.owner, []);
145
+ groups.get(ws.owner).push(view(ws));
146
+ }
147
+ return [...groups.values()].flat();
95
148
  }