dsh-builtin-browser 0.5.7 → 0.5.8

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 (94) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.en.md +48 -22
  3. package/README.md +48 -22
  4. package/client.js +469 -81
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +251 -159
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +151 -18
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/user-guide.md +28 -4
  11. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  12. package/lib/browser-electron/automatic-maintenance.js +426 -0
  13. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  14. package/lib/browser-electron/bridge-auto.js +113 -0
  15. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  16. package/lib/browser-electron/bridge-connection.js +2 -4
  17. package/lib/browser-electron/bridge-endpoint.js +1 -19
  18. package/lib/browser-electron/bridge-install.d.ts +41 -4
  19. package/lib/browser-electron/bridge-install.js +131 -18
  20. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  21. package/lib/browser-electron/bridge-maintenance.js +125 -0
  22. package/lib/browser-electron/bridge-status.d.ts +10 -3
  23. package/lib/browser-electron/bridge-status.js +76 -45
  24. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
  25. package/lib/browser-electron/desktop-bridge-host.js +54 -33
  26. package/lib/browser-electron/desktop-identity.js +21 -9
  27. package/lib/browser-electron/electron-provision.js +5 -2
  28. package/lib/browser-electron/entry.js +104 -74
  29. package/lib/browser-electron/ephemeral-profile.js +67 -26
  30. package/lib/browser-electron/history-store.js +2 -2
  31. package/lib/browser-electron/host-main.js +26 -37
  32. package/lib/browser-electron/http-body.d.ts +24 -0
  33. package/lib/browser-electron/http-body.js +33 -0
  34. package/lib/browser-electron/json-reply.d.ts +13 -1
  35. package/lib/browser-electron/json-reply.js +16 -2
  36. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  37. package/lib/browser-electron/maintenance-broker.js +114 -0
  38. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  39. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  40. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  41. package/lib/browser-electron/maintenance-route.js +75 -0
  42. package/lib/browser-electron/paths.d.ts +4 -0
  43. package/lib/browser-electron/paths.js +19 -0
  44. package/lib/browser-electron/process.d.ts +14 -0
  45. package/lib/browser-electron/process.js +24 -0
  46. package/lib/browser-electron/provider.d.ts +7 -7
  47. package/lib/browser-electron/provider.js +13 -14
  48. package/lib/browser-electron/remote-host.js +18 -16
  49. package/lib/browser-electron/runtime-status.d.ts +27 -13
  50. package/lib/browser-electron/runtime-status.js +24 -4
  51. package/lib/browser-electron/settings-store.d.ts +11 -0
  52. package/lib/browser-electron/settings-store.js +8 -2
  53. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  54. package/lib/browser-electron/sidebar-only-host.js +192 -0
  55. package/lib/browser-electron/system-browser.d.ts +1 -9
  56. package/lib/browser-electron/system-browser.js +19 -22
  57. package/lib/browser-electron/timing.d.ts +8 -0
  58. package/lib/browser-electron/timing.js +13 -0
  59. package/lib/browser-electron/windows-system.d.ts +3 -0
  60. package/lib/browser-electron/windows-system.js +19 -0
  61. package/lib/tool-browser/index.js +5 -4
  62. package/package.json +2 -2
  63. package/scripts/run-tests.mjs +32 -0
  64. package/scripts/verify-preview-route.mjs +19 -1
  65. package/src/browser-electron/automatic-maintenance.ts +414 -0
  66. package/src/browser-electron/bridge-auto.ts +158 -0
  67. package/src/browser-electron/bridge-connection.ts +2 -4
  68. package/src/browser-electron/bridge-endpoint.ts +1 -18
  69. package/src/browser-electron/bridge-install.ts +151 -20
  70. package/src/browser-electron/bridge-maintenance.ts +161 -0
  71. package/src/browser-electron/bridge-status.ts +78 -48
  72. package/src/browser-electron/desktop-bridge-host.ts +48 -32
  73. package/src/browser-electron/desktop-identity.ts +18 -9
  74. package/src/browser-electron/electron-provision.ts +5 -2
  75. package/src/browser-electron/entry.ts +91 -69
  76. package/src/browser-electron/ephemeral-profile.ts +65 -28
  77. package/src/browser-electron/history-store.ts +2 -2
  78. package/src/browser-electron/host-main.ts +23 -36
  79. package/src/browser-electron/http-body.ts +42 -0
  80. package/src/browser-electron/json-reply.ts +18 -3
  81. package/src/browser-electron/maintenance-broker.ts +142 -0
  82. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  83. package/src/browser-electron/maintenance-route.ts +64 -0
  84. package/src/browser-electron/paths.ts +21 -0
  85. package/src/browser-electron/process.ts +23 -0
  86. package/src/browser-electron/provider.ts +18 -18
  87. package/src/browser-electron/remote-host.ts +19 -19
  88. package/src/browser-electron/runtime-status.ts +52 -17
  89. package/src/browser-electron/settings-store.ts +20 -3
  90. package/src/browser-electron/sidebar-only-host.ts +199 -0
  91. package/src/browser-electron/system-browser.ts +19 -22
  92. package/src/browser-electron/timing.ts +16 -0
  93. package/src/browser-electron/windows-system.ts +23 -0
  94. package/src/tool-browser/index.ts +5 -4
@@ -16,9 +16,11 @@ import { randomUUID } from 'node:crypto';
16
16
  import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs';
17
17
  import { homedir } from 'node:os';
18
18
  import { dirname, join } from 'node:path';
19
+ import { dshHome } from './paths.js';
19
20
  import { setTimeout as wait } from 'node:timers/promises';
20
21
  import { defaultHostMainPath, RemoteElectronViewHost } from './remote-host.js';
21
22
  import { DesktopBridgeViewHost } from './desktop-bridge-host.js';
23
+ import { SidebarOnlyHost } from './sidebar-only-host.js';
22
24
  import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.js';
23
25
  import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralProfiles } from './ephemeral-profile.js';
24
26
  import { MissingSystemBrowserHost } from './missing-system-browser.js';
@@ -29,7 +31,12 @@ import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_S
29
31
  import { findDesktopInstall, readBridgeStatus } from './bridge-status.js';
30
32
  import { readBridgeEndpoint } from './bridge-endpoint.js';
31
33
  import { runBridgeAction } from './bridge-install.js';
32
- import { replyJson } from './json-reply.js';
34
+ import { prepareBridgeMaintenance } from './bridge-maintenance.js';
35
+ import { commitAutomaticMaintenance, readAutomaticMaintenance, startAutomaticMaintenance } from './automatic-maintenance.js';
36
+ import { AUTOMATIC_MAINTENANCE_ROUTE, createAutomaticMaintenanceHandler } from './maintenance-route.js';
37
+ import { runWithManualBridgePreference } from './bridge-auto.js';
38
+ import { replyJson, writeJsonText } from './json-reply.js';
39
+ import { readJsonBody, readTextBody } from './http-body.js';
33
40
  import { readRuntimeStatus } from './runtime-status.js';
34
41
  import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js';
35
42
  export { ELECTRON_BROWSER_PROVIDER_ID, ElectronBrowserProvider, } from './provider.js';
@@ -118,11 +125,8 @@ export function apply(ctx, config) {
118
125
  }
119
126
  return;
120
127
  }
121
- // Otherwise start self-hosted — a working browser from the first call, on every
122
- // surface — and upgrade to the desktop sidebar if this machine has one. The
123
- // upgrade is deliberately a swap of the whole provider: the two carriers own
124
- // different lifetimes (a spawned child vs. the shell's view), and pretending
125
- // otherwise would leave a stray window behind.
128
+ // Explicit sidebar selection stays on the desktop's carrier, including while its bridge
129
+ // reconnects. Other choices can use the independently hosted browser when appropriate.
126
130
  const selfHosted = new RemoteElectronViewHost(defaultHostMainPath());
127
131
  // The self-hosted carrier is the only one that needs Electron, and it is prepared HERE, lazily,
128
132
  // rather than during package installation (issue #41: a `postinstall` download made a default
@@ -135,12 +139,25 @@ export function apply(ctx, config) {
135
139
  if (wantedChannel === 'bundled' || wantedChannel === 'auto') {
136
140
  void provisionElectronInBackground(message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`));
137
141
  }
138
- let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(selfHosted, providerConfig));
142
+ const requiredSidebar = () => new SidebarOnlyHost(async () => {
143
+ for (const pause of [0, 1_000, 3_000, 8_000]) {
144
+ if (pause > 0)
145
+ await wait(pause);
146
+ const sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet);
147
+ if (sidebar !== undefined)
148
+ return sidebar;
149
+ if (DesktopBridgeViewHost.refusedIframePanel())
150
+ break;
151
+ }
152
+ throw new Error('dsh-builtin-browser: the selected DSH sidebar is not connected. Check or repair the desktop bridge in Browser settings, then retry the same operation.');
153
+ });
154
+ const initialHost = wantedChannel === 'sidebar' ? requiredSidebar() : selfHosted;
155
+ let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(initialHost, providerConfig));
139
156
  let disposed = false;
140
157
  let carrierChoice = 0;
141
158
  let discovery;
142
159
  /** The carrier an `adopt` installed, so a later choice can release it. */
143
- let adoptedCarrier;
160
+ let adoptedCarrier = initialHost === selfHosted ? undefined : initialHost;
144
161
  ctx.effect(() => () => {
145
162
  disposed = true;
146
163
  carrierChoice += 1;
@@ -169,18 +186,21 @@ export function apply(ctx, config) {
169
186
  if (disposed || adoptedCarrier !== adopted)
170
187
  return;
171
188
  try {
172
- const restored = new RemoteElectronViewHost(defaultHostMainPath());
189
+ const sidebarSelected = settings.get().browser.channel === 'sidebar';
190
+ const restored = sidebarSelected ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath());
173
191
  unregister();
174
192
  unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig));
175
193
  adoptedCarrier = restored;
176
- ctx.logger?.warn?.(reason === 'shell-exited'
177
- ? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
178
- + 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
179
- + 'open the page again.'
180
- : 'dsh-builtin-browser: this desktop shell renders the sidebar browser panel in a way that '
181
- + 'cannot be driven (no webContents, so no CDP endpoint), so the browser this plugin hosts '
182
- + 'itself takes over. The shell is still running and nothing else is affected; the page '
183
- + 'opens in this plugin\'s own window. Set browser.channel to another value to silence this.');
194
+ ctx.logger?.warn?.(sidebarSelected
195
+ ? 'dsh-builtin-browser: the selected DSH sidebar connection was lost; the next operation will reconnect to the sidebar.'
196
+ : reason === 'shell-exited'
197
+ ? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
198
+ + 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
199
+ + 'open the page again.'
200
+ : 'dsh-builtin-browser: this desktop shell renders the sidebar browser panel in a way that '
201
+ + 'cannot be driven (no webContents, so no CDP endpoint), so the browser this plugin hosts '
202
+ + 'itself takes over. The shell is still running and nothing else is affected; the page '
203
+ + 'opens in this plugin\'s own window. Set browser.channel to another value to silence this.');
184
204
  }
185
205
  catch (error) {
186
206
  // Nothing better is available: the adopted carrier is gone and a provider that throws is
@@ -232,7 +252,8 @@ export function apply(ctx, config) {
232
252
  // A borrowed carrier can lose the process behind it, and this is the only notification that
233
253
  // will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
234
254
  // against a provider that was never installed.
235
- host.onLost?.(reason => { restoreSelfHosted(host, reason); });
255
+ if (!(host instanceof SidebarOnlyHost))
256
+ host.onLost?.(reason => { restoreSelfHosted(host, reason); });
236
257
  // Released AFTER the replacement is installed, so the surface is never without a provider.
237
258
  if (previous !== undefined && previous !== host) {
238
259
  try {
@@ -257,7 +278,7 @@ export function apply(ctx, config) {
257
278
  // exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
258
279
  // session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
259
280
  try {
260
- const fallback = new RemoteElectronViewHost(defaultHostMainPath());
281
+ const fallback = settings.get().browser.channel === 'sidebar' ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath());
261
282
  unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig));
262
283
  adoptedCarrier = fallback;
263
284
  if (previous !== undefined && previous !== host) {
@@ -307,7 +328,12 @@ export function apply(ctx, config) {
307
328
  // and a user who picked a browser that is not installed would never see the explanation
308
329
  // written for exactly that case, because the sidebar would quietly replace it.
309
330
  const explicitChoice = channel !== 'bundled' && channel !== 'auto' && channel !== 'sidebar';
310
- if (channel !== 'bundled' && channel !== 'sidebar') {
331
+ if (channel === 'sidebar') {
332
+ if (!(adoptedCarrier instanceof SidebarOnlyHost))
333
+ adopt(requiredSidebar(), 'using only the selected DSH sidebar', choice);
334
+ return;
335
+ }
336
+ if (channel !== 'bundled') {
311
337
  const detected = detectBrowser(channel);
312
338
  if (detected === undefined) {
313
339
  // `auto` promises to take whatever is available, so falling back is what it
@@ -331,7 +357,7 @@ export function apply(ctx, config) {
331
357
  // `C:\Users\<user>\dsh-builtin-browser-host\` while its settings and history lived in
332
358
  // `~/.dsh/dsh-builtin-browser-host/` — two half-profiles that never met, and a
333
359
  // settings panel whose switches appeared not to apply.
334
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
360
+ const home = dshHome();
335
361
  // Login state lives in the browser profile, so the cookies setting decides where
336
362
  // that profile goes: a stable directory keeps the user signed in across restarts
337
363
  // (the point of using their own browser), while turning persistence off gets a
@@ -362,9 +388,8 @@ export function apply(ctx, config) {
362
388
  // An explicit choice was already adopted above; discovering the sidebar here would
363
389
  // replace it, which is exactly what this guard prevents.
364
390
  //
365
- // `sidebar` is explicit too, but it names the sidebar, so it is the one explicit choice that
366
- // must FALL THROUGH to the discovery below instead of returning here.
367
- if (explicitChoice && channel !== 'sidebar')
391
+ // Explicit sidebar selection was handled above by its reconnectable sidebar-only host.
392
+ if (explicitChoice)
368
393
  return;
369
394
  // The shell may not be up yet. `dsh web` starts before — or entirely without — the desktop app
370
395
  // that hosts the bridge, and a one-shot discovery meant a bridge that appeared a second later
@@ -417,15 +442,6 @@ export function apply(ctx, config) {
417
442
  + 'enables `webviewTag` would provide a drivable panel.');
418
443
  return;
419
444
  }
420
- // The user explicitly asked for the sidebar, so silence would leave them with a setting
421
- // that did nothing and no way to tell why. This is reachable on `dsh web`, and on a desktop
422
- // whose shell never published a bridge endpoint. An automatic attempt stays quiet (the
423
- // self-hosted window is a fine outcome); an explicit request does not.
424
- if (channel === 'sidebar') {
425
- ctx.logger?.warn?.('dsh-builtin-browser: the sidebar browser was requested but no desktop bridge was found — '
426
- + 'this DSH has no desktop shell, or its bridge never started. Falling back to the bundled '
427
- + 'browser; set browser.channel to another value to silence this.');
428
- }
429
445
  })();
430
446
  };
431
447
  chooseCarrier();
@@ -480,13 +496,9 @@ export function apply(ctx, config) {
480
496
  const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action';
481
497
  let bridgeActionRunning = false;
482
498
  /**
483
- * Install, repair or remove the bridge, from a button.
484
- *
485
- * The panel used to print a command. This step closes and reopens the desktop app, so a
486
- * half-finished manual run leaves the shell in a state the user then has to diagnose — the
487
- * packaged installer already handles the whole sequence unattended, and this hands it the one
488
- * decision that is not its own: which action the user pressed.
489
- * @param request - the incoming request (POST, JSON body `{action}`).
499
+ * Prepare external maintenance while Desktop remains open, or execute file maintenance from
500
+ * an independent local host after Desktop has exited.
501
+ * @param request - the incoming request (POST, JSON body `{action, prepare?}`).
490
502
  * @param response - the response to write.
491
503
  */
492
504
  async function handleBridgeAction(request, response) {
@@ -494,7 +506,7 @@ export function apply(ctx, config) {
494
506
  replyJson(response, 405, { error: 'method-not-allowed' });
495
507
  return;
496
508
  }
497
- // A write: it stops the shell. Same admission as a settings write, not the read rule.
509
+ // Both creating a local launcher and changing installation files require write admission.
498
510
  if (!sameOrigin(request, true)) {
499
511
  replyJson(response, 403, { error: 'not-same-origin' });
500
512
  return;
@@ -504,9 +516,13 @@ export function apply(ctx, config) {
504
516
  return;
505
517
  }
506
518
  let action;
519
+ let preparationOnly = false;
507
520
  try {
508
- const body = await readBody(request);
509
- action = JSON.parse(body === '' ? '{}' : body).action;
521
+ const input = await readJsonBody(request);
522
+ action = input.action;
523
+ if (input.prepare !== undefined && typeof input.prepare !== 'boolean')
524
+ throw new Error('prepare must be a boolean');
525
+ preparationOnly = input.prepare === true;
510
526
  }
511
527
  catch (error) {
512
528
  replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` });
@@ -526,10 +542,27 @@ export function apply(ctx, config) {
526
542
  replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' });
527
543
  return;
528
544
  }
545
+ const active = readAutomaticMaintenance();
546
+ if (!preparationOnly && active !== undefined && !['completed', 'failed', 'cancelled'].includes(active.phase)) {
547
+ replyJson(response, 409, { ok: false, error: 'an automatic bridge maintenance job is in progress' });
548
+ return;
549
+ }
529
550
  bridgeActionRunning = true;
530
551
  try {
531
- const result = await runBridgeAction(action, root);
532
- replyJson(response, 200, { ok: result.ok, action, code: result.code, output: result.output, command: result.command });
552
+ if (preparationOnly) {
553
+ const result = await prepareBridgeMaintenance(action, root);
554
+ replyJson(response, 200, { ...result, action });
555
+ return;
556
+ }
557
+ const result = await runWithManualBridgePreference(action, patch => settings.update(patch), () => runBridgeAction(action, root));
558
+ replyJson(response, 200, { ...result, action });
559
+ }
560
+ catch (error) {
561
+ if (preparationOnly) {
562
+ replyJson(response, 500, { ok: false, error: `could not prepare bridge maintenance: ${String(error)}` });
563
+ return;
564
+ }
565
+ replyJson(response, 500, { ok: false, error: String(error instanceof Error ? error.message : error) });
533
566
  }
534
567
  finally {
535
568
  bridgeActionRunning = false;
@@ -541,13 +574,29 @@ export function apply(ctx, config) {
541
574
  return;
542
575
  try {
543
576
  injectStatus(['webServer'], (host) => {
577
+ const automaticMaintenance = createAutomaticMaintenanceHandler({
578
+ supported: () => process.platform === 'win32',
579
+ busy: () => bridgeActionRunning,
580
+ read: () => readAutomaticMaintenance(),
581
+ commit: async (id) => { await commitAutomaticMaintenance(id); },
582
+ start: async (action, options) => {
583
+ const root = findDesktopInstall();
584
+ if (root === undefined)
585
+ throw new Error('no verified DSH Desktop installation was found');
586
+ return await runWithManualBridgePreference(action, patch => settings.update(patch), async () => await startAutomaticMaintenance(action, root, options));
587
+ },
588
+ });
589
+ host.effect(() => host.webServer.register({
590
+ kind: 'exact', path: AUTOMATIC_MAINTENANCE_ROUTE,
591
+ handler: authenticated(ctx, automaticMaintenance),
592
+ }, 'dsh-builtin-browser: explicit automatic bridge maintenance'));
544
593
  host.effect(() => host.webServer.register({
545
594
  kind: 'exact',
546
595
  path: BRIDGE_STATUS_ROUTE,
547
596
  handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
548
597
  }, 'dsh-builtin-browser: bridge status'));
549
- // The same information, one action later: install/repair or remove the bridge without the
550
- // user opening a terminal. Admitted as a write, because it closes and restarts the shell.
598
+ // The panel prepares a launcher without changing the running Desktop. Direct local
599
+ // maintenance remains available once Desktop has exited.
551
600
  host.effect(() => host.webServer.register({
552
601
  kind: 'exact',
553
602
  path: BRIDGE_ACTION_ROUTE,
@@ -560,6 +609,8 @@ export function apply(ctx, config) {
560
609
  }
561
610
  }
562
611
  installSettingsRoute(ctx, settings, () => { chooseCarrier(); });
612
+ // Bridge maintenance is explicit and requires DSH Desktop to be closed. Loading a provider
613
+ // never starts an installer, including with an older settings file's bridge.autoInstall=true.
563
614
  /**
564
615
  * Expose readiness — "can the browser serve a call right now" — for the settings panel.
565
616
  *
@@ -581,6 +632,8 @@ export function apply(ctx, config) {
581
632
  const deps = {
582
633
  report: () => readRuntimeStatus({
583
634
  channel: () => settings.get().browser.channel,
635
+ selectedCarrier: () => adoptedCarrier instanceof DesktopBridgeViewHost || adoptedCarrier instanceof SidebarOnlyHost ? 'sidebar'
636
+ : adoptedCarrier instanceof SystemBrowserViewHost ? 'system' : 'bundled',
584
637
  hasBinary: hasElectronRuntime,
585
638
  provision: provisionSnapshot,
586
639
  bridge: () => {
@@ -657,7 +710,7 @@ export function apply(ctx, config) {
657
710
  lastChannel = channel;
658
711
  ctx.logger?.info?.(`dsh-builtin-browser: settings changed on disk, re-choosing the carrier for channel "${channel}"`);
659
712
  chooseCarrier();
660
- }, 2_000);
713
+ }, 5_000);
661
714
  // Unref-ed so a poll never holds the process open.
662
715
  timer.unref?.();
663
716
  ctx.effect(() => () => { clearInterval(timer); }, "dsh-builtin-browser: settings file watch");
@@ -753,11 +806,10 @@ function installSettingsRoute(ctx, settings, onChannelChange) {
753
806
  */
754
807
  async function handleSettingsRequest(request, response, settings, onChannelChange) {
755
808
  const json = (status, body) => {
756
- response.writeHead(status, {
809
+ writeJsonText(response, status, JSON.stringify(body), {
757
810
  'content-type': 'application/json; charset=utf-8',
758
811
  'cache-control': 'no-store',
759
812
  });
760
- response.end(JSON.stringify(body));
761
813
  };
762
814
  const method = request.method ?? 'GET';
763
815
  if (!sameOrigin(request, method !== 'GET')) {
@@ -774,8 +826,8 @@ async function handleSettingsRequest(request, response, settings, onChannelChang
774
826
  return;
775
827
  }
776
828
  try {
777
- const body = await readBody(request);
778
- const patch = body.trim() === '' ? {} : JSON.parse(body);
829
+ const text = await readTextBody(request);
830
+ const patch = text.trim() === '' ? {} : JSON.parse(text);
779
831
  const before = settings.get().browser.channel;
780
832
  const updated = settings.update(patch);
781
833
  // A changed `browser.channel` is a request to switch carriers, not just a value to store. The
@@ -795,25 +847,3 @@ async function handleSettingsRequest(request, response, settings, onChannelChang
795
847
  json(400, { ok: false, error: `invalid settings patch: ${String(error)}` });
796
848
  }
797
849
  }
798
- /**
799
- * Read a request body with a hard cap (the settings patch is tiny, and an
800
- * unbounded read would let any same-origin caller exhaust memory).
801
- * @param request - the incoming request.
802
- * @param limit - maximum accepted characters.
803
- * @returns the body text.
804
- */
805
- function readBody(request, limit = 64 * 1024) {
806
- return new Promise((resolve, reject) => {
807
- let text = '';
808
- request.setEncoding('utf8');
809
- request.on('data', chunk => {
810
- text += String(chunk);
811
- if (text.length > limit) {
812
- request.destroy();
813
- reject(new Error('settings patch too large'));
814
- }
815
- });
816
- request.on('end', () => resolve(text));
817
- request.on('error', reject);
818
- });
819
- }
@@ -10,14 +10,15 @@
10
10
  * this module provides.
11
11
  *
12
12
  * Ownership is a marker file inside the directory naming the process that claimed it. A
13
- * directory whose owner is gone AND which has not been written to for a while is
14
- * abandoned. The age check is what keeps the sweep away from a profile an orphaned
15
- * browser (a child that outlived the parent which was killed) may still be using: a live
16
- * Chromium writes to its profile continuously, so a directory that has not changed in an
17
- * hour is not in use.
13
+ * directory whose owner is gone AND whose whole tree has not been written to for a while is
14
+ * abandoned. The age check is what keeps the sweep away from a profile an orphaned browser
15
+ * (a child that outlived the parent which was killed) may still be using: a live Chromium
16
+ * writes nested files continuously, so a tree with a recent write is not abandoned — even
17
+ * when the root directory's own timestamp is old, because writing a file does not update it.
18
18
  */
19
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
19
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
20
  import { join } from 'node:path';
21
+ import { pidAlive } from './process.js';
21
22
  /** The marker file, named once because both the claim and the sweep read it. */
22
23
  const OWNER_FILE = '.dsh-ephemeral-owner';
23
24
  /**
@@ -27,22 +28,10 @@ const OWNER_FILE = '.dsh-ephemeral-owner';
27
28
  */
28
29
  const ABANDONED_AFTER_MS = 60 * 60 * 1000;
29
30
  /**
30
- * Whether a process with this pid exists.
31
- *
32
- * A signal of 0 performs the permission and existence checks without delivering anything.
33
- * EPERM is a live process owned by someone else — alive, not gone.
34
- * @param pid - the pid to test.
35
- * @returns true when the process exists.
31
+ * Ceiling on how much of a profile tree one sweep inspects. A tree we cannot fully inspect is
32
+ * not proven abandoned, so it is kept; this only bounds the cost of saying so.
36
33
  */
37
- function processAlive(pid) {
38
- try {
39
- process.kill(pid, 0);
40
- return true;
41
- }
42
- catch (error) {
43
- return error.code === 'EPERM';
44
- }
45
- }
34
+ const MAX_SWEEP_ENTRIES = 20_000;
46
35
  /**
47
36
  * The directory name an ephemeral profile for `kind` gets, before it is claimed.
48
37
  *
@@ -92,6 +81,56 @@ function readOwner(dir) {
92
81
  return undefined;
93
82
  }
94
83
  }
84
+ /**
85
+ * The most recent write anywhere in a profile tree.
86
+ *
87
+ * A Chromium process writes nested files (`Default/Network/Cookies`, `Default/History`, ...).
88
+ * Writing a file does NOT refresh the mtime of the parent directory, so a quiet ROOT timestamp
89
+ * cannot prove the browser has exited — exactly the case where a killed DSH leaves a live child
90
+ * behind. Inspect the tree instead of just its root.
91
+ *
92
+ * Anything that cannot be inspected is reported as "written now", so the caller keeps the
93
+ * directory. When the evidence is incomplete, leaving a profile behind is the only safe outcome.
94
+ * Symbolic links are never followed, and an entry budget bounds the work.
95
+ * @param dir - the profile directory.
96
+ * @param now - the clock value used as the conservative "active" answer.
97
+ * @returns the newest mtime in the tree, or `-Infinity` when the tree holds nothing but our marker.
98
+ */
99
+ function latestWriteMs(dir, now) {
100
+ let latest = Number.NEGATIVE_INFINITY;
101
+ let budget = MAX_SWEEP_ENTRIES;
102
+ const pending = [dir];
103
+ while (pending.length > 0) {
104
+ const current = pending.pop();
105
+ let entries;
106
+ try {
107
+ entries = readdirSync(current, { withFileTypes: true });
108
+ }
109
+ catch {
110
+ return now;
111
+ }
112
+ for (const entry of entries) {
113
+ if (budget-- <= 0)
114
+ return now;
115
+ // Our owner marker is written once at claim time; it is not browser activity.
116
+ if (current === dir && entry.name === OWNER_FILE)
117
+ continue;
118
+ const path = join(current, entry.name);
119
+ let stat;
120
+ try {
121
+ stat = lstatSync(path);
122
+ }
123
+ catch {
124
+ return now;
125
+ }
126
+ if (stat.mtimeMs > latest)
127
+ latest = stat.mtimeMs;
128
+ if (stat.isDirectory() && !stat.isSymbolicLink())
129
+ pending.push(path);
130
+ }
131
+ }
132
+ return latest;
133
+ }
95
134
  /**
96
135
  * Delete the ephemeral profiles under `root` that belong to processes which are gone.
97
136
  *
@@ -104,7 +143,7 @@ function readOwner(dir) {
104
143
  */
105
144
  export function sweepAbandonedEphemeralProfiles(root, kind, options = {}) {
106
145
  const now = options.now ?? Date.now();
107
- const alive = options.alive ?? processAlive;
146
+ const alive = options.alive ?? pidAlive;
108
147
  const prefix = `${kind}-profile-ephemeral-`;
109
148
  const removed = [];
110
149
  let names;
@@ -119,15 +158,17 @@ export function sweepAbandonedEphemeralProfiles(root, kind, options = {}) {
119
158
  if (!name.startsWith(prefix))
120
159
  continue;
121
160
  const dir = join(root, name);
122
- let ageMs;
161
+ let rootMtime;
123
162
  try {
124
- ageMs = now - statSync(dir).mtimeMs;
163
+ rootMtime = statSync(dir).mtimeMs;
125
164
  }
126
165
  catch {
127
166
  continue;
128
167
  }
129
- // Recent writes mean a browser is still working in there. A killed DSH can leave its
130
- // Chromium child running, and that child's profile is not garbage.
168
+ // Recent writes ANYWHERE in the tree mean a browser is still working in there. A killed DSH
169
+ // can leave its Chromium child running, and a child writing Default/Network/Cookies does not
170
+ // refresh the root directory's mtime. Judging the root alone deleted live profiles.
171
+ const ageMs = now - Math.max(rootMtime, latestWriteMs(dir, now));
131
172
  if (ageMs < ABANDONED_AFTER_MS)
132
173
  continue;
133
174
  const owner = readOwner(dir);
@@ -13,8 +13,8 @@
13
13
  * @module dsh-browser/browser-electron/history-store
14
14
  */
15
15
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
16
- import { homedir } from 'node:os';
17
16
  import { dirname, join } from 'node:path';
17
+ import { dshHome } from './paths.js';
18
18
  import { writeFileAtomic } from './settings-store.js';
19
19
  /** Default entry cap — mirrors the documented retention rule. */
20
20
  const DEFAULT_MAX_ENTRIES = 5_000;
@@ -28,7 +28,7 @@ const PRUNE_SLACK = 500;
28
28
  * @returns the history file path.
29
29
  */
30
30
  export function visitedHistoryPath() {
31
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
31
+ const home = dshHome();
32
32
  return join(home, 'dsh-builtin-browser-host', 'history.jsonl');
33
33
  }
34
34
  /**
@@ -32,6 +32,7 @@ import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.js';
32
32
  import { createRpcLineReader } from './rpc-input.js';
33
33
  import { tmpdir } from 'node:os';
34
34
  import { join } from 'node:path';
35
+ import { withTimeoutShared } from './timing.js';
35
36
  // Report the binary actually running this child, even when ELECTRON_PATH
36
37
  // intentionally selects a different version from the plugin's dependency.
37
38
  // The parent mirrors stderr to the host log; discovery stays filesystem-only.
@@ -248,12 +249,7 @@ function ensureToolbarFiles() {
248
249
  * explicit error instead of a command that never settles.
249
250
  */
250
251
  function withTimeout(promise, ms, label) {
251
- return new Promise((resolve, reject) => {
252
- const timer = setTimeout(() => {
253
- reject(new Error(`${label} timed out after ${ms}ms`));
254
- }, ms);
255
- promise.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });
256
- });
252
+ return withTimeoutShared(promise, ms, () => new Error(`${label} timed out after ${ms}ms`));
257
253
  }
258
254
  /**
259
255
  * CDP commands are bounded here as well as in the parent: a view whose
@@ -463,10 +459,12 @@ function wireFocusRouting(win, view, focusKey) {
463
459
  if (input.type !== 'mouseDown')
464
460
  return;
465
461
  win.lastFocusedViewId = focusKey;
466
- try {
467
- view.webContents.focus();
462
+ if (win.window.isFocused()) {
463
+ try {
464
+ view.webContents.focus();
465
+ }
466
+ catch { /* destroyed */ }
468
467
  }
469
- catch { /* destroyed */ }
470
468
  });
471
469
  }
472
470
  /** Create the toolbar view for a window (best-effort; never fatal). */
@@ -599,35 +597,27 @@ function revealViewInWindow(win, viewId, label) {
599
597
  * @param viewId - the view to present.
600
598
  * @param label - session/task label, when known, for the window title.
601
599
  * @param quiet - `ui.quiet`: present without taking the screen over.
602
- * @param needSurface - quiet mode only: this presentation is the barrier before synthesized
603
- * input, so a newly created window needs an invisible display surface. A minimized window
604
- * stays minimized because restoring it can activate it.
600
+ * @param _needSurface - pre-input barrier flag retained by the RPC protocol. Quiet presentation
601
+ * opens a new visible window without activation and preserves an existing foreground page.
605
602
  */
606
- function showViewInWindow(win, viewId, label, quiet = false, needSurface = false) {
603
+ function showViewInWindow(win, viewId, label, quiet = false, _needSurface = false) {
607
604
  if (quiet) {
608
- if (win.window.isMinimized()) {
609
- if (needSurface)
610
- throw new Error('quiet mode will not restore a minimized browser window; restore it manually to send input');
605
+ if (win.window.isMinimized())
611
606
  return;
612
- }
613
- if (win.window.isVisible() && win.window.getOpacity() > 0) {
614
- if (win.visibleViewId !== viewId) {
615
- if (needSurface)
616
- throw new Error('quiet mode will not replace a visible browser tab; select the target tab manually to send input');
617
- return;
618
- }
619
- revealViewInWindow(win, viewId, label);
607
+ // Preserve the page the operator is actively reading. Other views remain addressable by
608
+ // their own CDP session, without switching the foreground window's selected page.
609
+ if (win.window.isFocused() && win.visibleViewId !== viewId)
620
610
  return;
621
- }
622
611
  revealViewInWindow(win, viewId, label);
623
- if (!needSurface || win.window.isVisible())
624
- return;
625
- win.window.setOpacity(0);
626
- if (win.window.getOpacity() > 0)
627
- throw new Error('quiet mode could not create an invisible browser surface');
628
- win.window.setSkipTaskbar(true);
629
- win.window.setFocusable(false);
630
- win.window.showInactive();
612
+ // Quiet means a normal usable window without activation, including on the first open.
613
+ // An invisible surface made the browser look broken even after navigation succeeded.
614
+ if (win.window.getOpacity() === 0) {
615
+ win.window.setOpacity(1);
616
+ win.window.setSkipTaskbar(false);
617
+ win.window.setFocusable(true);
618
+ }
619
+ if (!win.window.isVisible())
620
+ win.window.showInactive();
631
621
  return;
632
622
  }
633
623
  revealViewInWindow(win, viewId, label);
@@ -855,10 +845,9 @@ async function handle(op, msg) {
855
845
  // and `document.hasFocus()` inside the page even read true.
856
846
  const contents = entry.webContentsView.webContents;
857
847
  const hadWebFocus = contents.isFocused();
858
- if (msg.quiet === true && win.window.getOpacity() > 0 && !hadWebFocus) {
859
- throw new Error('quiet mode will not take keyboard focus from the visible browser; focus the target page manually');
860
- }
861
- if (msg.quiet !== true || !hadWebFocus)
848
+ // Electron webContents.focus() can activate its BrowserWindow. CDP input uses the
849
+ // target page's DOM focus and does not require that operating-system activation.
850
+ if (msg.quiet !== true)
862
851
  contents.focus();
863
852
  // Focus lands asynchronously, and a key dispatched in the same turn as
864
853
  // the request is still dropped, so hold the reply until the renderer can
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Bounded request bodies shared by every plugin HTTP route. Keeping one implementation means the
3
+ * byte limit, UTF-8 decoding and oversize behaviour cannot drift between the settings and the
4
+ * maintenance endpoints.
5
+ * @module dsh-browser/browser-electron/http-body
6
+ */
7
+ import type { IncomingMessage } from 'node:http';
8
+ /**
9
+ * Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
10
+ * encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
11
+ * happens to be split across two TCP chunks.
12
+ * @param request - the incoming request.
13
+ * @param limit - maximum accepted bytes.
14
+ * @returns the body text.
15
+ */
16
+ export declare function readTextBody(request: IncomingMessage, limit?: number): Promise<string>;
17
+ /**
18
+ * Read and parse a JSON body. An empty body is an empty object, matching the settings route's
19
+ * long-standing behaviour.
20
+ * @param request - the incoming request.
21
+ * @param limit - maximum accepted bytes.
22
+ * @returns the parsed value.
23
+ */
24
+ export declare function readJsonBody<T>(request: IncomingMessage, limit?: number): Promise<T>;