dsh-builtin-browser 0.4.14 → 0.5.1

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.en.md +17 -9
  3. package/README.md +48 -10
  4. package/client.js +410 -6
  5. package/desktop-bridge/install-and-start.cmd +36 -0
  6. package/desktop-bridge/install.mjs +166 -3
  7. package/desktop-bridge/plugin-browser-bridge.js +133 -11
  8. package/docs/development.md +19 -0
  9. package/docs/limitations.md +7 -3
  10. package/docs/user-guide.md +46 -18
  11. package/lib/browser/runtime.d.ts +21 -2
  12. package/lib/browser/runtime.js +30 -0
  13. package/lib/browser/types.d.ts +54 -0
  14. package/lib/browser-electron/bridge-status.d.ts +41 -0
  15. package/lib/browser-electron/bridge-status.js +164 -0
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
  17. package/lib/browser-electron/desktop-bridge-host.js +75 -44
  18. package/lib/browser-electron/entry.js +130 -11
  19. package/lib/browser-electron/file-write.d.ts +2 -0
  20. package/lib/browser-electron/file-write.js +39 -0
  21. package/lib/browser-electron/history-store.d.ts +8 -19
  22. package/lib/browser-electron/history-store.js +37 -58
  23. package/lib/browser-electron/host-main.js +15 -22
  24. package/lib/browser-electron/preview-route.d.ts +89 -0
  25. package/lib/browser-electron/preview-route.js +172 -0
  26. package/lib/browser-electron/provider.d.ts +62 -3
  27. package/lib/browser-electron/provider.js +246 -12
  28. package/lib/browser-electron/remote-host.js +5 -1
  29. package/lib/browser-electron/rpc-input.d.ts +4 -0
  30. package/lib/browser-electron/rpc-input.js +11 -0
  31. package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
  32. package/lib/browser-electron/runtime-diagnostics.js +29 -0
  33. package/lib/browser-electron/settings-store.d.ts +15 -2
  34. package/lib/browser-electron/settings-store.js +25 -5
  35. package/lib/browser-electron/system-browser.d.ts +18 -0
  36. package/lib/browser-electron/system-browser.js +158 -37
  37. package/lib/tool-browser/index.js +10 -1
  38. package/package.json +8 -3
  39. package/scripts/install-electron.mjs +66 -0
  40. package/scripts/verify-preview-route.mjs +150 -0
  41. package/src/browser/runtime.ts +36 -0
  42. package/src/browser/types.ts +55 -0
  43. package/src/browser-electron/bridge-status.ts +180 -0
  44. package/src/browser-electron/desktop-bridge-host.ts +75 -41
  45. package/src/browser-electron/entry.ts +119 -11
  46. package/src/browser-electron/file-write.ts +31 -0
  47. package/src/browser-electron/history-store.ts +36 -57
  48. package/src/browser-electron/host-main.ts +16 -18
  49. package/src/browser-electron/preview-route.ts +222 -0
  50. package/src/browser-electron/provider.ts +286 -16
  51. package/src/browser-electron/remote-host.ts +5 -1
  52. package/src/browser-electron/rpc-input.ts +13 -0
  53. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  54. package/src/browser-electron/settings-store.ts +37 -5
  55. package/src/browser-electron/system-browser.ts +149 -32
  56. package/src/tool-browser/index.ts +13 -1
@@ -0,0 +1,11 @@
1
+ import { createInterface } from 'node:readline';
2
+ /** Read RPC lines while keeping transport errors owned by the socket. */
3
+ export function createRpcLineReader(socket, onError) {
4
+ socket.on('error', onError);
5
+ const reader = createInterface({ input: socket });
6
+ // readline forwards input errors as its own 'error' event. The socket
7
+ // listener above already reports that same error; receive the forwarded
8
+ // event too so a transport failure does not become uncaughtException.
9
+ reader.on('error', () => { });
10
+ return reader;
11
+ }
@@ -0,0 +1,12 @@
1
+ /** Versions reported by the running child, never inferred from an npm package or path. */
2
+ interface RuntimeVersions {
3
+ readonly electron?: string;
4
+ readonly chrome?: string;
5
+ readonly node?: string;
6
+ }
7
+ /**
8
+ * Startup diagnostics only: an explicit runtime remains the user's choice.
9
+ * Keep this pure so availability checks never spawn Electron or download it.
10
+ */
11
+ export declare function electronRuntimeDiagnosticLines(versions: RuntimeVersions, stamp?: string): string[];
12
+ export {};
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Startup diagnostics only: an explicit runtime remains the user's choice.
3
+ * Keep this pure so availability checks never spawn Electron or download it.
4
+ */
5
+ export function electronRuntimeDiagnosticLines(versions, stamp = new Date().toISOString()) {
6
+ const electron = versions.electron?.trim() || 'unknown';
7
+ const lines = [
8
+ `${stamp} runtime: electron=${electron} chromium=${versions.chrome?.trim() || 'unknown'} node=${versions.node?.trim() || 'unknown'}`,
9
+ ];
10
+ const parsed = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(electron);
11
+ const continuing = 'continuing with the selected runtime. Update its installation, or change/remove ELECTRON_PATH if that override selects it.';
12
+ if (parsed === null || Number(parsed[1]) !== 44) {
13
+ // Other maintained branches can be patched for the advisory below. An
14
+ // untested major is a compatibility warning, not a vulnerability claim.
15
+ lines.push(`${stamp} warning: Electron ${electron} is not verified for this plugin; expected stable Electron 44.x >=44.9.1; ${continuing}`);
16
+ return lines;
17
+ }
18
+ const minor = Number(parsed[2]);
19
+ const patch = Number(parsed[3]);
20
+ const prerelease = parsed[4] !== undefined;
21
+ // A prerelease of 44.9.1 sorts before the patched stable release.
22
+ if (minor < 9 || (minor === 9 && (patch < 1 || (patch === 1 && prerelease)))) {
23
+ lines.push(`${stamp} warning: Electron ${electron} is below the 44.x security minimum 44.9.1 (GHSA-jr5w-w6x2-84p9); ${continuing}`);
24
+ }
25
+ else if (prerelease) {
26
+ lines.push(`${stamp} warning: Electron ${electron} is a prerelease and is not verified for this plugin; expected stable Electron 44.x >=44.9.1; ${continuing}`);
27
+ }
28
+ return lines;
29
+ }
@@ -4,8 +4,8 @@
4
4
  * they survive the browser process and DSH restarts.
5
5
  *
6
6
  * Every field is optional on disk and falls back to a default, so a hand-edited
7
- * or older file never breaks startup; an unreadable file is treated as "all
8
- * defaults" rather than an error.
7
+ * or older file never breaks startup; an unreadable document refuses capability
8
+ * gates while retaining the defaults for presentation and other conveniences.
9
9
  * @module dsh-browser/browser-electron/settings-store
10
10
  */
11
11
  import type { BrowserChannel } from './system-browser.js';
@@ -68,6 +68,19 @@ export interface BrowserSettings {
68
68
  readonly credentials: {
69
69
  readonly allowRead: boolean;
70
70
  };
71
+ /**
72
+ * Live view of the browser for a remote operator (issue #34).
73
+ *
74
+ * OFF by default, and that default is the feature's main safety property: a live browser frame can
75
+ * contain a CAPTCHA, an account name, or logged-in content, so nobody should be able to watch
76
+ * without the host having said yes first. The remote side also cannot turn it on: this file is
77
+ * written through the plugin's own settings route, which admits only same-origin requests from the
78
+ * host's own UI, and the frame endpoint refuses everything when this is false.
79
+ */
80
+ readonly remoteView: {
81
+ /** Serve browser frames to a remote viewer. */
82
+ readonly enabled: boolean;
83
+ };
71
84
  /**
72
85
  * What the agent is allowed to DO, as opposed to what it may look at.
73
86
  *
@@ -4,8 +4,8 @@
4
4
  * they survive the browser process and DSH restarts.
5
5
  *
6
6
  * Every field is optional on disk and falls back to a default, so a hand-edited
7
- * or older file never breaks startup; an unreadable file is treated as "all
8
- * defaults" rather than an error.
7
+ * or older file never breaks startup; an unreadable document refuses capability
8
+ * gates while retaining the defaults for presentation and other conveniences.
9
9
  * @module dsh-browser/browser-electron/settings-store
10
10
  */
11
11
  import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
@@ -24,6 +24,9 @@ export const DEFAULT_SETTINGS = {
24
24
  // it starts a real Chrome/Edge with its own profile.
25
25
  browser: { channel: 'bundled', headless: 'auto' },
26
26
  credentials: { allowRead: true },
27
+ // Off unless the host turns it on. A frame can show a CAPTCHA, an account name, or logged-in
28
+ // content, so watching is an explicit decision rather than something a remote client can arrange.
29
+ remoteView: { enabled: false },
27
30
  actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
28
31
  };
29
32
  /**
@@ -167,7 +170,9 @@ function section(source, key) {
167
170
  * @returns the resolved settings.
168
171
  */
169
172
  export function resolveSettings(raw, warn) {
170
- const source = typeof raw === 'object' && raw !== null ? raw : {};
173
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
174
+ return SETTINGS_WHEN_UNREADABLE;
175
+ const source = raw;
171
176
  const history = section(source, 'history');
172
177
  const cookies = section(source, 'cookies');
173
178
  const ui = section(source, 'ui');
@@ -175,6 +180,7 @@ export function resolveSettings(raw, warn) {
175
180
  const credentials = section(source, 'credentials');
176
181
  const browser = section(source, 'browser');
177
182
  const actions = section(source, 'actions');
183
+ const remoteView = section(source, 'remoteView');
178
184
  // A section that is present but unreadable refuses its gates rather than defaulting them
179
185
  // open. The rest of a broken section keeps its defaults: refusing history or presentation
180
186
  // would punish the user for a bad file without protecting anything.
@@ -215,6 +221,14 @@ export function resolveSettings(raw, warn) {
215
221
  ? false
216
222
  : gate(actionsUsable.allowCredentialWrite, DEFAULT_SETTINGS.actions.allowCredentialWrite),
217
223
  },
224
+ // Fail-closed, and stated separately from `gate`'s fallback so the intent is visible: an
225
+ // unreadable or absent section means nobody watches. Unlike the other switches, whose defaults
226
+ // are "on", this one has no safe default other than off.
227
+ remoteView: {
228
+ enabled: remoteView === undefined
229
+ ? false
230
+ : gate(remoteView.enabled, false),
231
+ },
218
232
  };
219
233
  }
220
234
  /**
@@ -251,8 +265,14 @@ export class SettingsStore {
251
265
  // stat already throws when the file is missing — which the catch below handles.
252
266
  mtimeMs = statSync(this.file).mtimeMs;
253
267
  }
254
- catch {
255
- // Unreadable file: fall through to defaults below.
268
+ catch (error) {
269
+ // Only an absent document means first-run defaults. Access/storage errors do not
270
+ // erase the operator's decisions, even when an earlier read was cached.
271
+ if (error.code !== 'ENOENT') {
272
+ this.cached = undefined;
273
+ this.cachedMtimeMs = -1;
274
+ return SETTINGS_WHEN_UNREADABLE;
275
+ }
256
276
  mtimeMs = -1;
257
277
  }
258
278
  // Return the cache BEFORE reading. The read used to happen first "just in case", which
@@ -316,6 +316,22 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
316
316
  private ensureSession;
317
317
  /** Create and attach the target for one view. Serialised by {@link ensureSession}. */
318
318
  private buildSession;
319
+ /**
320
+ * Take over a page the browser already has, so a person's own tab becomes one this plugin drives.
321
+ *
322
+ * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
323
+ * produced a SECOND page, because the only tab the provider knew about was one it created itself.
324
+ * The page the human was looking at was listed by `dsh_browser_list_tabs` (under `page:`) and
325
+ * could be closed, but not read or driven — the opposite of what "the page you are looking at"
326
+ * means.
327
+ *
328
+ * Attaching is all it takes: a CDP session is not exclusive, so the browser's own tab becomes a
329
+ * target this plugin has a session on. The page is not moved, reloaded or focused, and its
330
+ * existing session (logins, scroll position, form state) is untouched.
331
+ * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
332
+ * @returns a handle for that page, in the same shape {@link createView} returns.
333
+ */
334
+ adoptPage(targetId: string): Promise<ElectronViewHandle>;
319
335
  /**
320
336
  * Take an unclaimed blank page, if the browser has one to spare.
321
337
  *
@@ -349,6 +365,8 @@ export declare class SystemBrowserViewHost implements ElectronBrowserViewHost {
349
365
  private normalizeBlankPages;
350
366
  /** Views whose session is being created right now, so a second caller waits for the first. */
351
367
  private readonly sessionBuilding;
368
+ /** Serialises page selection/creation and attachment for each browser connection. */
369
+ private readonly targetBuilds;
352
370
  /** sessionId -> targetId, so a destroyed view can close the right page. */
353
371
  private readonly sessions;
354
372
  }
@@ -61,6 +61,20 @@ const CLOSE_GRACE_MS = 6_000;
61
61
  * interval, so a worst-case iteration costs 500 ms and the budget still affords ~60 attempts.
62
62
  */
63
63
  const PORT_PROBE_MS = 250;
64
+ /**
65
+ * How long to keep trying to adopt a browser after a launcher reported a clean exit.
66
+ *
67
+ * Exit code 0 means the launcher handed the request to an instance already holding this profile —
68
+ * but on Windows that stub exits BEFORE the real browser writes `DevToolsActivePort`. Measured on
69
+ * Chrome 156: stub gone at 300 ms, port file present at 441 ms (issue #33). A single attempt read
70
+ * too early and reported a launch failure for a browser that was starting normally, so this is a
71
+ * retry rather than one shot.
72
+ *
73
+ * 8 s is the reporter's measured-working bound and is generous against that ~150 ms gap: an honest
74
+ * hand-off resolves in well under a second, and a launch that genuinely failed still reaches the
75
+ * error within the same budget the CDP loop already allows.
76
+ */
77
+ const HANDOFF_ADOPT_MS = 8_000;
64
78
  /** The real launcher: spawn a detached-free child with pipes closed. */
65
79
  const defaultLauncher = (path, args) => spawn(path, [...args], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: false });
66
80
  import { spawn } from 'node:child_process';
@@ -745,7 +759,18 @@ export class SystemBrowserViewHost {
745
759
  // /dev/shm far smaller than a desktop. See resolveLaunchMode for why this is conditional.
746
760
  ...launch.headless ? ['--headless=new', '--disable-gpu', '--disable-dev-shm-usage'] : [],
747
761
  ...this.extraArgs,
748
- 'about:blank',
762
+ // NOT `about:blank`. Every page this plugin drives is created by `Target.createTarget` when a
763
+ // session first needs one (`buildSession`, which adopts a blank if the browser opened one and
764
+ // creates one otherwise), so a startup page is a tab nobody asked for and nobody closes: the
765
+ // tab strip showed `about:blank` next to the real page while `dsh_browser_list_tabs` reported
766
+ // only the real one. Reported as issue #33, banner and all.
767
+ //
768
+ // `--no-startup-window` keeps the browser alive with no window and no initial page; measured
769
+ // by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
770
+ // `/json/version`, listing two extension targets and no page, and then creating windows
771
+ // normally through `Target.createTarget`. A browser that does start a blank despite this is
772
+ // still handled: `normalizeBlankPages` closes the surplus and `buildSession` adopts the rest.
773
+ '--no-startup-window',
749
774
  ];
750
775
  // Chromium's own sandbox cannot start in some of these environments — running as root, or
751
776
  // inside a container without the namespaces it needs — and it exits rather than degrading.
@@ -998,10 +1023,23 @@ export class SystemBrowserViewHost {
998
1023
  // Exit code 0 IS the hand-off: the request went to an instance already holding this profile,
999
1024
  // so that instance is our browser and it is running right now. Adopting it turns the
1000
1025
  // reported "kill the leftovers by hand, on every restart" into a call that just works.
1026
+ //
1027
+ // Adopted with a bounded RETRY, because on Windows the launcher stub exits before the browser
1028
+ // has written its port file: measured 300 ms to exit against 441 ms for DevToolsActivePort.
1029
+ // One attempt therefore read too early and reported "exited immediately after launch" for a
1030
+ // browser that was starting normally — reported as issue #33, where the reporter's own
1031
+ // retry loop fixed it. 8 s at 250 ms is their measured-working bound and is generous against
1032
+ // the ~150 ms gap, without turning a genuinely failed launch into a slow failure.
1001
1033
  if (clean) {
1002
- const recovered = await this.adoptRunningBrowser('after a hand-off');
1003
- if (recovered !== undefined)
1004
- return recovered;
1034
+ const deadline = Date.now() + HANDOFF_ADOPT_MS;
1035
+ for (;;) {
1036
+ const recovered = await this.adoptRunningBrowser('after a hand-off');
1037
+ if (recovered !== undefined)
1038
+ return recovered;
1039
+ if (this.disposed || Date.now() >= deadline)
1040
+ break;
1041
+ await new Promise(resolve => setTimeout(resolve, PORT_PROBE_MS));
1042
+ }
1005
1043
  }
1006
1044
  throw new Error(clean
1007
1045
  ? `dsh-builtin-browser: ${target} exited immediately after launch (exit code 0). `
@@ -1116,9 +1154,41 @@ export class SystemBrowserViewHost {
1116
1154
  const session = cachedView !== undefined && cachedView.client === client
1117
1155
  ? cachedView.session
1118
1156
  : await this.ensureSession(viewId);
1157
+ /**
1158
+ * Send one page command, rebuilding the attach once if the browser no longer knows the
1159
+ * session.
1160
+ *
1161
+ * "Session with given id not found" means the session id is stale, and the causes differ:
1162
+ * a replaced client (handled where the client is dropped), a target the browser destroyed,
1163
+ * or a detach the page performed on itself. What they share is that the id is worthless and
1164
+ * the VIEW is fine, so the right answer is one fresh attach — not an error to the caller and
1165
+ * not a new page. Measured while solving a sudoku on a canvas page: after a tab switch every
1166
+ * command failed with this text and nothing in the plugin ever recovered it.
1167
+ *
1168
+ * Retried exactly once: a failure that survives a fresh attach is not a stale id, and
1169
+ * repeating it would turn an error into a loop.
1170
+ */
1171
+ const sendWithAttach = async (target) => {
1172
+ try {
1173
+ const result = await client.send(method, params, target);
1174
+ return (result ?? {});
1175
+ }
1176
+ catch (error) {
1177
+ const message = error instanceof Error ? error.message : String(error);
1178
+ if (!/Session with given id not found|No session with given id/i.test(message))
1179
+ throw error;
1180
+ // Drop the dead attach so `ensureSession` builds a new one instead of returning the same id.
1181
+ const stale = this.views.get(viewId);
1182
+ if (stale !== undefined)
1183
+ this.views.delete(viewId);
1184
+ this.sessions.delete(target);
1185
+ const rebuilt = await this.ensureSession(viewId);
1186
+ const retried = await client.send(method, params, rebuilt);
1187
+ return (retried ?? {});
1188
+ }
1189
+ };
1119
1190
  try {
1120
- const result = await client.send(method, params, session);
1121
- return (result ?? {});
1191
+ return await sendWithAttach(session);
1122
1192
  }
1123
1193
  catch (error) {
1124
1194
  // A CDP protocol error means the browser ANSWERED and refused this one command, so the
@@ -1261,30 +1331,36 @@ export class SystemBrowserViewHost {
1261
1331
  dying.once('exit', () => { clearTimeout(timer); });
1262
1332
  }
1263
1333
  const ephemeral = this.ephemeralDir;
1264
- if (ephemeral !== undefined && this.child !== undefined) {
1265
- // The browser flushes its profile while shutting down, so deleting later avoids
1266
- // racing it. Leftovers are only a stray temp directory, never a live credential.
1267
- //
1268
- // The timer is unref'd, so it never holds the process open — which also means that a
1269
- // process which exits inside this 3s window (a CLI probe, a DSH restart) leaves the
1270
- // directory behind for good, silently contradicting the user's "keep no profile"
1271
- // choice. The exit hook below is the same delete, run synchronously as a last resort;
1272
- // the callback is idempotent, so whichever runs first wins and the other is a no-op.
1334
+ if (ephemeral !== undefined) {
1273
1335
  const removeEphemeral = () => {
1274
1336
  try {
1275
1337
  rmSync(ephemeral, { recursive: true, force: true });
1276
1338
  }
1277
1339
  catch { /* best effort */ }
1278
1340
  };
1279
- setTimeout(removeEphemeral, 3_000).unref?.();
1280
- process.once('exit', removeEphemeral);
1281
- }
1282
- else if (ephemeral !== undefined) {
1283
- // Never started, so nothing can be holding it open.
1284
- try {
1285
- rmSync(ephemeral, { recursive: true, force: true });
1341
+ // `this.child` was cleared above; the saved processes still own the profile until
1342
+ // their exit events arrive. Deleting it now races Chromium's final cookie flush.
1343
+ const live = doomed.filter(child => child.exitCode === null && child.signalCode === null);
1344
+ if (live.length > 0) {
1345
+ const remaining = new Set(live);
1346
+ for (const child of live)
1347
+ child.once('exit', () => {
1348
+ remaining.delete(child);
1349
+ if (remaining.size === 0)
1350
+ removeEphemeral();
1351
+ });
1352
+ }
1353
+ else if (client !== undefined) {
1354
+ // A handed-off browser has no process handle. Give its graceful close time to
1355
+ // finish; abandoned profiles remain eligible for the next startup's safe sweep.
1356
+ setTimeout(() => {
1357
+ if (!client.isAlive())
1358
+ removeEphemeral();
1359
+ }, CLOSE_GRACE_MS).unref?.();
1360
+ }
1361
+ else {
1362
+ removeEphemeral();
1286
1363
  }
1287
- catch { /* best effort */ }
1288
1364
  }
1289
1365
  }
1290
1366
  /**
@@ -1311,23 +1387,66 @@ export class SystemBrowserViewHost {
1311
1387
  /** Create and attach the target for one view. Serialised by {@link ensureSession}. */
1312
1388
  async buildSession(viewId) {
1313
1389
  const client = await this.ensureClient();
1314
- // Adopt a blank page the browser opened on its own before creating another one.
1315
- //
1316
- // Chrome starts with more than one page when handed a URL on top of its own start page, so
1317
- // creating a target here discarded the original and left it behind as a tab that is not in
1318
- // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1319
- // through the tools. Taking the blank instead makes the page the browser already opened the
1320
- // one the caller gets.
1321
- const adopted = await this.adoptBlankTarget(client);
1322
- const targetId = adopted ?? await this.createTarget(client);
1390
+ // Different views can initialise concurrently. Selecting an unclaimed page and attaching
1391
+ // it must be one transaction, including when the page is created by a preceding view.
1392
+ const previous = this.targetBuilds.get(client) ?? Promise.resolve();
1393
+ let release;
1394
+ const building = new Promise(resolve => { release = resolve; });
1395
+ this.targetBuilds.set(client, building);
1396
+ await previous;
1397
+ try {
1398
+ // Adopt a blank page the browser opened on its own before creating another one.
1399
+ //
1400
+ // Chrome starts with more than one page when handed a URL on top of its own start page, so
1401
+ // creating a target here discarded the original and left it behind as a tab that is not in
1402
+ // the plugin's tab model — invisible to `dsh_browser_list_tabs`, and therefore unclosable
1403
+ // through the tools. Taking the blank instead makes the page the browser already opened the
1404
+ // one the caller gets.
1405
+ const adopted = await this.adoptBlankTarget(client);
1406
+ const targetId = adopted ?? await this.createTarget(client);
1407
+ const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
1408
+ const sessionId = attached?.sessionId;
1409
+ if (typeof sessionId !== 'string')
1410
+ throw new Error('dsh-builtin-browser: the browser did not attach to the new page');
1411
+ // The session id is what page commands ride; the target id is what closes it.
1412
+ this.sessions.set(sessionId, targetId);
1413
+ this.views.set(viewId, { session: sessionId, client });
1414
+ return sessionId;
1415
+ }
1416
+ finally {
1417
+ release();
1418
+ if (this.targetBuilds.get(client) === building)
1419
+ this.targetBuilds.delete(client);
1420
+ }
1421
+ }
1422
+ /**
1423
+ * Take over a page the browser already has, so a person's own tab becomes one this plugin drives.
1424
+ *
1425
+ * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
1426
+ * produced a SECOND page, because the only tab the provider knew about was one it created itself.
1427
+ * The page the human was looking at was listed by `dsh_browser_list_tabs` (under `page:`) and
1428
+ * could be closed, but not read or driven — the opposite of what "the page you are looking at"
1429
+ * means.
1430
+ *
1431
+ * Attaching is all it takes: a CDP session is not exclusive, so the browser's own tab becomes a
1432
+ * target this plugin has a session on. The page is not moved, reloaded or focused, and its
1433
+ * existing session (logins, scroll position, form state) is untouched.
1434
+ * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1435
+ * @returns a handle for that page, in the same shape {@link createView} returns.
1436
+ */
1437
+ async adoptPage(targetId) {
1438
+ const handle = this.createView();
1439
+ const client = await this.ensureClient();
1323
1440
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
1324
1441
  const sessionId = attached?.sessionId;
1325
- if (typeof sessionId !== 'string')
1326
- throw new Error('dsh-builtin-browser: the browser did not attach to the new page');
1327
- // The session id is what page commands ride; the target id is what closes it.
1442
+ if (typeof sessionId !== 'string') {
1443
+ throw new Error(`dsh-builtin-browser: could not attach to the existing page ${targetId}`);
1444
+ }
1445
+ // Point the view `createView` just made at the page that already exists, instead of the one it
1446
+ // would otherwise build on first use.
1328
1447
  this.sessions.set(sessionId, targetId);
1329
- this.views.set(viewId, { session: sessionId, client });
1330
- return sessionId;
1448
+ this.views.set(handle.id, { session: sessionId, client });
1449
+ return handle;
1331
1450
  }
1332
1451
  /**
1333
1452
  * Take an unclaimed blank page, if the browser has one to spare.
@@ -1419,6 +1538,8 @@ export class SystemBrowserViewHost {
1419
1538
  }
1420
1539
  /** Views whose session is being created right now, so a second caller waits for the first. */
1421
1540
  sessionBuilding = new Map();
1541
+ /** Serialises page selection/creation and attachment for each browser connection. */
1542
+ targetBuilds = new WeakMap();
1422
1543
  /** sessionId -> targetId, so a destroyed view can close the right page. */
1423
1544
  sessions = new Map();
1424
1545
  }
@@ -251,7 +251,16 @@ function formatSnapshot(snapshot, options = {}) {
251
251
  const showCoords = options.coords === true;
252
252
  const lines = snapshot.elements.map(el => `[${el.ref}] ${el.kind}: ${el.label}${el.selector !== undefined && el.selector !== '' ? ` {${el.selector}}` : ''}${el.frame === true ? ' (iframe)' : ''}${showCoords ? ` (${el.x},${el.y})` : ''}`);
253
253
  const header = `URL: ${snapshot.url}${snapshot.title !== undefined ? `\nTitle: ${snapshot.title}` : ''}`;
254
- const body = lines.length > 0 ? lines.join('\n') : '(no interactive elements found)';
254
+ // A blank page, a canvas page and a page with nothing interactive are three different facts, and
255
+ // the old wording reported all of them as "no interactive elements found" — which reads as a
256
+ // successful look. Each now says what it is and what to do next.
257
+ const body = snapshot.blank === true
258
+ ? `BLANK PAGE: ${snapshot.note ?? 'nothing has been opened in this browser'}. `
259
+ + 'Do not drive this page — open a URL first (`dsh_browser_open`).'
260
+ : snapshot.canvas === true
261
+ ? `CANVAS PAGE: ${snapshot.note ?? 'this page draws its interface on a canvas'}. `
262
+ + 'A DOM snapshot cannot describe it; use `dsh_browser_screenshot` and coordinate clicks.'
263
+ : lines.length > 0 ? lines.join('\n') : '(no interactive elements found)';
255
264
  const tail = snapshot.truncated === true ? '\n(snapshot truncated)' : '';
256
265
  const banner = snapshot.challenge?.blocked === true
257
266
  ? `\n\nCHALLENGE: ${snapshot.challenge.reason ?? 'human-verification'}. Do NOT keep retrying — ask the human to complete it in the shared browser window, then re-snapshot.`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-builtin-browser",
3
- "version": "0.4.14",
3
+ "version": "0.5.1",
4
4
  "description": "Shared real browser plugin for DeepSeek Harness: install-and-use — a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -44,9 +44,13 @@
44
44
  "LICENSE",
45
45
  "scripts"
46
46
  ],
47
+ "bin": {
48
+ "dsh-browser-install-electron": "scripts/install-electron.mjs"
49
+ },
47
50
  "scripts": {
48
51
  "build": "tsc -p tsconfig.json",
49
52
  "test": "tsc -p tsconfig.json && node --test \"tests/*.test.mjs\"",
53
+ "postinstall": "node scripts/install-electron.mjs",
50
54
  "prepack": "npm run build"
51
55
  },
52
56
  "keywords": [
@@ -69,7 +73,7 @@
69
73
  "dsh": ">=0.1.1-rc.2 <0.3.0"
70
74
  },
71
75
  "dependencies": {
72
- "electron": ">= 30.0.0"
76
+ "electron": "^44.10.0"
73
77
  },
74
78
  "peerDependencies": {
75
79
  "@deepseek-ai/cordis": "^4.0.1",
@@ -110,7 +114,8 @@
110
114
  "0.2.0-rc.1": "compatible",
111
115
  "0.2.0-rc.2": "compatible",
112
116
  "0.2.1-alpha.1": "compatible",
113
- "0.2.1-rc.1": "compatible"
117
+ "0.2.1-rc.1": "compatible",
118
+ "0.2.1-rc.5": "compatible"
114
119
  }
115
120
  }
116
121
  }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Provision the plugin's installed Electron dependency during postinstall or an
4
+ * explicit retry. Electron 44 no longer downloads its binary on package install,
5
+ * and browser discovery deliberately remains a pure filesystem probe.
6
+ */
7
+ import { spawn } from 'node:child_process'
8
+ import { existsSync, readFileSync } from 'node:fs'
9
+ import { createRequire } from 'node:module'
10
+ import { dirname, join } from 'node:path'
11
+
12
+ const label = '[dsh-builtin-browser]'
13
+
14
+ function retryInstructions() {
15
+ console.error(`${label} Retry from the profile that installed this plugin: npx --no dsh-browser-install-electron`)
16
+ }
17
+
18
+ async function install() {
19
+ // Respect operators who provision their runtime separately, including CI.
20
+ // --ignore-scripts is enforced by the package manager; the explicit bin remains
21
+ // usable afterwards without changing the profile's lifecycle-script policy.
22
+ if (process.env.ELECTRON_SKIP_BINARY_DOWNLOAD) {
23
+ console.log(`${label} Electron download skipped: ELECTRON_SKIP_BINARY_DOWNLOAD is set.`)
24
+ return 0
25
+ }
26
+
27
+ const require = createRequire(import.meta.url)
28
+ let manifest
29
+ try {
30
+ manifest = require.resolve('electron/package.json')
31
+ } catch (error) {
32
+ throw new Error(`Cannot resolve the installed electron dependency. Reinstall this plugin in the same profile. ${error.message}`)
33
+ }
34
+ const installer = join(dirname(manifest), 'install.js')
35
+ if (!existsSync(installer)) throw new Error(`The installed electron package is incomplete: missing ${installer}`)
36
+ const { version } = JSON.parse(readFileSync(manifest, 'utf8'))
37
+ console.log(`${label} Preparing Electron ${String(version)}. A missing runtime needs a network download; an existing runtime is reused.`)
38
+
39
+ // Run the actual dependency's installer, never require('electron'): in an
40
+ // Electron host that module name is the built-in API. Upstream validates its
41
+ // dist/version, path.txt and executable before deciding whether to download.
42
+ const result = await new Promise((resolve, reject) => {
43
+ const child = spawn(process.execPath, [installer], {
44
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
45
+ stdio: ['ignore', 'inherit', 'inherit'],
46
+ windowsHide: true,
47
+ })
48
+ child.once('error', reject)
49
+ child.once('close', (code, signal) => { resolve({ code, signal }) })
50
+ })
51
+ if (result.code !== 0) {
52
+ console.error(`${label} Electron installation failed (${result.signal ? `signal ${result.signal}` : `exit ${String(result.code)}`}). Fix the reported network, checksum or permission error before retrying.`)
53
+ retryInstructions()
54
+ return result.code ?? 1
55
+ }
56
+ console.log(`${label} Electron runtime is ready.`)
57
+ return 0
58
+ }
59
+
60
+ try {
61
+ process.exitCode = await install()
62
+ } catch (error) {
63
+ console.error(`${label} ${error instanceof Error ? error.message : String(error)}`)
64
+ retryInstructions()
65
+ process.exitCode = 1
66
+ }