@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.
- package/CONTRIBUTING.md +15 -0
- 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
- package/Docs/THIRD-PARTY-NOTICES.md +12 -0
- package/Docs/open-browser-api.d.ts +291 -0
- 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
- 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
- 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
- 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
- package/LICENSE +200 -0
- package/README.md +159 -2
- package/README.zh-CN.md +166 -0
- package/SECURITY.md +9 -0
- package/access-registry.mjs +156 -0
- package/action-execution.mjs +385 -0
- package/activity-notifier.mjs +34 -0
- package/api-contract.mjs +134 -0
- package/browser-extension/icons/open-browser-128.png +0 -0
- package/browser-extension/icons/open-browser-16.png +0 -0
- package/browser-extension/icons/open-browser-32.png +0 -0
- package/browser-extension/icons/open-browser-48.png +0 -0
- package/browser-extension/icons/open-browser-wordmark.png +0 -0
- package/browser-extension/manifest.json +35 -0
- package/browser-extension/newtab.css +26 -0
- package/browser-extension/newtab.html +19 -0
- package/browser-extension/newtab.js +174 -0
- package/browser-extension/phase-labels.js +9 -0
- package/browser-extension/popup.css +19 -0
- package/browser-extension/popup.html +56 -0
- package/browser-extension/popup.js +405 -0
- package/browser-extension/tab-action.js +138 -0
- package/browser-extension/worker.js +281 -0
- package/browser-extension/workspace-title.js +15 -0
- package/build-profile.mjs +23 -0
- package/capability-matrix.mjs +21 -0
- package/chromium-host.mjs +209 -0
- package/chromium-shell.mjs +179 -0
- package/cli.mjs +141 -0
- package/contract-validation.mjs +27 -0
- package/control.mjs +107 -0
- package/desktop/Info.plist +13 -0
- package/desktop/Launcher.m +117 -0
- package/desktop/OBControlBar.h +7 -0
- package/desktop/OBControlBar.m +217 -0
- package/desktop/OBPageView.h +6 -0
- package/desktop/OBPageView.m +348 -0
- package/desktop/WorkspacePanel.h +16 -0
- package/desktop/WorkspacePanel.m +916 -0
- package/desktop/archive-release.py +129 -0
- package/desktop/brand-keychain.py +111 -0
- package/desktop/brand-locales.py +93 -0
- package/desktop/brand-macos-icons.py +24 -0
- package/desktop/brand-windows-icons.mjs +48 -0
- package/desktop/build-macos.mjs +112 -0
- package/desktop/build-managed-input.mjs +37 -0
- package/desktop/build-portable.mjs +95 -0
- package/desktop/build-profile.mjs +6 -0
- package/desktop/build.mjs +13 -0
- package/desktop/create-shortcut.ps1 +9 -0
- package/desktop/generate-icons.py +39 -0
- package/desktop/icons/open-browser.icns +0 -0
- package/desktop/icons/open-browser.ico +0 -0
- package/desktop/install-menu-entry.mjs +24 -0
- package/desktop/macos-entitlements.plist +12 -0
- package/desktop/notarize-macos.mjs +145 -0
- package/desktop/package-assets.mjs +34 -0
- package/desktop/package-macos.mjs +54 -0
- package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
- package/desktop/patches/chromium-managed-input.patch +144 -0
- package/desktop/portable-archive.py +22 -0
- package/desktop/sign.mjs +77 -0
- package/desktop/smoke-portable.mjs +65 -0
- package/desktop/start-profile.mjs +5 -0
- package/desktop/start.mjs +34 -0
- package/desktop/verify-macos-release.mjs +61 -0
- package/desktop/verify-upgrade.mjs +74 -0
- package/desktop/verify-version.mjs +12 -0
- package/desktop-page.mjs +211 -0
- package/diagnostics.mjs +37 -0
- package/downloads.mjs +110 -0
- package/engine-service.mjs +1158 -0
- package/hosted/README.md +74 -0
- package/hosted/cli.mjs +17 -0
- package/hosted/directory.mjs +261 -0
- package/hosted/init.mjs +37 -0
- package/hosted/server.mjs +129 -0
- package/managed-input.mjs +138 -0
- package/managed-popup.mjs +54 -0
- package/mcp-http.mjs +84 -0
- package/mcp-server.mjs +41 -0
- package/mcp.mjs +5 -0
- package/network-policy.mjs +107 -0
- package/output-store.mjs +96 -0
- package/package.json +77 -4
- package/page-activity.mjs +188 -0
- package/page-dialogs.mjs +53 -0
- package/page-observation.mjs +318 -0
- package/paths.mjs +22 -0
- package/privacy-config.mjs +95 -0
- package/receipt-store.mjs +198 -0
- package/runtime.mjs +53 -0
- package/scheduler.mjs +70 -0
- package/sdk.mjs +193 -0
- package/service.mjs +290 -0
- package/site-workflow.mjs +115 -0
- package/skill-links.mjs +90 -0
- package/skills/open-browser/SKILL.macos.md +112 -0
- package/skills/open-browser/SKILL.md +107 -0
- package/skills/open-browser/SKILL.windows.md +112 -0
- package/skills/open-browser/scripts/bootstrap.mjs +213 -0
- package/skills/open-browser/scripts/open-browser +21 -0
- package/skills/open-browser/scripts/open-browser.cmd +9 -0
- package/skills/open-browser/workflows/login-export.json +10 -0
- package/skills/open-browser/workflows/upload-verify.json +8 -0
- package/studio/demo-site.mjs +111 -0
- package/studio/demo.css +1 -0
- package/studio/index.html +66 -0
- package/studio/index.mjs +57 -0
- package/studio/native-demo.mjs +124 -0
- package/studio/studio.css +119 -0
- package/studio/studio.js +438 -0
- package/tab-adoption.mjs +77 -0
- package/uploads.mjs +63 -0
- package/visual-page.mjs +306 -0
- package/workspace-lifecycle.mjs +238 -0
- package/workspace-state.mjs +107 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { checkAgentRequest } from './contract-validation.mjs';
|
|
2
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
3
|
+
import { chmodSync } from 'node:fs';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { readCapabilities } from './capability-matrix.mjs';
|
|
6
|
+
import { workspaceView } from './workspace-state.mjs';
|
|
7
|
+
|
|
8
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
const readMethods = new Set(readCapabilities);
|
|
10
|
+
function fail(code) { throw Object.assign(new Error(code), { code }); }
|
|
11
|
+
|
|
12
|
+
function validateRequest(method, params) {
|
|
13
|
+
// Let the engine classify an empty action batch as invalid_actions. All
|
|
14
|
+
// non-empty requests continue through the strict JSON schema.
|
|
15
|
+
if (method === 'act' && Array.isArray(params?.actions) && !params.actions.length) return params;
|
|
16
|
+
return checkAgentRequest(method, params);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class AccessRegistry {
|
|
20
|
+
constructor(file) {
|
|
21
|
+
this.db = new DatabaseSync(file);
|
|
22
|
+
chmodSync(file, 0o600);
|
|
23
|
+
this.db.exec(`PRAGMA foreign_keys=ON;
|
|
24
|
+
CREATE TABLE IF NOT EXISTS clients(id TEXT PRIMARY KEY,label TEXT NOT NULL,hash TEXT UNIQUE NOT NULL);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS tasks(
|
|
26
|
+
id TEXT PRIMARY KEY, owner TEXT NOT NULL, name TEXT NOT NULL DEFAULT '',
|
|
27
|
+
agentName TEXT NOT NULL DEFAULT '', createdAt INTEGER NOT NULL DEFAULT 0,
|
|
28
|
+
updatedAt INTEGER NOT NULL DEFAULT 0);
|
|
29
|
+
CREATE TABLE IF NOT EXISTS grants(client TEXT REFERENCES clients(id) ON DELETE CASCADE,
|
|
30
|
+
task TEXT REFERENCES tasks(id) ON DELETE CASCADE,permission TEXT NOT NULL,PRIMARY KEY(client,task));`);
|
|
31
|
+
const taskColumns = new Set(this.db.prepare('PRAGMA table_info(tasks)').all().map(field => field.name));
|
|
32
|
+
for (const [name, type, definition] of [
|
|
33
|
+
['name', 'TEXT', "TEXT NOT NULL DEFAULT ''"],
|
|
34
|
+
['agentName', 'TEXT', "TEXT NOT NULL DEFAULT ''"],
|
|
35
|
+
['createdAt', 'INTEGER', 'INTEGER NOT NULL DEFAULT 0'],
|
|
36
|
+
['updatedAt', 'INTEGER', 'INTEGER NOT NULL DEFAULT 0'],
|
|
37
|
+
]) {
|
|
38
|
+
if (!taskColumns.has(name)) this.db.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${definition}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
principal(token) {
|
|
42
|
+
if (!/^[a-f0-9]{64}$/.test(token)) return null;
|
|
43
|
+
return this.db.prepare('SELECT id FROM clients WHERE hash=?').get(digest(token))?.id;
|
|
44
|
+
}
|
|
45
|
+
owner(task) {
|
|
46
|
+
return typeof task === 'string' && this.db.prepare('SELECT owner FROM tasks WHERE id=?').get(task)?.owner;
|
|
47
|
+
}
|
|
48
|
+
hasDelegates(task) {
|
|
49
|
+
return !!this.db.prepare('SELECT 1 FROM grants WHERE task=? LIMIT 1').get(task);
|
|
50
|
+
}
|
|
51
|
+
permission(client, task) {
|
|
52
|
+
if (client === this.owner(task)) return 'owner';
|
|
53
|
+
return typeof task === 'string' && this.db.prepare('SELECT permission FROM grants WHERE client=? AND task=?').get(client,task)?.permission;
|
|
54
|
+
}
|
|
55
|
+
async call(engine, client, method, params) {
|
|
56
|
+
if (['capabilities','listWorkspaces','createWorkspace'].includes(method)) params = validateRequest(method,params);
|
|
57
|
+
if (method === 'capabilities') return engine.call(method,{},client);
|
|
58
|
+
if (method === 'createWorkspace') {
|
|
59
|
+
const info = await engine.call(method, params, client);
|
|
60
|
+
if (client !== 'local' && !this.db.prepare('SELECT id FROM clients WHERE id=?').get(client)) {
|
|
61
|
+
await engine.call('closeWorkspace', {workspaceId:info.workspaceId}, client);
|
|
62
|
+
fail('forbidden');
|
|
63
|
+
}
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
this.db.prepare('INSERT INTO tasks(id,owner,name,agentName,createdAt,updatedAt) VALUES(?,?,?,?,?,?)')
|
|
66
|
+
.run(info.workspaceId, client, info.name || '', info.agentName || '', now, now);
|
|
67
|
+
return info;
|
|
68
|
+
}
|
|
69
|
+
if (method === 'listWorkspaces') {
|
|
70
|
+
const list = await engine.call(method, {}, client);
|
|
71
|
+
const owned = new Set(list.map(workspace => workspace.workspaceId));
|
|
72
|
+
for (const {task} of this.db.prepare('SELECT task FROM grants WHERE client=?').all(client)) {
|
|
73
|
+
const ws = engine.workspaces.get(task);
|
|
74
|
+
if (ws && !owned.has(task)) list.push(workspaceView(ws));
|
|
75
|
+
}
|
|
76
|
+
return list;
|
|
77
|
+
}
|
|
78
|
+
const task = params.workspaceId;
|
|
79
|
+
const permission = this.permission(client,task);
|
|
80
|
+
if (!permission) {
|
|
81
|
+
// Trusted desktop demos may predate a registry entry.
|
|
82
|
+
if (client === 'local' && !this.owner(task)) return engine.call(method,validateRequest(method,params),client);
|
|
83
|
+
fail('workspace_not_found');
|
|
84
|
+
}
|
|
85
|
+
if (method === 'adoptCurrentTab' && (permission !== 'owner' || this.hasDelegates(task))) fail('forbidden');
|
|
86
|
+
if (permission === 'read' && !readMethods.has(method)) fail('forbidden');
|
|
87
|
+
const scopedMethod = permission === 'read' && method === 'observe' ? 'observeReadOnly' : method;
|
|
88
|
+
const result = await engine.call(scopedMethod,validateRequest(method,params),this.owner(task),client);
|
|
89
|
+
if (!this.permission(client,task) || (client !== 'local' &&
|
|
90
|
+
!this.db.prepare('SELECT id FROM clients WHERE id=?').get(client))) fail('forbidden');
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
/** Return local cockpit history without exposing another client's workspaces. */
|
|
94
|
+
async listHistory(engine, client, {limit = 24} = {}) {
|
|
95
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) fail('invalid_params');
|
|
96
|
+
const rows = this.db.prepare(
|
|
97
|
+
'SELECT id AS workspaceId,name,agentName,createdAt,updatedAt FROM tasks WHERE owner=? ORDER BY COALESCE(updatedAt,createdAt) DESC LIMIT ?'
|
|
98
|
+
).all(client, Math.min(100, limit * 2));
|
|
99
|
+
const history = rows.filter(row => !engine.workspaces.has(row.workspaceId));
|
|
100
|
+
return history.slice(0, limit).map(row => {
|
|
101
|
+
const operations = engine.store.list(client, row.workspaceId, 0, 8).operations;
|
|
102
|
+
const latest = operations.at(-1) || null;
|
|
103
|
+
return {
|
|
104
|
+
...row,
|
|
105
|
+
state: latest?.state === 'failed' ? 'failed' : 'completed',
|
|
106
|
+
mode: 'closed',
|
|
107
|
+
operationCount: operations.length,
|
|
108
|
+
recentOperation: latest,
|
|
109
|
+
};
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async admin(engine, method, {name, principalId, workspaceId, permission, origin, allow}) {
|
|
113
|
+
if (method === 'setPixelPermission') {
|
|
114
|
+
const owner=this.owner(workspaceId);
|
|
115
|
+
if(!owner || !this.permission(principalId,workspaceId)) fail('forbidden');
|
|
116
|
+
return engine.call(method,{workspaceId,principalId,origin,allow},owner,'desktop');
|
|
117
|
+
}
|
|
118
|
+
if (method === 'scheduler') return engine.slots.snapshot(engine.pending);
|
|
119
|
+
if (method === 'clearHistory') {
|
|
120
|
+
if (!this.owner(workspaceId) || engine.workspaces.has(workspaceId)) fail('invalid_workspace');
|
|
121
|
+
engine.store.clear(workspaceId);
|
|
122
|
+
this.db.prepare('DELETE FROM tasks WHERE id=?').run(workspaceId);
|
|
123
|
+
return {cleared:true};
|
|
124
|
+
}
|
|
125
|
+
if (method === 'pair') {
|
|
126
|
+
if (typeof name !== 'string' || !name.trim() || name.length > 80) fail('invalid_params');
|
|
127
|
+
const token = randomBytes(32).toString('hex'), id = randomUUID();
|
|
128
|
+
this.db.prepare('INSERT INTO clients VALUES(?,?,?)').run(id,name.trim(),digest(token));
|
|
129
|
+
return {principalId:id, token};
|
|
130
|
+
}
|
|
131
|
+
if (method === 'list') return this.db.prepare('SELECT id AS principalId,label AS name FROM clients ORDER BY label').all();
|
|
132
|
+
if (typeof principalId !== 'string' || !this.db.prepare('SELECT id FROM clients WHERE id=?').get(principalId)) fail('client_not_found');
|
|
133
|
+
let fenced = [];
|
|
134
|
+
if (method === 'revokeClient') {
|
|
135
|
+
fenced = this.db.prepare("SELECT task FROM grants WHERE client=? AND permission='control' UNION SELECT id FROM tasks WHERE owner=?").all(principalId,principalId);
|
|
136
|
+
this.db.prepare('DELETE FROM clients WHERE id=?').run(principalId);
|
|
137
|
+
for (const ws of engine.workspaces.values()) engine.visual.revokeActor(ws,principalId);
|
|
138
|
+
} else {
|
|
139
|
+
const owner = this.owner(workspaceId);
|
|
140
|
+
if (!owner || owner === principalId) fail('invalid_workspace');
|
|
141
|
+
if (method === 'grant' && engine.workspaces.get(workspaceId)?.singleTab) fail('single_tab_scope');
|
|
142
|
+
const prev = this.permission(principalId,workspaceId);
|
|
143
|
+
if (method === 'grant' && ['read','control'].includes(permission))
|
|
144
|
+
this.db.prepare('INSERT OR REPLACE INTO grants VALUES(?,?,?)').run(principalId,workspaceId,permission);
|
|
145
|
+
else if (method === 'revoke') this.db.prepare('DELETE FROM grants WHERE task=? AND client=?').run(workspaceId,principalId);
|
|
146
|
+
else fail('invalid_params');
|
|
147
|
+
if (method === 'revoke' && engine.workspaces.has(workspaceId)) engine.visual.revokeActor(engine.workspaces.get(workspaceId),principalId);
|
|
148
|
+
if (prev === 'control' && (method === 'revoke' || permission !== 'control')) fenced = [{task:workspaceId}];
|
|
149
|
+
}
|
|
150
|
+
await Promise.all(fenced.map(({task}) => {
|
|
151
|
+
const ws = engine.workspaces.get(task);
|
|
152
|
+
if (ws?.mode === 'agent' && !ws.finishing) return engine.handOff(ws,undefined,false);
|
|
153
|
+
}));
|
|
154
|
+
return {updated:true};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { chooseGrantedFile } from './uploads.mjs';
|
|
4
|
+
import { inspectDocument, observationDelta } from './page-observation.mjs';
|
|
5
|
+
import { rememberBlock } from './network-policy.mjs';
|
|
6
|
+
import { ServiceError, fail, redact, requirePageOrigin, webOrigin } from './workspace-state.mjs';
|
|
7
|
+
|
|
8
|
+
async function trackNavigation(tab) {
|
|
9
|
+
if (tab.navigation) return tab.navigation;
|
|
10
|
+
if (!tab.networkSession && !tab.summarySession)
|
|
11
|
+
tab.summarySession = await tab.page.context().newCDPSession(tab.page);
|
|
12
|
+
const session=tab.networkSession ?? tab.summarySession;
|
|
13
|
+
await session.send('Page.enable');
|
|
14
|
+
const navigation={documents:0,routes:0};
|
|
15
|
+
let mainFrame;
|
|
16
|
+
session.on('Page.frameNavigated', ({frame})=>{
|
|
17
|
+
if(!frame.parentId) {mainFrame=frame.id; navigation.documents++;}
|
|
18
|
+
});
|
|
19
|
+
session.on('Page.navigatedWithinDocument', ({frameId})=>{
|
|
20
|
+
if(frameId===mainFrame) navigation.routes++;
|
|
21
|
+
});
|
|
22
|
+
const {frameTree}=await session.send('Page.getFrameTree');
|
|
23
|
+
mainFrame=frameTree.frame.id;
|
|
24
|
+
tab.navigation=navigation;
|
|
25
|
+
return navigation;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function readCheckState(node) {
|
|
29
|
+
const control = node.control ?? node;
|
|
30
|
+
if (control.matches('input[type="checkbox"],input[type="radio"]'))
|
|
31
|
+
return control.type === 'checkbox' && control.indeterminate ? 'mixed' : control.checked;
|
|
32
|
+
const state = control.getAttribute('aria-checked');
|
|
33
|
+
return state === 'true' ? true : state === 'false' ? false : state === 'mixed' ? state : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function fillOutcome(handle, expected, credential) {
|
|
37
|
+
const actual = await handle.inputValue();
|
|
38
|
+
const type = await handle.getAttribute('type');
|
|
39
|
+
if (credential || type === 'password') return actual === expected ? 'exact' : actual ? 'transformed' : 'unchanged';
|
|
40
|
+
if (actual === expected) return 'exact';
|
|
41
|
+
if (actual.trim() === expected.trim()) return 'equivalent';
|
|
42
|
+
if (actual.includes(expected) || expected.includes(actual)) return 'appended';
|
|
43
|
+
return actual ? 'transformed' : 'unchanged';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function agentDispatch(service, tab, work) {
|
|
47
|
+
return service.withAgentInput ? service.withAgentInput(tab, work) : work();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function beforeDispatch(service, ws, tab, op, documentId, generation) {
|
|
51
|
+
if (op.cancel) fail('operation_cancelled');
|
|
52
|
+
ensureBudget(op);
|
|
53
|
+
service.requireControl(ws, generation);
|
|
54
|
+
requirePageOrigin(ws, tab);
|
|
55
|
+
if (tab.documentId !== documentId) fail('stale_document');
|
|
56
|
+
op.receipt.phase = 'dispatching';
|
|
57
|
+
// Persist before entering Playwright. A process crash must never turn an
|
|
58
|
+
// unacknowledged submission into permission to send it a second time.
|
|
59
|
+
service.store.save(ws.owner, ws.id, op.digest, op.receipt, true);
|
|
60
|
+
op.dispatched = true;
|
|
61
|
+
service.notify(ws);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function ensureBudget(op) {
|
|
65
|
+
if (op.deadline !== undefined && Date.now() >= op.deadline) fail('run_timeout');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function armClickProbe(handle, expectedClicks) {
|
|
69
|
+
const id = randomUUID();
|
|
70
|
+
await handle.evaluate((node, { id: probeId, count }) => {
|
|
71
|
+
const key = '__openBrowserClickProbes';
|
|
72
|
+
const probes = node.ownerDocument[key] || (node.ownerDocument[key] = Object.create(null));
|
|
73
|
+
const probe = { seen: 0 };
|
|
74
|
+
probe.handler = event => {
|
|
75
|
+
if (!event.isTrusted || !(event.target === node || node.contains(event.target))) return;
|
|
76
|
+
probe.seen++;
|
|
77
|
+
if (probe.seen >= count) {
|
|
78
|
+
node.ownerDocument.removeEventListener('click', probe.handler, true);
|
|
79
|
+
delete probes[probeId];
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
probes[probeId] = probe;
|
|
83
|
+
node.ownerDocument.addEventListener('click', probe.handler, true);
|
|
84
|
+
setTimeout(() => {
|
|
85
|
+
node.ownerDocument.removeEventListener('click', probe.handler, true);
|
|
86
|
+
delete probes[probeId];
|
|
87
|
+
}, 5000);
|
|
88
|
+
}, { id, count: expectedClicks });
|
|
89
|
+
return id;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function consumeClickProbe(handle, probeId, expectedClicks) {
|
|
93
|
+
try {
|
|
94
|
+
return await handle.evaluate((node, { id, count }) => {
|
|
95
|
+
const probes = node.ownerDocument.__openBrowserClickProbes;
|
|
96
|
+
const probe = probes?.[id];
|
|
97
|
+
if (!probe) return false;
|
|
98
|
+
node.ownerDocument.removeEventListener('click', probe.handler, true);
|
|
99
|
+
delete probes[id];
|
|
100
|
+
return probe.seen >= count;
|
|
101
|
+
}, { id: probeId, count: expectedClicks });
|
|
102
|
+
} catch { return false; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function waitActionable(service, ws, tab, op, el, kind, documentId, generation) {
|
|
106
|
+
if (op.receipt.phase !== 'actionability') {
|
|
107
|
+
op.receipt.phase = 'actionability';
|
|
108
|
+
service.store.save(ws.owner, ws.id, op.digest, op.receipt);
|
|
109
|
+
service.notify(ws);
|
|
110
|
+
}
|
|
111
|
+
const deadline = Math.min(Date.now() + 5000, op.deadline ?? Infinity);
|
|
112
|
+
while (!op.cancel) {
|
|
113
|
+
ensureBudget(op);
|
|
114
|
+
service.requireControl(ws, generation);
|
|
115
|
+
if (tab.documentId !== documentId) fail('stale_document');
|
|
116
|
+
const pointerAction = ['click', 'doubleClick', 'hover', 'drag', 'press', 'scroll'].includes(kind);
|
|
117
|
+
if (pointerAction) {
|
|
118
|
+
// Trial performs Chromium's hit, visibility, enabled and stability checks in
|
|
119
|
+
// one Playwright call. Avoid separate visibility and enabled RPCs for the
|
|
120
|
+
// common pointer path.
|
|
121
|
+
try {
|
|
122
|
+
if (kind === 'hover') await el.hover({ trial: true, timeout: Math.max(1, deadline - Date.now()) });
|
|
123
|
+
else await el.click({ trial: true, timeout: Math.max(1, deadline - Date.now()) });
|
|
124
|
+
return;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error.name !== 'TimeoutError') throw error;
|
|
127
|
+
if (!await el.evaluate(node => node.isConnected).catch(() => false)) fail('stale_ref');
|
|
128
|
+
if (op.cancel) fail('operation_cancelled');
|
|
129
|
+
if (Date.now() >= deadline)
|
|
130
|
+
fail(error.message.includes('intercepts pointer events') ? 'target_obscured' : 'target_not_actionable');
|
|
131
|
+
await delay(40, undefined, {signal:op.controller.signal});
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const visible = await el.isVisible();
|
|
136
|
+
if (!visible && await el.evaluate(node => !node.isConnected)) fail('stale_ref');
|
|
137
|
+
if (visible && !pointerAction && await el.isEditable()) return;
|
|
138
|
+
if (Date.now() >= deadline) fail('timeout');
|
|
139
|
+
await delay(40, undefined, {signal:op.controller.signal});
|
|
140
|
+
}
|
|
141
|
+
fail('operation_cancelled');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function perform(service, ws, tab, { documentId, controlGeneration, actions, observeAfter }, op, { finalize = true } = {}) {
|
|
145
|
+
const before = tab.lastObservation;
|
|
146
|
+
const receipt = op.receipt;
|
|
147
|
+
if (op.cancel) { receipt.state = 'cancelled'; receipt.phase = 'cancelled'; return; }
|
|
148
|
+
receipt.state = 'running';
|
|
149
|
+
const navigationStart = actions.some(a=>a.kind==='wait' && a.navigation)
|
|
150
|
+
? {...await trackNavigation(tab)} : null;
|
|
151
|
+
ws.credentialRequests.delete(tab.id);
|
|
152
|
+
for (const action of actions) {
|
|
153
|
+
ensureBudget(op);
|
|
154
|
+
op.pageId = tab.id;
|
|
155
|
+
op.stepKind = action.kind;
|
|
156
|
+
receipt.stepKind = action.kind;
|
|
157
|
+
service.notify(ws);
|
|
158
|
+
if (op.cancel) { receipt.state = 'cancelled'; receipt.phase = 'cancelled'; return; }
|
|
159
|
+
service.requireControl(ws, controlGeneration);
|
|
160
|
+
const origin = requirePageOrigin(ws, tab);
|
|
161
|
+
// A read-only completion condition may follow a navigation caused by this batch.
|
|
162
|
+
const followNavigation = action.kind === 'wait' && (receipt.completedSteps > 0 || action.navigation);
|
|
163
|
+
if (!followNavigation && tab.documentId !== documentId) fail('stale_document');
|
|
164
|
+
if (action.kind === 'wait') {
|
|
165
|
+
if (receipt.phase !== 'waiting') {
|
|
166
|
+
receipt.phase = 'waiting';
|
|
167
|
+
service.store.save(ws.owner, ws.id, op.digest, receipt);
|
|
168
|
+
service.notify(ws);
|
|
169
|
+
}
|
|
170
|
+
const deadline = Date.now() + (action.timeoutMs ?? 5000);
|
|
171
|
+
for (;;) {
|
|
172
|
+
ensureBudget(op);
|
|
173
|
+
if (op.cancel || op.controller.signal.aborted) { receipt.state = 'cancelled'; receipt.phase = 'cancelled'; return; }
|
|
174
|
+
service.requireControl(ws, controlGeneration);
|
|
175
|
+
requirePageOrigin(ws, tab);
|
|
176
|
+
if (!followNavigation && tab.documentId !== documentId) fail('stale_document');
|
|
177
|
+
let matched;
|
|
178
|
+
try {
|
|
179
|
+
if (action.url) matched = tab.page.url() === action.url;
|
|
180
|
+
else if(action.navigation) {
|
|
181
|
+
receipt.navigation=tab.navigation.documents!==navigationStart.documents ? 'document_committed' :
|
|
182
|
+
tab.navigation.routes!==navigationStart.routes ?
|
|
183
|
+
'same_document' : 'not_committed';
|
|
184
|
+
matched=receipt.navigation!=='not_committed';
|
|
185
|
+
} else if(action.absent || (action.element && Object.keys(action.element).length>2)) {
|
|
186
|
+
const {role,name,...expected}=action.element ?? action.absent;
|
|
187
|
+
const match=await tab.page.evaluate(inspectDocument,{locator:{role,name},summaryOnly:true,origins:[...ws.origins]});
|
|
188
|
+
matched=!!match && (action.absent ? match.match.count===0 : match.match.count===1 &&
|
|
189
|
+
Object.entries(expected).every(([key,value])=>match.details[0][key]===value));
|
|
190
|
+
} else if (action.element) matched = await tab.page.getByRole(action.element.role,
|
|
191
|
+
{name:action.element.name,exact:true}).first().isVisible();
|
|
192
|
+
else matched = redact(ws,await tab.page.evaluate(inspectDocument,true)).includes(action.text);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (!followNavigation || !/context was destroyed|navigation/i.test(error.message)) throw error;
|
|
195
|
+
}
|
|
196
|
+
service.requireControl(ws,controlGeneration);
|
|
197
|
+
requirePageOrigin(ws,tab);
|
|
198
|
+
if (matched) break;
|
|
199
|
+
if (Date.now() >= deadline) fail('wait_timeout');
|
|
200
|
+
const remaining = Math.min(deadline - Date.now(), op.deadline === undefined ? Infinity : op.deadline - Date.now());
|
|
201
|
+
if (remaining <= 0) fail('run_timeout');
|
|
202
|
+
await delay(Math.min(100, remaining), undefined, { signal: op.controller.signal }).catch(() => {});
|
|
203
|
+
}
|
|
204
|
+
receipt.completedSteps++;
|
|
205
|
+
service.notify(ws);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (action.kind === 'spatial') {
|
|
209
|
+
try {
|
|
210
|
+
await agentDispatch(service, tab, () => service.visual.input(ws,tab,service.actors.getStore(),{...action,documentId,controlGeneration},'agent',
|
|
211
|
+
() => beforeDispatch(service, ws,tab,op,documentId,controlGeneration)));
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (!op.dispatched) fail(error.code || 'visual_action_failed');
|
|
214
|
+
tab.needsSubmissionReview=true;
|
|
215
|
+
Object.assign(receipt,{state:'outcome_unknown',phase:'outcome_unknown',error:'inspect_before_retry'});
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
receipt.completedSteps++;
|
|
219
|
+
op.dispatched=false;
|
|
220
|
+
service.store.save(ws.owner,ws.id,op.digest,receipt);
|
|
221
|
+
service.notify(ws);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const frameEntry=tab.frameRefs.get(action.ref);
|
|
225
|
+
const el=frameEntry?.handle ?? tab.refs.get(action.ref);
|
|
226
|
+
if (!el) fail('stale_ref');
|
|
227
|
+
let destination;
|
|
228
|
+
if (action.kind === 'drag') {
|
|
229
|
+
const destinationFrame = tab.frameRefs.get(action.toRef);
|
|
230
|
+
destination = destinationFrame?.handle ?? tab.refs.get(action.toRef);
|
|
231
|
+
if (!destination || destinationFrame || frameEntry) fail('invalid_actions');
|
|
232
|
+
await service.checkSemanticTarget(ws, tab, action.toRef, null, destination, 'click');
|
|
233
|
+
}
|
|
234
|
+
let value = action.value;
|
|
235
|
+
if (action.kind === 'fillCredential') {
|
|
236
|
+
const targetOrigin=frameEntry?.document.origin ?? origin;
|
|
237
|
+
value=ws.credentials.get(targetOrigin+'\n'+action.credentialRef);
|
|
238
|
+
if (value === undefined) {
|
|
239
|
+
Object.assign(receipt, { state: 'failed', phase: 'failed', error: 'credential_required', credentialRef: action.credentialRef });
|
|
240
|
+
ws.credentialRequests.set(tab.id, {
|
|
241
|
+
origin:targetOrigin,...(frameEntry && {frameId:frameEntry.document.frameId}),credentialRef:action.credentialRef,pageId: tab.id, operationId: receipt.operationId, documentId, controlGeneration,
|
|
242
|
+
});
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
service.requireControl(ws, controlGeneration);
|
|
247
|
+
requirePageOrigin(ws, tab);
|
|
248
|
+
if (tab.documentId !== documentId) fail('stale_document');
|
|
249
|
+
if (op.cancel) { receipt.state = 'cancelled'; receipt.phase = 'cancelled'; return; }
|
|
250
|
+
let clickProbe;
|
|
251
|
+
try {
|
|
252
|
+
if (action.kind === 'upload') {
|
|
253
|
+
if (frameEntry) fail('file_origin_mismatch');
|
|
254
|
+
try { ws.uploads.get(ws,tab,action.fileId); } catch(error) { fail(error.code); }
|
|
255
|
+
await waitActionable(service, ws,tab,op,el,'click',documentId,controlGeneration);
|
|
256
|
+
await service.checkSemanticTarget(ws,tab,action.ref,frameEntry,el,'click');
|
|
257
|
+
await chooseGrantedFile(ws,tab,el,action.fileId,
|
|
258
|
+
()=>beforeDispatch(service, ws,tab,op,documentId,controlGeneration),
|
|
259
|
+
work => agentDispatch(service, tab, work),
|
|
260
|
+
()=>{ service.requireControl(ws,controlGeneration); if (op.cancel) fail('operation_cancelled'); });
|
|
261
|
+
} else if (action.kind === 'setChecked') {
|
|
262
|
+
const state = await el.evaluate(readCheckState);
|
|
263
|
+
if (state === null) fail('invalid_actions');
|
|
264
|
+
if (state !== action.checked) {
|
|
265
|
+
if(!action.checked && await el.evaluate(node=>(node.control ?? node).matches('input[type="radio"],[role="radio"]')))
|
|
266
|
+
fail('invalid_actions');
|
|
267
|
+
await waitActionable(service, ws,tab,op,el,'click',documentId,controlGeneration);
|
|
268
|
+
await service.checkSemanticTarget(ws,tab,action.ref,frameEntry,el,action.kind);
|
|
269
|
+
if (await el.evaluate(readCheckState) !== action.checked) {
|
|
270
|
+
beforeDispatch(service, ws,tab,op,documentId,controlGeneration);
|
|
271
|
+
await agentDispatch(service, tab, () => el.click({timeout:5000}));
|
|
272
|
+
if (await el.evaluate(readCheckState) !== action.checked) fail('state_mismatch');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
} else if (action.kind === 'click') {
|
|
276
|
+
const target = service.sharedContext && await el.evaluate(node =>
|
|
277
|
+
node.matches('a[href]') && node.target.toLowerCase() === '_blank' ? node.href : null);
|
|
278
|
+
service.requireControl(ws, controlGeneration);
|
|
279
|
+
requirePageOrigin(ws, tab);
|
|
280
|
+
if (tab.documentId !== documentId) fail('stale_document');
|
|
281
|
+
if (op.cancel) { receipt.state = 'cancelled'; receipt.phase = 'cancelled'; return; }
|
|
282
|
+
if (target && !ws.origins.has(webOrigin(target))) {
|
|
283
|
+
rememberBlock(ws, webOrigin(target), 'navigation', 'document', 'origin_denied');
|
|
284
|
+
fail('origin_denied');
|
|
285
|
+
}
|
|
286
|
+
service.notifyTarget(ws, tab, el, documentId, controlGeneration, origin, action.kind);
|
|
287
|
+
await waitActionable(service, ws, tab, op, el, action.kind, documentId, controlGeneration);
|
|
288
|
+
await service.checkSemanticTarget(ws,tab,action.ref,frameEntry,el,action.kind);
|
|
289
|
+
clickProbe = await armClickProbe(el, 1);
|
|
290
|
+
const lease={token:randomUUID(),op,generation:controlGeneration,origin,documentId,armDeadline:Date.now()+7500};
|
|
291
|
+
if (target && !frameEntry) {
|
|
292
|
+
beforeDispatch(service, ws,tab,op,documentId,controlGeneration);
|
|
293
|
+
await service.openPopup(ws,tab,lease,target);
|
|
294
|
+
} else {
|
|
295
|
+
if (!frameEntry) {
|
|
296
|
+
await tab.page.evaluate(token=>window.__openBrowserArmPopup?.(token),lease.token);
|
|
297
|
+
service.requireControl(ws,controlGeneration);
|
|
298
|
+
if (tab.documentId!==documentId || op.cancel) fail('stale_document');
|
|
299
|
+
tab.popupLease=lease;
|
|
300
|
+
}
|
|
301
|
+
beforeDispatch(service, ws,tab,op,documentId,controlGeneration);
|
|
302
|
+
// Chromium pauses JavaScript inside a modal. A handoff must finish
|
|
303
|
+
// while the user is still deciding how to answer it.
|
|
304
|
+
let interrupt;
|
|
305
|
+
const suspended = new Promise((_,reject) => {
|
|
306
|
+
interrupt = () => { if (tab.dialog) reject(new ServiceError('operation_cancelled')); };
|
|
307
|
+
op.controller.signal.addEventListener('abort',interrupt,{once:true});
|
|
308
|
+
});
|
|
309
|
+
try { await agentDispatch(service, tab, () => Promise.race([el.click({timeout:5000,noWaitAfter:!!navigationStart}), suspended])); }
|
|
310
|
+
finally { op.controller.signal.removeEventListener('abort',interrupt); }
|
|
311
|
+
if (lease.opening) await lease.opening;
|
|
312
|
+
}
|
|
313
|
+
} else if (action.kind === 'doubleClick' || action.kind === 'hover' || action.kind === 'press' || action.kind === 'scroll' || action.kind === 'drag') {
|
|
314
|
+
service.notifyTarget(ws, tab, el, documentId, controlGeneration, origin, action.kind);
|
|
315
|
+
await waitActionable(service, ws, tab, op, el, action.kind, documentId, controlGeneration);
|
|
316
|
+
await service.checkSemanticTarget(ws,tab,action.ref,frameEntry,el,action.kind);
|
|
317
|
+
if (action.kind === 'doubleClick') clickProbe = await armClickProbe(el, 2);
|
|
318
|
+
beforeDispatch(service, ws, tab, op, documentId, controlGeneration);
|
|
319
|
+
if (action.kind === 'doubleClick') {
|
|
320
|
+
await agentDispatch(service, tab, () => el.dblclick({timeout:5000}));
|
|
321
|
+
}
|
|
322
|
+
else if (action.kind === 'hover') await agentDispatch(service, tab, () => el.hover({timeout:5000}));
|
|
323
|
+
else if (action.kind === 'press') await agentDispatch(service, tab, () => el.press(action.key, {timeout:5000}));
|
|
324
|
+
else if (action.kind === 'scroll') {
|
|
325
|
+
await el.scrollIntoViewIfNeeded({timeout:5000});
|
|
326
|
+
await agentDispatch(service, tab, () => tab.page.mouse.wheel(action.deltaX ?? 0, action.deltaY));
|
|
327
|
+
} else await agentDispatch(service, tab, () => el.dragTo(destination, {timeout:5000}));
|
|
328
|
+
} else {
|
|
329
|
+
service.notifyTarget(ws, tab, el, documentId, controlGeneration, origin, action.kind);
|
|
330
|
+
await waitActionable(service, ws, tab, op, el, action.kind, documentId, controlGeneration);
|
|
331
|
+
await service.checkSemanticTarget(ws,tab,action.ref,frameEntry,el,action.kind);
|
|
332
|
+
beforeDispatch(service, ws, tab, op, documentId, controlGeneration);
|
|
333
|
+
if (action.kind === 'select') await agentDispatch(service, tab, () => el.selectOption({ value }, {timeout:5000}));
|
|
334
|
+
else {
|
|
335
|
+
await agentDispatch(service, tab, () => el.fill(value, {timeout:5000}));
|
|
336
|
+
receipt.fillOutcome = await fillOutcome(el, value, action.kind === 'fillCredential');
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (!op.dispatched) throw error;
|
|
341
|
+
if (clickProbe && !tab.dialog && await consumeClickProbe(el, clickProbe, action.kind === 'doubleClick' ? 2 : 1)) {
|
|
342
|
+
receipt.completedSteps++;
|
|
343
|
+
op.dispatched = false;
|
|
344
|
+
service.store.save(ws.owner, ws.id, op.digest, receipt);
|
|
345
|
+
service.notify(ws);
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
// A later observation may replace the latest receipt while the user
|
|
349
|
+
// still needs this tab to determine whether the site received a write.
|
|
350
|
+
tab.needsSubmissionReview = true;
|
|
351
|
+
receipt.state = 'outcome_unknown';
|
|
352
|
+
receipt.phase = 'outcome_unknown';
|
|
353
|
+
receipt.error = 'inspect_before_retry';
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
receipt.completedSteps++;
|
|
357
|
+
service.invalidateObservation?.(tab);
|
|
358
|
+
receipt.phase = 'verifying';
|
|
359
|
+
op.dispatched = false;
|
|
360
|
+
service.store.save(ws.owner, ws.id, op.digest, receipt);
|
|
361
|
+
service.notify(ws);
|
|
362
|
+
}
|
|
363
|
+
if (observeAfter) {
|
|
364
|
+
receipt.phase = 'verifying';
|
|
365
|
+
try {
|
|
366
|
+
service.requireControl(ws, controlGeneration);
|
|
367
|
+
const after = await service.observe(ws, tab);
|
|
368
|
+
const comparable = before?.controlGeneration === controlGeneration && before.documentId === after.documentId;
|
|
369
|
+
const payload = observeAfter === 'delta' && comparable ? {delta:observationDelta(before,after)} : {observation:after};
|
|
370
|
+
tab.actionObservation = { operationId: receipt.operationId, generation: controlGeneration,
|
|
371
|
+
documentId: after.documentId, payload };
|
|
372
|
+
} catch { /* Committed actions keep their receipt when the page changes during the optional read. */ }
|
|
373
|
+
}
|
|
374
|
+
if (finalize) {
|
|
375
|
+
receipt.state = 'completed';
|
|
376
|
+
receipt.phase = 'completed';
|
|
377
|
+
} else {
|
|
378
|
+
// A workflow owns the operation boundary. Keep the receipt running between
|
|
379
|
+
// steps so observers never see a completed intermediate step.
|
|
380
|
+
receipt.state = 'running';
|
|
381
|
+
receipt.phase = 'running';
|
|
382
|
+
service.store.save(ws.owner, ws.id, op.digest, receipt);
|
|
383
|
+
service.notify(ws);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { workspaceView } from './workspace-state.mjs';
|
|
2
|
+
|
|
3
|
+
// Coalesces synchronous phase changes into one ordered activity update. The
|
|
4
|
+
// service keeps all browser state ownership while this adapter owns delivery.
|
|
5
|
+
export class ActivityNotifier {
|
|
6
|
+
constructor(onActivity, hasWorkspace) {
|
|
7
|
+
this.onActivity = onActivity;
|
|
8
|
+
this.hasWorkspace = hasWorkspace;
|
|
9
|
+
this.pending = new Map();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
notify(ws) {
|
|
13
|
+
if (!this.onActivity || !this.hasWorkspace(ws.id)) return;
|
|
14
|
+
const pending = this.pending.get(ws.id) || { snapshot: null, scheduled: false };
|
|
15
|
+
pending.snapshot = workspaceView(ws);
|
|
16
|
+
this.pending.set(ws.id, pending);
|
|
17
|
+
if (pending.scheduled) return;
|
|
18
|
+
pending.scheduled = true;
|
|
19
|
+
void Promise.resolve().then(async () => {
|
|
20
|
+
const current = this.pending.get(ws.id);
|
|
21
|
+
if (!current) return;
|
|
22
|
+
const snapshot = current.snapshot;
|
|
23
|
+
current.scheduled = false;
|
|
24
|
+
if (this.hasWorkspace(ws.id)) await this.onActivity(snapshot);
|
|
25
|
+
if (current.snapshot === snapshot) this.pending.delete(ws.id);
|
|
26
|
+
else if (!current.scheduled) this.notify(ws);
|
|
27
|
+
}).catch(() => {
|
|
28
|
+
const current = this.pending.get(ws.id);
|
|
29
|
+
if (current?.snapshot === pending.snapshot) this.pending.delete(ws.id);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
clear(workspaceId) { this.pending.delete(workspaceId); }
|
|
34
|
+
}
|