thuthi-plugin 0.0.0-stage → 0.1.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/.claude-plugin/marketplace.json +55 -0
- package/README.md +13 -2
- package/bin/parallel-browser.js +109 -0
- package/extension/background.js +1329 -0
- package/extension/config.json +1 -0
- package/extension/guard.js +44 -0
- package/extension/manifest.json +10 -0
- package/extension/overlay.js +104 -0
- package/extension/popup.html +34 -0
- package/extension/popup.js +39 -0
- package/extension-reloader/manifest.json +13 -0
- package/extension-reloader/sw.js +17 -0
- package/package.json +13 -4
- package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
- package/plugins/thuthi/context.md +3 -0
- package/plugins/thuthi/hooks/hooks.json +15 -0
- package/plugins/thuthi/skills/setup/SKILL.md +55 -0
- package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
- package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
- package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
- package/plugins/thuthi/tools/legacy_launcher.py +65 -0
- package/plugins/thuthi/tools/statusline/statusline.py +8 -0
- package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-accounts/bin/claude-switch +5 -0
- package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
- package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
- package/plugins/thuthi-accounts/lib/tls.py +68 -0
- package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
- package/plugins/thuthi-accounts/setup_check.py +21 -0
- package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
- package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
- package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
- package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
- package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
- package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-agenda-picker/context.md +3 -0
- package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
- package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
- package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
- package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
- package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
- package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
- package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-browser/context.md +3 -0
- package/plugins/thuthi-browser/hooks/hooks.json +15 -0
- package/plugins/thuthi-browser/lib/pbpage.py +397 -0
- package/plugins/thuthi-browser/setup_check.py +93 -0
- package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
- package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
- package/plugins/thuthi-demo-video/setup_check.py +14 -0
- package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
- package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
- package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-orca/context.md +5 -0
- package/plugins/thuthi-orca/hooks/hooks.json +18 -0
- package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
- package/plugins/thuthi-orca/setup_check.py +12 -0
- package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
- package/runtime/client.js +69 -0
- package/runtime/daemon.js +503 -0
- package/runtime/focus-monitor.js +53 -0
- package/runtime/keys.js +86 -0
- package/runtime/owner.js +64 -0
- package/runtime/recorder.js +267 -0
- package/runtime/relay.js +95 -0
- package/runtime/session.js +1599 -0
|
@@ -0,0 +1,1329 @@
|
|
|
1
|
+
// parallel-browser bridge: MV3 service worker.
|
|
2
|
+
//
|
|
3
|
+
// Model
|
|
4
|
+
// - ONE dedicated agent window (never focused). Every agent session is a colored tab group
|
|
5
|
+
// inside it. The user's own windows are never touched.
|
|
6
|
+
// - chrome.debugger is attached only to tabs a session owns; CDP is relayed both ways.
|
|
7
|
+
// - Guard rails (guard.js), per-session tab budget, popup rerouting.
|
|
8
|
+
// - Never steal focus: no windows.update({focused:true}) on the agent window, no
|
|
9
|
+
// tabs.update({active:true}) on anyone's tab, no Target.activateTarget. (keepBlankInFront only
|
|
10
|
+
// swaps the unfocused agent window's own blank tab to the front, for recording.) Page popups are rerouted to
|
|
11
|
+
// inactive tabs because a foreground popup activates the app on macOS.
|
|
12
|
+
// - User takeover: focusing the agent window / clicking an agent tab pauses that session.
|
|
13
|
+
// - Crash ledger in chrome.storage.local so sessions can be reconciled after a browser death.
|
|
14
|
+
// - Kill switch: the toolbar icon (no keyboard shortcut, on purpose).
|
|
15
|
+
//
|
|
16
|
+
// Optional placements kept for experiments: 'window' (one window per session) and
|
|
17
|
+
// 'group' (tab group inside the user's last-focused window). Default is 'shared'.
|
|
18
|
+
|
|
19
|
+
import { checkCommand, isUrlBlocked } from './guard.js';
|
|
20
|
+
import { overlayInject, GROUP_COLOR_CSS } from './overlay.js';
|
|
21
|
+
|
|
22
|
+
// Relay port comes from config.json so a test copy of the extension (spikes) can use a different
|
|
23
|
+
// port than the copy installed in the user's real browser.
|
|
24
|
+
let RELAY_URL = 'ws://127.0.0.1:9333/ext';
|
|
25
|
+
// `testHooks` is set only in the throwaway copy the spikes load. It re-opens the cross-session
|
|
26
|
+
// listing and cleanup the production build deliberately does not have, so tests can tidy up
|
|
27
|
+
// after themselves without giving agents a way to see or close each other's work.
|
|
28
|
+
let TEST_HOOKS = false;
|
|
29
|
+
const config = fetch(chrome.runtime.getURL('config.json')).then((r) => r.json()).catch(() => ({}))
|
|
30
|
+
.then((c) => { if (c.relayPort) RELAY_URL = `ws://127.0.0.1:${c.relayPort}/ext`; TEST_HOOKS = !!c.testHooks; return c; });
|
|
31
|
+
const DEFAULT_TAB_BUDGET = 3;
|
|
32
|
+
// Name of the event the popup guard listens for to learn that the next gesture is the agent's.
|
|
33
|
+
// Random and kept in storage, so pages cannot guess it and a restarted worker keeps talking to
|
|
34
|
+
// guards that are already installed in open pages.
|
|
35
|
+
const popupToken = chrome.storage.local.get('popupToken').then(async ({ popupToken: t }) => {
|
|
36
|
+
if (typeof t === 'string' && /^pb[0-9a-f]{24}$/.test(t)) return t;
|
|
37
|
+
const fresh = 'pb' + [...crypto.getRandomValues(new Uint8Array(12))].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
38
|
+
await chrome.storage.local.set({ popupToken: fresh });
|
|
39
|
+
return fresh;
|
|
40
|
+
});
|
|
41
|
+
const COLORS = ['blue', 'red', 'green', 'purple', 'orange', 'cyan', 'pink', 'yellow'];
|
|
42
|
+
const AGENT_WINDOW_BOUNDS = { left: 80, top: 80, width: 1200, height: 800 };
|
|
43
|
+
// Changes whenever the MV3 service worker is torn down and restarted; in-flight
|
|
44
|
+
// chrome.debugger.sendCommand promises do not survive that.
|
|
45
|
+
const WORKER_STARTED_AT = Date.now();
|
|
46
|
+
|
|
47
|
+
/** @type {WebSocket|null} */
|
|
48
|
+
let ws = null;
|
|
49
|
+
let reconnectTimer = null;
|
|
50
|
+
const sessions = new Map(); // sessionId -> session
|
|
51
|
+
// Sessions are addressed by an opaque id, never by their display name. Two agents asking for
|
|
52
|
+
// "research" must get two different sessions; the id is the only handle that resumes one.
|
|
53
|
+
const newSessionId = () => 'pb-' + crypto.randomUUID().replace(/-/g, '').slice(0, 8);
|
|
54
|
+
// The id is a display handle and is listed to everyone; the key is the capability. Only the
|
|
55
|
+
// process that created the session is ever told the key, so knowing an id buys nothing.
|
|
56
|
+
const newSessionKey = () => crypto.randomUUID().replace(/-/g, '');
|
|
57
|
+
let agentWindowId = null; // the one dedicated window
|
|
58
|
+
let lostSessions = []; // ledger entries found at browser startup whose tabs no longer exist
|
|
59
|
+
let recentlyRemovedAt = 0; // closing an agent tab makes Chrome activate a neighbour; not a takeover
|
|
60
|
+
// Tab groups this extension made. Only these are ever cleaned up as strays: another copy of
|
|
61
|
+
// parallel-browser in the same browser (aidu-test's) titles its groups the same way, and closing
|
|
62
|
+
// "every ● group we do not know" closed its sessions each time this worker restarted (2026-11-16,
|
|
63
|
+
// 15:07:48.541 worker start → its two tabs closed 9 ms later).
|
|
64
|
+
const ownGroups = new Set();
|
|
65
|
+
// Which files this worker was loaded from: a hash the daemon gave when it last asked for a reload
|
|
66
|
+
// (kept in storage). The daemon compares it with the files on disk and asks again when they differ.
|
|
67
|
+
let codeHash = null;
|
|
68
|
+
// The reloader extension (extension-reloader/, fixed id from its manifest key). Optional: with it the
|
|
69
|
+
// browser reloads this extension from disk on request, in Edge and Chrome alike.
|
|
70
|
+
const RELOADER_ID = 'cfmfggjjblemoomieaomfbngbhbdocch';
|
|
71
|
+
|
|
72
|
+
// ---------- persistence ----------
|
|
73
|
+
|
|
74
|
+
// State lives in storage.local, not storage.session: session storage is wiped when the
|
|
75
|
+
// extension reloads, which used to strand the agent window and its tabs with nobody owning them.
|
|
76
|
+
async function saveState() {
|
|
77
|
+
// persistSession, not serializeSession: the stored copy has to carry the key, or an extension
|
|
78
|
+
// reload would leave every session alive but ownerless — no handle would match it again.
|
|
79
|
+
await chrome.storage.local.set({
|
|
80
|
+
state: { sessions: [...sessions.values()].map(persistSession), agentWindowId, groups: [...ownGroups] },
|
|
81
|
+
ledger: [...sessions.values()].map(ledgerEntry),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function serializeSession(s) {
|
|
86
|
+
return {
|
|
87
|
+
id: s.id, name: s.name, color: s.color, placement: s.placement, windowId: s.windowId, groupId: s.groupId,
|
|
88
|
+
tabIds: [...s.tabIds], budget: s.budget, status: s.status, paused: s.paused, pausedBy: s.pausedBy || null,
|
|
89
|
+
urls: s.urls,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** For chrome.storage only. Never send this to a client: it carries the key. */
|
|
94
|
+
function persistSession(s) {
|
|
95
|
+
// The emulated screen sizes go along, so a reload puts them back (otherwise a recording in
|
|
96
|
+
// progress drops to the tab area: 2026-11-16, Edge 157, 1792×848 came back as 1192×716).
|
|
97
|
+
return { ...serializeSession(s), key: s.key, emulation: s.emulation ? Object.fromEntries(s.emulation) : undefined };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function ledgerEntry(s) {
|
|
101
|
+
return { id: s.id, name: s.name, color: s.color, urls: s.urls, status: s.status, savedAt: Date.now() };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function restoreState() {
|
|
105
|
+
const { state } = await chrome.storage.local.get('state');
|
|
106
|
+
const st = state || {};
|
|
107
|
+
if (st.agentWindowId) agentWindowId = st.agentWindowId;
|
|
108
|
+
for (const g of st.groups || []) ownGroups.add(g);
|
|
109
|
+
for (const p of st.sessions || []) {
|
|
110
|
+
const emulation = p.emulation ? new Map(Object.entries(p.emulation).map(([t, v]) => [Number(t), v])) : undefined;
|
|
111
|
+
sessions.set(p.id, { ...p, tabIds: new Set(p.tabIds), frameTargets: new Map(), emulation });
|
|
112
|
+
}
|
|
113
|
+
({ codeHash = null } = await chrome.storage.local.get('codeHash'));
|
|
114
|
+
await reconcile();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Bring restored state back in line with the browser. Tabs and windows keep their ids across an
|
|
119
|
+
* extension reload but every debugger attachment is dropped, so surviving tabs are re-attached
|
|
120
|
+
* and anything that no longer exists is forgotten. Tab groups left behind by an earlier instance
|
|
121
|
+
* of this extension are cleaned up, so a reload cannot leave a second agent window on screen with
|
|
122
|
+
* nobody owning it. "Ours" means a group id this extension recorded when it made it, or a group
|
|
123
|
+
* titled like ours inside our own agent window — never a look-alike elsewhere, which may belong to
|
|
124
|
+
* another copy of parallel-browser loaded in the same browser.
|
|
125
|
+
*/
|
|
126
|
+
async function reconcile() {
|
|
127
|
+
if (agentWindowId && !(await chrome.windows.get(agentWindowId).catch(() => null))) agentWindowId = null;
|
|
128
|
+
|
|
129
|
+
for (const s of [...sessions.values()]) {
|
|
130
|
+
const alive = [];
|
|
131
|
+
for (const tabId of s.tabIds) if (await chrome.tabs.get(tabId).catch(() => null)) alive.push(tabId);
|
|
132
|
+
s.tabIds = new Set(alive);
|
|
133
|
+
// Nothing of this session survived: the browser was restarted (tab ids do not survive that).
|
|
134
|
+
// Report it rather than silently forgetting what was running.
|
|
135
|
+
if (!alive.length) { lostSessions.push(ledgerEntry(s)); sessions.delete(s.id); continue; }
|
|
136
|
+
for (const tabId of alive) {
|
|
137
|
+
// Bounded: a tab the browser has frozen can keep the attach from settling, and everything
|
|
138
|
+
// waits on this (no hello, no reply) — 2026-11-16 the bridge went silent for ten minutes
|
|
139
|
+
// after a reload.
|
|
140
|
+
try { await withTimeout(attach(s, tabId), 5000); await reapplyEmulation(s, tabId); }
|
|
141
|
+
catch (e) { emit('reconcile.attachFailed', { sessionId: s.id, tabId, error: String(e?.message || e) }); }
|
|
142
|
+
paintOverlay(s, tabId);
|
|
143
|
+
}
|
|
144
|
+
try { await chrome.tabGroups.update(s.groupId, { title: groupTitle(s), color: s.color }); } catch { /* group gone */ }
|
|
145
|
+
if (!agentWindowId && s.placement === 'shared') agentWindowId = s.windowId;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const known = new Set([...sessions.values()].map((s) => s.groupId));
|
|
149
|
+
const groups = await chrome.tabGroups.query({}).catch(() => []);
|
|
150
|
+
let strays = 0;
|
|
151
|
+
for (const g of groups) {
|
|
152
|
+
const ours = ownGroups.has(g.id) || (agentWindowId && g.windowId === agentWindowId && /^[●⏸] /.test(g.title || ''));
|
|
153
|
+
if (known.has(g.id) || !ours) continue;
|
|
154
|
+
const tabs = await chrome.tabs.query({ groupId: g.id }).catch(() => []);
|
|
155
|
+
if (!tabs.length) continue;
|
|
156
|
+
try { await chrome.tabs.remove(tabs.map((t) => t.id)); strays += tabs.length; } catch { /* already gone */ }
|
|
157
|
+
}
|
|
158
|
+
// Forget groups that no longer exist, so the list does not grow forever.
|
|
159
|
+
const alive = new Set(groups.map((g) => g.id));
|
|
160
|
+
for (const g of [...ownGroups]) if (!alive.has(g) || !known.has(g)) ownGroups.delete(g);
|
|
161
|
+
for (const g of known) ownGroups.add(g);
|
|
162
|
+
if (strays) emit('reconcile.cleaned', { strayTabs: strays });
|
|
163
|
+
await chrome.storage.local.set({ state: { sessions: [...sessions.values()].map(persistSession), agentWindowId, groups: [...ownGroups] } });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function withTimeout(promise, ms) {
|
|
167
|
+
let timer;
|
|
168
|
+
return Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms); })])
|
|
169
|
+
.finally(() => clearTimeout(timer));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Load this extension's files from disk again: the daemon asks when they differ from what this
|
|
174
|
+
* worker was loaded from. A service-worker restart is not enough (the browser keeps the old code).
|
|
175
|
+
* The reloader extension does it in any browser; without it only Edge reloads itself safely —
|
|
176
|
+
* Chrome left the extension gone after chrome.runtime.reload(), so there it is left to the user.
|
|
177
|
+
* The reply goes out before the reload.
|
|
178
|
+
*/
|
|
179
|
+
async function updateFromDisk(hash) {
|
|
180
|
+
if (TEST_HOOKS) return { reloading: false, reason: 'test copy: reloading would unload it' };
|
|
181
|
+
const pong = await withTimeout(chrome.runtime.sendMessage(RELOADER_ID, { type: 'ping' }), 2000).catch(() => null);
|
|
182
|
+
const via = pong?.ok ? 'reloader' : /\bEdg\//.test(navigator.userAgent) ? 'self' : null;
|
|
183
|
+
if (!via) return { reloading: false, reason: 'chrome without the reloader extension: reload parallel-browser on chrome://extensions, or load extension-reloader/ once' };
|
|
184
|
+
await chrome.storage.local.set({ codeHash: hash });
|
|
185
|
+
await saveState();
|
|
186
|
+
setTimeout(() => {
|
|
187
|
+
if (via === 'reloader') chrome.runtime.sendMessage(RELOADER_ID, { type: 'reload-me' }).catch(() => {});
|
|
188
|
+
else chrome.runtime.reload();
|
|
189
|
+
}, 200);
|
|
190
|
+
return { reloading: true, via };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// No onStartup handling is needed: reconcile() runs on every service-worker start and tells the
|
|
194
|
+
// two cases apart by whether the tabs still exist. An extension reload keeps tab ids, so
|
|
195
|
+
// sessions are re-attached; a browser restart does not, so they are reported as lost.
|
|
196
|
+
|
|
197
|
+
// ---------- relay ----------
|
|
198
|
+
|
|
199
|
+
function connect() {
|
|
200
|
+
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return;
|
|
201
|
+
try { ws = new WebSocket(RELAY_URL); } catch { scheduleReconnect(); return; }
|
|
202
|
+
ws.onopen = async () => {
|
|
203
|
+
await ready;
|
|
204
|
+
send({ type: 'hello', userAgent: navigator.userAgent, agentWindowId, workerStartedAt: WORKER_STARTED_AT, sessionCount: sessions.size, lost: lostSessions, codeHash });
|
|
205
|
+
for (const e of heldEvents.splice(0)) send(e);
|
|
206
|
+
lostSessions = [];
|
|
207
|
+
};
|
|
208
|
+
ws.onmessage = (ev) => handleMessage(ev.data);
|
|
209
|
+
ws.onclose = () => { ws = null; scheduleReconnect(); };
|
|
210
|
+
ws.onerror = () => { /* onclose follows */ };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function scheduleReconnect() {
|
|
214
|
+
if (reconnectTimer) return;
|
|
215
|
+
reconnectTimer = setTimeout(() => { reconnectTimer = null; connect(); }, 1000);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function send(obj) { if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(obj)); }
|
|
219
|
+
// Events from before the relay is connected — reconcile() at worker start runs first — are held and
|
|
220
|
+
// sent after hello, so the daemon's event log sees what the worker found (strays, failed re-attach).
|
|
221
|
+
// Page traffic is not worth holding.
|
|
222
|
+
const heldEvents = [];
|
|
223
|
+
function emit(event, params) {
|
|
224
|
+
if (ws && ws.readyState === WebSocket.OPEN) return send({ type: 'event', event, params });
|
|
225
|
+
if (event === 'cdp.event' || event === 'debug.cdp' || heldEvents.length >= 50) return;
|
|
226
|
+
heldEvents.push({ type: 'event', event, params });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function handleMessage(raw) {
|
|
230
|
+
let msg;
|
|
231
|
+
try { msg = JSON.parse(raw); } catch { return; }
|
|
232
|
+
if (msg.id === undefined) return;
|
|
233
|
+
try {
|
|
234
|
+
const result = await dispatch(msg.method, msg.params || {});
|
|
235
|
+
send({ id: msg.id, result: result ?? {} });
|
|
236
|
+
} catch (err) {
|
|
237
|
+
send({ id: msg.id, error: String(err?.message || err) });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ---------- lookups ----------
|
|
242
|
+
|
|
243
|
+
function sessionOf(sessionId) {
|
|
244
|
+
const s = sessions.get(sessionId);
|
|
245
|
+
if (!s) throw new Error(`unknown session ${sessionId}`);
|
|
246
|
+
return s;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Every session-scoped request has to prove it comes from the agent that created the session.
|
|
251
|
+
* Several agents share one browser and one daemon, and they can all see each other's ids in
|
|
252
|
+
* session.list, so the id alone must not be a handle. There is no takeover path: an agent that
|
|
253
|
+
* did not create a session can never drive it, whatever it knows.
|
|
254
|
+
*/
|
|
255
|
+
function requireOwner(sessionId, key) {
|
|
256
|
+
const s = sessionOf(sessionId);
|
|
257
|
+
if (!key || key !== s.key) {
|
|
258
|
+
throw new Error(`not your session: ${sessionId} belongs to another agent. An id alone grants nothing — you need the full handle printed when the session was created.`);
|
|
259
|
+
}
|
|
260
|
+
return s;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** session that OWNS the window (placement 'window' only) */
|
|
264
|
+
function sessionByWindow(windowId) {
|
|
265
|
+
for (const s of sessions.values()) if (s.windowId === windowId && s.placement === 'window') return s;
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function sessionByTab(tabId) {
|
|
270
|
+
for (const s of sessions.values()) if (s.tabIds.has(tabId)) return s;
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function sessionByTarget(targetId) {
|
|
275
|
+
for (const s of sessions.values()) if (s.frameTargets?.has(targetId)) return s;
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function isAgentWindow(windowId) {
|
|
280
|
+
return windowId === agentWindowId || !!sessionByWindow(windowId);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// The agent window's front tab is a plain blank tab, never a session's. Edge records the front tab
|
|
284
|
+
// at the window's real size, so a viewport bigger than the window comes out cropped to its top-left;
|
|
285
|
+
// a background tab records whole (2026-11-04, Edge 155: 1440×900 emulated in a 1086×674 tab area;
|
|
286
|
+
// 2026-11-16, Edge 157: a demo-video recording dropped from 1792×848 to the 1086×674 tab area a
|
|
287
|
+
// second in). A session tab gets to the front when someone clicks it, or when the front tab closes
|
|
288
|
+
// and Edge fronts its neighbour (another agent closing its session is enough). So whenever session
|
|
289
|
+
// tabs open or close, and when the user leaves the window, the blank tab is put back in front
|
|
290
|
+
// (made again if it was closed). This is the one tabs.update({active:true}) in the extension: it
|
|
291
|
+
// switches tabs inside the unfocused agent window only, never focuses or raises it, and leaves the
|
|
292
|
+
// window alone while the user is in it (they chose what to look at).
|
|
293
|
+
async function keepBlankInFront(windowId, closing = new Set()) {
|
|
294
|
+
if (!windowId || windowId !== agentWindowId) return;
|
|
295
|
+
const win = await chrome.windows.get(windowId, { populate: true }).catch(() => null);
|
|
296
|
+
if (!win || win.focused) return;
|
|
297
|
+
const active = win.tabs.find((t) => t.active);
|
|
298
|
+
if (active && !sessionByTab(active.id) && !closing.has(active.id)) return;
|
|
299
|
+
const blank = win.tabs.find((t) => !sessionByTab(t.id) && !closing.has(t.id) && t.groupId === -1);
|
|
300
|
+
if (blank) await chrome.tabs.update(blank.id, { active: true }).catch(() => {});
|
|
301
|
+
else await chrome.tabs.create({ windowId, url: 'about:blank', active: true, index: 0 }).catch(() => {});
|
|
302
|
+
const was = active && !closing.has(active.id) && sessionByTab(active.id);
|
|
303
|
+
if (was) await reapplyEmulation(was, active.id); // it recorded at the tab area while in front
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ---------- dispatch ----------
|
|
307
|
+
|
|
308
|
+
async function dispatch(method, p) {
|
|
309
|
+
await ready;
|
|
310
|
+
if (p && p.sessionId !== undefined) requireOwner(p.sessionId, p.key);
|
|
311
|
+
// A tab the browser replaced (see onReplaced) is still reachable by the id the caller holds.
|
|
312
|
+
if (p && p.sessionId !== undefined && p.tabId !== undefined) {
|
|
313
|
+
const now = sessions.get(p.sessionId)?.aliases?.get(p.tabId);
|
|
314
|
+
if (now !== undefined) p.tabId = now;
|
|
315
|
+
}
|
|
316
|
+
switch (method) {
|
|
317
|
+
case 'session.create': return createSession(p);
|
|
318
|
+
case 'session.close': return closeSession(p.sessionId, 'closed_by_runtime');
|
|
319
|
+
// There is no cross-session listing over the relay. An agent sees its own sessions, which it
|
|
320
|
+
// already holds handles for, and nothing else — not even that another session exists. The
|
|
321
|
+
// user's view is the extension dashboard, which reads this state directly rather than
|
|
322
|
+
// through the relay, so it is unaffected.
|
|
323
|
+
case 'debug.list': {
|
|
324
|
+
if (!TEST_HOOKS) throw new Error('session listing is not available: every agent sees only the sessions it created');
|
|
325
|
+
const list = [];
|
|
326
|
+
for (const s of sessions.values()) {
|
|
327
|
+
const ser = serializeSession(s);
|
|
328
|
+
ser.tabs = [];
|
|
329
|
+
for (const tabId of s.tabIds) {
|
|
330
|
+
const t = await chrome.tabs.get(tabId).catch(() => null);
|
|
331
|
+
if (t) ser.tabs.push({ tabId, url: t.url, title: t.title, active: t.active, status: t.status });
|
|
332
|
+
}
|
|
333
|
+
list.push(ser);
|
|
334
|
+
}
|
|
335
|
+
return { sessions: list, agentWindowId };
|
|
336
|
+
}
|
|
337
|
+
case 'session.status': return setStatus(sessionOf(p.sessionId), p.text, p.paused);
|
|
338
|
+
case 'session.resume': { const s = sessionOf(p.sessionId); s.paused = false; s.pausedBy = null; await setStatus(s, s.status, false); return {}; }
|
|
339
|
+
// The agent asking the user to step in (a login, a captcha, a confirmation it must not make
|
|
340
|
+
// on its own). Same paused state, but it was handed over rather than taken, and the overlay
|
|
341
|
+
// says so — otherwise the user sees "누가 뺏었지?" for something the agent chose to do.
|
|
342
|
+
case 'session.handOff': {
|
|
343
|
+
const s = sessionOf(p.sessionId);
|
|
344
|
+
s.pausedBy = 'agent';
|
|
345
|
+
await setStatus(s, String(p.message || '사용자 확인 필요').slice(0, 80), true);
|
|
346
|
+
emit('session.handedOff', { sessionId: s.id, message: p.message || '' });
|
|
347
|
+
return {};
|
|
348
|
+
}
|
|
349
|
+
// Resuming a session in a later invocation. The key was already checked above, so reaching
|
|
350
|
+
// this point is proof of ownership.
|
|
351
|
+
case 'session.attach': return serializeSession(sessionOf(p.sessionId));
|
|
352
|
+
// The user's escape hatch (`parallel-browser stop <id>`), deliberately outside the key check
|
|
353
|
+
// so they can clean up a session whose owning agent is gone. It only closes; it never hands
|
|
354
|
+
// control to the caller, so it cannot be used to hijack anything.
|
|
355
|
+
case 'debug.forceClose': {
|
|
356
|
+
if (!TEST_HOOKS) throw new Error('closing another session is not possible: use the dashboard, or just close the tabs');
|
|
357
|
+
return closeSession(p.id, 'closed_by_test');
|
|
358
|
+
}
|
|
359
|
+
case 'tab.create': {
|
|
360
|
+
const s = sessionOf(p.sessionId);
|
|
361
|
+
if (s.paused) throw new Error(`session paused: the user has control of "${s.name}".`);
|
|
362
|
+
return createTab(s, p.url);
|
|
363
|
+
}
|
|
364
|
+
case 'tab.close': {
|
|
365
|
+
const s = sessionOf(p.sessionId);
|
|
366
|
+
if (!s.tabIds.has(p.tabId)) throw new Error('tab not owned by session');
|
|
367
|
+
await keepBlankInFront(s.windowId, new Set([p.tabId]));
|
|
368
|
+
await chrome.tabs.remove(p.tabId);
|
|
369
|
+
return {};
|
|
370
|
+
}
|
|
371
|
+
case 'session.tabs': {
|
|
372
|
+
const s = sessionOf(p.sessionId);
|
|
373
|
+
const tabs = [];
|
|
374
|
+
for (const tabId of s.tabIds) {
|
|
375
|
+
const t = await chrome.tabs.get(tabId).catch(() => null);
|
|
376
|
+
if (t) tabs.push({ tabId, url: t.url, title: t.title, active: t.active, status: t.status });
|
|
377
|
+
}
|
|
378
|
+
return { tabs };
|
|
379
|
+
}
|
|
380
|
+
case 'group.collapse': { const s = sessionOf(p.sessionId); await chrome.tabGroups.update(s.groupId, { collapsed: !!p.collapsed }); return {}; }
|
|
381
|
+
case 'window.get': {
|
|
382
|
+
const s = sessionOf(p.sessionId);
|
|
383
|
+
const w = await chrome.windows.get(s.windowId);
|
|
384
|
+
return { windowId: w.id, state: w.state, focused: w.focused, left: w.left, top: w.top, width: w.width, height: w.height };
|
|
385
|
+
}
|
|
386
|
+
case 'window.setState': {
|
|
387
|
+
const s = sessionOf(p.sessionId);
|
|
388
|
+
if (s.placement === 'group') throw new Error('group-placed sessions do not own a window');
|
|
389
|
+
const w = await chrome.windows.get(s.windowId);
|
|
390
|
+
// Un-minimizing a window brings it to the front on macOS, which takes the user's focus.
|
|
391
|
+
// Minimizing is safe; coming back is the user's call, or an explicit allowFocus.
|
|
392
|
+
if (w.state === 'minimized' && p.state !== 'minimized' && !p.allowFocus) {
|
|
393
|
+
throw new Error('restoring a minimized window takes the user\'s focus; pass allowFocus if that is really wanted');
|
|
394
|
+
}
|
|
395
|
+
await chrome.windows.update(s.windowId, { state: p.state }); // never focused:true
|
|
396
|
+
return {};
|
|
397
|
+
}
|
|
398
|
+
case 'window.setBounds': {
|
|
399
|
+
const s = sessionOf(p.sessionId);
|
|
400
|
+
if (s.placement === 'group') throw new Error('group-placed sessions do not own a window');
|
|
401
|
+
await chrome.windows.update(s.windowId, { left: p.left, top: p.top, width: p.width, height: p.height });
|
|
402
|
+
return {};
|
|
403
|
+
}
|
|
404
|
+
case 'agentWindow.get': {
|
|
405
|
+
if (!agentWindowId) return { windowId: null };
|
|
406
|
+
const w = await chrome.windows.get(agentWindowId).catch(() => null);
|
|
407
|
+
if (!w) { agentWindowId = null; await saveState(); return { windowId: null }; }
|
|
408
|
+
return { windowId: w.id, state: w.state, focused: w.focused, left: w.left, top: w.top, width: w.width, height: w.height };
|
|
409
|
+
}
|
|
410
|
+
case 'agentWindow.setBounds': { const w = await ensureAgentWindow(); await chrome.windows.update(w.id, p); return {}; }
|
|
411
|
+
case 'agentWindow.setState': { const w = await ensureAgentWindow(); await chrome.windows.update(w.id, { state: p.state }); return {}; }
|
|
412
|
+
case 'browser.tabCount': {
|
|
413
|
+
// Diagnostic: how many tabs exist outside agent windows (spikes use it to prove isolation).
|
|
414
|
+
const all = await chrome.tabs.query({});
|
|
415
|
+
const owned = new Set([...sessions.values()].flatMap((s) => [...s.tabIds]));
|
|
416
|
+
return { total: all.length, foreign: all.filter((t) => !owned.has(t.id) && !isAgentWindow(t.windowId)).length };
|
|
417
|
+
}
|
|
418
|
+
// Pick up edited files without the user going to chrome://extensions. Unpacked extensions
|
|
419
|
+
// re-read from disk on reload; every debugger attachment drops and reconcile() restores it.
|
|
420
|
+
// Test-only: chrome.runtime.reload() unloads the extension and it does not come back by itself
|
|
421
|
+
// (2026-11-16: an agent called this on the user's Edge and the browser stayed disconnected for
|
|
422
|
+
// ten minutes; Chrome for Testing: the worker is gone 3 s later and never returns). After an
|
|
423
|
+
// update, reload the extension from edge://extensions instead.
|
|
424
|
+
case 'debug.reload': { if (!TEST_HOOKS) throw new Error('debug.reload is test-only: reload the extension from edge://extensions or chrome://extensions'); setTimeout(() => chrome.runtime.reload(), 50); return { reloading: true }; }
|
|
425
|
+
case 'debug.userWindow': {
|
|
426
|
+
// DIAGNOSTIC ONLY (spikes): manipulate a non-agent window to simulate the user.
|
|
427
|
+
const wins = await chrome.windows.getAll();
|
|
428
|
+
const user = wins.find((w) => !isAgentWindow(w.id));
|
|
429
|
+
if (!user) throw new Error('no user window');
|
|
430
|
+
const upd = {};
|
|
431
|
+
if (p.bounds) Object.assign(upd, p.bounds);
|
|
432
|
+
if (typeof p.focused === 'boolean') upd.focused = p.focused;
|
|
433
|
+
if (p.state) upd.state = p.state;
|
|
434
|
+
const w = await chrome.windows.update(user.id, upd);
|
|
435
|
+
if (p.url) {
|
|
436
|
+
const [tab] = await chrome.tabs.query({ windowId: user.id, active: true });
|
|
437
|
+
if (tab) await chrome.tabs.update(tab.id, { url: p.url });
|
|
438
|
+
}
|
|
439
|
+
return { windowId: w.id, state: w.state, focused: w.focused, left: w.left, top: w.top, width: w.width, height: w.height };
|
|
440
|
+
}
|
|
441
|
+
case 'debug.focusAgentWindow': {
|
|
442
|
+
// DIAGNOSTIC ONLY (spikes): the one place focused:true appears, to prove that focusing
|
|
443
|
+
// the agent window does NOT pause a session.
|
|
444
|
+
if (!agentWindowId) throw new Error('no agent window');
|
|
445
|
+
await chrome.windows.update(agentWindowId, { focused: true });
|
|
446
|
+
return {};
|
|
447
|
+
}
|
|
448
|
+
case 'debug.activateTab': {
|
|
449
|
+
// DIAGNOSTIC ONLY (spikes): simulates the user clicking another tab of the agent window.
|
|
450
|
+
const s = sessionOf(p.sessionId);
|
|
451
|
+
if (!s.tabIds.has(p.tabId)) throw new Error('tab not owned by session');
|
|
452
|
+
await chrome.tabs.update(p.tabId, { active: true });
|
|
453
|
+
return {};
|
|
454
|
+
}
|
|
455
|
+
// A real user's input never passes through cdp(), so tests cannot produce one there:
|
|
456
|
+
// anything sent that way is agent input by definition. This dispatches straight to the
|
|
457
|
+
// debuggee, which is what a genuine click looks like to the renderer.
|
|
458
|
+
case 'debug.rawInput': {
|
|
459
|
+
if (!TEST_HOOKS) throw new Error('debug.rawInput is test-only');
|
|
460
|
+
const s = sessionOf(p.sessionId);
|
|
461
|
+
const tabId = p.tabId ?? [...s.tabIds][0];
|
|
462
|
+
for (const ev of p.events || []) await chrome.debugger.sendCommand({ tabId }, 'Input.dispatchMouseEvent', ev);
|
|
463
|
+
return { dispatched: (p.events || []).length };
|
|
464
|
+
}
|
|
465
|
+
// Where the take-control button actually is, so a test can click it for real. It lives in a
|
|
466
|
+
// closed shadow root, so nothing outside the extension's own world can measure it.
|
|
467
|
+
case 'debug.overlayButton': {
|
|
468
|
+
if (!TEST_HOOKS) throw new Error('debug.overlayButton is test-only');
|
|
469
|
+
const s = sessionOf(p.sessionId);
|
|
470
|
+
const tabId = p.tabId ?? [...s.tabIds][0];
|
|
471
|
+
const [res] = await chrome.scripting.executeScript({
|
|
472
|
+
target: { tabId, allFrames: false },
|
|
473
|
+
func: () => {
|
|
474
|
+
const h = document.getElementById('__parallel_browser_overlay__');
|
|
475
|
+
const b = h && h.__pcRoot && h.__pcRoot.querySelector('#a');
|
|
476
|
+
if (!b) return { found: false };
|
|
477
|
+
const r = b.getBoundingClientRect();
|
|
478
|
+
return { found: true, label: b.textContent, x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
|
|
479
|
+
},
|
|
480
|
+
});
|
|
481
|
+
return res?.result ?? { found: false };
|
|
482
|
+
}
|
|
483
|
+
case 'debug.detach': {
|
|
484
|
+
// DIAGNOSTIC: drop the debugger from one tab, to measure the same page with and without CDP.
|
|
485
|
+
const s = sessionOf(p.sessionId);
|
|
486
|
+
const tabId = p.tabId ?? [...s.tabIds][0];
|
|
487
|
+
await chrome.debugger.detach({ tabId });
|
|
488
|
+
return { detached: tabId };
|
|
489
|
+
}
|
|
490
|
+
// TEST ONLY (spikes): what the browser does on its own — discard a tab (Edge does it to hidden
|
|
491
|
+
// tabs), read a tab's state, and plant a tab group that looks like ours but is not (another copy
|
|
492
|
+
// of parallel-browser in the same browser).
|
|
493
|
+
case 'debug.tabOp': {
|
|
494
|
+
if (!TEST_HOOKS) throw new Error('debug.tabOp is test-only');
|
|
495
|
+
if (p.op === 'discard') { const t = await chrome.tabs.discard(p.tabId); return { tabId: t?.id ?? null }; }
|
|
496
|
+
if (p.op === 'get') { const t = await chrome.tabs.get(p.tabId); return { tabId: t.id, active: t.active, discarded: t.discarded, autoDiscardable: t.autoDiscardable, groupId: t.groupId, windowId: t.windowId }; }
|
|
497
|
+
if (p.op === 'foreignGroup') {
|
|
498
|
+
const win = await chrome.windows.create({ url: 'about:blank', focused: false, state: 'normal', left: 40, top: 40, width: 500, height: 400 });
|
|
499
|
+
const groupId = await chrome.tabs.group({ tabIds: [win.tabs[0].id], createProperties: { windowId: win.id } });
|
|
500
|
+
await chrome.tabGroups.update(groupId, { title: '● foreign · not ours' });
|
|
501
|
+
return { windowId: win.id, tabId: win.tabs[0].id, groupId };
|
|
502
|
+
}
|
|
503
|
+
if (p.op === 'groupAlive') return { alive: !!(await chrome.tabGroups.get(p.groupId).catch(() => null)) };
|
|
504
|
+
if (p.op === 'active') { const [t] = await chrome.tabs.query({ windowId: agentWindowId, active: true }); return { tabId: t?.id ?? null, session: t ? sessionByTab(t.id)?.id ?? null : null }; }
|
|
505
|
+
throw new Error(`unknown op ${p.op}`);
|
|
506
|
+
}
|
|
507
|
+
case 'debug.scriptEval': {
|
|
508
|
+
// Runs code with chrome.scripting only — no debugger, no CDP. This is also the path a
|
|
509
|
+
// future no-CDP mode would use.
|
|
510
|
+
const s = sessionOf(p.sessionId);
|
|
511
|
+
const tabId = p.tabId ?? [...s.tabIds][0];
|
|
512
|
+
const [res] = await chrome.scripting.executeScript({
|
|
513
|
+
target: { tabId, allFrames: false },
|
|
514
|
+
world: p.world === 'isolated' ? 'ISOLATED' : 'MAIN',
|
|
515
|
+
args: [p.code],
|
|
516
|
+
func: (code) => {
|
|
517
|
+
try { return { value: eval(code) }; } catch (e) { return { error: String(e && e.message || e) }; }
|
|
518
|
+
},
|
|
519
|
+
});
|
|
520
|
+
return res?.result ?? { error: 'no result' };
|
|
521
|
+
}
|
|
522
|
+
case 'debug.windows': {
|
|
523
|
+
// DIAGNOSTIC: every window with its tabs, and whether we consider it ours.
|
|
524
|
+
const wins = await chrome.windows.getAll({ populate: true });
|
|
525
|
+
return {
|
|
526
|
+
agentWindowId,
|
|
527
|
+
windows: wins.map((w) => ({
|
|
528
|
+
id: w.id,
|
|
529
|
+
isAgentWindow: w.id === agentWindowId,
|
|
530
|
+
ownedByASession: !!sessionByWindow(w.id),
|
|
531
|
+
focused: w.focused,
|
|
532
|
+
tabs: w.tabs.map((t) => ({ tabId: t.id, groupId: t.groupId, owned: !!sessionByTab(t.id), url: (t.url || '').slice(0, 60) })),
|
|
533
|
+
})),
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
case 'debug.targets': {
|
|
537
|
+
const targets = await chrome.debugger.getTargets();
|
|
538
|
+
return { targets: targets.filter((t) => !p.url || (t.url || '').includes(p.url)).map((t) => ({ id: t.id, type: t.type, url: (t.url || '').slice(0, 80), tabId: t.tabId, attached: t.attached })) };
|
|
539
|
+
}
|
|
540
|
+
case 'debug.userProbe': {
|
|
541
|
+
// DIAGNOSTIC ONLY: measure a tab that has NO debugger attached (control group).
|
|
542
|
+
const wins = await chrome.windows.getAll();
|
|
543
|
+
const user = wins.find((w) => !isAgentWindow(w.id));
|
|
544
|
+
const [tab] = await chrome.tabs.query({ windowId: user.id, active: true });
|
|
545
|
+
const [{ result }] = await chrome.scripting.executeScript({
|
|
546
|
+
target: { tabId: tab.id },
|
|
547
|
+
func: () => new Promise((r) => {
|
|
548
|
+
let n = 0; const t = performance.now();
|
|
549
|
+
function f() { n++; if (performance.now() - t < 1000) requestAnimationFrame(f); else r({ visibilityState: document.visibilityState, hasFocus: document.hasFocus(), rafPerSec: n }); }
|
|
550
|
+
requestAnimationFrame(f);
|
|
551
|
+
setTimeout(() => r({ visibilityState: document.visibilityState, hasFocus: document.hasFocus(), rafPerSec: n, timedOut: true }), 1500);
|
|
552
|
+
}),
|
|
553
|
+
});
|
|
554
|
+
return { tabId: tab.id, ...result };
|
|
555
|
+
}
|
|
556
|
+
case 'cdp': return cdp(p);
|
|
557
|
+
case 'frames.discover': return discoverFrames(p);
|
|
558
|
+
case 'panic': {
|
|
559
|
+
if (!TEST_HOOKS) throw new Error('stopping every session is not possible from a script: use the dashboard');
|
|
560
|
+
return panic('runtime');
|
|
561
|
+
}
|
|
562
|
+
case 'ext.update': return updateFromDisk(String(p.codeHash || ''));
|
|
563
|
+
case 'ext.reload': { if (!TEST_HOOKS) throw new Error('ext.reload is test-only: reload the extension from edge://extensions or chrome://extensions'); setTimeout(() => chrome.runtime.reload(), 100); return { reloading: true }; }
|
|
564
|
+
default: throw new Error(`unknown method ${method}`);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// ---------- the dedicated agent window ----------
|
|
569
|
+
|
|
570
|
+
/** Returns the agent window, creating it (unfocused) if needed. `fresh` tells whether it was just created. */
|
|
571
|
+
async function ensureAgentWindow(bounds) {
|
|
572
|
+
if (agentWindowId) {
|
|
573
|
+
const w = await chrome.windows.get(agentWindowId).catch(() => null);
|
|
574
|
+
if (w) return { id: w.id, fresh: false };
|
|
575
|
+
agentWindowId = null;
|
|
576
|
+
}
|
|
577
|
+
const b = bounds || AGENT_WINDOW_BOUNDS;
|
|
578
|
+
const win = await chrome.windows.create({
|
|
579
|
+
url: 'about:blank', focused: false, type: 'normal', state: 'normal',
|
|
580
|
+
left: b.left, top: b.top, width: b.width, height: b.height,
|
|
581
|
+
});
|
|
582
|
+
agentWindowId = win.id;
|
|
583
|
+
await saveState();
|
|
584
|
+
emit('agentWindow.created', { windowId: win.id });
|
|
585
|
+
return { id: win.id, fresh: true };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// ---------- sessions ----------
|
|
589
|
+
|
|
590
|
+
async function createSession({ name, color, bounds, budget, placement = 'shared', windowId }) {
|
|
591
|
+
const id = newSessionId();
|
|
592
|
+
const chosen = color || COLORS[sessions.size % COLORS.length];
|
|
593
|
+
let winId, tab;
|
|
594
|
+
if (placement === 'shared') {
|
|
595
|
+
const w = await ensureAgentWindow(bounds);
|
|
596
|
+
winId = w.id;
|
|
597
|
+
// Session tabs always open in the background. The fresh window's own first tab stays as the
|
|
598
|
+
// window's front tab: a front tab is screencast at the window's real size (keepBlankInFront).
|
|
599
|
+
tab = await chrome.tabs.create({ windowId: winId, url: 'about:blank', active: false });
|
|
600
|
+
} else if (placement === 'group') {
|
|
601
|
+
const win = windowId ? await chrome.windows.get(windowId) : await chrome.windows.getLastFocused({ windowTypes: ['normal'] });
|
|
602
|
+
if (!win || isAgentWindow(win.id)) throw new Error('no user window to place the group in');
|
|
603
|
+
winId = win.id;
|
|
604
|
+
tab = await chrome.tabs.create({ windowId: winId, url: 'about:blank', active: false });
|
|
605
|
+
} else {
|
|
606
|
+
const n = sessions.size;
|
|
607
|
+
const b = bounds || { left: 60 + (n % 4) * 40, top: 60 + (n % 4) * 40, width: 1100, height: 760 };
|
|
608
|
+
const win = await chrome.windows.create({ url: 'about:blank', focused: false, type: 'normal', state: 'normal', left: b.left, top: b.top, width: b.width, height: b.height });
|
|
609
|
+
winId = win.id;
|
|
610
|
+
tab = win.tabs[0];
|
|
611
|
+
}
|
|
612
|
+
const groupId = await chrome.tabs.group({ tabIds: [tab.id], createProperties: { windowId: winId } });
|
|
613
|
+
const s = {
|
|
614
|
+
id, key: newSessionKey(), name: name || `session-${id}`, color: chosen, placement, windowId: winId, groupId,
|
|
615
|
+
tabIds: new Set([tab.id]), budget: budget || DEFAULT_TAB_BUDGET, status: 'starting', paused: false, pausedBy: null, urls: {},
|
|
616
|
+
};
|
|
617
|
+
sessions.set(id, s);
|
|
618
|
+
ownGroups.add(groupId);
|
|
619
|
+
await chrome.tabGroups.update(groupId, { title: groupTitle(s), color: chosen });
|
|
620
|
+
await attach(s, tab.id);
|
|
621
|
+
await keepBlankInFront(winId);
|
|
622
|
+
await saveState();
|
|
623
|
+
return { sessionId: id, key: s.key, placement, windowId: winId, groupId, tabId: tab.id, color: chosen };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function createTab(s, url) {
|
|
627
|
+
if (url && isUrlBlocked(url)) throw new Error(`blocked by guard: ${url}`);
|
|
628
|
+
// Reserve the slot before the first await: a page can fire several window.open calls at once,
|
|
629
|
+
// and they would all pass a check made against tabIds alone.
|
|
630
|
+
s.pending = (s.pending || 0) + 1;
|
|
631
|
+
try {
|
|
632
|
+
if (s.tabIds.size + s.pending - 1 >= s.budget) throw new Error(`tab budget (${s.budget}) reached for session ${s.id}`);
|
|
633
|
+
// active:false so nothing anyone is looking at changes. Placed right after the group's last tab.
|
|
634
|
+
const owned = await chrome.tabs.query({ windowId: s.windowId, groupId: s.groupId });
|
|
635
|
+
const index = owned.length ? Math.max(...owned.map((t) => t.index)) + 1 : undefined;
|
|
636
|
+
const tab = await chrome.tabs.create({ windowId: s.windowId, url: url || 'about:blank', active: false, index });
|
|
637
|
+
await adoptTab(s, tab.id, 'runtime');
|
|
638
|
+
await keepBlankInFront(s.windowId);
|
|
639
|
+
return { tabId: tab.id };
|
|
640
|
+
} finally {
|
|
641
|
+
s.pending--;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async function adoptTab(s, tabId, openedBy, bridge = null) {
|
|
646
|
+
if (s.tabIds.has(tabId)) return;
|
|
647
|
+
s.tabIds.add(tabId);
|
|
648
|
+
try { await chrome.tabs.group({ tabIds: [tabId], groupId: s.groupId }); } catch { /* group may be gone */ }
|
|
649
|
+
await attach(s, tabId, bridge);
|
|
650
|
+
await saveState();
|
|
651
|
+
emit('tab.adopted', { sessionId: s.id, tabId, openedBy });
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
async function closeSession(sessionId, reason) {
|
|
655
|
+
const s = sessions.get(sessionId);
|
|
656
|
+
if (!s) return {};
|
|
657
|
+
for (const tabId of s.tabIds) { try { await chrome.debugger.detach({ tabId }); } catch { /* gone */ } }
|
|
658
|
+
for (const targetId of s.frameTargets?.keys() || []) { try { await chrome.debugger.detach({ targetId }); } catch { /* gone */ } }
|
|
659
|
+
if (s.placement === 'shared') await keepBlankInFront(s.windowId, new Set(s.tabIds));
|
|
660
|
+
sessions.delete(sessionId);
|
|
661
|
+
recentlyRemovedAt = Date.now();
|
|
662
|
+
if (s.placement === 'window') { try { await chrome.windows.remove(s.windowId); } catch { /* gone */ } }
|
|
663
|
+
else { try { await chrome.tabs.remove([...s.tabIds]); } catch { /* gone */ } }
|
|
664
|
+
await saveState();
|
|
665
|
+
emit('session.closed', { sessionId, reason });
|
|
666
|
+
return {};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async function panic(source) {
|
|
670
|
+
const ids = [...sessions.keys()];
|
|
671
|
+
for (const id of ids) await closeSession(id, `panic:${source}`);
|
|
672
|
+
if (agentWindowId) { try { await chrome.windows.remove(agentWindowId); } catch { /* gone */ } agentWindowId = null; await saveState(); }
|
|
673
|
+
emit('panic', { source, closed: ids });
|
|
674
|
+
return { closed: ids };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function groupTitle(s) {
|
|
678
|
+
return `${s.paused ? '⏸' : '●'} ${s.name} · ${s.status}`;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
async function setStatus(s, text, paused) {
|
|
682
|
+
if (typeof text === 'string') s.status = text;
|
|
683
|
+
if (typeof paused === 'boolean') s.paused = paused;
|
|
684
|
+
try { await chrome.tabGroups.update(s.groupId, { title: groupTitle(s) }); } catch { /* group gone */ }
|
|
685
|
+
for (const tabId of s.tabIds) paintOverlay(s, tabId);
|
|
686
|
+
await saveState();
|
|
687
|
+
return {};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function paintOverlay(s, tabId) {
|
|
691
|
+
const css = GROUP_COLOR_CSS[s.color] || GROUP_COLOR_CSS.grey;
|
|
692
|
+
const handedOver = s.pausedBy === 'agent';
|
|
693
|
+
const status = s.paused ? (handedOver ? '에이전트가 넘김 · 사용자 차례' : '일시정지 · 내가 제어 중') : s.status;
|
|
694
|
+
chrome.scripting
|
|
695
|
+
.executeScript({ target: { tabId }, func: overlayInject, args: [s.id, s.name, css, status, !!s.paused, handedOver] })
|
|
696
|
+
.catch(() => { /* chrome:// or discarded pages cannot be scripted */ });
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async function takeover(s, tabId, via) {
|
|
700
|
+
if (s.paused) return;
|
|
701
|
+
s.pausedBy = 'user';
|
|
702
|
+
await setStatus(s, s.status, true);
|
|
703
|
+
emit('session.takeover', { sessionId: s.id, tabId, via });
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// ---------- debugger relay ----------
|
|
707
|
+
|
|
708
|
+
// Page-initiated new tabs (window.open, target=_blank) make Chrome show a foreground popup,
|
|
709
|
+
// which activates the app on macOS and steals focus. This main-world script, installed before
|
|
710
|
+
// any page script runs, reroutes them through the extension so they open as inactive tabs in
|
|
711
|
+
// the session's group (subject to the tab budget). window.print() is neutralised too.
|
|
712
|
+
//
|
|
713
|
+
// Popups the USER opens are left alone. A rerouted window.open returns null, which every login
|
|
714
|
+
// page reads as "popups are blocked", and the rerouted tab has no opener, so SSO popups that
|
|
715
|
+
// post their result back to window.opener cannot finish. The user is already working in that
|
|
716
|
+
// window, so a real popup in front of them is what they want. Agent and user input are both
|
|
717
|
+
// trusted events to the page, but agent input always goes through cdp(): right before it sends a
|
|
718
|
+
// press, cdp() fires the secret event below, and the guard tags the next gesture as the agent's.
|
|
719
|
+
// window.open with transient activation from an untagged gesture is the user's and stays native.
|
|
720
|
+
const OPEN_BINDING = '__parallelBrowserOpen';
|
|
721
|
+
const popupGuardSrc = (token, bridge = null) => `(() => {
|
|
722
|
+
// Runtime.addBinding puts a function on window. Take a reference and remove it, so the page
|
|
723
|
+
// cannot see (or call, or fingerprint) the automation's own hooks.
|
|
724
|
+
const __open = window.${OPEN_BINDING};
|
|
725
|
+
try { delete window.${OPEN_BINDING}; } catch (e) {}
|
|
726
|
+
const callOpen = (payload) => { const f = __open || window.${OPEN_BINDING}; if (f) f(payload); };
|
|
727
|
+
const send = (o) => { try { callOpen(JSON.stringify(o)); } catch (e) {} };
|
|
728
|
+
const abs = (u) => { try { return new URL(u || 'about:blank', location.href).href; } catch (e) { return 'about:blank'; } };
|
|
729
|
+
|
|
730
|
+
// A plain function assigned over a native one is trivially detectable through
|
|
731
|
+
// Function.prototype.toString. A Proxy around a function reports as native code instead,
|
|
732
|
+
// so replacing window.open leaves the page looking untouched.
|
|
733
|
+
const asNative = (name, impl) => new Proxy(function () {}, {
|
|
734
|
+
apply: (_t, _this, args) => impl(...args),
|
|
735
|
+
get: (t, prop, recv) => (prop === 'name' ? name : prop === 'length' ? impl.length : Reflect.get(t, prop, recv)),
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
// Messages from the extension arrive as an event whose name only the extension and this
|
|
739
|
+
// closure know. Agent-gesture marks use the bare token, everything else token + 'm'.
|
|
740
|
+
const T = ${JSON.stringify(token)};
|
|
741
|
+
const handlers = {};
|
|
742
|
+
addEventListener(T + 'm', (e) => {
|
|
743
|
+
e.stopImmediatePropagation();
|
|
744
|
+
let m; try { m = JSON.parse(e.detail); } catch (_) { return; }
|
|
745
|
+
const h = handlers[m.kind]; if (h) h(m);
|
|
746
|
+
}, true);
|
|
747
|
+
|
|
748
|
+
// Clicking, typing or scrolling in an agent page does NOT take the session. The agent keeps
|
|
749
|
+
// control until it hands over, or until the user presses the button on the overlay.
|
|
750
|
+
const nativeOpen = window.open;
|
|
751
|
+
let agentMarkAt = 0, gestureByAgent = false;
|
|
752
|
+
addEventListener(T, (e) => { e.stopImmediatePropagation(); agentMarkAt = performance.now(); }, true);
|
|
753
|
+
// One gesture = one pointerdown or keydown. The mark is consumed by the first one after it.
|
|
754
|
+
const onGesture = (e) => {
|
|
755
|
+
if (!e.isTrusted) return;
|
|
756
|
+
gestureByAgent = agentMarkAt > 0 && performance.now() - agentMarkAt < 2000;
|
|
757
|
+
agentMarkAt = 0;
|
|
758
|
+
};
|
|
759
|
+
addEventListener('pointerdown', onGesture, true);
|
|
760
|
+
addEventListener('keydown', onGesture, true);
|
|
761
|
+
const byUser = () => { const ua = navigator.userActivation; return !!(ua && ua.isActive) && !gestureByAgent; };
|
|
762
|
+
// Tell the extension first, so the tab the browser is about to create is left to the user
|
|
763
|
+
// rather than adopted into the session (or closed for being over the tab budget).
|
|
764
|
+
const userOpening = (url) => send({ user: true, url: abs(url) });
|
|
765
|
+
|
|
766
|
+
// ---- popups the agent causes: an inactive session tab plus a stand-in window object.
|
|
767
|
+
// The browser's own window.open would bring the browser forward (measured), so the extension
|
|
768
|
+
// opens the URL as an inactive tab instead. Returning null would make sign-in pages report a
|
|
769
|
+
// blocked popup, and that tab has no opener, so this hands back a stand-in that tracks the tab
|
|
770
|
+
// (closed, location once same-origin, close, postMessage) while the tab gets a stand-in
|
|
771
|
+
// window.opener whose postMessage, same-origin calls and window.close() are relayed back here.
|
|
772
|
+
const popups = new Map();
|
|
773
|
+
const securityError = () => new DOMException('Blocked a frame with origin "' + location.origin + '" from accessing a cross-origin frame.', 'SecurityError');
|
|
774
|
+
const popupHandle = (id, name) => {
|
|
775
|
+
const st = { href: 'about:blank', closed: false, handle: null };
|
|
776
|
+
popups.set(id, st);
|
|
777
|
+
const same = () => { try { return st.href === 'about:blank' || new URL(st.href).origin === location.origin; } catch (_) { return false; } };
|
|
778
|
+
const part = (k) => () => { if (!same()) throw securityError(); try { return new URL(st.href)[k]; } catch (_) { return ''; } };
|
|
779
|
+
const go = (v) => send({ kind: 'bridge.navigate', id, url: abs(String(v)) });
|
|
780
|
+
const loc = {};
|
|
781
|
+
for (const k of ['hash', 'search', 'pathname', 'host', 'hostname', 'port', 'protocol', 'origin']) Object.defineProperty(loc, k, { get: part(k), enumerable: true });
|
|
782
|
+
Object.defineProperty(loc, 'href', { get: () => { if (!same()) throw securityError(); return st.href; }, set: go, enumerable: true });
|
|
783
|
+
loc.assign = go; loc.replace = go; loc.reload = () => go(st.href);
|
|
784
|
+
loc.toString = () => loc.href;
|
|
785
|
+
const w = {
|
|
786
|
+
get closed() { return st.closed; },
|
|
787
|
+
close() { if (!st.closed) send({ kind: 'bridge.close', id }); },
|
|
788
|
+
focus() {}, blur() {},
|
|
789
|
+
postMessage(data, opts) {
|
|
790
|
+
const to = typeof opts === 'string' ? opts : (opts && opts.targetOrigin) || '/';
|
|
791
|
+
let json; try { json = JSON.stringify(data); } catch (_) { return; }
|
|
792
|
+
send({ kind: 'bridge.toPopup', id, data: json, targetOrigin: to });
|
|
793
|
+
},
|
|
794
|
+
get location() { return loc; }, set location(v) { go(v); },
|
|
795
|
+
get document() { throw securityError(); },
|
|
796
|
+
name: name || '', opener: window, length: 0,
|
|
797
|
+
};
|
|
798
|
+
w.window = w; w.self = w; w.top = w; w.parent = w; w.frames = w;
|
|
799
|
+
st.handle = w;
|
|
800
|
+
return w;
|
|
801
|
+
};
|
|
802
|
+
handlers['bridge.state'] = (m) => { const st = popups.get(m.id); if (!st) return; if (m.href) st.href = m.href; if (m.closed) st.closed = true; };
|
|
803
|
+
// A message posted by the popup (or, inside the popup, by the opener) becomes a 'message'
|
|
804
|
+
// event with the sender's real origin, the way a cross-window postMessage arrives.
|
|
805
|
+
handlers['bridge.message'] = (m) => {
|
|
806
|
+
let data; try { data = JSON.parse(m.data); } catch (_) { return; }
|
|
807
|
+
const st = popups.get(m.id);
|
|
808
|
+
const source = st ? st.handle : (BRIDGE && m.id === BRIDGE.id ? openerHandle : null);
|
|
809
|
+
// MessageEvent only takes a real window as source; the stand-in goes on the event itself.
|
|
810
|
+
const ev = new MessageEvent('message', { data, origin: m.origin });
|
|
811
|
+
try { Object.defineProperty(ev, 'source', { value: source, enumerable: true }); } catch (_) {}
|
|
812
|
+
dispatchEvent(ev);
|
|
813
|
+
};
|
|
814
|
+
// Old-style same-origin callbacks: window.opener.someFn(...) from the popup.
|
|
815
|
+
handlers['bridge.call'] = (m) => {
|
|
816
|
+
if (m.origin !== location.origin) return;
|
|
817
|
+
try {
|
|
818
|
+
const args = JSON.parse(m.args);
|
|
819
|
+
const parts = m.path.split('.'); const last = parts.pop();
|
|
820
|
+
const obj = parts.reduce((o, k) => (o == null ? o : o[k]), window);
|
|
821
|
+
if (obj && typeof obj[last] === 'function') obj[last](...args);
|
|
822
|
+
else if (obj && m.set) obj[last] = args[0];
|
|
823
|
+
} catch (_) {}
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
const reroute = (url, name) => {
|
|
827
|
+
const id = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
828
|
+
const ua = navigator.userActivation;
|
|
829
|
+
send({ url: abs(url), bridge: id, name: typeof name === 'string' ? name : '', gesture: !!(ua && ua.isActive) });
|
|
830
|
+
return popupHandle(id, name);
|
|
831
|
+
};
|
|
832
|
+
const open = (...args) => {
|
|
833
|
+
if (byUser()) { userOpening(args[0]); try { return nativeOpen.apply(window, args); } catch (e) { /* fall through to reroute */ } }
|
|
834
|
+
return reroute(args[0], args[1]);
|
|
835
|
+
};
|
|
836
|
+
try { Object.defineProperty(window, 'open', { value: asNative('open', open), writable: true, configurable: true }); } catch (e) {}
|
|
837
|
+
try { Object.defineProperty(window, 'print', { value: asNative('print', () => {}), writable: true, configurable: true }); } catch (e) {}
|
|
838
|
+
const newTabTarget = (t) => t && !['_self', '_parent', '_top'].includes(t.toLowerCase());
|
|
839
|
+
// target=_blank links open without an opener in Chrome anyway, so they need no stand-in.
|
|
840
|
+
addEventListener('click', (e) => {
|
|
841
|
+
const a = e.composedPath().find((n) => n && n.tagName === 'A' && n.href);
|
|
842
|
+
if (!a || !newTabTarget(a.getAttribute('target'))) return;
|
|
843
|
+
if (byUser()) { userOpening(a.href); return; }
|
|
844
|
+
e.preventDefault(); e.stopImmediatePropagation(); send({ url: abs(a.href) });
|
|
845
|
+
}, true);
|
|
846
|
+
addEventListener('submit', (e) => {
|
|
847
|
+
const f = e.target;
|
|
848
|
+
if (!f || !newTabTarget(f.getAttribute('target'))) return;
|
|
849
|
+
if (byUser()) { userOpening(f.action); return; }
|
|
850
|
+
f.target = '_self';
|
|
851
|
+
}, true);
|
|
852
|
+
|
|
853
|
+
// ---- inside a tab opened for the agent's popup: a stand-in window.opener.
|
|
854
|
+
const BRIDGE = ${JSON.stringify(bridge)};
|
|
855
|
+
let openerHandle = null;
|
|
856
|
+
if (BRIDGE) {
|
|
857
|
+
try { if (BRIDGE.name) window.name = BRIDGE.name; } catch (_) {}
|
|
858
|
+
const sameAsOpener = () => location.origin === BRIDGE.openerOrigin;
|
|
859
|
+
const call = (path, args, set) => {
|
|
860
|
+
if (!sameAsOpener()) throw securityError();
|
|
861
|
+
let json; try { json = JSON.stringify(args); } catch (_) { return; }
|
|
862
|
+
send({ kind: 'bridge.callOpener', id: BRIDGE.id, path, args: json, set: !!set, origin: location.origin });
|
|
863
|
+
};
|
|
864
|
+
const openerLoc = {
|
|
865
|
+
set href(v) { call('location.href', [abs(String(v))], true); },
|
|
866
|
+
get href() { throw securityError(); },
|
|
867
|
+
assign: (v) => call('location.assign', [abs(String(v))]),
|
|
868
|
+
replace: (v) => call('location.replace', [abs(String(v))]),
|
|
869
|
+
};
|
|
870
|
+
openerHandle = new Proxy({}, {
|
|
871
|
+
get(_t, k) {
|
|
872
|
+
if (typeof k === 'symbol') return undefined;
|
|
873
|
+
if (k === 'postMessage') return (data, opts) => {
|
|
874
|
+
const to = typeof opts === 'string' ? opts : (opts && opts.targetOrigin) || '/';
|
|
875
|
+
let json; try { json = JSON.stringify(data); } catch (_) { return; }
|
|
876
|
+
send({ kind: 'bridge.fromPopup', id: BRIDGE.id, data: json, targetOrigin: to, origin: location.origin });
|
|
877
|
+
};
|
|
878
|
+
if (k === 'closed') return false;
|
|
879
|
+
if (k === 'opener' || k === 'parent' || k === 'top') return null;
|
|
880
|
+
if (k === 'window' || k === 'self' || k === 'frames') return openerHandle;
|
|
881
|
+
if (k === 'location') return openerLoc;
|
|
882
|
+
if (k === 'focus' || k === 'blur') return () => {};
|
|
883
|
+
if (k === 'then') return undefined;
|
|
884
|
+
if (!sameAsOpener()) throw securityError();
|
|
885
|
+
return (...args) => call(k, args);
|
|
886
|
+
},
|
|
887
|
+
set(_t, k, v) { if (k === 'location') { openerLoc.href = v; return true; } call(String(k), [v], true); return true; },
|
|
888
|
+
});
|
|
889
|
+
try { Object.defineProperty(window, 'opener', { get: () => openerHandle, set: () => {}, configurable: true }); } catch (_) {}
|
|
890
|
+
// This tab was opened by the extension, not by a script, so the page's own window.close()
|
|
891
|
+
// would be ignored. Ask the extension to close it, as the real popup would close.
|
|
892
|
+
try { Object.defineProperty(window, 'close', { value: asNative('close', () => send({ kind: 'bridge.selfClose', id: BRIDGE.id })), writable: true, configurable: true }); } catch (_) {}
|
|
893
|
+
}
|
|
894
|
+
})();`;
|
|
895
|
+
|
|
896
|
+
async function attach(s, tabId, bridge = null) {
|
|
897
|
+
// Edge puts hidden tabs to sleep and discards them; a discarded tab comes back under a new id
|
|
898
|
+
// with the page reloaded (2026-11-16, Edge 157: a recording failed with "No tab with given id"
|
|
899
|
+
// 14 minutes in, tab_stats.discards_frozen 2). Agent tabs are never in front, so they are the
|
|
900
|
+
// first to go. Keep them out of automatic discarding; onReplaced covers whatever still swaps.
|
|
901
|
+
try { await chrome.tabs.update(tabId, { autoDiscardable: false }); } catch { /* tab gone */ }
|
|
902
|
+
await chrome.debugger.attach({ tabId }, '1.3');
|
|
903
|
+
const dbg = (m, p) => chrome.debugger.sendCommand({ tabId }, m, p || {});
|
|
904
|
+
await dbg('Runtime.enable');
|
|
905
|
+
await dbg('Runtime.addBinding', { name: OPEN_BINDING });
|
|
906
|
+
await dbg('Page.enable');
|
|
907
|
+
await dbg('Page.addScriptToEvaluateOnNewDocument', { source: popupGuardSrc(await popupToken, bridge), runImmediately: true });
|
|
908
|
+
emit('debugger.attached', { sessionId: s.id, tabId });
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// Tabs the user is about to open from a session tab (opener tab id -> deadline). Those are theirs:
|
|
912
|
+
// not adopted, not counted against the budget, never closed.
|
|
913
|
+
const userOpens = new Map();
|
|
914
|
+
const USER_OPEN_GRACE_MS = 3000;
|
|
915
|
+
|
|
916
|
+
// Popups the agent caused, opened as inactive session tabs: bridge id -> { s, opener, popup }.
|
|
917
|
+
// A popup opened from a click (a sign-in button) is part of the flow that opened it, so it may go
|
|
918
|
+
// up to two tabs over budget. Popups a script opens without a gesture get the plain budget.
|
|
919
|
+
const bridges = new Map();
|
|
920
|
+
const BRIDGE_EXTRA_TABS = 2;
|
|
921
|
+
|
|
922
|
+
/** Sends a message to the popup guard in a tab (handlers in popupGuardSrc). */
|
|
923
|
+
async function toGuard(tabId, msg) {
|
|
924
|
+
const token = await popupToken;
|
|
925
|
+
try {
|
|
926
|
+
await chrome.debugger.sendCommand({ tabId }, 'Runtime.evaluate', {
|
|
927
|
+
expression: `dispatchEvent(new CustomEvent(${JSON.stringify(token + 'm')}, { detail: ${JSON.stringify(JSON.stringify(msg))} }))`, silent: true,
|
|
928
|
+
});
|
|
929
|
+
} catch { /* tab gone or navigating */ }
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
const originOf = (url) => { try { return new URL(url).origin; } catch { return 'null'; } };
|
|
933
|
+
async function tabOrigin(tabId) { try { return originOf((await chrome.tabs.get(tabId)).url); } catch { return 'null'; } }
|
|
934
|
+
// postMessage delivery rule: '*' anywhere, '/' only to the sender's own origin, else exact match.
|
|
935
|
+
const originAllows = (targetOrigin, senderOrigin, receiverOrigin) =>
|
|
936
|
+
targetOrigin === '*' || (targetOrigin === '/' ? senderOrigin === receiverOrigin : originOf(targetOrigin) === receiverOrigin);
|
|
937
|
+
|
|
938
|
+
async function openBridgedPopup(s, openerTabId, url, id, name, gesture) {
|
|
939
|
+
if (isUrlBlocked(url)) { emit('tab.rejected', { sessionId: s.id, reason: `blocked by guard: ${url}`, url, openerTabId }); await toGuard(openerTabId, { kind: 'bridge.state', id, closed: true }); return; }
|
|
940
|
+
if (s.tabIds.size + (s.pending || 0) >= s.budget + (gesture ? BRIDGE_EXTRA_TABS : 0)) {
|
|
941
|
+
emit('tab.rejected', { sessionId: s.id, reason: `tab budget (${s.budget}) reached`, url, openerTabId });
|
|
942
|
+
await toGuard(openerTabId, { kind: 'bridge.state', id, closed: true });
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
s.pending = (s.pending || 0) + 1;
|
|
946
|
+
try {
|
|
947
|
+
const owned = await chrome.tabs.query({ windowId: s.windowId, groupId: s.groupId });
|
|
948
|
+
const index = owned.length ? Math.max(...owned.map((t) => t.index)) + 1 : undefined;
|
|
949
|
+
// Blank first, so the stand-in opener is in place before the first page of the popup runs.
|
|
950
|
+
const tab = await chrome.tabs.create({ windowId: s.windowId, url: 'about:blank', active: false, index });
|
|
951
|
+
bridges.set(id, { s, opener: openerTabId, popup: tab.id });
|
|
952
|
+
await adoptTab(s, tab.id, 'agent-popup', { id, name, openerOrigin: await tabOrigin(openerTabId) });
|
|
953
|
+
await chrome.tabs.update(tab.id, { url });
|
|
954
|
+
emit('tab.agentPopup', { sessionId: s.id, tabId: tab.id, openerTabId, url });
|
|
955
|
+
} catch (e) {
|
|
956
|
+
bridges.delete(id);
|
|
957
|
+
emit('tab.rejected', { sessionId: s.id, reason: String(e.message), url, openerTabId });
|
|
958
|
+
await toGuard(openerTabId, { kind: 'bridge.state', id, closed: true });
|
|
959
|
+
} finally {
|
|
960
|
+
s.pending--;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
async function onBridgeMessage(s, fromTabId, m) {
|
|
965
|
+
const b = bridges.get(m.id);
|
|
966
|
+
if (!b || b.s !== s) return;
|
|
967
|
+
const fromOpener = fromTabId === b.opener, fromPopup = fromTabId === b.popup;
|
|
968
|
+
switch (m.kind) {
|
|
969
|
+
case 'bridge.close': if (fromOpener) { try { await chrome.tabs.remove(b.popup); } catch { /* gone */ } } return;
|
|
970
|
+
case 'bridge.selfClose': if (fromPopup) { try { await chrome.tabs.remove(b.popup); } catch { /* gone */ } } return;
|
|
971
|
+
case 'bridge.navigate': if (fromOpener && !isUrlBlocked(m.url)) { try { await chrome.tabs.update(b.popup, { url: m.url }); } catch { /* gone */ } } return;
|
|
972
|
+
case 'bridge.toPopup': {
|
|
973
|
+
if (!fromOpener) return;
|
|
974
|
+
const from = await tabOrigin(b.opener), to = await tabOrigin(b.popup);
|
|
975
|
+
if (originAllows(m.targetOrigin, from, to)) await toGuard(b.popup, { kind: 'bridge.message', id: m.id, data: m.data, origin: from });
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
case 'bridge.fromPopup': {
|
|
979
|
+
if (!fromPopup) return;
|
|
980
|
+
const from = await tabOrigin(b.popup), to = await tabOrigin(b.opener);
|
|
981
|
+
if (originAllows(m.targetOrigin, from, to)) await toGuard(b.opener, { kind: 'bridge.message', id: m.id, data: m.data, origin: from });
|
|
982
|
+
emit('bridge.message', { sessionId: s.id, from: b.popup, to: b.opener, delivered: originAllows(m.targetOrigin, from, to) });
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
case 'bridge.callOpener': {
|
|
986
|
+
if (!fromPopup) return;
|
|
987
|
+
if (await tabOrigin(b.popup) !== await tabOrigin(b.opener)) return;
|
|
988
|
+
await toGuard(b.opener, { kind: 'bridge.call', id: m.id, path: m.path, args: m.args, set: m.set, origin: m.origin });
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
async function onRerouteOpen(s, fromTabId, payload) {
|
|
995
|
+
let m = {};
|
|
996
|
+
try { m = JSON.parse(payload) || {}; } catch { /* ignore */ }
|
|
997
|
+
if (typeof m.kind === 'string' && m.kind.startsWith('bridge.')) return onBridgeMessage(s, fromTabId, m);
|
|
998
|
+
const url = m.url || 'about:blank';
|
|
999
|
+
if (m.user === true) {
|
|
1000
|
+
userOpens.set(fromTabId, Date.now() + USER_OPEN_GRACE_MS);
|
|
1001
|
+
emit('tab.userOpening', { sessionId: s.id, openerTabId: fromTabId, url });
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
if (typeof m.bridge === 'string') return openBridgedPopup(s, fromTabId, url, m.bridge, m.name || '', m.gesture === true);
|
|
1005
|
+
if (isUrlBlocked(url)) { emit('tab.rejected', { sessionId: s.id, reason: `blocked by guard: ${url}`, url, openerTabId: fromTabId }); return; }
|
|
1006
|
+
if (s.tabIds.size + (s.pending || 0) >= s.budget) { emit('tab.rejected', { sessionId: s.id, reason: `tab budget (${s.budget}) reached`, url, openerTabId: fromTabId }); return; }
|
|
1007
|
+
try { await createTab(s, url); } catch (e) { emit('tab.rejected', { sessionId: s.id, reason: String(e.message), url, openerTabId: fromTabId }); }
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
// The popup's address and closing are pushed to the opener, which reads them synchronously
|
|
1011
|
+
// from the stand-in (popup.closed, popup.location.href once it is back on the same origin).
|
|
1012
|
+
chrome.tabs.onUpdated.addListener(async (tabId, info) => {
|
|
1013
|
+
if (!info.url) return;
|
|
1014
|
+
for (const [id, b] of bridges) if (b.popup === tabId) await toGuard(b.opener, { kind: 'bridge.state', id, href: info.url });
|
|
1015
|
+
});
|
|
1016
|
+
chrome.tabs.onRemoved.addListener(async (tabId) => {
|
|
1017
|
+
for (const [id, b] of bridges) {
|
|
1018
|
+
if (b.popup === tabId) { bridges.delete(id); await toGuard(b.opener, { kind: 'bridge.state', id, closed: true }); }
|
|
1019
|
+
else if (b.opener === tabId) bridges.delete(id);
|
|
1020
|
+
}
|
|
1021
|
+
});
|
|
1022
|
+
|
|
1023
|
+
// What counts as acting on the page, and so is refused while the user holds the session.
|
|
1024
|
+
// Reading — evaluating, snapshotting, screenshotting — stays allowed, so an agent can still
|
|
1025
|
+
// look and report while it waits.
|
|
1026
|
+
const CHANGES_THE_PAGE = [
|
|
1027
|
+
/^Input\./,
|
|
1028
|
+
/^Page\.(navigate|reload|navigateToHistoryEntry|handleJavaScriptDialog|setDownloadBehavior)/,
|
|
1029
|
+
/^DOM\.(setFileInputFiles|focus|setAttributeValue|setOuterHTML|removeNode)/,
|
|
1030
|
+
/^Emulation\.set(Device|Geolocation|UserAgent|Timezone)/,
|
|
1031
|
+
/^Network\.(setCookie|deleteCookies|setExtraHTTPHeaders|emulateNetworkConditions)/,
|
|
1032
|
+
];
|
|
1033
|
+
|
|
1034
|
+
async function cdp({ sessionId, tabId, targetId, method, params }) {
|
|
1035
|
+
const s = sessionOf(sessionId);
|
|
1036
|
+
let debuggee, label;
|
|
1037
|
+
if (targetId) {
|
|
1038
|
+
// Out-of-process iframe: its own debuggee, attached through frames.discover below.
|
|
1039
|
+
if (!s.frameTargets?.has(targetId)) throw new Error(`frame target ${targetId} not owned by session ${sessionId}`);
|
|
1040
|
+
debuggee = { targetId };
|
|
1041
|
+
label = `frame ${targetId.slice(0, 8)}`;
|
|
1042
|
+
} else {
|
|
1043
|
+
const target = tabId ?? [...s.tabIds][0];
|
|
1044
|
+
if (!s.tabIds.has(target)) throw new Error(`tab ${target} not owned by session ${sessionId}`);
|
|
1045
|
+
debuggee = { tabId: target };
|
|
1046
|
+
label = `tab ${target}`;
|
|
1047
|
+
}
|
|
1048
|
+
// While the user holds control, the agent may keep looking but must not touch. Reads go
|
|
1049
|
+
// through so it can still report what is on screen; anything that changes the page is refused
|
|
1050
|
+
// with a message the runtime turns into a typed error.
|
|
1051
|
+
if (s.paused && CHANGES_THE_PAGE.some((re) => re.test(method))) {
|
|
1052
|
+
emit('session.blocked', { sessionId, method });
|
|
1053
|
+
throw new Error(`session paused: the user has control of "${s.name}". Stop acting and report; they hand control back with the button on the page.`);
|
|
1054
|
+
}
|
|
1055
|
+
const problem = checkCommand(method, params);
|
|
1056
|
+
if (problem) { emit('guard.blocked', { sessionId, method, reason: problem }); throw new Error(problem); }
|
|
1057
|
+
if (!targetId && startsGesture(method, params)) await markAgentGesture(debuggee);
|
|
1058
|
+
const t0 = Date.now();
|
|
1059
|
+
emit('debug.cdp', { phase: 'start', sessionId, method, label, workerStartedAt: WORKER_STARTED_AT });
|
|
1060
|
+
try {
|
|
1061
|
+
const r = await chrome.debugger.sendCommand(debuggee, method, params || {});
|
|
1062
|
+
emit('debug.cdp', { phase: 'end', sessionId, method, label, ms: Date.now() - t0 });
|
|
1063
|
+
if (!targetId) rememberEmulation(s, debuggee.tabId, method, params);
|
|
1064
|
+
return r;
|
|
1065
|
+
} catch (e) {
|
|
1066
|
+
emit('debug.cdp', { phase: 'error', sessionId, method, label, ms: Date.now() - t0, error: String(e?.message || e) });
|
|
1067
|
+
throw e;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// The emulated screen size each session tab was given, whoever set it (Session.setViewport, or a
|
|
1072
|
+
// script sending Emulation.setDeviceMetricsOverride itself, as demo-video does). A tab that has
|
|
1073
|
+
// been the window's front tab keeps recording at the tab area after it goes behind again, until
|
|
1074
|
+
// the emulation is set again (2026-11-16, Chrome for Testing 1255: 1200×600 after, 1792×848 once
|
|
1075
|
+
// re-applied); and a tab the browser swapped in starts with none. Both get it back from here.
|
|
1076
|
+
function rememberEmulation(s, tabId, method, params) {
|
|
1077
|
+
if (method === 'Emulation.setDeviceMetricsOverride') (s.emulation = s.emulation || new Map()).set(tabId, params || {});
|
|
1078
|
+
else if (method === 'Emulation.clearDeviceMetricsOverride') s.emulation?.delete(tabId);
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
async function reapplyEmulation(s, tabId) {
|
|
1082
|
+
const params = s.emulation?.get(tabId);
|
|
1083
|
+
if (!params) return;
|
|
1084
|
+
try {
|
|
1085
|
+
await chrome.debugger.sendCommand({ tabId }, 'Emulation.clearDeviceMetricsOverride', {});
|
|
1086
|
+
await chrome.debugger.sendCommand({ tabId }, 'Emulation.setDeviceMetricsOverride', params);
|
|
1087
|
+
} catch { /* tab gone or not attached */ }
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// Input that starts a gesture (and so can grant the page transient activation to open a popup).
|
|
1091
|
+
function startsGesture(method, params) {
|
|
1092
|
+
if (method === 'Input.dispatchMouseEvent') return params?.type === 'mousePressed';
|
|
1093
|
+
if (method === 'Input.dispatchKeyEvent') return params?.type === 'keyDown' || params?.type === 'rawKeyDown';
|
|
1094
|
+
if (method === 'Input.dispatchTouchEvent') return params?.type === 'touchStart';
|
|
1095
|
+
return false;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// Tells the page's popup guard that the next gesture is the agent's (see popupGuardSrc).
|
|
1099
|
+
async function markAgentGesture(debuggee) {
|
|
1100
|
+
const token = await popupToken;
|
|
1101
|
+
try {
|
|
1102
|
+
await chrome.debugger.sendCommand(debuggee, 'Runtime.evaluate', { expression: `dispatchEvent(new Event(${JSON.stringify(token)}))`, silent: true });
|
|
1103
|
+
} catch { /* page navigating; the guard then treats the gesture as the user's only if it has activation */ }
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
// Out-of-process iframes are invisible to the tab's CDP session (they are separate targets and
|
|
1107
|
+
// do not appear in Page.getFrameTree). chrome.debugger.getTargets() does list them, so we attach
|
|
1108
|
+
// to them directly — no Target.* command is needed, which keeps that whole domain blocked.
|
|
1109
|
+
// Candidates are matched against iframe URLs the runtime found inside tabs this session owns,
|
|
1110
|
+
// and verified by frame id after attaching, so another tab's frames are never touched.
|
|
1111
|
+
async function discoverFrames({ sessionId, urls = [] }) {
|
|
1112
|
+
const s = sessionOf(sessionId);
|
|
1113
|
+
s.frameTargets ??= new Map();
|
|
1114
|
+
const wanted = new Set(urls);
|
|
1115
|
+
const found = [];
|
|
1116
|
+
for (const [targetId, info] of s.frameTargets) found.push({ targetId, ...info });
|
|
1117
|
+
const targets = await chrome.debugger.getTargets();
|
|
1118
|
+
for (const t of targets) {
|
|
1119
|
+
if (t.type === 'page' || t.tabId !== undefined) continue;
|
|
1120
|
+
if (!wanted.has(t.url) || s.frameTargets.has(t.id)) continue;
|
|
1121
|
+
if (t.attached) continue;
|
|
1122
|
+
try {
|
|
1123
|
+
await chrome.debugger.attach({ targetId: t.id }, '1.3');
|
|
1124
|
+
const tree = await chrome.debugger.sendCommand({ targetId: t.id }, 'Page.getFrameTree');
|
|
1125
|
+
const frameId = tree?.frameTree?.frame?.id;
|
|
1126
|
+
s.frameTargets.set(t.id, { frameId, url: t.url });
|
|
1127
|
+
await chrome.debugger.sendCommand({ targetId: t.id }, 'Page.enable');
|
|
1128
|
+
await chrome.debugger.sendCommand({ targetId: t.id }, 'Runtime.enable');
|
|
1129
|
+
await chrome.debugger.sendCommand({ targetId: t.id }, 'DOM.enable');
|
|
1130
|
+
// Without this the frame's document never counts as focused, so focus() inside it is a
|
|
1131
|
+
// no-op and typing goes nowhere.
|
|
1132
|
+
await chrome.debugger.sendCommand({ targetId: t.id }, 'Emulation.setFocusEmulationEnabled', { enabled: true }).catch(() => {});
|
|
1133
|
+
found.push({ targetId: t.id, frameId, url: t.url });
|
|
1134
|
+
emit('frame.attached', { sessionId, targetId: t.id, frameId, url: t.url });
|
|
1135
|
+
} catch (e) {
|
|
1136
|
+
emit('frame.attachFailed', { sessionId, targetId: t.id, url: t.url, error: String(e?.message || e) });
|
|
1137
|
+
try { await chrome.debugger.detach({ targetId: t.id }); } catch { /* ignore */ }
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
return { frames: found };
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
chrome.debugger.onEvent.addListener((source, method, params) => {
|
|
1144
|
+
if (source.targetId && !source.tabId) {
|
|
1145
|
+
const fs = sessionByTarget(source.targetId);
|
|
1146
|
+
if (fs) emit('cdp.event', { sessionId: fs.id, targetId: source.targetId, method, params });
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
const s = sessionByTab(source.tabId);
|
|
1150
|
+
if (!s) return;
|
|
1151
|
+
if (method === 'Runtime.bindingCalled' && params.name === OPEN_BINDING) { onRerouteOpen(s, source.tabId, params.payload); return; }
|
|
1152
|
+
emit('cdp.event', { sessionId: s.id, tabId: source.tabId, method, params });
|
|
1153
|
+
});
|
|
1154
|
+
|
|
1155
|
+
chrome.debugger.onDetach.addListener(async (source, reason) => {
|
|
1156
|
+
if (source.targetId && !source.tabId) {
|
|
1157
|
+
const fs = sessionByTarget(source.targetId);
|
|
1158
|
+
if (fs) { fs.frameTargets.delete(source.targetId); emit('frame.detached', { sessionId: fs.id, targetId: source.targetId, reason }); }
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
const s = sessionByTab(source.tabId);
|
|
1162
|
+
if (!s) return;
|
|
1163
|
+
// 'canceled_by_user' = the user clicked "Cancel" on the debugging infobar: treat as takeover.
|
|
1164
|
+
if (reason === 'canceled_by_user') await takeover(s, source.tabId, 'infobar_cancel');
|
|
1165
|
+
emit('debugger.detached', { sessionId: s.id, tabId: source.tabId, reason });
|
|
1166
|
+
});
|
|
1167
|
+
|
|
1168
|
+
// ---------- tab / window lifecycle ----------
|
|
1169
|
+
|
|
1170
|
+
chrome.tabs.onCreated.addListener(async (tab) => {
|
|
1171
|
+
await ready;
|
|
1172
|
+
// A tab opened *by* an agent tab belongs to that session. Tabs appearing in a session-owned
|
|
1173
|
+
// window (placement 'window') are adopted too. Anything else (e.g. the user opening a tab in
|
|
1174
|
+
// the agent window by hand) is left alone.
|
|
1175
|
+
const s = (tab.openerTabId && sessionByTab(tab.openerTabId)) || sessionByWindow(tab.windowId);
|
|
1176
|
+
if (!s || s.tabIds.has(tab.id)) return;
|
|
1177
|
+
// The extension is creating a tab for this session right now (createTab, a bridged popup) and
|
|
1178
|
+
// adopts it itself, with the right guard. Adopting it here first would race that.
|
|
1179
|
+
if (!tab.openerTabId && s.pending > 0) return;
|
|
1180
|
+
if (tab.openerTabId && sessionByTab(tab.openerTabId)) {
|
|
1181
|
+
// The guard's note that the user opened it may land a moment after the tab itself.
|
|
1182
|
+
for (let i = 0; i < 6 && !(userOpens.get(tab.openerTabId) > Date.now()); i++) await new Promise((r) => setTimeout(r, 50));
|
|
1183
|
+
if (userOpens.get(tab.openerTabId) > Date.now()) {
|
|
1184
|
+
userOpens.delete(tab.openerTabId);
|
|
1185
|
+
emit('tab.userOpened', { sessionId: s.id, tabId: tab.id, openerTabId: tab.openerTabId, url: tab.pendingUrl || tab.url });
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
if (s.tabIds.size >= s.budget) {
|
|
1190
|
+
try { await chrome.tabs.remove(tab.id); } catch { /* ignore */ }
|
|
1191
|
+
emit('tab.rejected', { sessionId: s.id, tabId: tab.id, reason: `tab budget (${s.budget}) reached`, url: tab.pendingUrl || tab.url });
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
await adoptTab(s, tab.id, 'page');
|
|
1195
|
+
});
|
|
1196
|
+
|
|
1197
|
+
chrome.tabs.onUpdated.addListener(async (tabId, info) => {
|
|
1198
|
+
await ready;
|
|
1199
|
+
const s = sessionByTab(tabId);
|
|
1200
|
+
if (!s) return;
|
|
1201
|
+
if (info.url) { s.urls[tabId] = info.url; await saveState(); }
|
|
1202
|
+
if (info.status === 'loading' || info.status === 'complete') paintOverlay(s, tabId);
|
|
1203
|
+
// The browser freezing or discarding a session tab on its own (Edge does it to hidden tabs). A
|
|
1204
|
+
// frozen page does not run script, so CDP calls into it wait until it thaws; the daemon's event
|
|
1205
|
+
// log keeps these so a timeout can be matched to a freeze.
|
|
1206
|
+
if (info.frozen !== undefined || info.discarded !== undefined) {
|
|
1207
|
+
emit('tab.lifecycle', { sessionId: s.id, tabId, frozen: info.frozen, discarded: info.discarded });
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
|
|
1211
|
+
// Looking is not taking over: focusing the agent window or switching to one of its tabs only
|
|
1212
|
+
// reports that the user is watching. A session pauses when the user actually types, clicks or
|
|
1213
|
+
// clicks Cancel on the debugging bar, or uses
|
|
1214
|
+
// the dashboard.
|
|
1215
|
+
chrome.tabs.onActivated.addListener(async ({ tabId, windowId }) => {
|
|
1216
|
+
await ready;
|
|
1217
|
+
const s = sessionByTab(tabId);
|
|
1218
|
+
if (!s) return;
|
|
1219
|
+
if (Date.now() - recentlyRemovedAt < 1000) return;
|
|
1220
|
+
emit('session.watched', { sessionId: s.id, tabId, windowId, via: 'tab_activated' });
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
chrome.windows.onFocusChanged.addListener(async (windowId) => {
|
|
1224
|
+
await ready;
|
|
1225
|
+
if (windowId !== agentWindowId) await keepBlankInFront(agentWindowId); // the user left the agent window
|
|
1226
|
+
if (windowId === chrome.windows.WINDOW_ID_NONE || !isAgentWindow(windowId)) return;
|
|
1227
|
+
const [active] = await chrome.tabs.query({ windowId, active: true });
|
|
1228
|
+
const s = active && sessionByTab(active.id);
|
|
1229
|
+
if (s) emit('session.watched', { sessionId: s.id, tabId: active.id, windowId, via: 'window_focus' });
|
|
1230
|
+
});
|
|
1231
|
+
|
|
1232
|
+
chrome.tabs.onRemoved.addListener(async (tabId) => {
|
|
1233
|
+
await ready;
|
|
1234
|
+
const s = sessionByTab(tabId);
|
|
1235
|
+
if (!s) return;
|
|
1236
|
+
recentlyRemovedAt = Date.now();
|
|
1237
|
+
s.tabIds.delete(tabId);
|
|
1238
|
+
delete s.urls[tabId];
|
|
1239
|
+
emit('tab.closed', { sessionId: s.id, tabId });
|
|
1240
|
+
if (s.tabIds.size === 0) { sessions.delete(s.id); emit('session.closed', { sessionId: s.id, reason: 'all_tabs_closed' }); }
|
|
1241
|
+
await saveState();
|
|
1242
|
+
await keepBlankInFront(s.windowId); // Edge fronts a neighbour, which may be another session's tab
|
|
1243
|
+
});
|
|
1244
|
+
|
|
1245
|
+
// The browser swapped a tab for another with a new id: a discarded tab brought back, a prerendered
|
|
1246
|
+
// page taking over. Nothing was closed, and no onRemoved comes, so without this the session keeps
|
|
1247
|
+
// the dead id and every call fails with "No tab with given id". The new tab joins the session in
|
|
1248
|
+
// its place, the debugger is attached again, and the old id keeps working as an alias for callers
|
|
1249
|
+
// that still hold it. The page was reloaded, so CDP state (emulation, enabled domains) is gone:
|
|
1250
|
+
// the runtime re-applies it on tab.replaced.
|
|
1251
|
+
chrome.tabs.onReplaced.addListener(async (addedTabId, removedTabId) => {
|
|
1252
|
+
await ready;
|
|
1253
|
+
const s = sessionByTab(removedTabId);
|
|
1254
|
+
if (!s) return;
|
|
1255
|
+
s.tabIds.delete(removedTabId);
|
|
1256
|
+
s.tabIds.add(addedTabId);
|
|
1257
|
+
if (s.urls[removedTabId]) { s.urls[addedTabId] = s.urls[removedTabId]; delete s.urls[removedTabId]; }
|
|
1258
|
+
s.aliases = s.aliases || new Map();
|
|
1259
|
+
for (const [from, to] of s.aliases) if (to === removedTabId) s.aliases.set(from, addedTabId);
|
|
1260
|
+
s.aliases.set(removedTabId, addedTabId);
|
|
1261
|
+
try { await chrome.tabs.group({ tabIds: [addedTabId], groupId: s.groupId }); } catch { /* group gone */ }
|
|
1262
|
+
try { await attach(s, addedTabId); } catch { /* another debugger may hold it */ }
|
|
1263
|
+
if (s.emulation?.has(removedTabId)) { s.emulation.set(addedTabId, s.emulation.get(removedTabId)); s.emulation.delete(removedTabId); }
|
|
1264
|
+
await reapplyEmulation(s, addedTabId);
|
|
1265
|
+
paintOverlay(s, addedTabId);
|
|
1266
|
+
await saveState();
|
|
1267
|
+
emit('tab.replaced', { sessionId: s.id, oldTabId: removedTabId, tabId: addedTabId });
|
|
1268
|
+
});
|
|
1269
|
+
|
|
1270
|
+
chrome.windows.onRemoved.addListener(async (windowId) => {
|
|
1271
|
+
await ready;
|
|
1272
|
+
if (windowId === agentWindowId) { agentWindowId = null; emit('agentWindow.closed', { windowId }); }
|
|
1273
|
+
const s = sessionByWindow(windowId);
|
|
1274
|
+
if (s) { sessions.delete(s.id); emit('session.closed', { sessionId: s.id, reason: 'window_closed' }); }
|
|
1275
|
+
await saveState();
|
|
1276
|
+
});
|
|
1277
|
+
|
|
1278
|
+
// An agent tab dragged into a user window is released to the user.
|
|
1279
|
+
chrome.tabs.onAttached.addListener(async (tabId, info) => {
|
|
1280
|
+
await ready;
|
|
1281
|
+
const from = sessionByTab(tabId);
|
|
1282
|
+
if (from && !isAgentWindow(info.newWindowId) && from.placement !== 'group') {
|
|
1283
|
+
from.tabIds.delete(tabId);
|
|
1284
|
+
try { await chrome.debugger.detach({ tabId }); } catch { /* ignore */ }
|
|
1285
|
+
await saveState();
|
|
1286
|
+
emit('tab.released', { sessionId: from.id, tabId, reason: 'moved_to_user_window' });
|
|
1287
|
+
}
|
|
1288
|
+
});
|
|
1289
|
+
|
|
1290
|
+
// Dashboard popup (popup.js). The kill switch lives inside it; no keyboard shortcut on purpose.
|
|
1291
|
+
chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
|
|
1292
|
+
(async () => {
|
|
1293
|
+
await ready;
|
|
1294
|
+
switch (msg.type) {
|
|
1295
|
+
case 'state': {
|
|
1296
|
+
const out = [];
|
|
1297
|
+
for (const s of sessions.values()) {
|
|
1298
|
+
const tabs = [];
|
|
1299
|
+
for (const tabId of s.tabIds) { const t = await chrome.tabs.get(tabId).catch(() => null); if (t) tabs.push({ tabId, title: t.title, url: t.url }); }
|
|
1300
|
+
out.push({ ...serializeSession(s), tabs });
|
|
1301
|
+
}
|
|
1302
|
+
return { relayConnected: !!ws && ws.readyState === WebSocket.OPEN, agentWindowId, sessions: out };
|
|
1303
|
+
}
|
|
1304
|
+
case 'pause': { const s = sessionOf(msg.sessionId); s.pausedBy = 'user'; await setStatus(s, s.status, true); emit('session.takeover', { sessionId: s.id, via: 'dashboard' }); return {}; }
|
|
1305
|
+
case 'resume': { const s = sessionOf(msg.sessionId); await setStatus(s, s.status, false); emit('session.resumed', { sessionId: s.id, via: 'dashboard' }); return {}; }
|
|
1306
|
+
case 'overlayAction': {
|
|
1307
|
+
// The button on the in-page overlay: the explicit way to take control and give it back.
|
|
1308
|
+
const s = sessionOf(msg.sessionId);
|
|
1309
|
+
const pause = msg.action !== 'resume';
|
|
1310
|
+
s.pausedBy = pause ? 'user' : null;
|
|
1311
|
+
await setStatus(s, s.status, pause);
|
|
1312
|
+
emit(pause ? 'session.takeover' : 'session.resumed', { sessionId: s.id, via: 'overlay_button' });
|
|
1313
|
+
return { paused: pause };
|
|
1314
|
+
}
|
|
1315
|
+
case 'close': return closeSession(msg.sessionId, 'dashboard');
|
|
1316
|
+
case 'panic': return panic('dashboard');
|
|
1317
|
+
default: throw new Error(`unknown message ${msg.type}`);
|
|
1318
|
+
}
|
|
1319
|
+
})().then(reply, (e) => reply({ error: String(e.message || e) }));
|
|
1320
|
+
return true; // async reply
|
|
1321
|
+
});
|
|
1322
|
+
|
|
1323
|
+
// ---------- keepalive ----------
|
|
1324
|
+
|
|
1325
|
+
chrome.alarms.create('keepalive', { periodInMinutes: 0.5 });
|
|
1326
|
+
chrome.alarms.onAlarm.addListener((a) => { if (a.name === 'keepalive') connect(); });
|
|
1327
|
+
|
|
1328
|
+
const ready = Promise.all([restoreState(), config]).then(() => {});
|
|
1329
|
+
ready.then(connect);
|