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.
- package/CHANGELOG.md +66 -0
- package/README.en.md +48 -22
- package/README.md +48 -22
- package/client.js +469 -81
- package/desktop-bridge/install-and-start.cmd +4 -5
- package/desktop-bridge/install.mjs +251 -159
- package/desktop-bridge/maintenance-progress.ps1 +166 -0
- package/desktop-bridge/plugin-browser-bridge.js +151 -18
- package/desktop-bridge/request-desktop-quit.ps1 +170 -0
- package/docs/user-guide.md +28 -4
- package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
- package/lib/browser-electron/automatic-maintenance.js +426 -0
- package/lib/browser-electron/bridge-auto.d.ts +93 -0
- package/lib/browser-electron/bridge-auto.js +113 -0
- package/lib/browser-electron/bridge-connection.d.ts +0 -2
- package/lib/browser-electron/bridge-connection.js +2 -4
- package/lib/browser-electron/bridge-endpoint.js +1 -19
- package/lib/browser-electron/bridge-install.d.ts +41 -4
- package/lib/browser-electron/bridge-install.js +131 -18
- package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
- package/lib/browser-electron/bridge-maintenance.js +125 -0
- package/lib/browser-electron/bridge-status.d.ts +10 -3
- package/lib/browser-electron/bridge-status.js +76 -45
- package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
- package/lib/browser-electron/desktop-bridge-host.js +54 -33
- package/lib/browser-electron/desktop-identity.js +21 -9
- package/lib/browser-electron/electron-provision.js +5 -2
- package/lib/browser-electron/entry.js +104 -74
- package/lib/browser-electron/ephemeral-profile.js +67 -26
- package/lib/browser-electron/history-store.js +2 -2
- package/lib/browser-electron/host-main.js +26 -37
- package/lib/browser-electron/http-body.d.ts +24 -0
- package/lib/browser-electron/http-body.js +33 -0
- package/lib/browser-electron/json-reply.d.ts +13 -1
- package/lib/browser-electron/json-reply.js +16 -2
- package/lib/browser-electron/maintenance-broker.d.ts +35 -0
- package/lib/browser-electron/maintenance-broker.js +114 -0
- package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
- package/lib/browser-electron/maintenance-lifecycle.js +67 -0
- package/lib/browser-electron/maintenance-route.d.ts +18 -0
- package/lib/browser-electron/maintenance-route.js +75 -0
- package/lib/browser-electron/paths.d.ts +4 -0
- package/lib/browser-electron/paths.js +19 -0
- package/lib/browser-electron/process.d.ts +14 -0
- package/lib/browser-electron/process.js +24 -0
- package/lib/browser-electron/provider.d.ts +7 -7
- package/lib/browser-electron/provider.js +13 -14
- package/lib/browser-electron/remote-host.js +18 -16
- package/lib/browser-electron/runtime-status.d.ts +27 -13
- package/lib/browser-electron/runtime-status.js +24 -4
- package/lib/browser-electron/settings-store.d.ts +11 -0
- package/lib/browser-electron/settings-store.js +8 -2
- package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
- package/lib/browser-electron/sidebar-only-host.js +192 -0
- package/lib/browser-electron/system-browser.d.ts +1 -9
- package/lib/browser-electron/system-browser.js +19 -22
- package/lib/browser-electron/timing.d.ts +8 -0
- package/lib/browser-electron/timing.js +13 -0
- package/lib/browser-electron/windows-system.d.ts +3 -0
- package/lib/browser-electron/windows-system.js +19 -0
- package/lib/tool-browser/index.js +5 -4
- package/package.json +2 -2
- package/scripts/run-tests.mjs +32 -0
- package/scripts/verify-preview-route.mjs +19 -1
- package/src/browser-electron/automatic-maintenance.ts +414 -0
- package/src/browser-electron/bridge-auto.ts +158 -0
- package/src/browser-electron/bridge-connection.ts +2 -4
- package/src/browser-electron/bridge-endpoint.ts +1 -18
- package/src/browser-electron/bridge-install.ts +151 -20
- package/src/browser-electron/bridge-maintenance.ts +161 -0
- package/src/browser-electron/bridge-status.ts +78 -48
- package/src/browser-electron/desktop-bridge-host.ts +48 -32
- package/src/browser-electron/desktop-identity.ts +18 -9
- package/src/browser-electron/electron-provision.ts +5 -2
- package/src/browser-electron/entry.ts +91 -69
- package/src/browser-electron/ephemeral-profile.ts +65 -28
- package/src/browser-electron/history-store.ts +2 -2
- package/src/browser-electron/host-main.ts +23 -36
- package/src/browser-electron/http-body.ts +42 -0
- package/src/browser-electron/json-reply.ts +18 -3
- package/src/browser-electron/maintenance-broker.ts +142 -0
- package/src/browser-electron/maintenance-lifecycle.ts +86 -0
- package/src/browser-electron/maintenance-route.ts +64 -0
- package/src/browser-electron/paths.ts +21 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/provider.ts +18 -18
- package/src/browser-electron/remote-host.ts +19 -19
- package/src/browser-electron/runtime-status.ts +52 -17
- package/src/browser-electron/settings-store.ts +20 -3
- package/src/browser-electron/sidebar-only-host.ts +199 -0
- package/src/browser-electron/system-browser.ts +19 -22
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/windows-system.ts +23 -0
- package/src/tool-browser/index.ts +5 -4
|
@@ -22,9 +22,11 @@ import { randomUUID } from 'node:crypto'
|
|
|
22
22
|
import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs'
|
|
23
23
|
import { homedir } from 'node:os'
|
|
24
24
|
import { dirname, join } from 'node:path'
|
|
25
|
+
import { dshHome } from './paths.js'
|
|
25
26
|
import { setTimeout as wait } from 'node:timers/promises'
|
|
26
27
|
import { defaultHostMainPath, RemoteElectronViewHost } from './remote-host.js'
|
|
27
28
|
import { DesktopBridgeViewHost } from './desktop-bridge-host.js'
|
|
29
|
+
import { SidebarOnlyHost } from './sidebar-only-host.js'
|
|
28
30
|
import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.js'
|
|
29
31
|
import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralProfiles } from './ephemeral-profile.js'
|
|
30
32
|
import { MissingSystemBrowserHost } from './missing-system-browser.js'
|
|
@@ -35,7 +37,12 @@ import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_S
|
|
|
35
37
|
import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
|
|
36
38
|
import { readBridgeEndpoint } from './bridge-endpoint.js'
|
|
37
39
|
import { runBridgeAction } from './bridge-install.js'
|
|
38
|
-
import {
|
|
40
|
+
import { prepareBridgeMaintenance } from './bridge-maintenance.js'
|
|
41
|
+
import { commitAutomaticMaintenance, readAutomaticMaintenance, startAutomaticMaintenance } from './automatic-maintenance.js'
|
|
42
|
+
import { AUTOMATIC_MAINTENANCE_ROUTE, createAutomaticMaintenanceHandler } from './maintenance-route.js'
|
|
43
|
+
import { runWithManualBridgePreference } from './bridge-auto.js'
|
|
44
|
+
import { replyJson, writeJsonText } from './json-reply.js'
|
|
45
|
+
import { readJsonBody, readTextBody } from './http-body.js'
|
|
39
46
|
import { readRuntimeStatus } from './runtime-status.js'
|
|
40
47
|
import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js'
|
|
41
48
|
|
|
@@ -155,11 +162,8 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
155
162
|
return
|
|
156
163
|
}
|
|
157
164
|
|
|
158
|
-
//
|
|
159
|
-
//
|
|
160
|
-
// upgrade is deliberately a swap of the whole provider: the two carriers own
|
|
161
|
-
// different lifetimes (a spawned child vs. the shell's view), and pretending
|
|
162
|
-
// otherwise would leave a stray window behind.
|
|
165
|
+
// Explicit sidebar selection stays on the desktop's carrier, including while its bridge
|
|
166
|
+
// reconnects. Other choices can use the independently hosted browser when appropriate.
|
|
163
167
|
const selfHosted = new RemoteElectronViewHost(defaultHostMainPath())
|
|
164
168
|
// The self-hosted carrier is the only one that needs Electron, and it is prepared HERE, lazily,
|
|
165
169
|
// rather than during package installation (issue #41: a `postinstall` download made a default
|
|
@@ -172,12 +176,22 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
172
176
|
if (wantedChannel === 'bundled' || wantedChannel === 'auto') {
|
|
173
177
|
void provisionElectronInBackground(message => ctx.logger?.info?.(`dsh-builtin-browser: ${message}`))
|
|
174
178
|
}
|
|
175
|
-
|
|
179
|
+
const requiredSidebar = (): SidebarOnlyHost => new SidebarOnlyHost(async () => {
|
|
180
|
+
for (const pause of [0, 1_000, 3_000, 8_000]) {
|
|
181
|
+
if (pause > 0) await wait(pause)
|
|
182
|
+
const sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet)
|
|
183
|
+
if (sidebar !== undefined) return sidebar
|
|
184
|
+
if (DesktopBridgeViewHost.refusedIframePanel()) break
|
|
185
|
+
}
|
|
186
|
+
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.')
|
|
187
|
+
})
|
|
188
|
+
const initialHost = wantedChannel === 'sidebar' ? requiredSidebar() : selfHosted
|
|
189
|
+
let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(initialHost, providerConfig))
|
|
176
190
|
let disposed = false
|
|
177
191
|
let carrierChoice = 0
|
|
178
192
|
let discovery: AbortController | undefined
|
|
179
193
|
/** The carrier an `adopt` installed, so a later choice can release it. */
|
|
180
|
-
let adoptedCarrier: ElectronBrowserViewHost | undefined
|
|
194
|
+
let adoptedCarrier: ElectronBrowserViewHost | undefined = initialHost === selfHosted ? undefined : initialHost
|
|
181
195
|
|
|
182
196
|
ctx.effect(() => () => {
|
|
183
197
|
disposed = true
|
|
@@ -207,12 +221,15 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
207
221
|
// A replaced carrier may finish an outstanding request after the new choice is installed.
|
|
208
222
|
if (disposed || adoptedCarrier !== adopted) return
|
|
209
223
|
try {
|
|
210
|
-
const
|
|
224
|
+
const sidebarSelected = settings.get().browser.channel === 'sidebar'
|
|
225
|
+
const restored = sidebarSelected ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath())
|
|
211
226
|
unregister()
|
|
212
227
|
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig))
|
|
213
228
|
adoptedCarrier = restored
|
|
214
229
|
ctx.logger?.warn?.(
|
|
215
|
-
|
|
230
|
+
sidebarSelected
|
|
231
|
+
? 'dsh-builtin-browser: the selected DSH sidebar connection was lost; the next operation will reconnect to the sidebar.'
|
|
232
|
+
: reason === 'shell-exited'
|
|
216
233
|
? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
|
|
217
234
|
+ 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
|
|
218
235
|
+ 'open the page again.'
|
|
@@ -267,7 +284,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
267
284
|
// A borrowed carrier can lose the process behind it, and this is the only notification that
|
|
268
285
|
// will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
|
|
269
286
|
// against a provider that was never installed.
|
|
270
|
-
host.onLost?.(reason => { restoreSelfHosted(host, reason) })
|
|
287
|
+
if (!(host instanceof SidebarOnlyHost)) host.onLost?.(reason => { restoreSelfHosted(host, reason) })
|
|
271
288
|
// Released AFTER the replacement is installed, so the surface is never without a provider.
|
|
272
289
|
if (previous !== undefined && previous !== host) {
|
|
273
290
|
try { previous.dispose?.() } catch { /* the replacement is already serving */ }
|
|
@@ -285,7 +302,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
285
302
|
// exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
|
|
286
303
|
// session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
|
|
287
304
|
try {
|
|
288
|
-
const fallback = new RemoteElectronViewHost(defaultHostMainPath())
|
|
305
|
+
const fallback = settings.get().browser.channel === 'sidebar' ? requiredSidebar() : new RemoteElectronViewHost(defaultHostMainPath())
|
|
289
306
|
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig))
|
|
290
307
|
adoptedCarrier = fallback
|
|
291
308
|
if (previous !== undefined && previous !== host) {
|
|
@@ -332,7 +349,11 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
332
349
|
// and a user who picked a browser that is not installed would never see the explanation
|
|
333
350
|
// written for exactly that case, because the sidebar would quietly replace it.
|
|
334
351
|
const explicitChoice: boolean = channel !== 'bundled' && channel !== 'auto' && channel !== 'sidebar'
|
|
335
|
-
if (channel
|
|
352
|
+
if (channel === 'sidebar') {
|
|
353
|
+
if (!(adoptedCarrier instanceof SidebarOnlyHost)) adopt(requiredSidebar(), 'using only the selected DSH sidebar', choice)
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
if (channel !== 'bundled') {
|
|
336
357
|
const detected = detectBrowser(channel)
|
|
337
358
|
if (detected === undefined) {
|
|
338
359
|
// `auto` promises to take whatever is available, so falling back is what it
|
|
@@ -355,7 +376,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
355
376
|
// `C:\Users\<user>\dsh-builtin-browser-host\` while its settings and history lived in
|
|
356
377
|
// `~/.dsh/dsh-builtin-browser-host/` — two half-profiles that never met, and a
|
|
357
378
|
// settings panel whose switches appeared not to apply.
|
|
358
|
-
const home =
|
|
379
|
+
const home = dshHome()
|
|
359
380
|
// Login state lives in the browser profile, so the cookies setting decides where
|
|
360
381
|
// that profile goes: a stable directory keeps the user signed in across restarts
|
|
361
382
|
// (the point of using their own browser), while turning persistence off gets a
|
|
@@ -388,9 +409,8 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
388
409
|
// An explicit choice was already adopted above; discovering the sidebar here would
|
|
389
410
|
// replace it, which is exactly what this guard prevents.
|
|
390
411
|
//
|
|
391
|
-
//
|
|
392
|
-
|
|
393
|
-
if (explicitChoice && channel !== 'sidebar') return
|
|
412
|
+
// Explicit sidebar selection was handled above by its reconnectable sidebar-only host.
|
|
413
|
+
if (explicitChoice) return
|
|
394
414
|
|
|
395
415
|
// The shell may not be up yet. `dsh web` starts before — or entirely without — the desktop app
|
|
396
416
|
// that hosts the bridge, and a one-shot discovery meant a bridge that appeared a second later
|
|
@@ -434,17 +454,6 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
434
454
|
)
|
|
435
455
|
return
|
|
436
456
|
}
|
|
437
|
-
// The user explicitly asked for the sidebar, so silence would leave them with a setting
|
|
438
|
-
// that did nothing and no way to tell why. This is reachable on `dsh web`, and on a desktop
|
|
439
|
-
// whose shell never published a bridge endpoint. An automatic attempt stays quiet (the
|
|
440
|
-
// self-hosted window is a fine outcome); an explicit request does not.
|
|
441
|
-
if (channel === 'sidebar') {
|
|
442
|
-
ctx.logger?.warn?.(
|
|
443
|
-
'dsh-builtin-browser: the sidebar browser was requested but no desktop bridge was found — '
|
|
444
|
-
+ 'this DSH has no desktop shell, or its bridge never started. Falling back to the bundled '
|
|
445
|
-
+ 'browser; set browser.channel to another value to silence this.',
|
|
446
|
-
)
|
|
447
|
-
}
|
|
448
457
|
})()
|
|
449
458
|
}
|
|
450
459
|
|
|
@@ -501,24 +510,23 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
501
510
|
let bridgeActionRunning = false
|
|
502
511
|
|
|
503
512
|
/**
|
|
504
|
-
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
* half-finished manual run leaves the shell in a state the user then has to diagnose — the
|
|
508
|
-
* packaged installer already handles the whole sequence unattended, and this hands it the one
|
|
509
|
-
* decision that is not its own: which action the user pressed.
|
|
510
|
-
* @param request - the incoming request (POST, JSON body `{action}`).
|
|
513
|
+
* Prepare external maintenance while Desktop remains open, or execute file maintenance from
|
|
514
|
+
* an independent local host after Desktop has exited.
|
|
515
|
+
* @param request - the incoming request (POST, JSON body `{action, prepare?}`).
|
|
511
516
|
* @param response - the response to write.
|
|
512
517
|
*/
|
|
513
518
|
async function handleBridgeAction(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
514
519
|
if (request.method !== 'POST') { replyJson(response, 405, { error: 'method-not-allowed' }); return }
|
|
515
|
-
//
|
|
520
|
+
// Both creating a local launcher and changing installation files require write admission.
|
|
516
521
|
if (!sameOrigin(request, true)) { replyJson(response, 403, { error: 'not-same-origin' }); return }
|
|
517
522
|
if (!isDirectLoopback(request)) { replyJson(response, 403, { error: 'local-request-required' }); return }
|
|
518
523
|
let action: unknown
|
|
524
|
+
let preparationOnly = false
|
|
519
525
|
try {
|
|
520
|
-
const
|
|
521
|
-
action =
|
|
526
|
+
const input = await readJsonBody<{ action?: unknown; prepare?: unknown }>(request)
|
|
527
|
+
action = input.action
|
|
528
|
+
if (input.prepare !== undefined && typeof input.prepare !== 'boolean') throw new Error('prepare must be a boolean')
|
|
529
|
+
preparationOnly = input.prepare === true
|
|
522
530
|
} catch (error) {
|
|
523
531
|
replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` })
|
|
524
532
|
return
|
|
@@ -537,10 +545,26 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
537
545
|
replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' })
|
|
538
546
|
return
|
|
539
547
|
}
|
|
548
|
+
const active = readAutomaticMaintenance()
|
|
549
|
+
if (!preparationOnly && active !== undefined && !['completed', 'failed', 'cancelled'].includes(active.phase)) {
|
|
550
|
+
replyJson(response, 409, { ok: false, error: 'an automatic bridge maintenance job is in progress' })
|
|
551
|
+
return
|
|
552
|
+
}
|
|
540
553
|
bridgeActionRunning = true
|
|
541
554
|
try {
|
|
542
|
-
|
|
543
|
-
|
|
555
|
+
if (preparationOnly) {
|
|
556
|
+
const result = await prepareBridgeMaintenance(action, root)
|
|
557
|
+
replyJson(response, 200, { ...result, action })
|
|
558
|
+
return
|
|
559
|
+
}
|
|
560
|
+
const result = await runWithManualBridgePreference(action, patch => settings.update(patch), () => runBridgeAction(action, root))
|
|
561
|
+
replyJson(response, 200, { ...result, action })
|
|
562
|
+
} catch (error) {
|
|
563
|
+
if (preparationOnly) {
|
|
564
|
+
replyJson(response, 500, { ok: false, error: `could not prepare bridge maintenance: ${String(error)}` })
|
|
565
|
+
return
|
|
566
|
+
}
|
|
567
|
+
replyJson(response, 500, { ok: false, error: String(error instanceof Error ? error.message : error) })
|
|
544
568
|
} finally {
|
|
545
569
|
bridgeActionRunning = false
|
|
546
570
|
}
|
|
@@ -553,13 +577,29 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
553
577
|
if (typeof injectStatus !== 'function') return
|
|
554
578
|
try {
|
|
555
579
|
injectStatus(['webServer'], (host) => {
|
|
580
|
+
const automaticMaintenance = createAutomaticMaintenanceHandler({
|
|
581
|
+
supported: () => process.platform === 'win32',
|
|
582
|
+
busy: () => bridgeActionRunning,
|
|
583
|
+
read: () => readAutomaticMaintenance(),
|
|
584
|
+
commit: async id => { await commitAutomaticMaintenance(id) },
|
|
585
|
+
start: async (action, options) => {
|
|
586
|
+
const root = findDesktopInstall()
|
|
587
|
+
if (root === undefined) throw new Error('no verified DSH Desktop installation was found')
|
|
588
|
+
return await runWithManualBridgePreference(action, patch => settings.update(patch),
|
|
589
|
+
async () => await startAutomaticMaintenance(action, root, options))
|
|
590
|
+
},
|
|
591
|
+
})
|
|
592
|
+
host.effect(() => host.webServer.register({
|
|
593
|
+
kind: 'exact', path: AUTOMATIC_MAINTENANCE_ROUTE,
|
|
594
|
+
handler: authenticated(ctx, automaticMaintenance),
|
|
595
|
+
}, 'dsh-builtin-browser: explicit automatic bridge maintenance'))
|
|
556
596
|
host.effect(() => host.webServer.register({
|
|
557
597
|
kind: 'exact',
|
|
558
598
|
path: BRIDGE_STATUS_ROUTE,
|
|
559
599
|
handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
|
|
560
600
|
}, 'dsh-builtin-browser: bridge status'))
|
|
561
|
-
// The
|
|
562
|
-
//
|
|
601
|
+
// The panel prepares a launcher without changing the running Desktop. Direct local
|
|
602
|
+
// maintenance remains available once Desktop has exited.
|
|
563
603
|
host.effect(() => host.webServer.register({
|
|
564
604
|
kind: 'exact',
|
|
565
605
|
path: BRIDGE_ACTION_ROUTE,
|
|
@@ -573,6 +613,9 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
573
613
|
|
|
574
614
|
installSettingsRoute(ctx, settings, () => { chooseCarrier() })
|
|
575
615
|
|
|
616
|
+
// Bridge maintenance is explicit and requires DSH Desktop to be closed. Loading a provider
|
|
617
|
+
// never starts an installer, including with an older settings file's bridge.autoInstall=true.
|
|
618
|
+
|
|
576
619
|
/**
|
|
577
620
|
* Expose readiness — "can the browser serve a call right now" — for the settings panel.
|
|
578
621
|
*
|
|
@@ -595,6 +638,8 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
595
638
|
const deps = {
|
|
596
639
|
report: () => readRuntimeStatus({
|
|
597
640
|
channel: () => settings.get().browser.channel,
|
|
641
|
+
selectedCarrier: () => adoptedCarrier instanceof DesktopBridgeViewHost || adoptedCarrier instanceof SidebarOnlyHost ? 'sidebar'
|
|
642
|
+
: adoptedCarrier instanceof SystemBrowserViewHost ? 'system' : 'bundled',
|
|
598
643
|
hasBinary: hasElectronRuntime,
|
|
599
644
|
provision: provisionSnapshot,
|
|
600
645
|
bridge: () => {
|
|
@@ -662,7 +707,7 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
662
707
|
lastChannel = channel
|
|
663
708
|
ctx.logger?.info?.(`dsh-builtin-browser: settings changed on disk, re-choosing the carrier for channel "${channel}"`)
|
|
664
709
|
chooseCarrier()
|
|
665
|
-
},
|
|
710
|
+
}, 5_000)
|
|
666
711
|
// Unref-ed so a poll never holds the process open.
|
|
667
712
|
timer.unref?.()
|
|
668
713
|
ctx.effect(() => () => { clearInterval(timer) }, "dsh-builtin-browser: settings file watch")
|
|
@@ -795,11 +840,10 @@ async function handleSettingsRequest(
|
|
|
795
840
|
onChannelChange?: () => void,
|
|
796
841
|
): Promise<void> {
|
|
797
842
|
const json = (status: number, body: unknown): void => {
|
|
798
|
-
response.
|
|
843
|
+
writeJsonText(response, status, JSON.stringify(body), {
|
|
799
844
|
'content-type': 'application/json; charset=utf-8',
|
|
800
845
|
'cache-control': 'no-store',
|
|
801
846
|
})
|
|
802
|
-
response.end(JSON.stringify(body))
|
|
803
847
|
}
|
|
804
848
|
const method = request.method ?? 'GET'
|
|
805
849
|
if (!sameOrigin(request, method !== 'GET')) {
|
|
@@ -816,8 +860,8 @@ async function handleSettingsRequest(
|
|
|
816
860
|
return
|
|
817
861
|
}
|
|
818
862
|
try {
|
|
819
|
-
const
|
|
820
|
-
const patch: unknown =
|
|
863
|
+
const text = await readTextBody(request)
|
|
864
|
+
const patch: unknown = text.trim() === '' ? {} : JSON.parse(text)
|
|
821
865
|
const before = settings.get().browser.channel
|
|
822
866
|
const updated = settings.update(patch)
|
|
823
867
|
// A changed `browser.channel` is a request to switch carriers, not just a value to store. The
|
|
@@ -836,25 +880,3 @@ async function handleSettingsRequest(
|
|
|
836
880
|
}
|
|
837
881
|
}
|
|
838
882
|
|
|
839
|
-
/**
|
|
840
|
-
* Read a request body with a hard cap (the settings patch is tiny, and an
|
|
841
|
-
* unbounded read would let any same-origin caller exhaust memory).
|
|
842
|
-
* @param request - the incoming request.
|
|
843
|
-
* @param limit - maximum accepted characters.
|
|
844
|
-
* @returns the body text.
|
|
845
|
-
*/
|
|
846
|
-
function readBody(request: IncomingMessage, limit = 64 * 1024): Promise<string> {
|
|
847
|
-
return new Promise<string>((resolve, reject) => {
|
|
848
|
-
let text = ''
|
|
849
|
-
request.setEncoding('utf8')
|
|
850
|
-
request.on('data', chunk => {
|
|
851
|
-
text += String(chunk)
|
|
852
|
-
if (text.length > limit) {
|
|
853
|
-
request.destroy()
|
|
854
|
-
reject(new Error('settings patch too large'))
|
|
855
|
-
}
|
|
856
|
-
})
|
|
857
|
-
request.on('end', () => resolve(text))
|
|
858
|
-
request.on('error', reject)
|
|
859
|
-
})
|
|
860
|
-
}
|
|
@@ -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
|
|
14
|
-
* abandoned. The age check is what keeps the sweep away from a profile an orphaned
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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
|
|
|
22
23
|
/** The marker file, named once because both the claim and the sweep read it. */
|
|
23
24
|
const OWNER_FILE = '.dsh-ephemeral-owner'
|
|
@@ -29,6 +30,12 @@ const OWNER_FILE = '.dsh-ephemeral-owner'
|
|
|
29
30
|
*/
|
|
30
31
|
const ABANDONED_AFTER_MS = 60 * 60 * 1000
|
|
31
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Ceiling on how much of a profile tree one sweep inspects. A tree we cannot fully inspect is
|
|
35
|
+
* not proven abandoned, so it is kept; this only bounds the cost of saying so.
|
|
36
|
+
*/
|
|
37
|
+
const MAX_SWEEP_ENTRIES = 20_000
|
|
38
|
+
|
|
32
39
|
/** Test seams; production passes neither. */
|
|
33
40
|
export interface SweepOptions {
|
|
34
41
|
/** The clock, for the age check. */
|
|
@@ -37,23 +44,6 @@ export interface SweepOptions {
|
|
|
37
44
|
readonly alive?: (pid: number) => boolean
|
|
38
45
|
}
|
|
39
46
|
|
|
40
|
-
/**
|
|
41
|
-
* Whether a process with this pid exists.
|
|
42
|
-
*
|
|
43
|
-
* A signal of 0 performs the permission and existence checks without delivering anything.
|
|
44
|
-
* EPERM is a live process owned by someone else — alive, not gone.
|
|
45
|
-
* @param pid - the pid to test.
|
|
46
|
-
* @returns true when the process exists.
|
|
47
|
-
*/
|
|
48
|
-
function processAlive(pid: number): boolean {
|
|
49
|
-
try {
|
|
50
|
-
process.kill(pid, 0)
|
|
51
|
-
return true
|
|
52
|
-
} catch (error) {
|
|
53
|
-
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
47
|
/**
|
|
58
48
|
* The directory name an ephemeral profile for `kind` gets, before it is claimed.
|
|
59
49
|
*
|
|
@@ -104,6 +94,51 @@ function readOwner(dir: string): number | undefined {
|
|
|
104
94
|
}
|
|
105
95
|
}
|
|
106
96
|
|
|
97
|
+
/**
|
|
98
|
+
* The most recent write anywhere in a profile tree.
|
|
99
|
+
*
|
|
100
|
+
* A Chromium process writes nested files (`Default/Network/Cookies`, `Default/History`, ...).
|
|
101
|
+
* Writing a file does NOT refresh the mtime of the parent directory, so a quiet ROOT timestamp
|
|
102
|
+
* cannot prove the browser has exited — exactly the case where a killed DSH leaves a live child
|
|
103
|
+
* behind. Inspect the tree instead of just its root.
|
|
104
|
+
*
|
|
105
|
+
* Anything that cannot be inspected is reported as "written now", so the caller keeps the
|
|
106
|
+
* directory. When the evidence is incomplete, leaving a profile behind is the only safe outcome.
|
|
107
|
+
* Symbolic links are never followed, and an entry budget bounds the work.
|
|
108
|
+
* @param dir - the profile directory.
|
|
109
|
+
* @param now - the clock value used as the conservative "active" answer.
|
|
110
|
+
* @returns the newest mtime in the tree, or `-Infinity` when the tree holds nothing but our marker.
|
|
111
|
+
*/
|
|
112
|
+
function latestWriteMs(dir: string, now: number): number {
|
|
113
|
+
let latest = Number.NEGATIVE_INFINITY
|
|
114
|
+
let budget = MAX_SWEEP_ENTRIES
|
|
115
|
+
const pending = [dir]
|
|
116
|
+
while (pending.length > 0) {
|
|
117
|
+
const current = pending.pop() as string
|
|
118
|
+
let entries
|
|
119
|
+
try {
|
|
120
|
+
entries = readdirSync(current, { withFileTypes: true })
|
|
121
|
+
} catch {
|
|
122
|
+
return now
|
|
123
|
+
}
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (budget-- <= 0) return now
|
|
126
|
+
// Our owner marker is written once at claim time; it is not browser activity.
|
|
127
|
+
if (current === dir && entry.name === OWNER_FILE) continue
|
|
128
|
+
const path = join(current, entry.name)
|
|
129
|
+
let stat
|
|
130
|
+
try {
|
|
131
|
+
stat = lstatSync(path)
|
|
132
|
+
} catch {
|
|
133
|
+
return now
|
|
134
|
+
}
|
|
135
|
+
if (stat.mtimeMs > latest) latest = stat.mtimeMs
|
|
136
|
+
if (stat.isDirectory() && !stat.isSymbolicLink()) pending.push(path)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return latest
|
|
140
|
+
}
|
|
141
|
+
|
|
107
142
|
/**
|
|
108
143
|
* Delete the ephemeral profiles under `root` that belong to processes which are gone.
|
|
109
144
|
*
|
|
@@ -116,7 +151,7 @@ function readOwner(dir: string): number | undefined {
|
|
|
116
151
|
*/
|
|
117
152
|
export function sweepAbandonedEphemeralProfiles(root: string, kind: string, options: SweepOptions = {}): string[] {
|
|
118
153
|
const now = options.now ?? Date.now()
|
|
119
|
-
const alive = options.alive ??
|
|
154
|
+
const alive = options.alive ?? pidAlive
|
|
120
155
|
const prefix = `${kind}-profile-ephemeral-`
|
|
121
156
|
const removed: string[] = []
|
|
122
157
|
let names: string[]
|
|
@@ -129,14 +164,16 @@ export function sweepAbandonedEphemeralProfiles(root: string, kind: string, opti
|
|
|
129
164
|
for (const name of names) {
|
|
130
165
|
if (!name.startsWith(prefix)) continue
|
|
131
166
|
const dir = join(root, name)
|
|
132
|
-
let
|
|
167
|
+
let rootMtime: number
|
|
133
168
|
try {
|
|
134
|
-
|
|
169
|
+
rootMtime = statSync(dir).mtimeMs
|
|
135
170
|
} catch {
|
|
136
171
|
continue
|
|
137
172
|
}
|
|
138
|
-
// Recent writes mean a browser is still working in there. A killed DSH
|
|
139
|
-
// Chromium child running, and
|
|
173
|
+
// Recent writes ANYWHERE in the tree mean a browser is still working in there. A killed DSH
|
|
174
|
+
// can leave its Chromium child running, and a child writing Default/Network/Cookies does not
|
|
175
|
+
// refresh the root directory's mtime. Judging the root alone deleted live profiles.
|
|
176
|
+
const ageMs = now - Math.max(rootMtime, latestWriteMs(dir, now))
|
|
140
177
|
if (ageMs < ABANDONED_AFTER_MS) continue
|
|
141
178
|
const owner = readOwner(dir)
|
|
142
179
|
if (owner !== undefined && alive(owner)) continue
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
17
|
-
import { homedir } from 'node:os'
|
|
18
17
|
import { dirname, join } from 'node:path'
|
|
18
|
+
import { dshHome } from './paths.js'
|
|
19
19
|
import type { VisitedPage } from '../browser/types.js'
|
|
20
20
|
import { writeFileAtomic } from './settings-store.js'
|
|
21
21
|
|
|
@@ -42,7 +42,7 @@ const PRUNE_SLACK = 500
|
|
|
42
42
|
* @returns the history file path.
|
|
43
43
|
*/
|
|
44
44
|
export function visitedHistoryPath(): string {
|
|
45
|
-
const home =
|
|
45
|
+
const home = dshHome()
|
|
46
46
|
return join(home, 'dsh-builtin-browser-host', 'history.jsonl')
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -33,6 +33,7 @@ import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.js'
|
|
|
33
33
|
import { createRpcLineReader } from './rpc-input.js'
|
|
34
34
|
import { tmpdir } from 'node:os'
|
|
35
35
|
import { join } from 'node:path'
|
|
36
|
+
import { withTimeoutShared } from './timing.js'
|
|
36
37
|
|
|
37
38
|
// Report the binary actually running this child, even when ELECTRON_PATH
|
|
38
39
|
// intentionally selects a different version from the plugin's dependency.
|
|
@@ -293,15 +294,7 @@ function ensureToolbarFiles(): void {
|
|
|
293
294
|
* explicit error instead of a command that never settles.
|
|
294
295
|
*/
|
|
295
296
|
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
|
|
296
|
-
return
|
|
297
|
-
const timer = setTimeout(() => {
|
|
298
|
-
reject(new Error(`${label} timed out after ${ms}ms`))
|
|
299
|
-
}, ms)
|
|
300
|
-
promise.then(
|
|
301
|
-
(value) => { clearTimeout(timer); resolve(value) },
|
|
302
|
-
(error) => { clearTimeout(timer); reject(error) },
|
|
303
|
-
)
|
|
304
|
-
})
|
|
297
|
+
return withTimeoutShared(promise, ms, () => new Error(`${label} timed out after ${ms}ms`))
|
|
305
298
|
}
|
|
306
299
|
|
|
307
300
|
/**
|
|
@@ -500,7 +493,9 @@ function wireFocusRouting(win: HostWindow, view: WebContentsView, focusKey: stri
|
|
|
500
493
|
view.webContents.on('input-event', (_event, input) => {
|
|
501
494
|
if (input.type !== 'mouseDown') return
|
|
502
495
|
win.lastFocusedViewId = focusKey
|
|
503
|
-
|
|
496
|
+
if (win.window.isFocused()) {
|
|
497
|
+
try { view.webContents.focus() } catch { /* destroyed */ }
|
|
498
|
+
}
|
|
504
499
|
})
|
|
505
500
|
}
|
|
506
501
|
|
|
@@ -620,31 +615,24 @@ function revealViewInWindow(win: HostWindow, viewId: string, label?: string): vo
|
|
|
620
615
|
* @param viewId - the view to present.
|
|
621
616
|
* @param label - session/task label, when known, for the window title.
|
|
622
617
|
* @param quiet - `ui.quiet`: present without taking the screen over.
|
|
623
|
-
* @param
|
|
624
|
-
*
|
|
625
|
-
* stays minimized because restoring it can activate it.
|
|
618
|
+
* @param _needSurface - pre-input barrier flag retained by the RPC protocol. Quiet presentation
|
|
619
|
+
* opens a new visible window without activation and preserves an existing foreground page.
|
|
626
620
|
*/
|
|
627
|
-
function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false,
|
|
621
|
+
function showViewInWindow(win: HostWindow, viewId: string, label?: string, quiet = false, _needSurface = false): void {
|
|
628
622
|
if (quiet) {
|
|
629
|
-
if (win.window.isMinimized())
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
if (win.window.isVisible() && win.window.getOpacity() > 0) {
|
|
634
|
-
if (win.visibleViewId !== viewId) {
|
|
635
|
-
if (needSurface) throw new Error('quiet mode will not replace a visible browser tab; select the target tab manually to send input')
|
|
636
|
-
return
|
|
637
|
-
}
|
|
638
|
-
revealViewInWindow(win, viewId, label)
|
|
639
|
-
return
|
|
640
|
-
}
|
|
623
|
+
if (win.window.isMinimized()) return
|
|
624
|
+
// Preserve the page the operator is actively reading. Other views remain addressable by
|
|
625
|
+
// their own CDP session, without switching the foreground window's selected page.
|
|
626
|
+
if (win.window.isFocused() && win.visibleViewId !== viewId) return
|
|
641
627
|
revealViewInWindow(win, viewId, label)
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
if (win.window.getOpacity()
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
628
|
+
// Quiet means a normal usable window without activation, including on the first open.
|
|
629
|
+
// An invisible surface made the browser look broken even after navigation succeeded.
|
|
630
|
+
if (win.window.getOpacity() === 0) {
|
|
631
|
+
win.window.setOpacity(1)
|
|
632
|
+
win.window.setSkipTaskbar(false)
|
|
633
|
+
win.window.setFocusable(true)
|
|
634
|
+
}
|
|
635
|
+
if (!win.window.isVisible()) win.window.showInactive()
|
|
648
636
|
return
|
|
649
637
|
}
|
|
650
638
|
revealViewInWindow(win, viewId, label)
|
|
@@ -837,10 +825,9 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
|
|
|
837
825
|
// and `document.hasFocus()` inside the page even read true.
|
|
838
826
|
const contents = entry.webContentsView.webContents
|
|
839
827
|
const hadWebFocus = contents.isFocused()
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
if (msg.quiet !== true || !hadWebFocus) contents.focus()
|
|
828
|
+
// Electron webContents.focus() can activate its BrowserWindow. CDP input uses the
|
|
829
|
+
// target page's DOM focus and does not require that operating-system activation.
|
|
830
|
+
if (msg.quiet !== true) contents.focus()
|
|
844
831
|
// Focus lands asynchronously, and a key dispatched in the same turn as
|
|
845
832
|
// the request is still dropped, so hold the reply until the renderer can
|
|
846
833
|
// take input. Only on the call where focus actually had to move.
|
|
@@ -0,0 +1,42 @@
|
|
|
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
|
+
/**
|
|
10
|
+
* Read a body as UTF-8 text. Chunks are collected as Buffers and decoded once: setting an
|
|
11
|
+
* encoding on the stream and concatenating `String(chunk)` corrupts a multi-byte character that
|
|
12
|
+
* happens to be split across two TCP chunks.
|
|
13
|
+
* @param request - the incoming request.
|
|
14
|
+
* @param limit - maximum accepted bytes.
|
|
15
|
+
* @returns the body text.
|
|
16
|
+
*/
|
|
17
|
+
export async function readTextBody(request: IncomingMessage, limit = 64 * 1024): Promise<string> {
|
|
18
|
+
const chunks: Buffer[] = []
|
|
19
|
+
let size = 0
|
|
20
|
+
for await (const chunk of request) {
|
|
21
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
22
|
+
size += buffer.length
|
|
23
|
+
if (size > limit) {
|
|
24
|
+
request.destroy()
|
|
25
|
+
throw new Error(`request body exceeds ${limit} bytes`)
|
|
26
|
+
}
|
|
27
|
+
chunks.push(buffer)
|
|
28
|
+
}
|
|
29
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Read and parse a JSON body. An empty body is an empty object, matching the settings route's
|
|
34
|
+
* long-standing behaviour.
|
|
35
|
+
* @param request - the incoming request.
|
|
36
|
+
* @param limit - maximum accepted bytes.
|
|
37
|
+
* @returns the parsed value.
|
|
38
|
+
*/
|
|
39
|
+
export async function readJsonBody<T>(request: IncomingMessage, limit = 64 * 1024): Promise<T> {
|
|
40
|
+
const text = await readTextBody(request, limit)
|
|
41
|
+
return JSON.parse(text === '' ? '{}' : text) as T
|
|
42
|
+
}
|