dsh-builtin-browser 0.5.6 → 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 (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -102,21 +102,37 @@ function electronVersion() {
102
102
  return 'unknown';
103
103
  }
104
104
  }
105
+ let runningInstaller;
105
106
  /** The real dependencies: this process's spawn, fs and logger. */
106
107
  export function defaultDeps(log = () => { }) {
107
108
  return {
108
109
  hasBinary: hasElectronRuntime,
109
110
  installerScript: electronInstallerScript,
110
- run: async (script) => {
111
- const child = spawn(process.execPath, [script], {
112
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
113
- stdio: ['ignore', 'ignore', 'ignore'],
114
- windowsHide: true,
115
- });
116
- return await new Promise(resolve => {
117
- child.once('error', error => resolve({ code: null, detail: String(error) }));
118
- child.once('close', code => resolve({ code, detail: undefined }));
111
+ run: (script, signal) => {
112
+ if (runningInstaller !== undefined)
113
+ return runningInstaller;
114
+ const run = new Promise(resolve => {
115
+ const child = spawn(process.execPath, [script], {
116
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
117
+ stdio: ['ignore', 'ignore', 'ignore'],
118
+ windowsHide: true,
119
+ });
120
+ let failure;
121
+ const abort = () => { child.kill('SIGKILL'); };
122
+ signal?.addEventListener('abort', abort, { once: true });
123
+ if (signal?.aborted)
124
+ abort();
125
+ child.once('error', error => { failure = String(error); });
126
+ child.once('close', code => {
127
+ signal?.removeEventListener('abort', abort);
128
+ resolve({ code, detail: failure });
129
+ });
119
130
  });
131
+ runningInstaller = run;
132
+ const clear = () => { if (runningInstaller === run)
133
+ runningInstaller = undefined; };
134
+ void run.then(clear, clear);
135
+ return run;
120
136
  },
121
137
  log,
122
138
  skip: () => typeof process.env.ELECTRON_SKIP_BINARY_DOWNLOAD === 'string'
@@ -141,12 +157,15 @@ export async function ensureElectronRuntime(deps = defaultDeps()) {
141
157
  if (script === undefined) {
142
158
  return record({ status: 'failed', detail: 'the installed electron package has no install.js; reinstall the plugin in this profile' });
143
159
  }
160
+ // Resolve the installed Electron version once: each call re-runs createRequire,
161
+ // require.resolve and a synchronous package.json read + parse.
162
+ const version = electronVersion();
144
163
  latest = {
145
164
  state: 'preparing',
146
- detail: `downloading Electron ${electronVersion()} (one time, about a minute)`,
165
+ detail: `downloading Electron ${version} (one time, about a minute)`,
147
166
  at: new Date().toISOString(),
148
167
  };
149
- deps.log(`preparing Electron ${electronVersion()} in the background (a missing runtime needs a download)`);
168
+ deps.log(`preparing Electron ${version} in the background (a missing runtime needs a download)`);
150
169
  // The bound has to be a REFERENCED timer, and it has to be cleared when the race finishes.
151
170
  //
152
171
  // A first version unref'd it — "do not keep the process alive for a download" — which is exactly
@@ -155,12 +174,16 @@ export async function ensureElectronRuntime(deps = defaultDeps()) {
155
174
  // this path failed with "Promise resolution is still pending but the event loop has already
156
175
  // resolved". Keep it referenced, and clear it so a success does not leave a 180 s handle behind.
157
176
  let timer;
177
+ const controller = new AbortController();
158
178
  const timeout = new Promise(resolve => {
159
- timer = setTimeout(() => resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` }), deps.timeoutMs);
179
+ timer = setTimeout(() => {
180
+ controller.abort();
181
+ resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` });
182
+ }, deps.timeoutMs);
160
183
  });
161
184
  let outcome;
162
185
  try {
163
- outcome = await Promise.race([deps.run(script), timeout]);
186
+ outcome = await Promise.race([deps.run(script, controller.signal), timeout]);
164
187
  }
165
188
  catch (error) {
166
189
  return record({ status: 'failed', detail: `the download failed: ${String(error)}` });
@@ -16,17 +16,27 @@ 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';
25
27
  import { SettingsStore, settingsPath } from './settings-store.js';
26
28
  import { sameOrigin } from './settings-route.js';
29
+ import { authenticatedRoute, isDirectLoopback } from './authenticated-route.js';
27
30
  import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js';
28
31
  import { findDesktopInstall, readBridgeStatus } from './bridge-status.js';
29
32
  import { readBridgeEndpoint } from './bridge-endpoint.js';
33
+ import { runBridgeAction } from './bridge-install.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';
30
40
  import { readRuntimeStatus } from './runtime-status.js';
31
41
  import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js';
32
42
  export { ELECTRON_BROWSER_PROVIDER_ID, ElectronBrowserProvider, } from './provider.js';
@@ -115,11 +125,8 @@ export function apply(ctx, config) {
115
125
  }
116
126
  return;
117
127
  }
118
- // Otherwise start self-hosted — a working browser from the first call, on every
119
- // surface — and upgrade to the desktop sidebar if this machine has one. The
120
- // upgrade is deliberately a swap of the whole provider: the two carriers own
121
- // different lifetimes (a spawned child vs. the shell's view), and pretending
122
- // 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.
123
130
  const selfHosted = new RemoteElectronViewHost(defaultHostMainPath());
124
131
  // The self-hosted carrier is the only one that needs Electron, and it is prepared HERE, lazily,
125
132
  // rather than during package installation (issue #41: a `postinstall` download made a default
@@ -132,12 +139,25 @@ export function apply(ctx, config) {
132
139
  if (wantedChannel === 'bundled' || wantedChannel === 'auto') {
133
140
  void provisionElectronInBackground(message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`));
134
141
  }
135
- 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));
136
156
  let disposed = false;
137
157
  let carrierChoice = 0;
138
158
  let discovery;
139
159
  /** The carrier an `adopt` installed, so a later choice can release it. */
140
- let adoptedCarrier;
160
+ let adoptedCarrier = initialHost === selfHosted ? undefined : initialHost;
141
161
  ctx.effect(() => () => {
142
162
  disposed = true;
143
163
  carrierChoice += 1;
@@ -166,18 +186,21 @@ export function apply(ctx, config) {
166
186
  if (disposed || adoptedCarrier !== adopted)
167
187
  return;
168
188
  try {
169
- const restored = new RemoteElectronViewHost(defaultHostMainPath());
189
+ const sidebarSelected = settings.get().browser.channel === 'sidebar';
190
+ const restored = sidebarSelected ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath());
170
191
  unregister();
171
192
  unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig));
172
193
  adoptedCarrier = restored;
173
- ctx.logger?.warn?.(reason === 'shell-exited'
174
- ? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
175
- + 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
176
- + 'open the page again.'
177
- : 'dsh-builtin-browser: this desktop shell renders the sidebar browser panel in a way that '
178
- + 'cannot be driven (no webContents, so no CDP endpoint), so the browser this plugin hosts '
179
- + 'itself takes over. The shell is still running and nothing else is affected; the page '
180
- + '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.');
181
204
  }
182
205
  catch (error) {
183
206
  // Nothing better is available: the adopted carrier is gone and a provider that throws is
@@ -229,7 +252,8 @@ export function apply(ctx, config) {
229
252
  // A borrowed carrier can lose the process behind it, and this is the only notification that
230
253
  // will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
231
254
  // against a provider that was never installed.
232
- host.onLost?.(reason => { restoreSelfHosted(host, reason); });
255
+ if (!(host instanceof SidebarOnlyHost))
256
+ host.onLost?.(reason => { restoreSelfHosted(host, reason); });
233
257
  // Released AFTER the replacement is installed, so the surface is never without a provider.
234
258
  if (previous !== undefined && previous !== host) {
235
259
  try {
@@ -254,7 +278,7 @@ export function apply(ctx, config) {
254
278
  // exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
255
279
  // session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
256
280
  try {
257
- const fallback = new RemoteElectronViewHost(defaultHostMainPath());
281
+ const fallback = settings.get().browser.channel === 'sidebar' ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath());
258
282
  unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig));
259
283
  adoptedCarrier = fallback;
260
284
  if (previous !== undefined && previous !== host) {
@@ -304,7 +328,12 @@ export function apply(ctx, config) {
304
328
  // and a user who picked a browser that is not installed would never see the explanation
305
329
  // written for exactly that case, because the sidebar would quietly replace it.
306
330
  const explicitChoice = channel !== 'bundled' && channel !== 'auto' && channel !== 'sidebar';
307
- 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') {
308
337
  const detected = detectBrowser(channel);
309
338
  if (detected === undefined) {
310
339
  // `auto` promises to take whatever is available, so falling back is what it
@@ -328,7 +357,7 @@ export function apply(ctx, config) {
328
357
  // `C:\Users\<user>\dsh-builtin-browser-host\` while its settings and history lived in
329
358
  // `~/.dsh/dsh-builtin-browser-host/` — two half-profiles that never met, and a
330
359
  // settings panel whose switches appeared not to apply.
331
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
360
+ const home = dshHome();
332
361
  // Login state lives in the browser profile, so the cookies setting decides where
333
362
  // that profile goes: a stable directory keeps the user signed in across restarts
334
363
  // (the point of using their own browser), while turning persistence off gets a
@@ -348,7 +377,7 @@ export function apply(ctx, config) {
348
377
  }
349
378
  // The headless mode rides along so a display-less host (systemd, container, SSH-only server)
350
379
  // still gets a working browser instead of "exited immediately after launch" — issue #32.
351
- adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir, undefined, settings.get().browser.headless), `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`);
380
+ adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir, undefined, settings.get().browser.headless, () => settings.get().ui.quiet), `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`);
352
381
  }
353
382
  }
354
383
  else if (adoptedCarrier !== undefined) {
@@ -359,9 +388,8 @@ export function apply(ctx, config) {
359
388
  // An explicit choice was already adopted above; discovering the sidebar here would
360
389
  // replace it, which is exactly what this guard prevents.
361
390
  //
362
- // `sidebar` is explicit too, but it names the sidebar, so it is the one explicit choice that
363
- // must FALL THROUGH to the discovery below instead of returning here.
364
- if (explicitChoice && channel !== 'sidebar')
391
+ // Explicit sidebar selection was handled above by its reconnectable sidebar-only host.
392
+ if (explicitChoice)
365
393
  return;
366
394
  // The shell may not be up yet. `dsh web` starts before — or entirely without — the desktop app
367
395
  // that hosts the bridge, and a one-shot discovery meant a bridge that appeared a second later
@@ -384,7 +412,7 @@ export function apply(ctx, config) {
384
412
  return;
385
413
  let sidebar;
386
414
  try {
387
- sidebar = await DesktopBridgeViewHost.discover(sessionId);
415
+ sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet);
388
416
  }
389
417
  catch {
390
418
  sidebar = undefined; // discovery is documented not to throw; never let it stop the retries
@@ -414,15 +442,6 @@ export function apply(ctx, config) {
414
442
  + 'enables `webviewTag` would provide a drivable panel.');
415
443
  return;
416
444
  }
417
- // The user explicitly asked for the sidebar, so silence would leave them with a setting
418
- // that did nothing and no way to tell why. This is reachable on `dsh web`, and on a desktop
419
- // whose shell never published a bridge endpoint. An automatic attempt stays quiet (the
420
- // self-hosted window is a fine outcome); an explicit request does not.
421
- if (channel === 'sidebar') {
422
- ctx.logger?.warn?.('dsh-builtin-browser: the sidebar browser was requested but no desktop bridge was found — '
423
- + 'this DSH has no desktop shell, or its bridge never started. Falling back to the bundled '
424
- + 'browser; set browser.channel to another value to silence this.');
425
- }
426
445
  })();
427
446
  };
428
447
  chooseCarrier();
@@ -451,13 +470,13 @@ export function apply(ctx, config) {
451
470
  host.effect(() => host.webServer.register({
452
471
  kind: 'exact',
453
472
  path: PREVIEW_ROUTE,
454
- handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
473
+ handler: authenticated(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
455
474
  }, 'dsh-builtin-browser: live view frame'));
456
475
  // The list the panel needs before it can build a frame URL at all: session ids only.
457
476
  host.effect(() => host.webServer.register({
458
477
  kind: 'exact',
459
478
  path: PREVIEW_SESSIONS_ROUTE,
460
- handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
479
+ handler: authenticated(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
461
480
  }, 'dsh-builtin-browser: live view sessions'));
462
481
  });
463
482
  }
@@ -473,17 +492,116 @@ export function apply(ctx, config) {
473
492
  * exactly like the other two.
474
493
  * @param ctx - the plugin context.
475
494
  */
495
+ /** Where the panel asks to install or remove the bridge. */
496
+ const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action';
497
+ let bridgeActionRunning = false;
498
+ /**
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?}`).
502
+ * @param response - the response to write.
503
+ */
504
+ async function handleBridgeAction(request, response) {
505
+ if (request.method !== 'POST') {
506
+ replyJson(response, 405, { error: 'method-not-allowed' });
507
+ return;
508
+ }
509
+ // Both creating a local launcher and changing installation files require write admission.
510
+ if (!sameOrigin(request, true)) {
511
+ replyJson(response, 403, { error: 'not-same-origin' });
512
+ return;
513
+ }
514
+ if (!isDirectLoopback(request)) {
515
+ replyJson(response, 403, { error: 'local-request-required' });
516
+ return;
517
+ }
518
+ let action;
519
+ let preparationOnly = false;
520
+ try {
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;
526
+ }
527
+ catch (error) {
528
+ replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` });
529
+ return;
530
+ }
531
+ if (action !== 'install' && action !== 'uninstall') {
532
+ replyJson(response, 400, { ok: false, error: 'action must be "install" or "uninstall"' });
533
+ return;
534
+ }
535
+ const root = findDesktopInstall();
536
+ if (root === undefined) {
537
+ // Nothing to patch: say so instead of running an installer against a guess.
538
+ replyJson(response, 409, { ok: false, error: 'no DSH Desktop install was found on this machine' });
539
+ return;
540
+ }
541
+ if (bridgeActionRunning) {
542
+ replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' });
543
+ return;
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
+ }
550
+ bridgeActionRunning = true;
551
+ try {
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) });
566
+ }
567
+ finally {
568
+ bridgeActionRunning = false;
569
+ }
570
+ }
476
571
  function installBridgeStatusRoute(ctx) {
477
572
  const injectStatus = ctx.inject;
478
573
  if (typeof injectStatus !== 'function')
479
574
  return;
480
575
  try {
481
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'));
482
593
  host.effect(() => host.webServer.register({
483
594
  kind: 'exact',
484
595
  path: BRIDGE_STATUS_ROUTE,
485
- handler: (request, response) => handleBridgeStatus(request, response),
596
+ handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
486
597
  }, 'dsh-builtin-browser: bridge status'));
598
+ // The panel prepares a launcher without changing the running Desktop. Direct local
599
+ // maintenance remains available once Desktop has exited.
600
+ host.effect(() => host.webServer.register({
601
+ kind: 'exact',
602
+ path: BRIDGE_ACTION_ROUTE,
603
+ handler: authenticated(ctx, (request, response) => handleBridgeAction(request, response)),
604
+ }, 'dsh-builtin-browser: bridge action'));
487
605
  });
488
606
  }
489
607
  catch {
@@ -491,6 +609,8 @@ export function apply(ctx, config) {
491
609
  }
492
610
  }
493
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.
494
614
  /**
495
615
  * Expose readiness — "can the browser serve a call right now" — for the settings panel.
496
616
  *
@@ -512,6 +632,8 @@ export function apply(ctx, config) {
512
632
  const deps = {
513
633
  report: () => readRuntimeStatus({
514
634
  channel: () => settings.get().browser.channel,
635
+ selectedCarrier: () => adoptedCarrier instanceof DesktopBridgeViewHost || adoptedCarrier instanceof SidebarOnlyHost ? 'sidebar'
636
+ : adoptedCarrier instanceof SystemBrowserViewHost ? 'system' : 'bundled',
515
637
  hasBinary: hasElectronRuntime,
516
638
  provision: provisionSnapshot,
517
639
  bridge: () => {
@@ -534,12 +656,12 @@ export function apply(ctx, config) {
534
656
  host.effect(() => host.webServer.register({
535
657
  kind: 'exact',
536
658
  path: RUNTIME_STATUS_ROUTE,
537
- handler: (request, response) => handleRuntimeStatus(request, response, deps),
659
+ handler: authenticated(ctx, (request, response) => handleRuntimeStatus(request, response, deps)),
538
660
  }, 'dsh-builtin-browser: runtime status'));
539
661
  host.effect(() => host.webServer.register({
540
662
  kind: 'exact',
541
663
  path: RUNTIME_PROVISION_ROUTE,
542
- handler: (request, response) => handleRuntimeProvision(request, response, deps),
664
+ handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
543
665
  }, 'dsh-builtin-browser: runtime provision'));
544
666
  });
545
667
  }
@@ -588,7 +710,7 @@ export function apply(ctx, config) {
588
710
  lastChannel = channel;
589
711
  ctx.logger?.info?.(`dsh-builtin-browser: settings changed on disk, re-choosing the carrier for channel "${channel}"`);
590
712
  chooseCarrier();
591
- }, 2_000);
713
+ }, 5_000);
592
714
  // Unref-ed so a poll never holds the process open.
593
715
  timer.unref?.();
594
716
  ctx.effect(() => () => { clearInterval(timer); }, "dsh-builtin-browser: settings file watch");
@@ -642,6 +764,13 @@ export function adoptLegacyProfileRoot(profileRoot, legacyRoot = join(homedir(),
642
764
  // Nothing here is worth failing an apply over; the fallback is the pre-existing behaviour.
643
765
  }
644
766
  }
767
+ /** Bind the host's signed browser-session authentication to a plugin route. */
768
+ function authenticated(ctx, handler) {
769
+ return authenticatedRoute(() => {
770
+ const surface = ctx;
771
+ return surface.get('connection');
772
+ }, handler);
773
+ }
645
774
  /**
646
775
  * Expose the settings document over the host's web server, which is how the
647
776
  * settings panel reads and writes it. A host without that service (headless /
@@ -659,7 +788,7 @@ function installSettingsRoute(ctx, settings, onChannelChange) {
659
788
  host.effect(() => host.webServer.register({
660
789
  kind: 'exact',
661
790
  path: SETTINGS_ROUTE,
662
- handler: (request, response) => handleSettingsRequest(request, response, settings, onChannelChange),
791
+ handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
663
792
  }, 'dsh-builtin-browser: settings'));
664
793
  });
665
794
  }
@@ -677,11 +806,10 @@ function installSettingsRoute(ctx, settings, onChannelChange) {
677
806
  */
678
807
  async function handleSettingsRequest(request, response, settings, onChannelChange) {
679
808
  const json = (status, body) => {
680
- response.writeHead(status, {
809
+ writeJsonText(response, status, JSON.stringify(body), {
681
810
  'content-type': 'application/json; charset=utf-8',
682
811
  'cache-control': 'no-store',
683
812
  });
684
- response.end(JSON.stringify(body));
685
813
  };
686
814
  const method = request.method ?? 'GET';
687
815
  if (!sameOrigin(request, method !== 'GET')) {
@@ -698,8 +826,8 @@ async function handleSettingsRequest(request, response, settings, onChannelChang
698
826
  return;
699
827
  }
700
828
  try {
701
- const body = await readBody(request);
702
- const patch = body.trim() === '' ? {} : JSON.parse(body);
829
+ const text = await readTextBody(request);
830
+ const patch = text.trim() === '' ? {} : JSON.parse(text);
703
831
  const before = settings.get().browser.channel;
704
832
  const updated = settings.update(patch);
705
833
  // A changed `browser.channel` is a request to switch carriers, not just a value to store. The
@@ -719,25 +847,3 @@ async function handleSettingsRequest(request, response, settings, onChannelChang
719
847
  json(400, { ok: false, error: `invalid settings patch: ${String(error)}` });
720
848
  }
721
849
  }
722
- /**
723
- * Read a request body with a hard cap (the settings patch is tiny, and an
724
- * unbounded read would let any same-origin caller exhaust memory).
725
- * @param request - the incoming request.
726
- * @param limit - maximum accepted characters.
727
- * @returns the body text.
728
- */
729
- function readBody(request, limit = 64 * 1024) {
730
- return new Promise((resolve, reject) => {
731
- let text = '';
732
- request.setEncoding('utf8');
733
- request.on('data', chunk => {
734
- text += String(chunk);
735
- if (text.length > limit) {
736
- request.destroy();
737
- reject(new Error('settings patch too large'));
738
- }
739
- });
740
- request.on('end', () => resolve(text));
741
- request.on('error', reject);
742
- });
743
- }
@@ -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);