-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
514 lines (439 loc) · 14.9 KB
/
content.js
File metadata and controls
514 lines (439 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/**
* RPC Extension Content Script
* Handles automation execution in the page context
*/
// ========== EFFECTS STATE ==========
// Wait for effects to be ready
function waitForEffects(callback, maxWait = 2000) {
const start = Date.now();
function check() {
if (window.rpcEffects) {
callback();
} else if (Date.now() - start < maxWait) {
requestAnimationFrame(check);
}
}
check();
}
// Track scan start time for minimum duration
let scanStartTime = 0;
const MIN_SCAN_DURATION = 3000; // 3 seconds minimum
// Start effects for automation
function startAutomationEffects(method) {
waitForEffects(() => {
// Always show glow during automation
window.rpcEffects.startAgentGlow();
// Show scan effect for DOM snapshot (reading structure)
if (method === 'take_dom_snapshot') {
scanStartTime = Date.now();
window.rpcEffects.startScan();
}
// Show screenshot effect for GUI snapshot (capturing pixels)
else if (method === 'take_gui_snapshot') {
window.rpcEffects.startScreenshot();
}
});
}
// Stop effects after automation completes
function stopAutomationEffects(method) {
waitForEffects(() => {
// Stop scan effect for DOM snapshot (with minimum duration)
if (method === 'take_dom_snapshot') {
const elapsed = Date.now() - scanStartTime;
const remaining = MIN_SCAN_DURATION - elapsed;
if (remaining > 0) {
// Wait for minimum duration before stopping
setTimeout(() => {
window.rpcEffects.stopScan();
}, remaining);
} else {
window.rpcEffects.stopScan();
}
}
// Screenshot effect auto-stops after its animation completes (2.1s)
// No need to manually stop it here
// Note: We don't stop the glow here - it persists until session disconnect
});
}
// ========== EFFECT FORWARDING ==========
// Listen for stop_automation_effects message (sent when session disconnects)
browser.runtime.onMessage.addListener((message, sender) => {
if (message.type !== 'stop_automation_effects') {
return false;
}
waitForEffects(() => {
window.rpcEffects.stopAgentGlow();
window.rpcEffects.stopScan();
});
return false;
});
// Listen for result events from other extensions and forward to background script
// Background script publishes results to RPC service via Centrifugo
window.addEventListener('webfuse-rpc-result', (event) => {
const detail = event.detail;
// Forward to background script which will post via Centrifugo
browser.runtime.sendMessage({
type: 'post_rpc_result',
id: detail.id,
status: detail.status,
result: detail.result,
error: detail.error
});
});
// ========== AUTOMATION HANDLING ==========
/**
* Map old method names to new namespaced API structure
* Old: automation.left_click(target, moveMouse)
* New: automation.act.click(target, { button: 'left', mouseMove })
*/
const METHOD_MAP = {
// Actuation methods -> automation.act.*
'mouse_move': { namespace: 'act', method: 'mouseMove' },
'scroll': { namespace: 'act', method: 'scroll' },
'left_click': { namespace: 'act', method: 'click', button: 'left' },
'middle_click': { namespace: 'act', method: 'click', button: 'middle' },
'right_click': { namespace: 'act', method: 'click', button: 'right' },
'type': { namespace: 'act', method: 'type' },
'key_press': { namespace: 'act', method: 'keyPress' },
// Perception methods -> automation.see.*
'take_dom_snapshot': { namespace: 'see', method: 'domSnapshot' },
'take_gui_snapshot': { namespace: 'see', method: 'guiSnapshot' },
// Utility methods -> automation.*
'wait': { namespace: null, method: 'wait' }
};
// Listen for automation execution requests from background script
browser.runtime.onMessage.addListener((message, sender) => {
if (message.type !== 'execute_automation') {
return false;
}
const { method, params, id, skipResultPost } = message;
// Execute async without returning a Promise
(async () => {
// Start visual effects
startAutomationEffects(method);
try {
// Access the Automation API
const automation = browser.webfuseSession.automation;
if (!automation) {
throw new Error('Automation API not available');
}
// Check if method is mapped and exists
const mapping = METHOD_MAP[method];
if (!mapping) {
throw new Error(`Unknown automation method: ${method}`);
}
// Verify the method exists on the API
if (mapping.namespace) {
const ns = automation[mapping.namespace];
if (!ns || typeof ns[mapping.method] !== 'function') {
throw new Error(`Automation method not found: automation.${mapping.namespace}.${mapping.method}`);
}
} else {
if (typeof automation[mapping.method] !== 'function') {
throw new Error(`Automation method not found: automation.${mapping.method}`);
}
}
// Convert params to arguments for the new API
const args = convertParamsToNewApi(method, params);
// Call the function directly on its namespace to preserve 'this' binding
let result;
if (mapping.namespace) {
const ns = automation[mapping.namespace];
result = await ns[mapping.method](...args);
} else {
result = await automation[mapping.method](...args);
}
// Stop scan effect (glow continues)
stopAutomationEffects(method);
// Serialize the result (async for ImageBitmap conversion)
const serializedResult = await serializeResult(result);
// Post result via background script (unless background is handling it)
if (!skipResultPost) {
browser.runtime.sendMessage({
type: 'post_rpc_result',
id: id,
status: 'success',
result: serializedResult
});
}
} catch (error) {
console.error(`[RPC Extension] ${method} failed:`, error);
// Stop scan effect on error too
stopAutomationEffects(method);
// Post error via background script (always post errors, even if skipResultPost is true)
browser.runtime.sendMessage({
type: 'post_rpc_result',
id: id,
status: 'error',
error: error.message
});
}
})();
// Don't return anything - fire and forget
return false;
});
/**
* Convert parameters to arguments for the new namespaced API
*
* New API signatures:
* - act.click(target, { button, mouseMove })
* - act.type(target, text, { overwrite, timePerChar, mouseMove })
* - act.scroll(target, direction, amount)
* - act.mouseMove(target, persistent)
* - act.keyPress(target, key, options)
* - see.domSnapshot(config)
* - see.guiSnapshot()
* - wait(ms)
*/
function convertParamsToNewApi(methodName, params) {
if (!params) return [];
const mapping = METHOD_MAP[methodName];
switch (methodName) {
case 'mouse_move':
// act.mouseMove(target, persistent)
return [params.target, params.persistent];
case 'scroll':
// act.scroll(target, direction, amount)
return [params.target, params.direction, params.amount];
case 'left_click':
case 'middle_click':
case 'right_click':
// act.click(target, { button, mouseMove })
return [params.target, {
button: mapping.button,
mouseMove: params.moveMouse
}];
case 'type':
// act.type(target, text, { overwrite, timePerChar, mouseMove })
return [
params.target,
params.text,
{
mouseMove: params.moveMouse,
overwrite: params.overwrite,
timePerChar: params.timePerChar
}
];
case 'key_press':
// act.keyPress(target, key, options)
return [params.target, params.key, params.options];
case 'take_dom_snapshot':
// see.domSnapshot(config) - returns raw HTML
const snapshotConfig = params.options || {};
// Map old option names to new ones if needed
const config = {
root: snapshotConfig.rootSelector || snapshotConfig.root,
crossframe: snapshotConfig.crossframe,
crossshadow: snapshotConfig.crossshadow,
revealMaskedElements: snapshotConfig.revealMaskedElements
};
// Clean undefined values
Object.keys(config).forEach(k => config[k] === undefined && delete config[k]);
// Return empty array if no config, otherwise config object
return Object.keys(config).length > 0 ? [config] : [];
case 'take_gui_snapshot':
// see.guiSnapshot() - no parameters
return [];
case 'wait':
// wait(ms)
return [params.ms];
default:
return [params];
}
}
/**
* Serialize result for transmission
*/
async function serializeResult(result) {
if (result === null || result === undefined) {
return result;
}
// Handle ImageBitmap - convert to base64 PNG
if (typeof ImageBitmap !== 'undefined' && result instanceof ImageBitmap) {
try {
// MCP has ~1MB limit, target 800KB base64 to be safe
const MAX_SIZE_KB = 800;
const MAX_ATTEMPTS = 20;
// Start with reasonable initial size (800px max dimension)
let maxDim = 800;
let width = result.width;
let height = result.height;
// Initial resize
if (width > maxDim || height > maxDim) {
const scale = maxDim / Math.max(width, height);
width = Math.floor(width * scale);
height = Math.floor(height * scale);
}
// Create canvas
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(result, 0, 0, width, height);
// Aggressively compress until under size limit
let quality = 0.5; // Start lower
let dataUrl = canvas.toDataURL('image/jpeg', quality);
let sizeKB = dataUrl.length / 1024;
let attempts = 0;
// Main compression loop
while (sizeKB > MAX_SIZE_KB && attempts < MAX_ATTEMPTS) {
attempts++;
// Try reducing quality first (faster)
if (quality > 0.15) {
quality = Math.max(0.15, quality - 0.05);
dataUrl = canvas.toDataURL('image/jpeg', quality);
sizeKB = dataUrl.length / 1024;
if (sizeKB <= MAX_SIZE_KB) break;
}
// If quality is already very low, reduce dimensions instead
if (quality <= 0.2) {
const scale = 0.85;
width = Math.floor(width * scale);
height = Math.floor(height * scale);
// Don't go too small
if (width < 200 || height < 200) break;
canvas.width = width;
canvas.height = height;
ctx.drawImage(result, 0, 0, width, height);
dataUrl = canvas.toDataURL('image/jpeg', quality);
sizeKB = dataUrl.length / 1024;
}
}
if (sizeKB > MAX_SIZE_KB) {
console.warn(`[RPC Extension] Image compression: ${Math.round(sizeKB)}KB exceeds ${MAX_SIZE_KB}KB limit`);
}
return {
type: 'image',
data: dataUrl,
width: width,
height: height,
mimeType: 'image/jpeg'
};
} catch (error) {
console.error('[RPC Extension] Failed to convert ImageBitmap:', error);
return {
type: 'ImageBitmap',
width: result.width,
height: result.height,
error: error.message
};
}
}
if (result instanceof Element) {
return {
type: 'Element',
tagName: result.tagName,
id: result.id,
className: result.className
};
}
if (Array.isArray(result)) {
return await Promise.all(result.map(item => serializeResult(item)));
}
if (typeof result === 'object') {
const serialized = {};
for (const [key, value] of Object.entries(result)) {
try {
serialized[key] = await serializeResult(value);
} catch (error) {
serialized[key] = `[Error: ${error.message}]`;
}
}
return serialized;
}
if (typeof result === 'function') {
return '[Function]';
}
return result;
}
// ========== GLOBAL RPC API FOR CUSTOM EXTENSIONS ==========
//
// Custom extensions can use window.webfuse.rpc to register functions that are
// callable via RPC. This is the primary API for creating custom RPC-enabled extensions.
//
// Example usage:
//
// window.webfuse.rpc.register('rotate_page', async (params) => {
// const { degrees = 360, duration = 3000 } = params;
// // ... animation code ...
// return { success: true, degrees, duration };
// });
// Track registered handlers for custom functions
const registeredHandlers = new Map();
// Use webfuse.rpc namespace, preserving any existing webfuse global
window.webfuse = window.webfuse || {};
window.webfuse.rpc = window.webfuse.rpc || {};
Object.assign(window.webfuse.rpc, {
/**
* Register a custom RPC function
* @param {string} name - Function name (e.g., 'rotate_page')
* @param {Function} handler - Async function(params) => result
*/
register: (name, handler) => {
registeredHandlers.set(name, handler);
console.log(`[RPC Extension] Registered custom function: ${name}`);
},
/**
* Unregister a custom RPC function
* @param {string} name - Function name to unregister
*/
unregister: (name) => {
registeredHandlers.delete(name);
console.log(`[RPC Extension] Unregistered custom function: ${name}`);
},
/**
* Post a successful result back to RPC service (via background script)
* For advanced use - register() handles this automatically
* @param {string} id - The RPC request ID
* @param {any} result - The result data
*/
postResult: (id, result) => {
browser.runtime.sendMessage({
type: 'post_rpc_result',
id: id,
status: 'success',
result: result
});
},
/**
* Post an error back to RPC service (via background script)
* For advanced use - register() handles this automatically
* @param {string} id - The RPC request ID
* @param {string} error - The error message
*/
postError: (id, error) => {
browser.runtime.sendMessage({
type: 'post_rpc_result',
id: id,
status: 'error',
error: error
});
}
});
// Listen for RPC execution requests from background script for custom functions
browser.runtime.onMessage.addListener((message, sender) => {
if (message.type !== 'execute_effect') {
return false;
}
const { method, params, id } = message;
// Check if we have a registered handler for this method
const handler = registeredHandlers.get(method);
if (!handler) {
// No handler registered - dispatch DOM event for legacy compatibility
window.dispatchEvent(new CustomEvent('webfuse-rpc-execute', {
detail: { method, params, id }
}));
return false;
}
// Execute the registered handler
(async () => {
try {
const result = await handler(params || {});
window.webfuse.rpc.postResult(id, result);
} catch (error) {
console.error(`[RPC Extension] ${method} failed:`, error);
window.webfuse.rpc.postError(id, error.message || String(error));
}
})();
return false;
});