dsh-builtin-browser 0.1.15 → 0.1.16

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.
@@ -1,14 +1,23 @@
1
1
  /**
2
2
  * Self-hosted Electron browser host (child side): the Electron main process
3
- * spawned by {@link RemoteElectronViewHost}. Owns one `BrowserWindow` plus
4
- * `WebContentsView`s and their `webContents.debugger` (CDP), and answers
5
- * line-delimited JSON-RPC on stdio.
3
+ * spawned by {@link RemoteElectronViewHost}. Owns one `BrowserWindow` PER
4
+ * SESSION (each session's views live in their own window) plus a browser
5
+ * toolbar (address bar, back/forward/reload, tab strip) that makes the
6
+ * built-in browser usable as a real browser by the human — every window has
7
+ * its own toolbar. Views are `WebContentsView`s driven over
8
+ * `webContents.debugger` (CDP); user toolbar actions are routed back to the
9
+ * parent so the agent and the human always share one tab/navigation model.
6
10
  *
7
11
  * Protocol (one JSON object per line, both directions):
8
12
  * <- { id, op: 'ping' } | { id, op: 'createView', viewId } |
9
13
  * { id, op: 'destroyView', viewId } | { id, op: 'showView', viewId } |
10
- * { id, op: 'command', viewId, method, params }
14
+ * { id, op: 'groupView', viewId, windowId, label? } |
15
+ * { id, op: 'command', viewId, method, params } |
16
+ * { id, op: 'userActionError', windowId, message }
17
+ * -> { id: 0, op: 'hello', token } (our FIRST message — proves we know the
18
+ * parent's stdin token; the parent refuses the connection otherwise)
11
19
  * -> { id, ok: true, result? } | { id, ok: false, err }
20
+ * -> { id: 0, op: 'userAction', action } (fire-and-forget; no reply)
12
21
  *
13
22
  * The parent never parses stderr, so diagnostics may go there freely.
14
23
  * @module dsh-browser/browser-electron/host-main
@@ -16,29 +25,187 @@
16
25
  import { app, BrowserWindow, WebContentsView } from 'electron';
17
26
  import { createInterface } from 'node:readline';
18
27
  import { createConnection } from 'node:net';
19
- import { join } from 'node:path';
28
+ import { mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
29
+ import { tmpdir } from 'node:os';
30
+ import { dirname, join } from 'node:path';
31
+ /**
32
+ * The spawn token the parent sent via stdin (first line). Must be echoed in
33
+ * our hello. Read from stdin so the token never appears in argv (WMI /
34
+ * Process Explorer / /proc/*).
35
+
20
36
  // Isolate this host's profile from the DSH app's default Electron userData:
21
37
  // several Electron instances sharing Roaming\Electron fight over the GPU
22
38
  // cache/session locks, which can leave the window without a display surface
23
39
  // (capturePage then fails). A dedicated userData also persists cookies across
24
40
  // host restarts (on top of browser_auth). Must run before app is ready.
25
41
  try {
26
- const base = process.env.DSH_HOME ?? app.getPath('appData');
27
- app.setPath('userData', join(base, 'dsh-builtin-browser-host'));
42
+ const base = process.env.DSH_HOME ?? app.getPath('appData')
43
+ app.setPath('userData', join(base, 'dsh-builtin-browser-host'))
44
+ } catch (error) {
45
+ process.stderr.write(`[dsh-browser host] userData setup failed: ${String(error)}\n`)
28
46
  }
29
- catch (error) {
30
- process.stderr.write(`[dsh-browser host] userData setup failed: ${String(error)}\n`);
47
+
48
+ /**
49
+ * Read the spawn token. The parent sends it two ways and the child prefers
50
+ * the first that yields a value:
51
+ * 1. stdin (first line) — the secure channel on Unix/macOS;
52
+ * 2. DSH_BROWSER_RPC_TOKEN env — the fallback on Windows, where Electron is
53
+ * a GUI-subsystem process and never receives piped stdin (the parent
54
+ * sets it in the spawn env for exactly this reason).
55
+ * stdin wins over env so the parent's token never has to touch argv.
56
+ */
57
+ let RPC_TOKEN = process.env.DSH_BROWSER_RPC_TOKEN ?? '';
58
+ const stdinDelivered = RPC_TOKEN !== '';
59
+ if (process.stdin !== null && process.stdin.readable) {
60
+ const stdinLines = createInterface({ input: process.stdin, terminal: false });
61
+ stdinLines.on('line', (line) => {
62
+ if (RPC_TOKEN === '') {
63
+ RPC_TOKEN = line.trim();
64
+ stdinLines.close();
65
+ }
66
+ });
67
+ stdinLines.on('close', () => {
68
+ if (RPC_TOKEN === '' && !stdinDelivered) {
69
+ process.stderr.write('[dsh-browser host] warning: no token received on stdin or env\n');
70
+ }
71
+ });
31
72
  }
32
73
  /** CDP protocol version attached to every view's debugger. */
33
74
  const CDP_VERSION = '1.3';
34
75
  /** Download cap: the body is shipped base64 as one JSON line; bound the memory. */
35
76
  const MAX_DOWNLOAD_BYTES = 256 * 1024 * 1024;
36
- /** Views by the id the parent assigned at createView time. */
37
- const views = new Map();
38
- /** The single browser window; created lazily on first createView. */
39
- let window;
77
+ /** Toolbar height in CSS px: nav row + tab strip. Page views sit below it. */
78
+ const TOOLBAR_HEIGHT = 64;
79
+ /** Fallback group for views whose groupView never arrived (defensive only). */
80
+ const SHARED_WINDOW_ID = 'shared';
81
+ /** Focus key for the toolbar view (it is not in win.views). */
82
+ const TOOLBAR_FOCUS = '\u0000toolbar';
83
+ /** Windows by group key (session id). */
84
+ const windows = new Map();
85
+ /**
86
+ * Window assignments received via groupView BEFORE the view's createView:
87
+ * the parent sends groupView right after createView (both deferred until the
88
+ * child is ready), so either order may arrive first.
89
+ */
90
+ const assignments = new Map();
40
91
  /** The RPC socket to the parent; set when the connection is established. */
41
92
  let rpcSocket;
93
+ // ---------------------------------------------------------------------------
94
+ // Toolbar: a small HTML strip (address bar, back/forward/reload, tab strip)
95
+ // rendered in its own WebContentsView on top of every window. It talks to
96
+ // this main process over IPC; user actions go to the PARENT (which owns the
97
+ // session/tab model) as fire-and-forget `userAction` messages.
98
+ // ---------------------------------------------------------------------------
99
+ const TOOLBAR_PRELOAD = `const { contextBridge, ipcRenderer } = require('electron')
100
+ contextBridge.exposeInMainWorld('bridge', {
101
+ post: (action, payload) => ipcRenderer.send('toolbar-action', action, payload),
102
+ onTabs: cb => ipcRenderer.on('tabs', (_e, payload) => cb(payload)),
103
+ onError: cb => ipcRenderer.on('user-action-error', (_e, text) => cb(text)),
104
+ })
105
+ `;
106
+ const TOOLBAR_HTML = `<!doctype html>
107
+ <html>
108
+ <head>
109
+ <meta charset="utf-8">
110
+ <style>
111
+ :root { color-scheme: light dark; }
112
+ * { box-sizing: border-box; margin: 0; padding: 0; }
113
+ html, body { height: 100%; overflow: hidden; font-family: system-ui, "Segoe UI", sans-serif; font-size: 12px; }
114
+ body { display: flex; flex-direction: column; background: #2b2d31; color: #e8e8e8; }
115
+ .nav { display: flex; align-items: center; gap: 4px; padding: 4px 6px; height: 32px; }
116
+ button.tool { background: transparent; border: none; color: inherit; width: 28px; height: 24px; border-radius: 4px; cursor: pointer; font-size: 13px; line-height: 1; flex: 0 0 auto; }
117
+ button.tool:hover { background: rgba(255,255,255,.12); }
118
+ #addr { flex: 1; min-width: 0; height: 24px; border: 1px solid rgba(255,255,255,.18); border-radius: 12px; background: rgba(255,255,255,.08); color: inherit; padding: 0 12px; font-size: 12px; outline: none; }
119
+ #addr:focus { border-color: #4a90d9; background: rgba(255,255,255,.14); }
120
+ #newtab { font-size: 15px; }
121
+ .strip { display: flex; align-items: stretch; gap: 2px; padding: 0 6px 4px; height: 30px; overflow-x: auto; }
122
+ .strip::-webkit-scrollbar { height: 4px; }
123
+ .tab { display: flex; align-items: center; gap: 6px; max-width: 180px; min-width: 90px; height: 24px; padding: 0 4px 0 10px; border-radius: 6px; background: rgba(255,255,255,.06); cursor: pointer; white-space: nowrap; flex: 0 0 auto; }
124
+ .tab:hover { background: rgba(255,255,255,.12); }
125
+ .tab.active { background: #3d4148; }
126
+ .tab .tt { overflow: hidden; text-overflow: ellipsis; flex: 1; }
127
+ .tab .x { width: 15px; height: 15px; border-radius: 3px; text-align: center; line-height: 15px; font-size: 10px; flex: 0 0 auto; }
128
+ .tab .x:hover { background: rgba(255,255,255,.25); }
129
+ #err { height: 0; overflow: hidden; font-size: 11px; color: #ff9090; padding: 0 8px; transition: height .15s; }
130
+ #err.show { height: 17px; }
131
+ </style>
132
+ </head>
133
+ <body>
134
+ <div class="nav">
135
+ <button class="tool" id="back" title="Back">&#9664;</button>
136
+ <button class="tool" id="fwd" title="Forward">&#9654;</button>
137
+ <button class="tool" id="reload" title="Reload">&#10227;</button>
138
+ <input id="addr" placeholder="Search or enter address" spellcheck="false">
139
+ <button class="tool" id="newtab" title="New tab">&#43;</button>
140
+ </div>
141
+ <div class="strip" id="strip"></div>
142
+ <div id="err"></div>
143
+ <script>
144
+ const bridge = window.bridge
145
+ const addr = document.getElementById('addr')
146
+ const strip = document.getElementById('strip')
147
+ const errBox = document.getElementById('err')
148
+ let showErrT = 0
149
+ function showErr(text) {
150
+ errBox.textContent = String(text)
151
+ errBox.classList.add('show')
152
+ clearTimeout(showErrT)
153
+ showErrT = setTimeout(() => errBox.classList.remove('show'), 5000)
154
+ }
155
+ function post(action, payload) { bridge.post(action, payload || {}) }
156
+ document.getElementById('back').onclick = () => post('back')
157
+ document.getElementById('fwd').onclick = () => post('forward')
158
+ document.getElementById('reload').onclick = () => post('reload')
159
+ document.getElementById('newtab').onclick = () => {
160
+ const v = addr.value.trim()
161
+ post('new-tab', v !== '' ? { url: v } : {})
162
+ addr.value = ''
163
+ }
164
+ addr.addEventListener('keydown', e => {
165
+ if (e.key === 'Enter') {
166
+ const v = addr.value.trim()
167
+ if (v !== '') { post('navigate', { url: v }); addr.blur() }
168
+ }
169
+ })
170
+ bridge.onTabs(payload => {
171
+ const tabs = (payload && payload.tabs) || []
172
+ strip.textContent = ''
173
+ for (const t of tabs) {
174
+ const el = document.createElement('div')
175
+ el.className = 'tab' + (t.active ? ' active' : '')
176
+ const tt = document.createElement('span')
177
+ tt.className = 'tt'
178
+ tt.textContent = (t.title && t.title !== '') ? t.title : ((t.url && t.url !== '' && t.url !== 'about:blank') ? t.url : 'New tab')
179
+ tt.title = t.url || ''
180
+ el.appendChild(tt)
181
+ const x = document.createElement('span')
182
+ x.className = 'x'
183
+ x.textContent = '\\u2715'
184
+ x.onclick = e => { e.stopPropagation(); post('close', { viewId: t.viewId }) }
185
+ el.appendChild(x)
186
+ el.onclick = () => post('activate', { viewId: t.viewId })
187
+ strip.appendChild(el)
188
+ }
189
+ const act = tabs.find(t => t.active)
190
+ if (act && document.activeElement !== addr) addr.value = act.url || ''
191
+ })
192
+ bridge.onError(text => showErr(text))
193
+ </script>
194
+ </body>
195
+ </html>
196
+ `;
197
+ /** Temp dir for the toolbar files; written once per process. */
198
+ const TOOLBAR_DIR = join(tmpdir(), `dsh-browser-toolbar-${process.pid}`);
199
+ let toolbarFilesReady = false;
200
+ /** Write the toolbar's html + preload to disk once. */
201
+ function ensureToolbarFiles() {
202
+ if (toolbarFilesReady)
203
+ return;
204
+ toolbarFilesReady = true;
205
+ mkdirSync(TOOLBAR_DIR, { recursive: true });
206
+ writeFileSync(join(TOOLBAR_DIR, 'preload.js'), TOOLBAR_PRELOAD);
207
+ writeFileSync(join(TOOLBAR_DIR, 'toolbar.html'), TOOLBAR_HTML);
208
+ }
42
209
  /** Reply to the parent over the RPC socket. */
43
210
  function reply(id, payload) {
44
211
  if (rpcSocket === undefined) {
@@ -47,6 +214,268 @@ function reply(id, payload) {
47
214
  }
48
215
  rpcSocket.write(JSON.stringify({ id, ...payload }) + '\n');
49
216
  }
217
+ /** Send a fire-and-forget user action to the parent (no reply expected). */
218
+ function sendUserAction(action) {
219
+ if (rpcSocket === undefined)
220
+ return;
221
+ try {
222
+ rpcSocket.write(JSON.stringify({ id: 0, op: 'userAction', action }) + '\n');
223
+ }
224
+ catch { /* socket closed */ }
225
+ }
226
+ /** Turn a typed-in address into a URL (add https:// when no scheme is given). */
227
+ function normalizeUrl(raw) {
228
+ const trimmed = raw.trim();
229
+ if (trimmed === '')
230
+ return '';
231
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed))
232
+ return trimmed;
233
+ return 'https://' + trimmed;
234
+ }
235
+ /** Route one toolbar interaction to the parent (which owns the session model). */
236
+ function handleToolbarAction(win, action, payload) {
237
+ const windowId = win.windowId;
238
+ switch (action) {
239
+ case 'navigate': {
240
+ const url = normalizeUrl(String(payload.url ?? ''));
241
+ if (url === '')
242
+ return;
243
+ sendUserAction({ type: 'navigate', windowId, url });
244
+ return;
245
+ }
246
+ case 'new-tab': {
247
+ const raw = String(payload.url ?? '').trim();
248
+ const url = raw !== '' ? normalizeUrl(raw) : undefined;
249
+ sendUserAction({ type: 'newTab', windowId, ...url !== undefined ? { url } : {} });
250
+ return;
251
+ }
252
+ case 'activate':
253
+ sendUserAction({ type: 'activateTab', windowId, viewId: String(payload.viewId ?? '') });
254
+ return;
255
+ case 'close':
256
+ sendUserAction({ type: 'closeTab', windowId, viewId: String(payload.viewId ?? '') });
257
+ return;
258
+ case 'back':
259
+ sendUserAction({ type: 'back', windowId });
260
+ return;
261
+ case 'forward':
262
+ sendUserAction({ type: 'forward', windowId });
263
+ return;
264
+ case 'reload':
265
+ sendUserAction({ type: 'reload', windowId });
266
+ return;
267
+ default:
268
+ process.stderr.write(`[dsh-browser host] unknown toolbar action: ${action}\n`);
269
+ }
270
+ }
271
+ /** Find the window holding a view, if any. */
272
+ function windowOfView(viewId) {
273
+ for (const win of windows.values()) {
274
+ if (win.views.has(viewId))
275
+ return win;
276
+ }
277
+ return undefined;
278
+ }
279
+ /** Get (or lazily create) the window for a group key. */
280
+ function windowFor(windowId) {
281
+ const key = windowId === undefined || windowId === '' ? SHARED_WINDOW_ID : windowId;
282
+ const existing = windows.get(key);
283
+ if (existing !== undefined)
284
+ return existing;
285
+ const w = new BrowserWindow({ width: 1400, height: 900, show: true, title: 'dsh-browser' });
286
+ w.on('closed', () => { windows.delete(key); });
287
+ const win = { windowId: key, window: w, toolbarView: undefined, views: new Map(), visibleViewId: undefined, lastFocusedViewId: undefined, closeTimer: undefined };
288
+ // Keep every view (and the toolbar) filling the window as the human
289
+ // resizes it; otherwise pages stay at their original size and break.
290
+ w.on('resize', () => layoutWindow(win));
291
+ // Windows: keyboard input goes only to the FOCUSED webContents, and a window
292
+ // regaining focus (alt-tab, click) does not automatically refocus any view
293
+ // (electron#28163) — the last addChildView keeps the focus. Restore the view
294
+ // the human was last using (click steering via wireFocusRouting), falling
295
+ // back to the visible page view.
296
+ w.on('focus', () => {
297
+ const last = win.lastFocusedViewId;
298
+ const wc = last === TOOLBAR_FOCUS ? win.toolbarView?.webContents
299
+ : last !== undefined ? win.views.get(last)?.webContentsView.webContents
300
+ : undefined;
301
+ const fallback = win.visibleViewId !== undefined ? win.views.get(win.visibleViewId)?.webContentsView.webContents : undefined;
302
+ try {
303
+ (wc ?? fallback)?.focus();
304
+ }
305
+ catch { /* destroyed */ }
306
+ });
307
+ windows.set(key, win);
308
+ win.toolbarView = createToolbar(win);
309
+ layoutWindow(win);
310
+ return win;
311
+ }
312
+ /** Position the toolbar and every page view within a window. */
313
+ function layoutWindow(win) {
314
+ try {
315
+ const size = win.window.getContentSize() ?? [0, 0];
316
+ const width = size[0] ?? 0;
317
+ const height = size[1] ?? 0;
318
+ try {
319
+ win.toolbarView?.setBounds({ x: 0, y: 0, width, height: TOOLBAR_HEIGHT });
320
+ }
321
+ catch { /* destroyed */ }
322
+ for (const v of win.views.values()) {
323
+ try {
324
+ v.webContentsView.setBounds({ x: 0, y: TOOLBAR_HEIGHT, width, height: Math.max(0, height - TOOLBAR_HEIGHT) });
325
+ }
326
+ catch { /* destroyed */ }
327
+ }
328
+ }
329
+ catch { /* window gone */ }
330
+ }
331
+ /**
332
+ * Route keyboard focus on Windows. Mouse clicks reach any view regardless of
333
+ * focus, but keyboard events go only to the FOCUSED webContents (and a window
334
+ * regaining focus does not refocus any view, electron#28163). Focusing the
335
+ * clicked view on mousedown makes the toolbar and pages behave like a real
336
+ * browser: click the URL bar and type, click the page and type/scroll.
337
+ */
338
+ function wireFocusRouting(win, view, focusKey) {
339
+ view.webContents.on('input-event', (_event, input) => {
340
+ if (input.type !== 'mouseDown')
341
+ return;
342
+ win.lastFocusedViewId = focusKey;
343
+ try {
344
+ view.webContents.focus();
345
+ }
346
+ catch { /* destroyed */ }
347
+ });
348
+ }
349
+ /** Create the toolbar view for a window (best-effort; never fatal). */
350
+ function createToolbar(win) {
351
+ try {
352
+ ensureToolbarFiles();
353
+ const view = new WebContentsView({
354
+ webPreferences: {
355
+ preload: join(TOOLBAR_DIR, 'preload.js'),
356
+ sandbox: true,
357
+ contextIsolation: true,
358
+ nodeIntegration: false,
359
+ },
360
+ });
361
+ void view.webContents.loadFile(join(TOOLBAR_DIR, 'toolbar.html')).catch(() => { });
362
+ view.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
363
+ view.webContents.on('ipc-message', (_event, channel, ...args) => {
364
+ if (channel !== 'toolbar-action')
365
+ return;
366
+ // Diagnostics only; the parent never parses stderr.
367
+ process.stderr.write(`[dsh-browser host] toolbar action: ${String(args[0] ?? '')}\n`);
368
+ handleToolbarAction(win, String(args[0] ?? ''), (args[1] ?? {}));
369
+ });
370
+ // Once the toolbar page is up, push the current tab strip so it is not
371
+ // empty until the first navigation event.
372
+ view.webContents.on('dom-ready', () => syncToolbar(win));
373
+ wireFocusRouting(win, view, TOOLBAR_FOCUS);
374
+ win.window.contentView.addChildView(view);
375
+ return view;
376
+ }
377
+ catch (error) {
378
+ process.stderr.write(`[dsh-browser host] toolbar creation failed: ${String(error)}\n`);
379
+ return undefined;
380
+ }
381
+ }
382
+ /** Push the window's tab strip state to its toolbar. */
383
+ function syncToolbar(win) {
384
+ if (win.toolbarView === undefined)
385
+ return;
386
+ const tabs = [];
387
+ for (const [viewId, v] of win.views) {
388
+ let title = '';
389
+ let url = '';
390
+ try {
391
+ title = v.webContentsView.webContents.getTitle();
392
+ url = v.webContentsView.webContents.getURL();
393
+ }
394
+ catch { /* destroyed */ }
395
+ tabs.push({ viewId, title, url, active: viewId === win.visibleViewId });
396
+ }
397
+ try {
398
+ win.toolbarView.webContents.send('tabs', { tabs });
399
+ }
400
+ catch { /* toolbar not loaded yet */ }
401
+ }
402
+ /** Set a window's title: dsh-browser [label] — page title — url. */
403
+ function updateWindowTitle(win, viewId, label) {
404
+ try {
405
+ let title = 'dsh-browser';
406
+ if (label !== undefined && label !== '')
407
+ title += ` [${label.slice(0, 48)}]`;
408
+ const entry = viewId !== undefined ? win.views.get(viewId) : undefined;
409
+ if (entry !== undefined) {
410
+ const pageTitle = entry.webContentsView.webContents.getTitle();
411
+ const url = entry.webContentsView.webContents.getURL();
412
+ if (pageTitle !== '')
413
+ title += ` — ${pageTitle}`;
414
+ if (url !== '' && url !== 'about:blank')
415
+ title += ` — ${url}`;
416
+ }
417
+ win.window.setTitle(title);
418
+ }
419
+ catch { /* destroyed */ }
420
+ }
421
+ /** Make one view the visible (topmost) one within its window. */
422
+ function showViewInWindow(win, viewId, label) {
423
+ const entry = win.views.get(viewId);
424
+ if (entry === undefined)
425
+ return;
426
+ if (win.visibleViewId !== viewId) {
427
+ // Hide every other view in THIS window, then show and RAISE the target
428
+ // (topmost child wins). When the target is already visible, skip the
429
+ // remove/re-add dance — doing it on every operation flickered.
430
+ for (const v of win.views.values()) {
431
+ if (v === entry)
432
+ continue;
433
+ try {
434
+ v.webContentsView.setVisible(false);
435
+ }
436
+ catch { /* destroyed */ }
437
+ }
438
+ entry.webContentsView.setVisible(true);
439
+ try {
440
+ win.window.contentView.removeChildView(entry.webContentsView);
441
+ win.window.contentView.addChildView(entry.webContentsView);
442
+ }
443
+ catch { /* window closing */ }
444
+ win.visibleViewId = viewId;
445
+ syncToolbar(win);
446
+ }
447
+ // Always refresh the title: it reflects the CURRENT page of the visible
448
+ // view, which changes as the agent navigates.
449
+ updateWindowTitle(win, viewId, label);
450
+ // Raise this session's window so the human sees the page being worked on
451
+ // (moveTop raises without stealing keyboard focus).
452
+ try {
453
+ if (!win.window.isVisible())
454
+ win.window.show();
455
+ win.window.moveTop();
456
+ }
457
+ catch { /* closing */ }
458
+ }
459
+ /** Close a session window once its last view is gone (deferred, flicker-free). */
460
+ function scheduleWindowClose(win) {
461
+ if (win.windowId === SHARED_WINDOW_ID)
462
+ return; // shared fallback persists
463
+ if (win.closeTimer !== undefined)
464
+ clearTimeout(win.closeTimer);
465
+ win.closeTimer = setTimeout(() => {
466
+ win.closeTimer = undefined;
467
+ if (win.views.size > 0)
468
+ return; // a new tab arrived; keep the window
469
+ try {
470
+ win.toolbarView?.webContents.close();
471
+ }
472
+ catch { /* already gone */ }
473
+ try {
474
+ win.window.close();
475
+ }
476
+ catch { /* already gone */ }
477
+ }, 250);
478
+ }
50
479
  /** Handle one command. */
51
480
  async function handle(op, msg) {
52
481
  try {
@@ -54,27 +483,59 @@ async function handle(op, msg) {
54
483
  case 'ping':
55
484
  reply(msg.id, { ok: true });
56
485
  return;
486
+ case 'groupView': {
487
+ const viewId = msg.viewId;
488
+ const windowId = msg.windowId;
489
+ if (viewId === undefined || typeof windowId !== 'string')
490
+ throw new Error('groupView missing viewId/windowId');
491
+ // May arrive before or after createView; createView consumes it.
492
+ assignments.set(viewId, { windowId, ...typeof msg.label === 'string' ? { label: msg.label } : {} });
493
+ reply(msg.id, { ok: true });
494
+ return;
495
+ }
57
496
  case 'createView': {
58
497
  const viewId = msg.viewId;
59
498
  if (viewId === undefined)
60
499
  throw new Error('createView missing viewId');
61
- if (window === undefined) {
62
- window = new BrowserWindow({ width: 1400, height: 900, show: true, title: 'dsh-browser' });
63
- window.on('closed', () => { window = undefined; });
64
- }
500
+ const assignment = assignments.get(viewId);
501
+ const win = windowFor(assignment?.windowId);
65
502
  const view = new WebContentsView();
503
+ // Route popups (window.open / target=_blank) back into THIS view
504
+ // instead of letting Electron open untracked native windows that would
505
+ // diverge from the session/tab model.
506
+ view.webContents.setWindowOpenHandler(({ url }) => {
507
+ // HTTP(S) popups (target=_blank, ads): redirect into this view
508
+ // instead of opening an untracked native window.
509
+ if (/^https?:/i.test(url)) {
510
+ void view.webContents.loadURL(url).catch(() => { });
511
+ return { action: 'deny' };
512
+ }
513
+ // Non-HTTP popups (OAuth redirects, mailto:, custom schemes):
514
+ // allow the native window so OAuth flows and deep links work.
515
+ return { action: 'allow' };
516
+ });
66
517
  // Attach the debugger BEFORE the view can be seen: an attach failure
67
518
  // then leaves nothing in the window (no visible ghost view).
68
519
  view.webContents.debugger.attach(CDP_VERSION);
69
- // New views start hidden: with several sessions/tabs only the shown
70
- // one may be visible (they stack in contentView child order).
520
+ // New views start hidden: only the shown one may be visible.
71
521
  view.setVisible(false);
72
- window.contentView.addChildView(view);
73
- const [width, height] = window.getContentSize();
74
- view.setBounds({ x: 0, y: 0, width: width ?? 0, height: height ?? 0 });
75
- if (views.size === 0)
522
+ win.window.contentView.addChildView(view);
523
+ win.views.set(viewId, { webContentsView: view });
524
+ // Keep the window title and the toolbar tab strip live as the page
525
+ // changes (navigations, title updates).
526
+ view.webContents.on('page-title-updated', () => { updateWindowTitle(win, viewId, undefined); syncToolbar(win); });
527
+ view.webContents.on('did-navigate', () => { updateWindowTitle(win, viewId, undefined); syncToolbar(win); });
528
+ view.webContents.on('did-navigate-in-page', () => syncToolbar(win));
529
+ wireFocusRouting(win, view, viewId);
530
+ const first = win.views.size === 1;
531
+ if (first) {
76
532
  view.setVisible(true);
77
- views.set(viewId, { webContentsView: view });
533
+ win.visibleViewId = viewId;
534
+ }
535
+ layoutWindow(win);
536
+ if (first)
537
+ updateWindowTitle(win, viewId, undefined);
538
+ syncToolbar(win);
78
539
  reply(msg.id, { ok: true });
79
540
  return;
80
541
  }
@@ -82,16 +543,42 @@ async function handle(op, msg) {
82
543
  const viewId = msg.viewId;
83
544
  if (viewId === undefined)
84
545
  throw new Error('destroyView missing viewId');
85
- const entry = views.get(viewId);
86
- if (entry !== undefined) {
87
- views.delete(viewId);
546
+ const win = windowOfView(viewId);
547
+ if (win !== undefined) {
548
+ const entry = win.views.get(viewId);
549
+ win.views.delete(viewId);
550
+ if (win.visibleViewId === viewId)
551
+ win.visibleViewId = undefined;
88
552
  try {
89
- entry.webContentsView.webContents.debugger.detach();
553
+ entry?.webContentsView.webContents.debugger.detach();
90
554
  }
91
555
  catch { /* already detached */ }
92
- entry.webContentsView.webContents.close();
93
- window?.contentView.removeChildView(entry.webContentsView);
556
+ try {
557
+ entry?.webContentsView.webContents.close();
558
+ }
559
+ catch { /* destroyed */ }
560
+ try {
561
+ if (entry !== undefined)
562
+ win.window.contentView.removeChildView(entry.webContentsView);
563
+ }
564
+ catch { /* destroyed */ }
565
+ // The visible tab was destroyed: show the next one in this window.
566
+ if (win.visibleViewId === undefined && win.views.size > 0) {
567
+ const next = win.views.keys().next().value;
568
+ if (next !== undefined)
569
+ showViewInWindow(win, next);
570
+ }
571
+ else if (win.visibleViewId === undefined) {
572
+ // No views left — reset the window title so it doesn't
573
+ // retain the old page's title.
574
+ updateWindowTitle(win, undefined, undefined);
575
+ }
576
+ syncToolbar(win);
577
+ // Close the window with its last view — deferred because the
578
+ // provider re-creates a blank tab right after closing the last one.
579
+ scheduleWindowClose(win);
94
580
  }
581
+ assignments.delete(viewId);
95
582
  reply(msg.id, { ok: true });
96
583
  return;
97
584
  }
@@ -99,23 +586,23 @@ async function handle(op, msg) {
99
586
  const viewId = msg.viewId;
100
587
  if (viewId === undefined)
101
588
  throw new Error('showView missing viewId');
102
- const entry = views.get(viewId);
103
- if (entry !== undefined) {
104
- // Hide every other view, then show and RAISE the target so the
105
- // human actually sees the active tab/session (topmost child wins).
106
- for (const v of views.values()) {
107
- if (v === entry)
108
- continue;
109
- try {
110
- v.webContentsView.setVisible(false);
111
- }
112
- catch { /* destroyed */ }
113
- }
114
- entry.webContentsView.setVisible(true);
115
- if (window !== undefined) {
116
- window.contentView.removeChildView(entry.webContentsView);
117
- window.contentView.addChildView(entry.webContentsView);
589
+ const win = windowOfView(viewId);
590
+ if (win !== undefined)
591
+ showViewInWindow(win, viewId, typeof msg.label === 'string' ? msg.label : undefined);
592
+ reply(msg.id, { ok: true });
593
+ return;
594
+ }
595
+ case 'userActionError': {
596
+ const windowId = msg.windowId;
597
+ const message = msg.message;
598
+ if (typeof windowId !== 'string' || typeof message !== 'string')
599
+ throw new Error('userActionError missing windowId/message');
600
+ const win = windows.get(windowId);
601
+ if (win !== undefined) {
602
+ try {
603
+ win.toolbarView?.webContents.send('user-action-error', message);
118
604
  }
605
+ catch { /* toolbar not loaded */ }
119
606
  }
120
607
  reply(msg.id, { ok: true });
121
608
  return;
@@ -124,8 +611,9 @@ async function handle(op, msg) {
124
611
  const viewId = msg.viewId;
125
612
  if (viewId === undefined)
126
613
  throw new Error('command missing viewId');
127
- const entry = views.get(viewId);
128
- if (entry === undefined)
614
+ const win = windowOfView(viewId);
615
+ const entry = win?.views.get(viewId);
616
+ if (win === undefined || entry === undefined)
129
617
  throw new Error(`command: unknown view ${viewId}`);
130
618
  const method = msg.method;
131
619
  if (typeof method !== 'string')
@@ -138,8 +626,9 @@ async function handle(op, msg) {
138
626
  const viewId = msg.viewId;
139
627
  if (viewId === undefined)
140
628
  throw new Error('capture missing viewId');
141
- const entry = views.get(viewId);
142
- if (entry === undefined)
629
+ const win = windowOfView(viewId);
630
+ const entry = win?.views.get(viewId);
631
+ if (win === undefined || entry === undefined)
143
632
  throw new Error(`capture: unknown view ${viewId}`);
144
633
  // Two complementary paths, because each has a failure mode:
145
634
  // - capturePage: fast and reliable with several WebContentsViews in
@@ -148,18 +637,23 @@ async function handle(op, msg) {
148
637
  // - CDP Page.captureScreenshot: works without a display surface, but
149
638
  // can hang when another hidden WebContentsView exists in the window.
150
639
  // Try capturePage first (show/focus/restore + one retry), then CDP.
151
- if (window !== undefined) {
152
- try {
153
- if (!window.isVisible())
154
- window.show();
155
- }
156
- catch { /* closing */ }
157
- try {
158
- window.restore();
159
- }
160
- catch { /* not minimized */ }
161
- window.focus();
640
+ // PNG/JPEG + downscale are applied on the NativeImage here, so the
641
+ // body never needs a second round-trip.
642
+ const wantFormat = msg.format === 'jpeg' ? 'jpeg' : 'png';
643
+ const wantQuality = typeof msg.quality === 'number' ? msg.quality : 80;
644
+ const maxW = typeof msg.maxWidth === 'number' ? msg.maxWidth : 0;
645
+ const maxH = typeof msg.maxHeight === 'number' ? msg.maxHeight : 0;
646
+ let mime = 'image/png';
647
+ try {
648
+ if (!win.window.isVisible())
649
+ win.window.show();
650
+ }
651
+ catch { /* closing */ }
652
+ try {
653
+ win.window.restore();
162
654
  }
655
+ catch { /* not minimized */ }
656
+ win.window.focus();
163
657
  let base64 = '';
164
658
  try {
165
659
  let image;
@@ -171,28 +665,46 @@ async function handle(op, msg) {
171
665
  await new Promise(resolve => setTimeout(resolve, 400));
172
666
  image = await entry.webContentsView.webContents.capturePage();
173
667
  }
174
- const png = image.toPNG();
175
- if (png.length > 0)
176
- base64 = png.toString('base64');
668
+ // Downscale to fit the requested box, preserving aspect ratio.
669
+ const size = image.getSize();
670
+ let w = size.width ?? 0;
671
+ let h = size.height ?? 0;
672
+ if (maxW > 0 && w > maxW) {
673
+ h = Math.round(h * maxW / w);
674
+ w = maxW;
675
+ }
676
+ if (maxH > 0 && h > maxH) {
677
+ w = Math.round(w * maxH / h);
678
+ h = maxH;
679
+ }
680
+ if (w > 0 && h > 0 && (w !== size.width || h !== size.height))
681
+ image = image.resize({ width: w, height: h });
682
+ const buf = wantFormat === 'jpeg' ? image.toJPEG(wantQuality) : image.toPNG();
683
+ if (wantFormat === 'jpeg')
684
+ mime = 'image/jpeg';
685
+ if (buf.length > 0)
686
+ base64 = buf.toString('base64');
177
687
  }
178
688
  catch (error) {
179
- const state = window !== undefined
180
- ? JSON.stringify({
181
- win: { visible: window.isVisible(), minimized: window.isMinimized(), focused: window.isFocused() },
182
- })
183
- : 'no-window';
184
- process.stderr.write(`[dsh-browser host] capturePage retry failed: ${String(error)} state=${state}\n`);
689
+ process.stderr.write(`[dsh-browser host] capturePage retry failed: ${String(error)}\n`);
185
690
  base64 = '';
186
691
  }
187
692
  if (base64 === '') {
188
693
  // CDP fallback. Page.captureScreenshot can hang when OTHER views
189
694
  // (especially hidden attach-first ones) are in the window, so
190
- // temporarily detach the siblings, capture in single-view state,
191
- // then restore them (target stays on top).
192
- const siblings = [...views.values()].filter(v => v !== entry);
695
+ // temporarily detach the siblings AND the toolbar, capture in
696
+ // single-view state, then restore them (target stays on top).
697
+ const siblings = [...win.views.values()].filter(v => v !== entry);
698
+ const toolbar = win.toolbarView;
193
699
  for (const v of siblings) {
194
700
  try {
195
- window?.contentView.removeChildView(v.webContentsView);
701
+ win.window.contentView.removeChildView(v.webContentsView);
702
+ }
703
+ catch { /* already gone */ }
704
+ }
705
+ if (toolbar !== undefined) {
706
+ try {
707
+ win.window.contentView.removeChildView(toolbar);
196
708
  }
197
709
  catch { /* already gone */ }
198
710
  }
@@ -203,15 +715,21 @@ async function handle(op, msg) {
203
715
  base64 = data;
204
716
  }
205
717
  finally {
718
+ if (toolbar !== undefined) {
719
+ try {
720
+ win.window.contentView.addChildView(toolbar);
721
+ }
722
+ catch { /* destroyed */ }
723
+ }
206
724
  for (const v of siblings) {
207
725
  try {
208
- window?.contentView.addChildView(v.webContentsView);
726
+ win.window.contentView.addChildView(v.webContentsView);
209
727
  }
210
728
  catch { /* destroyed */ }
211
729
  }
212
730
  try {
213
- window?.contentView.removeChildView(entry.webContentsView);
214
- window?.contentView.addChildView(entry.webContentsView);
731
+ win.window.contentView.removeChildView(entry.webContentsView);
732
+ win.window.contentView.addChildView(entry.webContentsView);
215
733
  }
216
734
  catch { /* closing */ }
217
735
  }
@@ -219,7 +737,7 @@ async function handle(op, msg) {
219
737
  if (base64 === '') {
220
738
  throw new Error('capture produced no image (view not painted)');
221
739
  }
222
- reply(msg.id, { ok: true, result: { base64, width: 0, height: 0 } });
740
+ reply(msg.id, { ok: true, result: { base64, mime } });
223
741
  return;
224
742
  }
225
743
  case 'download': {
@@ -229,20 +747,51 @@ async function handle(op, msg) {
229
747
  if (viewId === undefined || typeof url !== 'string' || typeof savePath !== 'string') {
230
748
  throw new Error('download missing viewId/url/savePath');
231
749
  }
232
- const entry = views.get(viewId);
233
- if (entry === undefined)
750
+ const win = windowOfView(viewId);
751
+ const entry = win?.views.get(viewId);
752
+ if (win === undefined || entry === undefined)
234
753
  throw new Error(`download: unknown view ${viewId}`);
235
754
  // Fetch the URL inside the page context (keeps cookies/login), read
236
- // the body as base64, and return it; the parent writes the file. This
237
- // avoids Electron's download pipeline entirely (CDP debugger attach
238
- // can interfere with will-download).
755
+ // the body as base64, and write the file HERE — the body never
756
+ // crosses the RPC line protocol, so large downloads cannot balloon
757
+ // the parent's memory or hit the single-line cap. This also avoids
758
+ // Electron's download pipeline entirely (CDP debugger attach can
759
+ // interfere with will-download).
239
760
  const result = await entry.webContentsView.webContents.debugger.sendCommand('Runtime.evaluate', {
761
+ // Stream the body through a reader so the size cap is enforced as
762
+ // bytes arrive — never buffer an unbounded download into memory
763
+ // before checking the limit (a huge URL would otherwise OOM the
764
+ // renderer). The declared Content-Length short-circuits large files
765
+ // before any body is read.
240
766
  expression: `(async () => {
241
767
  const r = await fetch(${JSON.stringify(url)}, { credentials: 'include' })
242
768
  if (!r.ok) throw new Error('HTTP ' + r.status)
243
- const b = await r.arrayBuffer()
244
- const bytes = new Uint8Array(b)
245
- if (bytes.length > ${String(MAX_DOWNLOAD_BYTES)}) throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, got ' + bytes.length + ')')
769
+ const declared = Number(r.headers.get('content-length') || 0)
770
+ if (declared > ${String(MAX_DOWNLOAD_BYTES)}) throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, declared ' + declared + ')')
771
+ if (!r.body || typeof r.body.getReader !== 'function') {
772
+ const b = await r.arrayBuffer()
773
+ const bytes = new Uint8Array(b)
774
+ if (bytes.length > ${String(MAX_DOWNLOAD_BYTES)}) throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, got ' + bytes.length + ')')
775
+ let bin = ''
776
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000))
777
+ return btoa(bin)
778
+ }
779
+ const reader = r.body.getReader()
780
+ const chunks = []
781
+ let total = 0
782
+ for (;;) {
783
+ const { done, value } = await reader.read()
784
+ if (done) break
785
+ total += value.length
786
+ if (total > ${String(MAX_DOWNLOAD_BYTES)}) {
787
+ await reader.cancel()
788
+ throw new Error('download too large (limit ' + ${String(MAX_DOWNLOAD_BYTES)} + ' bytes, got ' + total + ')')
789
+ }
790
+ chunks.push(value)
791
+ }
792
+ const bytes = new Uint8Array(total)
793
+ let off = 0
794
+ for (const c of chunks) { bytes.set(c, off); off += c.length }
246
795
  let bin = ''
247
796
  for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000))
248
797
  return btoa(bin)
@@ -255,28 +804,49 @@ async function handle(op, msg) {
255
804
  const detail = result.exceptionDetails;
256
805
  throw new Error(`download failed: ${detail?.exception?.description ?? 'no data'}`);
257
806
  }
258
- reply(msg.id, { ok: true, result: { base64: value, savePath } });
807
+ // Temp file + rename keeps the write atomic-ish: a crash mid-write
808
+ // leaves only a `.part` file, never a half-written final file.
809
+ const tmpPath = savePath + '.part';
810
+ mkdirSync(dirname(savePath), { recursive: true });
811
+ writeFileSync(tmpPath, Buffer.from(value, 'base64'));
812
+ try {
813
+ renameSync(tmpPath, savePath);
814
+ }
815
+ catch (error) {
816
+ // A failed rename must not leave a stray .part behind.
817
+ try {
818
+ unlinkSync(tmpPath);
819
+ }
820
+ catch { /* already gone */ }
821
+ throw error;
822
+ }
823
+ reply(msg.id, { ok: true, result: { path: savePath } });
259
824
  return;
260
825
  }
261
826
  case 'flushAuth': {
262
827
  const viewId = msg.viewId;
263
828
  if (viewId === undefined)
264
829
  throw new Error('flushAuth missing viewId');
265
- const entry = views.get(viewId);
266
- if (entry === undefined)
830
+ const win = windowOfView(viewId);
831
+ const entry = win?.views.get(viewId);
832
+ if (win === undefined || entry === undefined)
267
833
  throw new Error(`flushAuth: unknown view ${viewId}`);
268
834
  // Export the session's cookies so login state can be saved/restored
269
835
  // across browser hosts (or shared with another machine).
270
836
  const cookies = await entry.webContentsView.webContents.session.cookies.get({});
271
837
  const exported = cookies.map(c => {
272
- const host = c.domain.startsWith('.') ? c.domain.slice(1) : c.domain;
838
+ // Electron types the cookie domain as optional; a missing domain
839
+ // cannot be exported meaningfully, so default to '' (matches the
840
+ // shim's string typing and keeps the export shape stable).
841
+ const domain = c.domain ?? '';
842
+ const host = domain.startsWith('.') ? domain.slice(1) : domain;
273
843
  // IPv6 literal domains need brackets in a URL (e.g. http://[::1]/).
274
844
  const hostPart = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
275
845
  return {
276
846
  url: `http${c.secure ? 's' : ''}://${hostPart}${c.path}`,
277
847
  name: c.name,
278
848
  value: c.value,
279
- domain: c.domain,
849
+ domain,
280
850
  path: c.path,
281
851
  secure: c.secure,
282
852
  httpOnly: c.httpOnly,
@@ -291,8 +861,9 @@ async function handle(op, msg) {
291
861
  const cookies = msg.cookies;
292
862
  if (viewId === undefined)
293
863
  throw new Error('restoreAuth missing viewId');
294
- const entry = views.get(viewId);
295
- if (entry === undefined)
864
+ const win = windowOfView(viewId);
865
+ const entry = win?.views.get(viewId);
866
+ if (win === undefined || entry === undefined)
296
867
  throw new Error(`restoreAuth: unknown view ${viewId}`);
297
868
  if (!Array.isArray(cookies))
298
869
  throw new Error('restoreAuth missing cookies array');
@@ -340,6 +911,28 @@ void app.whenReady().then(() => {
340
911
  const socket = createConnection({ host: '127.0.0.1', port });
341
912
  rpcSocket = socket;
342
913
  socket.setEncoding('utf8');
914
+ // Prove we know the parent's spawn token before anything else; the parent
915
+ // refuses a connection whose first line is not this hello. The token is
916
+ // written to stdin at spawn (moments after process start, long before
917
+ // Electron's whenReady resolves), but guard the ordering anyway: sending an
918
+ // empty hello would read as a spoofed connection and tear the session down.
919
+ const writeHello = () => {
920
+ socket.write(JSON.stringify({ id: 0, op: 'hello', token: RPC_TOKEN }) + '\n');
921
+ };
922
+ if (RPC_TOKEN !== '') {
923
+ writeHello();
924
+ }
925
+ else {
926
+ // No token yet (env absent and stdin still pending): wait for stdin's
927
+ // first line with a bounded fallback, then send whatever we have — an
928
+ // empty hello is refused by the parent, which then fails cleanly.
929
+ const fallback = setTimeout(() => writeHello(), 2_000);
930
+ if (process.stdin !== null && process.stdin.readable) {
931
+ const stdinLines = createInterface({ input: process.stdin, terminal: false });
932
+ stdinLines.once('line', () => { clearTimeout(fallback); writeHello(); });
933
+ stdinLines.once('close', () => { clearTimeout(fallback); writeHello(); });
934
+ }
935
+ }
343
936
  const rl = createInterface({ input: socket });
344
937
  rl.on('line', line => {
345
938
  const text = line.trim();