dsh-builtin-browser 0.4.14 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/README.en.md +17 -9
- package/README.md +48 -10
- package/client.js +410 -6
- package/desktop-bridge/install-and-start.cmd +36 -0
- package/desktop-bridge/install.mjs +166 -3
- package/desktop-bridge/plugin-browser-bridge.js +133 -11
- package/docs/development.md +19 -0
- package/docs/limitations.md +7 -3
- package/docs/user-guide.md +46 -18
- package/lib/browser/runtime.d.ts +21 -2
- package/lib/browser/runtime.js +30 -0
- package/lib/browser/types.d.ts +54 -0
- package/lib/browser-electron/bridge-status.d.ts +41 -0
- package/lib/browser-electron/bridge-status.js +164 -0
- package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
- package/lib/browser-electron/desktop-bridge-host.js +75 -44
- package/lib/browser-electron/entry.js +130 -11
- package/lib/browser-electron/file-write.d.ts +2 -0
- package/lib/browser-electron/file-write.js +39 -0
- package/lib/browser-electron/history-store.d.ts +8 -19
- package/lib/browser-electron/history-store.js +37 -58
- package/lib/browser-electron/host-main.js +15 -22
- package/lib/browser-electron/preview-route.d.ts +89 -0
- package/lib/browser-electron/preview-route.js +172 -0
- package/lib/browser-electron/provider.d.ts +62 -3
- package/lib/browser-electron/provider.js +246 -12
- package/lib/browser-electron/remote-host.js +5 -1
- package/lib/browser-electron/rpc-input.d.ts +4 -0
- package/lib/browser-electron/rpc-input.js +11 -0
- package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
- package/lib/browser-electron/runtime-diagnostics.js +29 -0
- package/lib/browser-electron/settings-store.d.ts +15 -2
- package/lib/browser-electron/settings-store.js +25 -5
- package/lib/browser-electron/system-browser.d.ts +18 -0
- package/lib/browser-electron/system-browser.js +158 -37
- package/lib/tool-browser/index.js +10 -1
- package/package.json +8 -3
- package/scripts/install-electron.mjs +66 -0
- package/scripts/verify-preview-route.mjs +150 -0
- package/src/browser/runtime.ts +36 -0
- package/src/browser/types.ts +55 -0
- package/src/browser-electron/bridge-status.ts +180 -0
- package/src/browser-electron/desktop-bridge-host.ts +75 -41
- package/src/browser-electron/entry.ts +119 -11
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/history-store.ts +36 -57
- package/src/browser-electron/host-main.ts +16 -18
- package/src/browser-electron/preview-route.ts +222 -0
- package/src/browser-electron/provider.ts +286 -16
- package/src/browser-electron/remote-host.ts +5 -1
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/settings-store.ts +37 -5
- package/src/browser-electron/system-browser.ts +149 -32
- package/src/tool-browser/index.ts +13 -1
|
@@ -21,6 +21,7 @@ import { randomUUID } from 'node:crypto'
|
|
|
21
21
|
import { existsSync, mkdirSync, renameSync } from 'node:fs'
|
|
22
22
|
import { homedir } from 'node:os'
|
|
23
23
|
import { dirname, join } from 'node:path'
|
|
24
|
+
import { setTimeout as wait } from 'node:timers/promises'
|
|
24
25
|
import { defaultHostMainPath, RemoteElectronViewHost } from './remote-host.js'
|
|
25
26
|
import { DesktopBridgeViewHost } from './desktop-bridge-host.js'
|
|
26
27
|
import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.js'
|
|
@@ -28,6 +29,7 @@ import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralPro
|
|
|
28
29
|
import { MissingSystemBrowserHost } from './missing-system-browser.js'
|
|
29
30
|
import { SettingsStore } from './settings-store.js'
|
|
30
31
|
import { sameOrigin } from './settings-route.js'
|
|
32
|
+
import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js'
|
|
31
33
|
|
|
32
34
|
export {
|
|
33
35
|
ELECTRON_BROWSER_PROVIDER_ID,
|
|
@@ -152,12 +154,18 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
152
154
|
// otherwise would leave a stray window behind.
|
|
153
155
|
const selfHosted = new RemoteElectronViewHost(defaultHostMainPath())
|
|
154
156
|
let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(selfHosted, providerConfig))
|
|
155
|
-
let
|
|
157
|
+
let disposed = false
|
|
158
|
+
let carrierChoice = 0
|
|
159
|
+
let discovery: AbortController | undefined
|
|
156
160
|
/** The carrier an `adopt` installed, so a later choice can release it. */
|
|
157
161
|
let adoptedCarrier: ElectronBrowserViewHost | undefined
|
|
158
162
|
|
|
159
163
|
ctx.effect(() => () => {
|
|
164
|
+
disposed = true
|
|
165
|
+
carrierChoice += 1
|
|
166
|
+
discovery?.abort()
|
|
160
167
|
unregister()
|
|
168
|
+
adoptedCarrier?.dispose?.()
|
|
161
169
|
selfHosted.dispose()
|
|
162
170
|
})
|
|
163
171
|
|
|
@@ -177,10 +185,13 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
177
185
|
* @param reason - which failure this was; see {@link CarrierLossReason}.
|
|
178
186
|
*/
|
|
179
187
|
const restoreSelfHosted = (adopted: ElectronBrowserViewHost, reason: CarrierLossReason): void => {
|
|
188
|
+
// A replaced carrier may finish an outstanding request after the new choice is installed.
|
|
189
|
+
if (disposed || adoptedCarrier !== adopted) return
|
|
180
190
|
try {
|
|
181
191
|
const restored = new RemoteElectronViewHost(defaultHostMainPath())
|
|
182
192
|
unregister()
|
|
183
193
|
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig))
|
|
194
|
+
adoptedCarrier = restored
|
|
184
195
|
ctx.logger?.warn?.(
|
|
185
196
|
reason === 'shell-exited'
|
|
186
197
|
? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
|
|
@@ -218,23 +229,26 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
218
229
|
* @param host - the carrier to adopt.
|
|
219
230
|
* @param note - a one-line description for the log.
|
|
220
231
|
*/
|
|
221
|
-
const adopt = (host: ElectronBrowserViewHost, note: string): void => {
|
|
232
|
+
const adopt = (host: ElectronBrowserViewHost, note: string, choice = carrierChoice): void => {
|
|
233
|
+
if (disposed || choice !== carrierChoice) {
|
|
234
|
+
try { host.dispose?.() } catch { /* a stale result must not escape its retry */ }
|
|
235
|
+
return
|
|
236
|
+
}
|
|
222
237
|
// This guard used to make the FIRST choice final, disposing anything that arrived later. That
|
|
223
238
|
// is right against two carriers racing in, and exactly wrong for a user changing the setting:
|
|
224
239
|
// `chooseCarrier` runs again on purpose, and a refusal here is indistinguishable from the
|
|
225
240
|
// write having done nothing. The previous carrier is now released by the replacement instead.
|
|
226
|
-
|
|
241
|
+
const previous = adoptedCarrier
|
|
227
242
|
try {
|
|
228
243
|
unregister()
|
|
229
244
|
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(host, providerConfig))
|
|
230
245
|
selfHosted.dispose()
|
|
246
|
+
adoptedCarrier = host
|
|
231
247
|
ctx.logger?.info?.(`dsh-builtin-browser: ${note}`)
|
|
232
248
|
// A borrowed carrier can lose the process behind it, and this is the only notification that
|
|
233
249
|
// will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
|
|
234
250
|
// against a provider that was never installed.
|
|
235
251
|
host.onLost?.(reason => { restoreSelfHosted(host, reason) })
|
|
236
|
-
const previous = adoptedCarrier
|
|
237
|
-
adoptedCarrier = host
|
|
238
252
|
// Released AFTER the replacement is installed, so the surface is never without a provider.
|
|
239
253
|
if (previous !== undefined && previous !== host) {
|
|
240
254
|
try { previous.dispose?.() } catch { /* the replacement is already serving */ }
|
|
@@ -252,8 +266,12 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
252
266
|
// exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
|
|
253
267
|
// session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
|
|
254
268
|
try {
|
|
255
|
-
|
|
256
|
-
|
|
269
|
+
const fallback = new RemoteElectronViewHost(defaultHostMainPath())
|
|
270
|
+
unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig))
|
|
271
|
+
adoptedCarrier = fallback
|
|
272
|
+
if (previous !== undefined && previous !== host) {
|
|
273
|
+
try { previous.dispose?.() } catch { /* fallback is already serving */ }
|
|
274
|
+
}
|
|
257
275
|
ctx.logger?.warn?.(`dsh-builtin-browser: could not adopt ${note} (${String(error)})`)
|
|
258
276
|
} catch (fallbackError) {
|
|
259
277
|
ctx.logger?.warn?.(
|
|
@@ -274,6 +292,12 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
274
292
|
* exactly what a second call does.
|
|
275
293
|
*/
|
|
276
294
|
const chooseCarrier = (): void => {
|
|
295
|
+
if (disposed) return
|
|
296
|
+
const choice = ++carrierChoice
|
|
297
|
+
discovery?.abort()
|
|
298
|
+
const controller = new AbortController()
|
|
299
|
+
discovery = controller
|
|
300
|
+
const { signal } = controller
|
|
277
301
|
// A browser the user explicitly asked for outranks every automatic choice: the
|
|
278
302
|
// whole point of the setting is that they know which browser they want. It is
|
|
279
303
|
// launched with a plugin-owned profile, so their own windows are untouched.
|
|
@@ -298,6 +322,9 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
298
322
|
// confusing error about Electron later on. Report it instead.
|
|
299
323
|
if (channel === 'auto') {
|
|
300
324
|
ctx.logger?.warn?.('dsh-builtin-browser: no installed browser was found; using the bundled browser')
|
|
325
|
+
if (adoptedCarrier !== undefined) {
|
|
326
|
+
adopt(new RemoteElectronViewHost(defaultHostMainPath()), 'using the bundled browser', choice)
|
|
327
|
+
}
|
|
301
328
|
} else {
|
|
302
329
|
adopt(new MissingSystemBrowserHost(channel, searchSummary(channel)),
|
|
303
330
|
`the selected ${channel} is not installed — commands will explain how to fix it`)
|
|
@@ -333,6 +360,10 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
333
360
|
undefined, settings.get().browser.headless),
|
|
334
361
|
`will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`)
|
|
335
362
|
}
|
|
363
|
+
} else if (adoptedCarrier !== undefined) {
|
|
364
|
+
// The original self-hosted carrier was disposed by the first adoption. Switching back
|
|
365
|
+
// must install a new one, even when no sidebar is found during the discovery below.
|
|
366
|
+
adopt(new RemoteElectronViewHost(defaultHostMainPath()), 'using the bundled browser', choice)
|
|
336
367
|
}
|
|
337
368
|
|
|
338
369
|
// An explicit choice was already adopted above; discovering the sidebar here would
|
|
@@ -347,19 +378,26 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
347
378
|
// was never adopted for the rest of the process's life. Retry a handful of times over roughly
|
|
348
379
|
// half a minute, then stop: this is a convenience, not a promise, and the session the user is
|
|
349
380
|
// already driving in the self-hosted window is not worth replacing minutes into their work.
|
|
350
|
-
//
|
|
351
|
-
//
|
|
381
|
+
// Each attempt belongs to this choice. A later settings write or teardown cancels its waits,
|
|
382
|
+
// and an endpoint returned by an already-running discovery is disposed instead of installed.
|
|
352
383
|
void (async () => {
|
|
353
384
|
for (const delay of [0, 2_000, 5_000, 15_000]) {
|
|
354
|
-
if (delay > 0)
|
|
385
|
+
if (delay > 0) {
|
|
386
|
+
try { await wait(delay, undefined, { signal }) } catch { return }
|
|
387
|
+
}
|
|
388
|
+
if (signal.aborted || disposed) return
|
|
355
389
|
let sidebar: Awaited<ReturnType<typeof DesktopBridgeViewHost.discover>>
|
|
356
390
|
try {
|
|
357
391
|
sidebar = await DesktopBridgeViewHost.discover(sessionId)
|
|
358
392
|
} catch {
|
|
359
393
|
sidebar = undefined // discovery is documented not to throw; never let it stop the retries
|
|
360
394
|
}
|
|
395
|
+
if (signal.aborted || disposed) {
|
|
396
|
+
try { sidebar?.dispose?.() } catch { /* the choice no longer owns this result */ }
|
|
397
|
+
return
|
|
398
|
+
}
|
|
361
399
|
if (sidebar === undefined) continue
|
|
362
|
-
adopt(sidebar, 'driving the desktop sidebar browser')
|
|
400
|
+
adopt(sidebar, 'driving the desktop sidebar browser', choice)
|
|
363
401
|
return
|
|
364
402
|
}
|
|
365
403
|
// A bridge exists but its sidebar panel is an iframe. Saying nothing here would leave the user
|
|
@@ -396,7 +434,70 @@ export function apply(ctx: Context & { browser: BrowserRuntime }, config: Config
|
|
|
396
434
|
// Wired AFTER the chooser exists, because the handler re-runs it: a settings write that changes
|
|
397
435
|
// `browser.channel` is a request to switch carriers, and answering `ok` without switching is the
|
|
398
436
|
// one thing a caller cannot tell apart from a write that worked.
|
|
437
|
+
/**
|
|
438
|
+
* Expose the live-view frame endpoint on the host's web server (issue #34).
|
|
439
|
+
*
|
|
440
|
+
* Registered exactly like the settings route and skipped the same way when a surface has no web
|
|
441
|
+
* server: a CLI session simply has no viewer, which is not a plugin-startup failure. The endpoint
|
|
442
|
+
* is inert until the host turns `remoteView.enabled` on, and it refuses a request whose session the
|
|
443
|
+
* plugin never handed out.
|
|
444
|
+
* @param ctx - the plugin context.
|
|
445
|
+
* @param settings - the settings document, for the share switch.
|
|
446
|
+
*/
|
|
447
|
+
function installPreviewRoute(ctx: Context, settings: SettingsStore): void {
|
|
448
|
+
const injectPreview = (ctx as unknown as {
|
|
449
|
+
inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
|
|
450
|
+
}).inject
|
|
451
|
+
if (typeof injectPreview !== 'function') return
|
|
452
|
+
try {
|
|
453
|
+
injectPreview(['webServer', 'browser'], (host) => {
|
|
454
|
+
const browser = (ctx as unknown as { browser?: PreviewBrowser }).browser
|
|
455
|
+
if (browser === undefined) return
|
|
456
|
+
host.effect(() => host.webServer.register({
|
|
457
|
+
kind: 'exact',
|
|
458
|
+
path: PREVIEW_ROUTE,
|
|
459
|
+
handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
|
|
460
|
+
}, 'dsh-builtin-browser: live view frame'))
|
|
461
|
+
// The list the panel needs before it can build a frame URL at all: session ids only.
|
|
462
|
+
host.effect(() => host.webServer.register({
|
|
463
|
+
kind: 'exact',
|
|
464
|
+
path: PREVIEW_SESSIONS_ROUTE,
|
|
465
|
+
handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
|
|
466
|
+
}, 'dsh-builtin-browser: live view sessions')) })
|
|
467
|
+
} catch {
|
|
468
|
+
// No web server on this surface: watching is simply unavailable, and nothing else changes.
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Expose the bridge's install state on the host's web server, for the settings panel.
|
|
474
|
+
*
|
|
475
|
+
* Separate from the live-view routes because it needs no browser service: it reads the install
|
|
476
|
+
* tree, which is on disk and independent of any carrier. A surface without a web server skips it,
|
|
477
|
+
* exactly like the other two.
|
|
478
|
+
* @param ctx - the plugin context.
|
|
479
|
+
*/
|
|
480
|
+
function installBridgeStatusRoute(ctx: Context): void {
|
|
481
|
+
const injectStatus = (ctx as unknown as {
|
|
482
|
+
inject?: (deps: readonly string[], callback: (host: WebServerHost) => void) => void
|
|
483
|
+
}).inject
|
|
484
|
+
if (typeof injectStatus !== 'function') return
|
|
485
|
+
try {
|
|
486
|
+
injectStatus(['webServer'], (host) => {
|
|
487
|
+
host.effect(() => host.webServer.register({
|
|
488
|
+
kind: 'exact',
|
|
489
|
+
path: BRIDGE_STATUS_ROUTE,
|
|
490
|
+
handler: (request, response) => handleBridgeStatus(request, response),
|
|
491
|
+
}, 'dsh-builtin-browser: bridge status'))
|
|
492
|
+
})
|
|
493
|
+
} catch {
|
|
494
|
+
// No web server: the panel is unreachable, and the installer stays the interface.
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
399
498
|
installSettingsRoute(ctx, settings, () => { chooseCarrier() })
|
|
499
|
+
installPreviewRoute(ctx, settings)
|
|
500
|
+
installBridgeStatusRoute(ctx)
|
|
400
501
|
}
|
|
401
502
|
|
|
402
503
|
/** Route the settings panel reads and writes. */
|
|
@@ -446,6 +547,13 @@ export function adoptLegacyProfileRoot(
|
|
|
446
547
|
}
|
|
447
548
|
}
|
|
448
549
|
|
|
550
|
+
/** What the frame route needs from the browser service. */
|
|
551
|
+
interface PreviewBrowser {
|
|
552
|
+
exists(session: string): boolean
|
|
553
|
+
capturePassive(session: string, signal?: AbortSignal): Promise<{ readonly dataUrl: string }>
|
|
554
|
+
watchableSessions?(): readonly string[]
|
|
555
|
+
}
|
|
556
|
+
|
|
449
557
|
/** The host web-server surface this plugin uses, described structurally. */
|
|
450
558
|
interface WebServerHost {
|
|
451
559
|
readonly webServer: {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { closeSync, constants, copyFileSync, linkSync, mkdirSync, openSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
/** Write a complete new file without replacing any existing directory entry. */
|
|
6
|
+
export function writeFileNoReplace(file: string, contents: Uint8Array): void {
|
|
7
|
+
const directory = dirname(file)
|
|
8
|
+
mkdirSync(directory, { recursive: true })
|
|
9
|
+
// Never touch a predictable .part file: it may be somebody else's download or a link.
|
|
10
|
+
const temporary = join(directory, `.dsh-download-${randomUUID()}.part`)
|
|
11
|
+
const descriptor = openSync(temporary, 'wx', 0o600)
|
|
12
|
+
try {
|
|
13
|
+
writeFileSync(descriptor, contents)
|
|
14
|
+
// A hard-link commit is atomic and fails with EEXIST even if another writer created
|
|
15
|
+
// the final name after admission. rename() would silently replace it on Windows too.
|
|
16
|
+
try {
|
|
17
|
+
linkSync(temporary, file)
|
|
18
|
+
} catch (error) {
|
|
19
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
20
|
+
if (!['ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EXDEV', 'ENOSYS'].includes(code ?? '')) throw error
|
|
21
|
+
// FAT/exFAT and some network shares cannot create hard links. Exclusive copy keeps
|
|
22
|
+
// the no-replacement guarantee there; unlike a hard link, it is not crash-atomic.
|
|
23
|
+
copyFileSync(temporary, file, constants.COPYFILE_EXCL)
|
|
24
|
+
}
|
|
25
|
+
} finally {
|
|
26
|
+
// Cleanup may be blocked by a scanner/lock after the final file was committed. It
|
|
27
|
+
// must neither turn that success into a failure nor hide the original write error.
|
|
28
|
+
try { closeSync(descriptor) } catch { /* best-effort cleanup */ }
|
|
29
|
+
try { unlinkSync(temporary) } catch { /* best-effort cleanup */ }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -52,22 +52,16 @@ export function visitedHistoryPath(): string {
|
|
|
52
52
|
* a corrupted line must never hide the rest of the history.
|
|
53
53
|
*/
|
|
54
54
|
export class HistoryStore {
|
|
55
|
-
/**
|
|
56
|
-
* File size at which the next rewrite happens.
|
|
57
|
-
*
|
|
58
|
-
* Advanced after each rewrite so the cost is paid once per PRUNE_SLACK appends
|
|
59
|
-
* rather than on every append: asking "is it over the cap?" was true from the first
|
|
60
|
-
* over-cap write onwards, which is what made every later navigation rewrite the file.
|
|
61
|
-
*/
|
|
55
|
+
/** Entry count at which another batched rewrite is due. */
|
|
62
56
|
private pruneThreshold: number
|
|
63
|
-
/**
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
* prune() runs after every navigation, and the answer is almost always "nothing to
|
|
67
|
-
* do" — but working that out from the file costs a full parse. Counting instead makes
|
|
68
|
-
* the common case a comparison.
|
|
69
|
-
*/
|
|
57
|
+
/** Number of entries at the last full read, unknown until the first prune. */
|
|
58
|
+
private knownEntries: number | undefined
|
|
59
|
+
/** Successful appends since the last full read. */
|
|
70
60
|
private appendedSincePrune = 0
|
|
61
|
+
/** Earliest retained visit's expiry; time can require a prune without any new visit. */
|
|
62
|
+
private nextExpiryAt = Infinity
|
|
63
|
+
/** Changing retention invalidates both the count and the age calculation. */
|
|
64
|
+
private limitsChanged = false
|
|
71
65
|
private maxEntries: number
|
|
72
66
|
private maxAgeMs: number
|
|
73
67
|
|
|
@@ -94,10 +88,13 @@ export class HistoryStore {
|
|
|
94
88
|
* @param limits - the current retention overrides.
|
|
95
89
|
*/
|
|
96
90
|
updateLimits(limits: HistoryLimits): void {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
this.
|
|
91
|
+
const maxEntries = limits.maxEntries ?? DEFAULT_MAX_ENTRIES
|
|
92
|
+
const maxAgeMs = (limits.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS) * 24 * 60 * 60 * 1000
|
|
93
|
+
if (maxEntries === this.maxEntries && maxAgeMs === this.maxAgeMs) return
|
|
94
|
+
this.maxEntries = maxEntries
|
|
95
|
+
this.maxAgeMs = maxAgeMs
|
|
96
|
+
this.pruneThreshold = this.maxEntries + this.slack()
|
|
97
|
+
this.limitsChanged = true
|
|
101
98
|
}
|
|
102
99
|
|
|
103
100
|
/** Whether the history file exists yet (diagnostics and tests). */
|
|
@@ -115,10 +112,11 @@ export class HistoryStore {
|
|
|
115
112
|
try {
|
|
116
113
|
mkdirSync(dirname(this.file), { recursive: true })
|
|
117
114
|
appendFileSync(this.file, `${JSON.stringify(page)}\n`)
|
|
115
|
+
this.appendedSincePrune++
|
|
116
|
+
this.nextExpiryAt = Math.min(this.nextExpiryAt, page.at + this.maxAgeMs + 1)
|
|
118
117
|
} catch {
|
|
119
118
|
// Best-effort: history is not worth failing a navigation over.
|
|
120
119
|
}
|
|
121
|
-
this.appendedSincePrune++
|
|
122
120
|
}
|
|
123
121
|
|
|
124
122
|
/**
|
|
@@ -130,13 +128,15 @@ export class HistoryStore {
|
|
|
130
128
|
* @returns the matching visits, newest first.
|
|
131
129
|
*/
|
|
132
130
|
list(options: { readonly limit?: number; readonly domain?: string; readonly query?: string; readonly session?: string } = {}): VisitedPage[] {
|
|
133
|
-
|
|
131
|
+
// The on-disk count may include the small batch slack; that is a write optimization,
|
|
132
|
+
// not permission to expose visits beyond the operator's retained-entry limit.
|
|
134
133
|
const cutoff = Date.now() - this.maxAgeMs
|
|
134
|
+
const fresh = this.readAll().filter(page => page.at >= cutoff)
|
|
135
|
+
const all = fresh.length > this.maxEntries ? fresh.slice(-this.maxEntries) : fresh
|
|
135
136
|
const domain = options.domain?.toLowerCase()
|
|
136
137
|
const query = options.query?.toLowerCase()
|
|
137
138
|
const session = options.session
|
|
138
139
|
const matches = all.filter(page => {
|
|
139
|
-
if (page.at < cutoff) return false
|
|
140
140
|
if (session !== undefined && page.session !== session) return false
|
|
141
141
|
if (query !== undefined) {
|
|
142
142
|
const haystack = `${page.url}\n${page.title ?? ''}`.toLowerCase()
|
|
@@ -153,11 +153,6 @@ export class HistoryStore {
|
|
|
153
153
|
return options.limit === undefined ? matches : matches.slice(0, Math.max(0, options.limit))
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
-
/**
|
|
157
|
-
* Enforce retention: drop entries past the age limit, then the oldest beyond
|
|
158
|
-
* the count cap. Cheap no-op until the file grows past the cap, so callers can
|
|
159
|
-
* run it after every append.
|
|
160
|
-
*/
|
|
161
156
|
/**
|
|
162
157
|
* How far past the cap the file may grow before it is rewritten.
|
|
163
158
|
*
|
|
@@ -171,44 +166,28 @@ export class HistoryStore {
|
|
|
171
166
|
}
|
|
172
167
|
|
|
173
168
|
prune(): void {
|
|
174
|
-
//
|
|
175
|
-
//
|
|
176
|
-
|
|
169
|
+
// Ordinary navigations compare counters and a timestamp only. Read once on startup,
|
|
170
|
+
// when a batch fills, when limits change, or when an existing visit actually expires.
|
|
171
|
+
const now = Date.now()
|
|
172
|
+
if (this.knownEntries !== undefined && !this.limitsChanged
|
|
173
|
+
&& this.knownEntries + this.appendedSincePrune < this.pruneThreshold
|
|
174
|
+
&& now < this.nextExpiryAt) return
|
|
177
175
|
const all = this.readAll()
|
|
178
|
-
const cutoff =
|
|
176
|
+
const cutoff = now - this.maxAgeMs
|
|
179
177
|
const fresh = all.filter(page => page.at >= cutoff)
|
|
180
178
|
const kept = fresh.length > this.maxEntries ? fresh.slice(fresh.length - this.maxEntries) : fresh
|
|
181
|
-
// Every early exit has to retire the count it just spent, or the gate above stops gating.
|
|
182
|
-
// It counted appends so that the common "nothing to do" case is a comparison; leaving the
|
|
183
|
-
// counter set on the two paths that DO read the file meant it was never zero again, so
|
|
184
|
-
// every navigation paid the full parse this was written to avoid.
|
|
185
|
-
if (kept.length === all.length) {
|
|
186
|
-
this.appendedSincePrune = 0
|
|
187
|
-
return
|
|
188
|
-
}
|
|
189
|
-
// Only rewrite once the file has grown PRUNE_SLACK past what we last wrote. Asking
|
|
190
|
-
// "is the file over the cap?" instead was true from the first over-cap append
|
|
191
|
-
// onwards, so every single navigation after that rewrote the whole file.
|
|
192
|
-
if (all.length < this.pruneThreshold) {
|
|
193
|
-
// Deliberately NOT reset here: the count is what tracks progress toward the threshold,
|
|
194
|
-
// so clearing it would postpone the rewrite indefinitely. The read is the price of
|
|
195
|
-
// staying under the threshold, and the threshold is what bounds how often that happens.
|
|
196
|
-
return
|
|
197
|
-
}
|
|
198
179
|
try {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
// half-written TAIL rather than the middle, so everything after the tear was lost.
|
|
204
|
-
writeFileAtomic(this.file, body)
|
|
205
|
-
// The file now holds only what was kept, so the next rewrite is due once
|
|
206
|
-
// PRUNE_SLACK more entries have been appended.
|
|
207
|
-
this.pruneThreshold = kept.length + this.slack()
|
|
180
|
+
if (kept.length !== all.length) {
|
|
181
|
+
writeFileAtomic(this.file, kept.map(page => `${JSON.stringify(page)}\n`).join(''))
|
|
182
|
+
}
|
|
183
|
+
this.knownEntries = kept.length
|
|
208
184
|
this.appendedSincePrune = 0
|
|
185
|
+
this.limitsChanged = false
|
|
186
|
+
this.nextExpiryAt = kept.reduce((earliest, page) => Math.min(earliest, page.at + this.maxAgeMs + 1), Infinity)
|
|
209
187
|
} catch {
|
|
210
188
|
// Best-effort: an unpruned file still reads correctly, and the atomic write leaves the
|
|
211
|
-
// previous one in place when it fails.
|
|
189
|
+
// previous one in place when it fails. Keep the next prune eligible to retry.
|
|
190
|
+
this.limitsChanged = true
|
|
212
191
|
}
|
|
213
192
|
}
|
|
214
193
|
|
|
@@ -27,9 +27,19 @@
|
|
|
27
27
|
import { app, BrowserWindow, WebContentsView } from 'electron'
|
|
28
28
|
import { createInterface } from 'node:readline'
|
|
29
29
|
import { createConnection } from 'node:net'
|
|
30
|
-
import { mkdirSync,
|
|
30
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
31
|
+
import { writeFileNoReplace } from './file-write.js'
|
|
32
|
+
import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.js'
|
|
33
|
+
import { createRpcLineReader } from './rpc-input.js'
|
|
31
34
|
import { tmpdir } from 'node:os'
|
|
32
|
-
import {
|
|
35
|
+
import { join } from 'node:path'
|
|
36
|
+
|
|
37
|
+
// Report the binary actually running this child, even when ELECTRON_PATH
|
|
38
|
+
// intentionally selects a different version from the plugin's dependency.
|
|
39
|
+
// The parent mirrors stderr to the host log; discovery stays filesystem-only.
|
|
40
|
+
for (const line of electronRuntimeDiagnosticLines(process.versions)) {
|
|
41
|
+
process.stderr.write(line + '\n')
|
|
42
|
+
}
|
|
33
43
|
|
|
34
44
|
/**
|
|
35
45
|
* The spawn token the parent sent via stdin (first line). Must be echoed in
|
|
@@ -959,18 +969,7 @@ async function handle(op: string, msg: { id: number; viewId?: string; windowId?:
|
|
|
959
969
|
const detail = (result as { exceptionDetails?: { exception?: { description?: string } } }).exceptionDetails
|
|
960
970
|
throw new Error(`download failed: ${detail?.exception?.description ?? 'no data'}`)
|
|
961
971
|
}
|
|
962
|
-
|
|
963
|
-
// leaves only a `.part` file, never a half-written final file.
|
|
964
|
-
const tmpPath = savePath + '.part'
|
|
965
|
-
mkdirSync(dirname(savePath), { recursive: true })
|
|
966
|
-
writeFileSync(tmpPath, Buffer.from(value, 'base64'))
|
|
967
|
-
try {
|
|
968
|
-
renameSync(tmpPath, savePath)
|
|
969
|
-
} catch (error) {
|
|
970
|
-
// A failed rename must not leave a stray .part behind.
|
|
971
|
-
try { unlinkSync(tmpPath) } catch { /* already gone */ }
|
|
972
|
-
throw error
|
|
973
|
-
}
|
|
972
|
+
writeFileNoReplace(savePath, Buffer.from(value, 'base64'))
|
|
974
973
|
reply(msg.id, { ok: true, result: { path: savePath } })
|
|
975
974
|
return
|
|
976
975
|
}
|
|
@@ -1131,7 +1130,9 @@ void app.whenReady().then(() => {
|
|
|
1131
1130
|
stdinLines.once('close', send)
|
|
1132
1131
|
}
|
|
1133
1132
|
}
|
|
1134
|
-
const rl =
|
|
1133
|
+
const rl = createRpcLineReader(socket, error => {
|
|
1134
|
+
process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`)
|
|
1135
|
+
})
|
|
1135
1136
|
// Handle messages STRICTLY in order. Ops depend on each other completing:
|
|
1136
1137
|
// a `command` for a view must not overtake the `createView` that makes it,
|
|
1137
1138
|
// and the parent's present-barrier (`showView` then `ping`) is only
|
|
@@ -1154,9 +1155,6 @@ void app.whenReady().then(() => {
|
|
|
1154
1155
|
const op = msg.op
|
|
1155
1156
|
queue = queue.then(() => handle(op, msg)).catch(() => { /* reply already sent inside handle */ })
|
|
1156
1157
|
})
|
|
1157
|
-
socket.on('error', error => {
|
|
1158
|
-
process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`)
|
|
1159
|
-
})
|
|
1160
1158
|
// The parent owns our lifetime: when it closes the socket (dispose) or dies
|
|
1161
1159
|
// without cleanup, exit so no zombie Electron window is left behind.
|
|
1162
1160
|
socket.on('close', () => {
|