dsh-embedded-browser-next 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.en.md +275 -0
- package/README.md +274 -2
- package/cordis.patch.yml +16 -0
- package/lib/browser.js +2634 -0
- package/lib/cdp.js +320 -0
- package/lib/client.js +3991 -0
- package/lib/diagnostics.js +48 -0
- package/lib/downloads.js +73 -0
- package/lib/external.js +96 -0
- package/lib/human.js +145 -0
- package/lib/index.js +609 -0
- package/lib/lazy.js +193 -0
- package/lib/mjpeg.js +154 -0
- package/lib/paths.js +107 -0
- package/lib/residency.js +234 -0
- package/lib/router.js +687 -0
- package/lib/routes.js +446 -0
- package/lib/screencast.js +1629 -0
- package/lib/snapshot-window.js +73 -0
- package/lib/tools.js +740 -0
- package/lib/ws.js +253 -0
- package/package.json +60 -4
package/lib/router.js
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route tool calls to the browser the human is actually looking at.
|
|
3
|
+
*
|
|
4
|
+
* There are two browsers in a session and only one of them is honest:
|
|
5
|
+
*
|
|
6
|
+
* - the **native guest** inside the panel, which is a real Chromium window: sites
|
|
7
|
+
* treat it as a person, its logins are the human's logins, and every pixel the
|
|
8
|
+
* human sees is proof the agent is on the same page;
|
|
9
|
+
* - the **headless tab**, which is fast and always available, but is invisible,
|
|
10
|
+
* keeps its own (empty) login state, and gets stopped by bot checks — Baidu
|
|
11
|
+
* answers a plain search with a slider CAPTCHA.
|
|
12
|
+
*
|
|
13
|
+
* The native one wins whenever it is mounted. Everything the guest cannot do (file
|
|
14
|
+
* pickers, downloads, tab management, dialog inspection) still falls through to the
|
|
15
|
+
* headless tab, because those paths are not about *seeing* a page.
|
|
16
|
+
*
|
|
17
|
+
* The shapes returned here are deliberately identical in both branches: the tool
|
|
18
|
+
* layer must not be able to tell which browser answered.
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-embedded-browser/router
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { readFile } from 'node:fs/promises'
|
|
24
|
+
import { basename, extname } from 'node:path'
|
|
25
|
+
import { downloadDir, saveDownload } from './downloads.js'
|
|
26
|
+
|
|
27
|
+
/** The panel's way of saying "I don't implement that", which is safe to retry. */
|
|
28
|
+
const UNSUPPORTED = /^guest cannot do /i
|
|
29
|
+
|
|
30
|
+
/** Uploads travel over the WebSocket as base64, so they get a ceiling. */
|
|
31
|
+
const MAX_UPLOAD_BYTES = 16 * 1024 * 1024
|
|
32
|
+
|
|
33
|
+
/** Just enough MIME guessing for a file input to see a believable type. */
|
|
34
|
+
const UPLOAD_TYPES = {
|
|
35
|
+
'.json': 'application/json',
|
|
36
|
+
'.txt': 'text/plain',
|
|
37
|
+
'.csv': 'text/csv',
|
|
38
|
+
'.html': 'text/html',
|
|
39
|
+
'.md': 'text/markdown',
|
|
40
|
+
'.png': 'image/png',
|
|
41
|
+
'.jpg': 'image/jpeg',
|
|
42
|
+
'.jpeg': 'image/jpeg',
|
|
43
|
+
'.gif': 'image/gif',
|
|
44
|
+
'.webp': 'image/webp',
|
|
45
|
+
'.pdf': 'application/pdf',
|
|
46
|
+
'.zip': 'application/zip',
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Build the manager-shaped router handed to the tool layer.
|
|
51
|
+
*
|
|
52
|
+
* @param options - `manager` (CDP backend), `hub` (guest RPC), `logger`.
|
|
53
|
+
* @returns an object with the same method surface as {@link BrowserManager}.
|
|
54
|
+
*/
|
|
55
|
+
export function createBrowserRouter({ manager, hub, logger }) {
|
|
56
|
+
const guestReady = (sessionId) => {
|
|
57
|
+
if (typeof sessionId !== 'string' || sessionId === '') return false
|
|
58
|
+
// `off` is the deployment saying "nothing here is ever looked at": honour it
|
|
59
|
+
// even when a panel happens to be mounted, or the setting would only be
|
|
60
|
+
// advisory.
|
|
61
|
+
if (hub?.residency?.mode === 'off') return false
|
|
62
|
+
return hub?.guestAvailable?.(sessionId) === true
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Normalize a target.
|
|
67
|
+
*
|
|
68
|
+
* The tool layer passes either `{ index }`/`{ selector }` (via `targetOf`) or a
|
|
69
|
+
* bare index. Spreading a number yields `{}` — which silently produced "name the
|
|
70
|
+
* element with index" for a call that *did* name an index.
|
|
71
|
+
*/
|
|
72
|
+
const asTarget = (target) => {
|
|
73
|
+
if (typeof target === 'number') return { index: target }
|
|
74
|
+
if (target !== null && typeof target === 'object') return { ...target }
|
|
75
|
+
return {}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Which surface the tools are answering from, in one word.
|
|
80
|
+
*
|
|
81
|
+
* - `sidebar` / `float` — a panel is connected and reported where it sits.
|
|
82
|
+
* - `window` — no panel, but the browser itself is a visible OS window (headed).
|
|
83
|
+
* - `headless` — nothing on screen; the page lives in an invisible tab.
|
|
84
|
+
*
|
|
85
|
+
* This is a fact about *where the human can see the page*, which is what the
|
|
86
|
+
* model needs before deciding to hand over, to keep working, or to ask for the
|
|
87
|
+
* page to be brought somewhere visible.
|
|
88
|
+
*/
|
|
89
|
+
const layerOf = (sessionId) => {
|
|
90
|
+
if (guestReady(sessionId) === true) return hub?.surfaceOf?.(sessionId) === 'float' ? 'float' : 'sidebar'
|
|
91
|
+
return manager.mode === 'headed' ? 'window' : 'headless'
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** What each layer means, in the words the model gets when a move happens. */
|
|
95
|
+
const LAYER_NOTE = {
|
|
96
|
+
sidebar: '页面现在讨论区右侧栏里(docked)。',
|
|
97
|
+
float: '页面现在是 DSH 窗口内的浮动面板:可以拖走、放大,切到别的对话就会跟着收起来。',
|
|
98
|
+
window: '页面现在在一台独立的浏览器窗口里(看得见、可以拖到副屏),面板没参与。',
|
|
99
|
+
headless: '页面现在在后台那台看不见的浏览器里:没有人的登录态,人看不到你在做什么。',
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Last layer observed per session, so one move is reported once, not on every call. */
|
|
103
|
+
const lastLayer = new Map()
|
|
104
|
+
/**
|
|
105
|
+
* Attach the current layer to a tool answer — and say so loudly the first time it
|
|
106
|
+
* differs from the previous answer, because "the page moved" changes the meaning
|
|
107
|
+
* of every coordinate and every login the model is about to rely on.
|
|
108
|
+
*/
|
|
109
|
+
const withLayer = (sessionId, result) => {
|
|
110
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)) return result
|
|
111
|
+
const layer = layerOf(sessionId)
|
|
112
|
+
const previous = lastLayer.get(sessionId)
|
|
113
|
+
lastLayer.set(sessionId, layer)
|
|
114
|
+
if (previous === layer) return result
|
|
115
|
+
const decorated = { ...result, layer }
|
|
116
|
+
if (previous !== undefined) {
|
|
117
|
+
decorated.layerChanged = `${previous} → ${layer}`
|
|
118
|
+
decorated.layerNote = LAYER_NOTE[layer]
|
|
119
|
+
}
|
|
120
|
+
return decorated
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Try the guest first.
|
|
125
|
+
*
|
|
126
|
+
* Only "not implemented" falls back. A real failure — "no element matches
|
|
127
|
+
* #submit" — must surface as-is, or the agent would get a confident answer from a
|
|
128
|
+
* browser showing a different page.
|
|
129
|
+
*/
|
|
130
|
+
const viaGuestCore = async (sessionId, method, params, fallback) => {
|
|
131
|
+
if (guestReady(sessionId) !== true) {
|
|
132
|
+
const result = await fallback()
|
|
133
|
+
// A panel that went away and did not come back is worth one sentence. The
|
|
134
|
+
// failure mode this prevents is not an exception — it is *silence*: the
|
|
135
|
+
// answer arrives, looks like success, and describes the other browser (empty
|
|
136
|
+
// login store, freshly loaded page). Whether to stop, retry, or tell the human
|
|
137
|
+
// is the agent's call, so this is a notice rather than an error.
|
|
138
|
+
const lost = hub?.takeLostPanel?.(sessionId)
|
|
139
|
+
if (lost === undefined) return result
|
|
140
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)) return result
|
|
141
|
+
return {
|
|
142
|
+
...result,
|
|
143
|
+
via: 'headless',
|
|
144
|
+
notice:
|
|
145
|
+
`这个对话的真实浏览器已关闭(${lost.reason === 'reclaimed' ? '闲置回收' : '页签被关闭,或你切到了别的对话'})。`
|
|
146
|
+
+ '你现在操作的是后台那台:它没有你的登录态,页面也是重新加载的。'
|
|
147
|
+
+ '要不要继续、停下、还是告诉用户,由你决定。',
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
return await hub.callGuest(sessionId, method, params)
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (UNSUPPORTED.test(String(error?.message ?? '')) !== true) throw error
|
|
154
|
+
logger?.debug?.(`guest cannot ${method}, falling back to cdp: ${error.message}`)
|
|
155
|
+
return await fallback()
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const viaGuest = async (sessionId, method, params, fallback) =>
|
|
160
|
+
withLayer(sessionId, await viaGuestCore(sessionId, method, params, fallback))
|
|
161
|
+
|
|
162
|
+
const router = {}
|
|
163
|
+
for (const name of ['start', 'stop', 'restart', 'ensureBrowser', 'ensureSession', 'closeSession', 'closeAllSessions', 'status', 'listSessions', 'session', 'setWatched', 'activateSession', 'restoreViewport', 'fitViewport', 'maxFitHeight', 'viewportSize', 'renderScale', 'touch', 'pageFor', 'dialog', 'pendingDialog', 'listTabs', 'bindTab', 'closeTab', 'setDownloadPath', 'cookies', 'clickAt', 'replaceTab', 'profileDir']) {
|
|
164
|
+
router[name] = (...args) => manager[name](...args)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// `navSeq` is read by `pushState`; it must keep reading the manager's own counter.
|
|
168
|
+
Object.defineProperty(router, 'navSeq', {
|
|
169
|
+
get: () => manager.navSeq ?? 0,
|
|
170
|
+
enumerable: true,
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
router.pageInfo = async (sessionId) => {
|
|
174
|
+
const info = await viaGuest(sessionId, 'pageInfo', {}, () => manager.pageInfo(sessionId))
|
|
175
|
+
// Which browser answered is a fact about the answer, not a separate question. It
|
|
176
|
+
// used to be inferable only from the viewport width, which nobody thinks to do.
|
|
177
|
+
const answer = { ...info, via: guestReady(sessionId) === true ? 'panel' : 'headless', layer: layerOf(sessionId) }
|
|
178
|
+
// A collapsed panel reports 0x0 while every DOM question still answers, so the
|
|
179
|
+
// model has to be told what that number means or it will keep clicking.
|
|
180
|
+
if (info?.viewport !== undefined && (Number(info.viewport.width) <= 0 || Number(info.viewport.height) <= 0)) {
|
|
181
|
+
answer.notice = '面板是 0×0(被折叠或隐藏):点击、输入、拖动都到不了页面。把右侧栏展开或让面板可见后再操作。'
|
|
182
|
+
}
|
|
183
|
+
return answer
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Move the human's view of this page onto another surface.
|
|
188
|
+
*
|
|
189
|
+
* `sidebar` and `float` are Sidebar layout operations, and only the panel can
|
|
190
|
+
* perform them — the host does not draw that column. `window` is not an
|
|
191
|
+
* operation at all: a headed deployment already *is* a window, and a headless
|
|
192
|
+
* one has nothing to show, so pretending would be worse than refusing.
|
|
193
|
+
*/
|
|
194
|
+
/**
|
|
195
|
+
* Bring a page back from the real window into the panel.
|
|
196
|
+
*
|
|
197
|
+
* The window and the panel are two different browsers: the panel's guest is a
|
|
198
|
+
* DSH webview with its own partition, the window is this plugin's own profile.
|
|
199
|
+
* So "move the page back" is three steps in order — remember where the page is,
|
|
200
|
+
* stop the window (the browser becomes headless, profile kept), and let the
|
|
201
|
+
* panel mount its guest again on that URL.
|
|
202
|
+
*
|
|
203
|
+
* Skipping the middle step leaves a window showing a page nobody drives; skipping
|
|
204
|
+
* the last one leaves the panel as an overlay over an empty box. Measured
|
|
205
|
+
* 2026-11-29: after switching to the window, 「浮窗」 moved an empty panel and
|
|
206
|
+
* there was no control that could bring the page back at all.
|
|
207
|
+
*/
|
|
208
|
+
router.restorePanel = async (sessionId) => {
|
|
209
|
+
// The window handler is already restarting the browser when its window is
|
|
210
|
+
// closed; racing it would start two browsers. Let that one finish first.
|
|
211
|
+
const waited = Date.now() + 5_000
|
|
212
|
+
while (manager.restoring === true && Date.now() < waited) {
|
|
213
|
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
214
|
+
}
|
|
215
|
+
const wasWindowed = hub?.windowed?.has?.(sessionId) === true || manager.mode === 'headed'
|
|
216
|
+
// Where the page is, before the browser that knows it is gone.
|
|
217
|
+
let url
|
|
218
|
+
try {
|
|
219
|
+
const info = await manager.pageInfo(sessionId)
|
|
220
|
+
if (typeof info?.url === 'string' && info.url !== '' && info.url.startsWith('about:') !== true) url = info.url
|
|
221
|
+
} catch {
|
|
222
|
+
/* the window may already be closed; lastUrls is the fallback */
|
|
223
|
+
}
|
|
224
|
+
if (url === undefined) url = manager.lastUrls?.get?.(sessionId)
|
|
225
|
+
let restarted = false
|
|
226
|
+
if (manager.mode === 'headed') {
|
|
227
|
+
const closed = await manager.closeWindow()
|
|
228
|
+
restarted = closed.restarted === true
|
|
229
|
+
}
|
|
230
|
+
// From this moment the panel may answer for the page again — for *every*
|
|
231
|
+
// session, not just this one. A real window is one process for all
|
|
232
|
+
// conversations, so this restart took the window away from all of them; the
|
|
233
|
+
// `windowClosed` event that normally clears the set cannot fire here, because
|
|
234
|
+
// `stop()` marks the shutdown as deliberate and `browser.js` reports
|
|
235
|
+
// `windowClosed: false` for it. Clearing one id left the other conversations
|
|
236
|
+
// stuck on `windowed: true` with no window to answer for them (2026-11-30).
|
|
237
|
+
hub?.clearWindowedAll?.()
|
|
238
|
+
// The restart closed every tab; reopen this session on the URL the window was
|
|
239
|
+
// showing, so the panel's guest loads that page rather than the one from before
|
|
240
|
+
// the window existed.
|
|
241
|
+
await manager.ensureSession(sessionId, url !== undefined ? { url } : undefined).catch((error) => {
|
|
242
|
+
logger?.debug?.(`restorePanel: could not reopen the tab: ${error?.message ?? error}`)
|
|
243
|
+
})
|
|
244
|
+
await hub?.pushState?.({ force: true })
|
|
245
|
+
return { ok: true, requested: 'panel', restarted, wasWindowed, url: url ?? null }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
router.present = async (sessionId, mode) => {
|
|
249
|
+
const wanted = String(mode ?? '')
|
|
250
|
+
if (wanted === 'window') {
|
|
251
|
+
// A window is a property of the **process**: a headless browser has none,
|
|
252
|
+
// and no panel operation can turn this page into an OS window. So asking
|
|
253
|
+
// for the window layer is a request to run the browser with a window —
|
|
254
|
+
// the host restarts it once if needed (profile kept, pages carry over).
|
|
255
|
+
const result = await router.openWindow(sessionId)
|
|
256
|
+
return {
|
|
257
|
+
ok: true,
|
|
258
|
+
requested: 'window',
|
|
259
|
+
layer: 'window',
|
|
260
|
+
moved: result.restarted !== true,
|
|
261
|
+
restarted: result.restarted === true,
|
|
262
|
+
panelDetached: result.panelDetached,
|
|
263
|
+
url: result.url,
|
|
264
|
+
note:
|
|
265
|
+
result.restarted === true
|
|
266
|
+
? 'browser restarted into windowed mode: the profile (and every login) is kept, and each conversation’s page reopens on its own URL. The window is now in front.'
|
|
267
|
+
: 'the real browser window is now in front.',
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* The page is in the real window; a panel operation has nothing to move yet.
|
|
272
|
+
*
|
|
273
|
+
* The window owns the page (that is what `windowed` records), so asking for a
|
|
274
|
+
* panel layer is really a request to *come back* from the window: stop it, hand
|
|
275
|
+
* routing back, remount the guest, and only then dock or float it.
|
|
276
|
+
*/
|
|
277
|
+
if ((wanted === 'sidebar' || wanted === 'float') && hub?.windowed?.has?.(sessionId) === true) {
|
|
278
|
+
const restored = await router.restorePanel(sessionId)
|
|
279
|
+
const ready =
|
|
280
|
+
typeof hub?.waitForGuest === 'function'
|
|
281
|
+
? await hub.waitForGuest(sessionId, 6_000)
|
|
282
|
+
: guestReady(sessionId) === true
|
|
283
|
+
if (ready !== true) {
|
|
284
|
+
return {
|
|
285
|
+
ok: true,
|
|
286
|
+
requested: wanted,
|
|
287
|
+
layer: layerOf(sessionId),
|
|
288
|
+
restored: true,
|
|
289
|
+
restarted: restored.restarted,
|
|
290
|
+
moved: true,
|
|
291
|
+
url: restored.url,
|
|
292
|
+
note:
|
|
293
|
+
'the page was brought back from the real window, but no panel is open for this session to dock it into. Open the browser tab to see it.',
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const result = await hub.callGuest(sessionId, 'present', { mode: wanted }, { timeoutMs: 5_000 })
|
|
297
|
+
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
298
|
+
const answer = {
|
|
299
|
+
ok: true,
|
|
300
|
+
requested: wanted,
|
|
301
|
+
restored: true,
|
|
302
|
+
restarted: restored.restarted,
|
|
303
|
+
...(result ?? {}),
|
|
304
|
+
layer: layerOf(sessionId),
|
|
305
|
+
}
|
|
306
|
+
if (typeof answer.note !== 'string') {
|
|
307
|
+
answer.note =
|
|
308
|
+
restored.restarted === true
|
|
309
|
+
? 'brought back from the real browser window into the panel (the window was closed; the plugin profile and its logins are kept).'
|
|
310
|
+
: 'brought back from the real browser window into the panel.'
|
|
311
|
+
}
|
|
312
|
+
if (answer.moved === false) {
|
|
313
|
+
// The guest says "I was already here", which is true of the panel pane but
|
|
314
|
+
// not of the page: it just came back from a different browser.
|
|
315
|
+
answer.moved = true
|
|
316
|
+
}
|
|
317
|
+
return answer
|
|
318
|
+
}
|
|
319
|
+
if (guestReady(sessionId) !== true) {
|
|
320
|
+
throw new Error(
|
|
321
|
+
'present: the Sidebar panel is not open for this session, so there is no panel to move. Open the browser tab first (ask_human does that), or use mode: "window" for a real browser window.',
|
|
322
|
+
)
|
|
323
|
+
}
|
|
324
|
+
const result = await hub.callGuest(sessionId, 'present', { mode: wanted }, { timeoutMs: 5_000 })
|
|
325
|
+
// Moving the page onto a panel layer hands routing back to the guest.
|
|
326
|
+
hub?.clearWindowed?.(sessionId)
|
|
327
|
+
// The Sidebar commits the layout and re-renders; give it a beat so the layer
|
|
328
|
+
// reported back describes where the page *is*, not where it was asked to go.
|
|
329
|
+
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
330
|
+
const answer = { ok: true, requested: wanted, ...(result ?? {}), layer: layerOf(sessionId) }
|
|
331
|
+
// "moved: false" means the page was already there. Left unsaid, a model that
|
|
332
|
+
// asked to "switch surfaces" reads it as done while the human sees no change
|
|
333
|
+
// (measured 2026-11-29: present sidebar returned moved:false and the answer
|
|
334
|
+
// was taken as a successful switch).
|
|
335
|
+
if (result?.moved === false && typeof answer.note !== 'string') {
|
|
336
|
+
answer.note = `the page was already on the ${answer.layer} layer — nothing moved. Use mode: "window" to put it into a real browser window.`
|
|
337
|
+
}
|
|
338
|
+
return answer
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Hand the page to a real browser window (the panel's 「独立窗口」 button and
|
|
343
|
+
* `present mode=window`).
|
|
344
|
+
*
|
|
345
|
+
* Unlike `present` on the panel layers, this may restart the browser into
|
|
346
|
+
* headed mode — that is exactly what the ask is for. It then has to do one
|
|
347
|
+
* more thing the panel normally does for us: **detach the panel's guest**.
|
|
348
|
+
* The panel and the window are two different browsers, and `viaGuestCore`
|
|
349
|
+
* prefers the guest whenever one is mounted — so leaving it attached means
|
|
350
|
+
* every later tool call keeps driving the panel page while the human looks at
|
|
351
|
+
* the window. Measured 2026-11-29: that is how "the agent describes something
|
|
352
|
+
* different from what I see on screen" happens.
|
|
353
|
+
*/
|
|
354
|
+
router.openWindow = async (sessionId, options = {}) => {
|
|
355
|
+
const result = await manager.openWindow(sessionId, options)
|
|
356
|
+
// Ask before marking: `markWindowed` itself makes `guestAvailable` false, so a
|
|
357
|
+
// check after it can never see the guest that is being displaced.
|
|
358
|
+
const hadGuest = guestReady(sessionId) === true
|
|
359
|
+
// From here on the window owns the page: even if the panel re-mounts a guest,
|
|
360
|
+
// routing must not flip back to it (that is how the agent ended up driving a
|
|
361
|
+
// different page from the one on screen).
|
|
362
|
+
hub?.markWindowed?.(sessionId)
|
|
363
|
+
/**
|
|
364
|
+
* The panel learns "window" **only from this push**, and it has to go out
|
|
365
|
+
* before anything waits on the guest.
|
|
366
|
+
*
|
|
367
|
+
* The restart inside `manager.openWindow` emits its own state changes, and
|
|
368
|
+
* they fire *before* this mark — so a panel that reconnects while the window is
|
|
369
|
+
* coming up receives `windowed: false` and mounts its guest anyway. Measured
|
|
370
|
+
* 2026-11-29: after switching to the window the panel kept showing (and
|
|
371
|
+
* floating) the page, the real window stayed visible, and 「浮窗」 moved the
|
|
372
|
+
* panel copy instead of closing the window.
|
|
373
|
+
*/
|
|
374
|
+
await hub?.pushState?.({ force: true })
|
|
375
|
+
if (hadGuest) {
|
|
376
|
+
// A panel that missed the state push (or an older panel build) still has a
|
|
377
|
+
// live guest; ask it to let go and wait, so the detached answer is a fact.
|
|
378
|
+
try {
|
|
379
|
+
hub?.broadcast?.({ type: 'reclaim', sessionId, reason: 'window' }, sessionId)
|
|
380
|
+
} catch {
|
|
381
|
+
/* the panel may already be gone */
|
|
382
|
+
}
|
|
383
|
+
const deadline = Date.now() + 3_000
|
|
384
|
+
while (Date.now() < deadline && guestReady(sessionId) === true) {
|
|
385
|
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
// This is not "your browser went away": the page was moved on purpose.
|
|
389
|
+
hub?.takeLostPanel?.(sessionId)
|
|
390
|
+
if (hadGuest) {
|
|
391
|
+
result.panelDetached = guestReady(sessionId) !== true
|
|
392
|
+
if (result.panelDetached !== true) {
|
|
393
|
+
result.note =
|
|
394
|
+
'the panel still holds a stale guest, but routing now follows the window; reload the panel to clear it'
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return result
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Report the page the tools actually answer from.
|
|
402
|
+
*
|
|
403
|
+
* `manager.status` describes the headless tab, so once the panel is mounted it
|
|
404
|
+
* reports a 1440×900 viewport for a session whose tools are hitting a 700 px
|
|
405
|
+
* panel — which reads as "the AI is driving the invisible browser after all".
|
|
406
|
+
* The panel is the truth whenever it is there.
|
|
407
|
+
*/
|
|
408
|
+
router.status = async (sessionId) => {
|
|
409
|
+
const status = await manager.status(sessionId)
|
|
410
|
+
if (guestReady(sessionId) !== true) {
|
|
411
|
+
// The panel being closed is the single most confusing state this plugin has:
|
|
412
|
+
// everything still "works", on a browser nobody can see, with its own empty
|
|
413
|
+
// login store. Say so out loud instead of leaving the caller to infer it from
|
|
414
|
+
// a viewport number.
|
|
415
|
+
status.via = 'headless'
|
|
416
|
+
status.layer = layerOf(sessionId)
|
|
417
|
+
status.hint = 'the side panel browser is not open for this session, so these calls ran on the headless tab — not the page the human is looking at'
|
|
418
|
+
if (status.session !== undefined && status.session !== null) status.session.via = 'headless'
|
|
419
|
+
return status
|
|
420
|
+
}
|
|
421
|
+
// Bounded hard: this is a two-field read from a UI that may have just gone away.
|
|
422
|
+
// The default 30 s ceiling turns "the panel is gone" into half a minute of silence.
|
|
423
|
+
const info = await hub.callGuest(sessionId, 'info', {}, { timeoutMs: 3000 }).catch(() => undefined)
|
|
424
|
+
const session = status?.session
|
|
425
|
+
status.via = 'panel'
|
|
426
|
+
status.layer = layerOf(sessionId)
|
|
427
|
+
if (session === undefined || session === null) return status
|
|
428
|
+
if (typeof info?.w === 'number' && typeof info?.h === 'number') session.viewport = { width: info.w, height: info.h }
|
|
429
|
+
if (typeof info?.url === 'string') session.url = info.url
|
|
430
|
+
if (typeof info?.title === 'string' && info.title !== '') session.title = info.title
|
|
431
|
+
session.via = 'panel'
|
|
432
|
+
status.mode = 'panel'
|
|
433
|
+
return status
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
router.navigate = (sessionId, url, options = {}) =>
|
|
437
|
+
viaGuest(sessionId, 'navigate', { url }, () => manager.navigate(sessionId, url, options))
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Open a cross-origin frame as a page of its own.
|
|
441
|
+
*
|
|
442
|
+
* The DOM inside a cross-origin iframe is a security wall: the parent page's
|
|
443
|
+
* JavaScript cannot read it, so snapshot and selector clicks cannot either. The
|
|
444
|
+
* page *can* be shown as a top document, and that is what this does — at the
|
|
445
|
+
* cost of the parent page's live state. Form fields, scroll position, open
|
|
446
|
+
* dropdowns and anything not yet submitted are gone, and `op: back` only
|
|
447
|
+
* reloads the URL; it does not restore the state. Both facts travel back in
|
|
448
|
+
* `warning`, because a lost form is a real cost the caller has to weigh.
|
|
449
|
+
*/
|
|
450
|
+
const frameReturn = new Map()
|
|
451
|
+
|
|
452
|
+
router.frameOpen = async (sessionId, { index, url } = {}) => {
|
|
453
|
+
const explicit = typeof url === 'string' ? url.trim() : ''
|
|
454
|
+
let target = explicit
|
|
455
|
+
let frameIndex
|
|
456
|
+
if (target === '') {
|
|
457
|
+
if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) {
|
|
458
|
+
throw new Error('browser_embedded_frame op=open needs index (from a snapshot frames list) or url')
|
|
459
|
+
}
|
|
460
|
+
const snap = await router.snapshot(sessionId, { maxElements: 1, maxChars: 1 })
|
|
461
|
+
const frames = Array.isArray(snap?.frames) ? snap.frames : []
|
|
462
|
+
const frame = frames[index]
|
|
463
|
+
if (frame === undefined) {
|
|
464
|
+
throw new Error(`no frame [${index}] on this page — call browser_embedded_snapshot and read its 内嵌框架 list (there are ${frames.length})`)
|
|
465
|
+
}
|
|
466
|
+
if (typeof frame.src !== 'string' || frame.src === '') throw new Error(`frame [${index}] has no src to open`)
|
|
467
|
+
target = frame.src
|
|
468
|
+
frameIndex = index
|
|
469
|
+
}
|
|
470
|
+
const before = await router.pageInfo(sessionId)
|
|
471
|
+
const returnTo = typeof before?.url === 'string' && before.url !== '' ? before.url : undefined
|
|
472
|
+
// Record before navigating: a failed navigation still leaves the tab on the
|
|
473
|
+
// browser's error page, and without this the caller has no way back either.
|
|
474
|
+
if (returnTo !== undefined) frameReturn.set(sessionId, { url: returnTo, at: Date.now() })
|
|
475
|
+
try {
|
|
476
|
+
await router.navigate(sessionId, target)
|
|
477
|
+
} catch (error) {
|
|
478
|
+
throw new Error(
|
|
479
|
+
`${error.message} — the tab is now on the browser's error page; call browser_embedded_frame op=back to return to ${returnTo ?? 'the previous page'}`,
|
|
480
|
+
)
|
|
481
|
+
}
|
|
482
|
+
return {
|
|
483
|
+
frame: frameIndex,
|
|
484
|
+
url: target,
|
|
485
|
+
returnTo,
|
|
486
|
+
warning:
|
|
487
|
+
'The original page was navigated away from: form fields, scroll position, open dropdowns and any state not yet submitted are LOST, and op=back only reloads the original URL — it does not restore that state. Read and act inside the frame, then go back.',
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
router.frameBack = async (sessionId) => {
|
|
492
|
+
const pending = frameReturn.get(sessionId)
|
|
493
|
+
if (pending === undefined) {
|
|
494
|
+
throw new Error('nothing to go back to: op=back only undoes the last browser_embedded_frame op=open in this session (use navigate with the URL you want)')
|
|
495
|
+
}
|
|
496
|
+
frameReturn.delete(sessionId)
|
|
497
|
+
await router.navigate(sessionId, pending.url)
|
|
498
|
+
return {
|
|
499
|
+
url: pending.url,
|
|
500
|
+
note: 'the original URL is reloaded; its previous form and scroll state is not restored',
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
router.snapshot = (sessionId, options = {}) =>
|
|
505
|
+
viaGuest(sessionId, 'snapshot', options, () => manager.snapshot(sessionId, options))
|
|
506
|
+
|
|
507
|
+
router.click = (sessionId, target, options = {}) =>
|
|
508
|
+
viaGuest(sessionId, 'click', { ...asTarget(target), double: options.double }, () => manager.click(sessionId, target, options))
|
|
509
|
+
|
|
510
|
+
router.clickSelector = (sessionId, selector, options = {}) =>
|
|
511
|
+
viaGuest(sessionId, 'click', { selector, double: options.double }, () => manager.clickSelector(sessionId, selector, options))
|
|
512
|
+
|
|
513
|
+
router.clickText = (sessionId, text) => viaGuest(sessionId, 'clickText', { text }, () => manager.clickText(sessionId, text))
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Coordinate paths.
|
|
517
|
+
*
|
|
518
|
+
* A cross-origin frame is opaque to every selector — the top document cannot
|
|
519
|
+
* see into it — but input is dispatched *at a point*, so the browser hands it to
|
|
520
|
+
* whichever renderer owns that point, frames included. That is the entire
|
|
521
|
+
* reason these three exist; everything reachable by a selector should keep
|
|
522
|
+
* using index or selector.
|
|
523
|
+
*/
|
|
524
|
+
/**
|
|
525
|
+
* Say out loud when the panel cannot deliver a coordinate click into a frame.
|
|
526
|
+
*
|
|
527
|
+
* Measured: inside the panel a **same-origin** frame receives the click (its own
|
|
528
|
+
* document logs the mousedown, `downs: ["180,82"]`), while a **cross-origin**
|
|
529
|
+
* frame receives nothing at all — the host's Electron keeps it in a separate
|
|
530
|
+
* process and the webview input path does not forward into it. The headless tab
|
|
531
|
+
* is fine (it launches with site isolation off, which is the 0.10.6 fix), but the
|
|
532
|
+
* panel is the page the human is looking at, so a silent "verified: true" there
|
|
533
|
+
* is the worst possible answer: the caller concludes the dialog was handled.
|
|
534
|
+
*/
|
|
535
|
+
const panelFrameMiss = (sessionId, result) => {
|
|
536
|
+
if (guestReady(sessionId) !== true) return result
|
|
537
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)) return result
|
|
538
|
+
if (result.inFrame !== true || result.frameReadable !== false) return result
|
|
539
|
+
return {
|
|
540
|
+
...result,
|
|
541
|
+
note:
|
|
542
|
+
'这次的点落在跨域 iframe 上,而这一下打的是面板(人在看的那台):宿主的站点隔离让跨域 frame 收不到输入,'
|
|
543
|
+
+ '这是 Electron 的进程模型,插件改不了。四条出路:'
|
|
544
|
+
+ '① browser_embedded_screenshot 看清弹窗,把坐标交给人点;'
|
|
545
|
+
+ '② browser_embedded_frame op=open 把 frame 当页面读(会丢原页面状态);'
|
|
546
|
+
+ '③ browser_embedded_present mode=window 切到独立窗口——那里输入走 CDP,跨域 frame 能收到'
|
|
547
|
+
+ '(会重启一次浏览器,登录态保留,其他对话的页面按各自网址重开);'
|
|
548
|
+
+ '④ 或者改用无头那台(会换成另一台浏览器:没有你的登录态,页面会重新加载)。',
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
router.clickPoint = async (sessionId, point, options = {}) =>
|
|
553
|
+
panelFrameMiss(
|
|
554
|
+
sessionId,
|
|
555
|
+
await viaGuest(sessionId, 'click', { x: point?.x, y: point?.y, double: options.double }, () =>
|
|
556
|
+
manager.clickPoint(sessionId, point, options),
|
|
557
|
+
),
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
router.hoverPoint = async (sessionId, point) =>
|
|
561
|
+
panelFrameMiss(
|
|
562
|
+
sessionId,
|
|
563
|
+
await viaGuest(sessionId, 'hover', { x: point?.x, y: point?.y }, () => manager.hoverPoint(sessionId, point)),
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
router.typePoint = async (sessionId, point, text, options = {}) =>
|
|
567
|
+
panelFrameMiss(
|
|
568
|
+
sessionId,
|
|
569
|
+
await viaGuest(sessionId, 'type', { x: point?.x, y: point?.y, text, submit: options.submit }, () =>
|
|
570
|
+
manager.typePoint(sessionId, point, text, options),
|
|
571
|
+
),
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
router.drag = (sessionId, from, to) =>
|
|
575
|
+
viaGuest(sessionId, 'drag', { from: asTarget(from), to: asTarget(to) }, () => manager.drag(sessionId, from, to))
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Upload, in the panel.
|
|
579
|
+
*
|
|
580
|
+
* A page cannot read a local path, and the panel's renderer has no filesystem, so
|
|
581
|
+
* the node half reads the bytes and posts them over the guest channel; the page
|
|
582
|
+
* rebuilds real `File` objects and attaches them the way a picker would. The
|
|
583
|
+
* headless tab does the same thing natively through `DOM.setFileInputFiles`.
|
|
584
|
+
*/
|
|
585
|
+
router.upload = async (sessionId, target, files) => {
|
|
586
|
+
if (guestReady(sessionId) !== true) return await manager.upload(sessionId, target, files)
|
|
587
|
+
const paths = (Array.isArray(files) ? files : [files]).map((file) => String(file))
|
|
588
|
+
if (paths.length === 0) throw new Error('upload needs at least one file path')
|
|
589
|
+
const packed = []
|
|
590
|
+
let total = 0
|
|
591
|
+
for (const path of paths) {
|
|
592
|
+
const data = await readFile(path)
|
|
593
|
+
total += data.length
|
|
594
|
+
if (total > MAX_UPLOAD_BYTES) {
|
|
595
|
+
throw new Error(`upload is capped at ${MAX_UPLOAD_BYTES} bytes across all files; ${path} pushed it over`)
|
|
596
|
+
}
|
|
597
|
+
packed.push({
|
|
598
|
+
name: basename(path),
|
|
599
|
+
type: UPLOAD_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream',
|
|
600
|
+
base64: data.toString('base64'),
|
|
601
|
+
})
|
|
602
|
+
}
|
|
603
|
+
return await hub.callGuest(sessionId, 'upload', { target: asTarget(target), files: packed })
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// Fetch from inside the panel's page: same cookies, same origin policy, same
|
|
607
|
+
// login as the tab the human is looking at. The headless tab would fetch with
|
|
608
|
+
// an empty jar and get the logged-out answer.
|
|
609
|
+
router.httpFetch = (sessionId, options = {}) =>
|
|
610
|
+
viaGuest(sessionId, 'http', options, () => manager.httpFetch(sessionId, options))
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Download a URL through whichever browser is live.
|
|
614
|
+
*
|
|
615
|
+
* With the panel mounted the host has cancelled real downloads for that session, so
|
|
616
|
+
* "download" here means: the page fetches the bytes with its own cookies, and the
|
|
617
|
+
* node half writes them to disk. Without the panel the CDP tab still has a real
|
|
618
|
+
* download directory, which is all this call has ever meant.
|
|
619
|
+
*/
|
|
620
|
+
router.download = async (sessionId, options = {}) => {
|
|
621
|
+
const url = typeof options.url === 'string' ? options.url.trim() : ''
|
|
622
|
+
const dir = downloadDir(options.downloadPath)
|
|
623
|
+
if (url === '') return await manager.setDownloadPath(dir)
|
|
624
|
+
if (guestReady(sessionId) !== true) return await manager.download(sessionId, { url, downloadPath: dir })
|
|
625
|
+
const fetched = await hub.callGuest(sessionId, 'download', { url, maxBytes: options.maxBytes })
|
|
626
|
+
const saved = await saveDownload({ name: fetched?.name, base64: fetched?.base64, dir, url })
|
|
627
|
+
return { ...saved, url, via: 'panel' }
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
router.type = (sessionId, target, text, options = {}) =>
|
|
631
|
+
viaGuest(sessionId, 'type', { ...asTarget(target), text, submit: options.submit }, () => manager.type(sessionId, target, text, options))
|
|
632
|
+
|
|
633
|
+
router.fill = (sessionId, target, text) =>
|
|
634
|
+
viaGuest(sessionId, 'fill', { ...asTarget(target), text }, () => manager.fill(sessionId, target, text))
|
|
635
|
+
|
|
636
|
+
router.press = (sessionId, key) => viaGuest(sessionId, 'press', { key }, () => manager.press(sessionId, key))
|
|
637
|
+
|
|
638
|
+
router.scroll = (sessionId, direction, options = {}) =>
|
|
639
|
+
viaGuest(sessionId, 'scroll', { direction, pixels: options.pixels }, () => manager.scroll(sessionId, direction, options))
|
|
640
|
+
|
|
641
|
+
router.hover = (sessionId, target) => viaGuest(sessionId, 'hover', { ...asTarget(target) }, () => manager.hover(sessionId, target))
|
|
642
|
+
|
|
643
|
+
router.waitFor = (sessionId, options = {}) =>
|
|
644
|
+
viaGuest(sessionId, 'waitFor', options, () => manager.waitFor(sessionId, options))
|
|
645
|
+
|
|
646
|
+
router.readElement = (sessionId, selector, what = 'text', attribute) =>
|
|
647
|
+
viaGuest(sessionId, 'read', { selector, what, attribute }, () => manager.readElement(sessionId, selector, what, attribute))
|
|
648
|
+
|
|
649
|
+
router.select = (sessionId, target, value) =>
|
|
650
|
+
viaGuest(sessionId, 'select', { ...asTarget(target), value }, () => manager.select(sessionId, target, value))
|
|
651
|
+
|
|
652
|
+
router.check = (sessionId, target, checked = true) =>
|
|
653
|
+
viaGuest(sessionId, 'check', { ...asTarget(target), checked }, () => manager.check(sessionId, target, checked))
|
|
654
|
+
|
|
655
|
+
router.evaluate = (sessionId, expression) =>
|
|
656
|
+
viaGuest(sessionId, 'eval', { expression }, () => manager.evaluate(sessionId, expression))
|
|
657
|
+
|
|
658
|
+
router.evalJs = (sessionId, expression, options = {}) =>
|
|
659
|
+
viaGuest(sessionId, 'eval', { expression, userGesture: options.awaitPromise !== false }, () => manager.evalJs(sessionId, expression, options))
|
|
660
|
+
|
|
661
|
+
router.goBack = (sessionId) => viaGuest(sessionId, 'back', {}, () => manager.goBack(sessionId))
|
|
662
|
+
router.goForward = (sessionId) => viaGuest(sessionId, 'forward', {}, () => manager.goForward(sessionId))
|
|
663
|
+
router.reload = (sessionId) => viaGuest(sessionId, 'reload', {}, () => manager.reload(sessionId))
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Screenshots need a shape translation: the panel hands back a data URL, the tool
|
|
667
|
+
* layer expects bytes plus a media type.
|
|
668
|
+
*/
|
|
669
|
+
router.screenshot = async (sessionId, options = {}) => {
|
|
670
|
+
if (guestReady(sessionId) !== true) return await manager.screenshot(sessionId, options)
|
|
671
|
+
if (options.selector !== undefined || options.fullPage === true) {
|
|
672
|
+
// The panel captures its whole viewport; a clip is a headless-only trick.
|
|
673
|
+
logger?.debug?.('screenshot selector/fullPage asked for, using the cdp tab')
|
|
674
|
+
return await manager.screenshot(sessionId, options)
|
|
675
|
+
}
|
|
676
|
+
const shot = await hub.callGuest(sessionId, 'screenshot', { format: options.format ?? 'png' })
|
|
677
|
+
const dataUrl = String(shot?.dataUrl ?? '')
|
|
678
|
+
const comma = dataUrl.indexOf(',')
|
|
679
|
+
if (comma < 0) throw new Error('the panel returned no image data for the screenshot')
|
|
680
|
+
return {
|
|
681
|
+
data: Buffer.from(dataUrl.slice(comma + 1), 'base64'),
|
|
682
|
+
mediaType: dataUrl.startsWith('data:image/jpeg') ? 'image/jpeg' : 'image/png',
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
return router
|
|
687
|
+
}
|