dsh-builtin-browser 0.4.14 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.en.md +17 -9
  3. package/README.md +48 -10
  4. package/client.js +410 -6
  5. package/desktop-bridge/install-and-start.cmd +36 -0
  6. package/desktop-bridge/install.mjs +166 -3
  7. package/desktop-bridge/plugin-browser-bridge.js +133 -11
  8. package/docs/development.md +19 -0
  9. package/docs/limitations.md +7 -3
  10. package/docs/user-guide.md +46 -18
  11. package/lib/browser/runtime.d.ts +21 -2
  12. package/lib/browser/runtime.js +30 -0
  13. package/lib/browser/types.d.ts +54 -0
  14. package/lib/browser-electron/bridge-status.d.ts +41 -0
  15. package/lib/browser-electron/bridge-status.js +164 -0
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
  17. package/lib/browser-electron/desktop-bridge-host.js +75 -44
  18. package/lib/browser-electron/entry.js +130 -11
  19. package/lib/browser-electron/file-write.d.ts +2 -0
  20. package/lib/browser-electron/file-write.js +39 -0
  21. package/lib/browser-electron/history-store.d.ts +8 -19
  22. package/lib/browser-electron/history-store.js +37 -58
  23. package/lib/browser-electron/host-main.js +15 -22
  24. package/lib/browser-electron/preview-route.d.ts +89 -0
  25. package/lib/browser-electron/preview-route.js +172 -0
  26. package/lib/browser-electron/provider.d.ts +62 -3
  27. package/lib/browser-electron/provider.js +246 -12
  28. package/lib/browser-electron/remote-host.js +5 -1
  29. package/lib/browser-electron/rpc-input.d.ts +4 -0
  30. package/lib/browser-electron/rpc-input.js +11 -0
  31. package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
  32. package/lib/browser-electron/runtime-diagnostics.js +29 -0
  33. package/lib/browser-electron/settings-store.d.ts +15 -2
  34. package/lib/browser-electron/settings-store.js +25 -5
  35. package/lib/browser-electron/system-browser.d.ts +18 -0
  36. package/lib/browser-electron/system-browser.js +158 -37
  37. package/lib/tool-browser/index.js +10 -1
  38. package/package.json +8 -3
  39. package/scripts/install-electron.mjs +66 -0
  40. package/scripts/verify-preview-route.mjs +150 -0
  41. package/src/browser/runtime.ts +36 -0
  42. package/src/browser/types.ts +55 -0
  43. package/src/browser-electron/bridge-status.ts +180 -0
  44. package/src/browser-electron/desktop-bridge-host.ts +75 -41
  45. package/src/browser-electron/entry.ts +119 -11
  46. package/src/browser-electron/file-write.ts +31 -0
  47. package/src/browser-electron/history-store.ts +36 -57
  48. package/src/browser-electron/host-main.ts +16 -18
  49. package/src/browser-electron/preview-route.ts +222 -0
  50. package/src/browser-electron/provider.ts +286 -16
  51. package/src/browser-electron/remote-host.ts +5 -1
  52. package/src/browser-electron/rpc-input.ts +13 -0
  53. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  54. package/src/browser-electron/settings-store.ts +37 -5
  55. package/src/browser-electron/system-browser.ts +149 -32
  56. package/src/tool-browser/index.ts +13 -1
@@ -15,6 +15,7 @@ import { randomUUID } from 'node:crypto';
15
15
  import { existsSync, mkdirSync, renameSync } from 'node:fs';
16
16
  import { homedir } from 'node:os';
17
17
  import { dirname, join } from 'node:path';
18
+ import { setTimeout as wait } from 'node:timers/promises';
18
19
  import { defaultHostMainPath, RemoteElectronViewHost } from './remote-host.js';
19
20
  import { DesktopBridgeViewHost } from './desktop-bridge-host.js';
20
21
  import { detectBrowser, searchSummary, SystemBrowserViewHost } from './system-browser.js';
@@ -22,6 +23,7 @@ import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralPro
22
23
  import { MissingSystemBrowserHost } from './missing-system-browser.js';
23
24
  import { SettingsStore } from './settings-store.js';
24
25
  import { sameOrigin } from './settings-route.js';
26
+ import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js';
25
27
  export { ELECTRON_BROWSER_PROVIDER_ID, ElectronBrowserProvider, } from './provider.js';
26
28
  export { RemoteElectronViewHost, defaultHostMainPath } from './remote-host.js';
27
29
  /** Cordis plugin name used by loader diagnostics. */
@@ -115,11 +117,17 @@ export function apply(ctx, config) {
115
117
  // otherwise would leave a stray window behind.
116
118
  const selfHosted = new RemoteElectronViewHost(defaultHostMainPath());
117
119
  let unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(selfHosted, providerConfig));
118
- let upgraded = false;
120
+ let disposed = false;
121
+ let carrierChoice = 0;
122
+ let discovery;
119
123
  /** The carrier an `adopt` installed, so a later choice can release it. */
120
124
  let adoptedCarrier;
121
125
  ctx.effect(() => () => {
126
+ disposed = true;
127
+ carrierChoice += 1;
128
+ discovery?.abort();
122
129
  unregister();
130
+ adoptedCarrier?.dispose?.();
123
131
  selfHosted.dispose();
124
132
  });
125
133
  /**
@@ -138,10 +146,14 @@ export function apply(ctx, config) {
138
146
  * @param reason - which failure this was; see {@link CarrierLossReason}.
139
147
  */
140
148
  const restoreSelfHosted = (adopted, reason) => {
149
+ // A replaced carrier may finish an outstanding request after the new choice is installed.
150
+ if (disposed || adoptedCarrier !== adopted)
151
+ return;
141
152
  try {
142
153
  const restored = new RemoteElectronViewHost(defaultHostMainPath());
143
154
  unregister();
144
155
  unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(restored, providerConfig));
156
+ adoptedCarrier = restored;
145
157
  ctx.logger?.warn?.(reason === 'shell-exited'
146
158
  ? 'dsh-builtin-browser: the desktop shell backed the sidebar browser and has exited, so the '
147
159
  + 'browser this plugin hosts itself takes over. Pages from the sidebar are gone with it; '
@@ -179,23 +191,29 @@ export function apply(ctx, config) {
179
191
  * @param host - the carrier to adopt.
180
192
  * @param note - a one-line description for the log.
181
193
  */
182
- const adopt = (host, note) => {
194
+ const adopt = (host, note, choice = carrierChoice) => {
195
+ if (disposed || choice !== carrierChoice) {
196
+ try {
197
+ host.dispose?.();
198
+ }
199
+ catch { /* a stale result must not escape its retry */ }
200
+ return;
201
+ }
183
202
  // This guard used to make the FIRST choice final, disposing anything that arrived later. That
184
203
  // is right against two carriers racing in, and exactly wrong for a user changing the setting:
185
204
  // `chooseCarrier` runs again on purpose, and a refusal here is indistinguishable from the
186
205
  // write having done nothing. The previous carrier is now released by the replacement instead.
187
- upgraded = true;
206
+ const previous = adoptedCarrier;
188
207
  try {
189
208
  unregister();
190
209
  unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(host, providerConfig));
191
210
  selfHosted.dispose();
211
+ adoptedCarrier = host;
192
212
  ctx.logger?.info?.(`dsh-builtin-browser: ${note}`);
193
213
  // A borrowed carrier can lose the process behind it, and this is the only notification that
194
214
  // will ever arrive. Registering AFTER the swap succeeded means a listener can never fire
195
215
  // against a provider that was never installed.
196
216
  host.onLost?.(reason => { restoreSelfHosted(host, reason); });
197
- const previous = adoptedCarrier;
198
- adoptedCarrier = host;
199
217
  // Released AFTER the replacement is installed, so the surface is never without a provider.
200
218
  if (previous !== undefined && previous !== host) {
201
219
  try {
@@ -220,7 +238,15 @@ export function apply(ctx, config) {
220
238
  // exit code 1: a failed upgrade, which should only ever cost a warning, took the whole
221
239
  // session down instead. Observed 2026-10-05 (crash-…-host.log, phase: running).
222
240
  try {
223
- unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(new RemoteElectronViewHost(defaultHostMainPath()), providerConfig));
241
+ const fallback = new RemoteElectronViewHost(defaultHostMainPath());
242
+ unregister = ctx.browser.registerBrowserProvider(new ElectronBrowserProvider(fallback, providerConfig));
243
+ adoptedCarrier = fallback;
244
+ if (previous !== undefined && previous !== host) {
245
+ try {
246
+ previous.dispose?.();
247
+ }
248
+ catch { /* fallback is already serving */ }
249
+ }
224
250
  ctx.logger?.warn?.(`dsh-builtin-browser: could not adopt ${note} (${String(error)})`);
225
251
  }
226
252
  catch (fallbackError) {
@@ -240,6 +266,13 @@ export function apply(ctx, config) {
240
266
  * exactly what a second call does.
241
267
  */
242
268
  const chooseCarrier = () => {
269
+ if (disposed)
270
+ return;
271
+ const choice = ++carrierChoice;
272
+ discovery?.abort();
273
+ const controller = new AbortController();
274
+ discovery = controller;
275
+ const { signal } = controller;
243
276
  // A browser the user explicitly asked for outranks every automatic choice: the
244
277
  // whole point of the setting is that they know which browser they want. It is
245
278
  // launched with a plugin-owned profile, so their own windows are untouched.
@@ -264,6 +297,9 @@ export function apply(ctx, config) {
264
297
  // confusing error about Electron later on. Report it instead.
265
298
  if (channel === 'auto') {
266
299
  ctx.logger?.warn?.('dsh-builtin-browser: no installed browser was found; using the bundled browser');
300
+ if (adoptedCarrier !== undefined) {
301
+ adopt(new RemoteElectronViewHost(defaultHostMainPath()), 'using the bundled browser', choice);
302
+ }
267
303
  }
268
304
  else {
269
305
  adopt(new MissingSystemBrowserHost(channel, searchSummary(channel)), `the selected ${channel} is not installed — commands will explain how to fix it`);
@@ -299,6 +335,11 @@ export function apply(ctx, config) {
299
335
  adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir, undefined, settings.get().browser.headless), `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`);
300
336
  }
301
337
  }
338
+ else if (adoptedCarrier !== undefined) {
339
+ // The original self-hosted carrier was disposed by the first adoption. Switching back
340
+ // must install a new one, even when no sidebar is found during the discovery below.
341
+ adopt(new RemoteElectronViewHost(defaultHostMainPath()), 'using the bundled browser', choice);
342
+ }
302
343
  // An explicit choice was already adopted above; discovering the sidebar here would
303
344
  // replace it, which is exactly what this guard prevents.
304
345
  //
@@ -311,12 +352,20 @@ export function apply(ctx, config) {
311
352
  // was never adopted for the rest of the process's life. Retry a handful of times over roughly
312
353
  // half a minute, then stop: this is a convenience, not a promise, and the session the user is
313
354
  // already driving in the self-hosted window is not worth replacing minutes into their work.
314
- // `adopt` is itself one-shot (its `upgraded` guard), so the only possible effect of a retry
315
- // that lands late is adopting a bridge that showed up just after startup.
355
+ // Each attempt belongs to this choice. A later settings write or teardown cancels its waits,
356
+ // and an endpoint returned by an already-running discovery is disposed instead of installed.
316
357
  void (async () => {
317
358
  for (const delay of [0, 2_000, 5_000, 15_000]) {
318
- if (delay > 0)
319
- await new Promise(resolve => setTimeout(resolve, delay));
359
+ if (delay > 0) {
360
+ try {
361
+ await wait(delay, undefined, { signal });
362
+ }
363
+ catch {
364
+ return;
365
+ }
366
+ }
367
+ if (signal.aborted || disposed)
368
+ return;
320
369
  let sidebar;
321
370
  try {
322
371
  sidebar = await DesktopBridgeViewHost.discover(sessionId);
@@ -324,9 +373,16 @@ export function apply(ctx, config) {
324
373
  catch {
325
374
  sidebar = undefined; // discovery is documented not to throw; never let it stop the retries
326
375
  }
376
+ if (signal.aborted || disposed) {
377
+ try {
378
+ sidebar?.dispose?.();
379
+ }
380
+ catch { /* the choice no longer owns this result */ }
381
+ return;
382
+ }
327
383
  if (sidebar === undefined)
328
384
  continue;
329
- adopt(sidebar, 'driving the desktop sidebar browser');
385
+ adopt(sidebar, 'driving the desktop sidebar browser', choice);
330
386
  return;
331
387
  }
332
388
  // A bridge exists but its sidebar panel is an iframe. Saying nothing here would leave the user
@@ -357,7 +413,70 @@ export function apply(ctx, config) {
357
413
  // Wired AFTER the chooser exists, because the handler re-runs it: a settings write that changes
358
414
  // `browser.channel` is a request to switch carriers, and answering `ok` without switching is the
359
415
  // one thing a caller cannot tell apart from a write that worked.
416
+ /**
417
+ * Expose the live-view frame endpoint on the host's web server (issue #34).
418
+ *
419
+ * Registered exactly like the settings route and skipped the same way when a surface has no web
420
+ * server: a CLI session simply has no viewer, which is not a plugin-startup failure. The endpoint
421
+ * is inert until the host turns `remoteView.enabled` on, and it refuses a request whose session the
422
+ * plugin never handed out.
423
+ * @param ctx - the plugin context.
424
+ * @param settings - the settings document, for the share switch.
425
+ */
426
+ function installPreviewRoute(ctx, settings) {
427
+ const injectPreview = ctx.inject;
428
+ if (typeof injectPreview !== 'function')
429
+ return;
430
+ try {
431
+ injectPreview(['webServer', 'browser'], (host) => {
432
+ const browser = ctx.browser;
433
+ if (browser === undefined)
434
+ return;
435
+ host.effect(() => host.webServer.register({
436
+ kind: 'exact',
437
+ path: PREVIEW_ROUTE,
438
+ handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
439
+ }, 'dsh-builtin-browser: live view frame'));
440
+ // The list the panel needs before it can build a frame URL at all: session ids only.
441
+ host.effect(() => host.webServer.register({
442
+ kind: 'exact',
443
+ path: PREVIEW_SESSIONS_ROUTE,
444
+ handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
445
+ }, 'dsh-builtin-browser: live view sessions'));
446
+ });
447
+ }
448
+ catch {
449
+ // No web server on this surface: watching is simply unavailable, and nothing else changes.
450
+ }
451
+ }
452
+ /**
453
+ * Expose the bridge's install state on the host's web server, for the settings panel.
454
+ *
455
+ * Separate from the live-view routes because it needs no browser service: it reads the install
456
+ * tree, which is on disk and independent of any carrier. A surface without a web server skips it,
457
+ * exactly like the other two.
458
+ * @param ctx - the plugin context.
459
+ */
460
+ function installBridgeStatusRoute(ctx) {
461
+ const injectStatus = ctx.inject;
462
+ if (typeof injectStatus !== 'function')
463
+ return;
464
+ try {
465
+ injectStatus(['webServer'], (host) => {
466
+ host.effect(() => host.webServer.register({
467
+ kind: 'exact',
468
+ path: BRIDGE_STATUS_ROUTE,
469
+ handler: (request, response) => handleBridgeStatus(request, response),
470
+ }, 'dsh-builtin-browser: bridge status'));
471
+ });
472
+ }
473
+ catch {
474
+ // No web server: the panel is unreachable, and the installer stays the interface.
475
+ }
476
+ }
360
477
  installSettingsRoute(ctx, settings, () => { chooseCarrier(); });
478
+ installPreviewRoute(ctx, settings);
479
+ installBridgeStatusRoute(ctx);
361
480
  }
362
481
  /** Route the settings panel reads and writes. */
363
482
  const SETTINGS_ROUTE = '/dsh-builtin-browser/settings';
@@ -0,0 +1,2 @@
1
+ /** Write a complete new file without replacing any existing directory entry. */
2
+ export declare function writeFileNoReplace(file: string, contents: Uint8Array): void;
@@ -0,0 +1,39 @@
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
+ /** Write a complete new file without replacing any existing directory entry. */
5
+ export function writeFileNoReplace(file, contents) {
6
+ const directory = dirname(file);
7
+ mkdirSync(directory, { recursive: true });
8
+ // Never touch a predictable .part file: it may be somebody else's download or a link.
9
+ const temporary = join(directory, `.dsh-download-${randomUUID()}.part`);
10
+ const descriptor = openSync(temporary, 'wx', 0o600);
11
+ try {
12
+ writeFileSync(descriptor, contents);
13
+ // A hard-link commit is atomic and fails with EEXIST even if another writer created
14
+ // the final name after admission. rename() would silently replace it on Windows too.
15
+ try {
16
+ linkSync(temporary, file);
17
+ }
18
+ catch (error) {
19
+ const code = error.code;
20
+ if (!['ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EXDEV', 'ENOSYS'].includes(code ?? ''))
21
+ throw error;
22
+ // FAT/exFAT and some network shares cannot create hard links. Exclusive copy keeps
23
+ // the no-replacement guarantee there; unlike a hard link, it is not crash-atomic.
24
+ copyFileSync(temporary, file, constants.COPYFILE_EXCL);
25
+ }
26
+ }
27
+ finally {
28
+ // Cleanup may be blocked by a scanner/lock after the final file was committed. It
29
+ // must neither turn that success into a failure nor hide the original write error.
30
+ try {
31
+ closeSync(descriptor);
32
+ }
33
+ catch { /* best-effort cleanup */ }
34
+ try {
35
+ unlinkSync(temporary);
36
+ }
37
+ catch { /* best-effort cleanup */ }
38
+ }
39
+ }
@@ -34,22 +34,16 @@ export declare function visitedHistoryPath(): string;
34
34
  */
35
35
  export declare class HistoryStore {
36
36
  private readonly file;
37
- /**
38
- * File size at which the next rewrite happens.
39
- *
40
- * Advanced after each rewrite so the cost is paid once per PRUNE_SLACK appends
41
- * rather than on every append: asking "is it over the cap?" was true from the first
42
- * over-cap write onwards, which is what made every later navigation rewrite the file.
43
- */
37
+ /** Entry count at which another batched rewrite is due. */
44
38
  private pruneThreshold;
45
- /**
46
- * Appends since the last rewrite.
47
- *
48
- * prune() runs after every navigation, and the answer is almost always "nothing to
49
- * do" — but working that out from the file costs a full parse. Counting instead makes
50
- * the common case a comparison.
51
- */
39
+ /** Number of entries at the last full read, unknown until the first prune. */
40
+ private knownEntries;
41
+ /** Successful appends since the last full read. */
52
42
  private appendedSincePrune;
43
+ /** Earliest retained visit's expiry; time can require a prune without any new visit. */
44
+ private nextExpiryAt;
45
+ /** Changing retention invalidates both the count and the age calculation. */
46
+ private limitsChanged;
53
47
  private maxEntries;
54
48
  private maxAgeMs;
55
49
  /**
@@ -89,11 +83,6 @@ export declare class HistoryStore {
89
83
  readonly query?: string;
90
84
  readonly session?: string;
91
85
  }): VisitedPage[];
92
- /**
93
- * Enforce retention: drop entries past the age limit, then the oldest beyond
94
- * the count cap. Cheap no-op until the file grows past the cap, so callers can
95
- * run it after every append.
96
- */
97
86
  /**
98
87
  * How far past the cap the file may grow before it is rewritten.
99
88
  *
@@ -38,22 +38,16 @@ export function visitedHistoryPath() {
38
38
  */
39
39
  export class HistoryStore {
40
40
  file;
41
- /**
42
- * File size at which the next rewrite happens.
43
- *
44
- * Advanced after each rewrite so the cost is paid once per PRUNE_SLACK appends
45
- * rather than on every append: asking "is it over the cap?" was true from the first
46
- * over-cap write onwards, which is what made every later navigation rewrite the file.
47
- */
41
+ /** Entry count at which another batched rewrite is due. */
48
42
  pruneThreshold;
49
- /**
50
- * Appends since the last rewrite.
51
- *
52
- * prune() runs after every navigation, and the answer is almost always "nothing to
53
- * do" — but working that out from the file costs a full parse. Counting instead makes
54
- * the common case a comparison.
55
- */
43
+ /** Number of entries at the last full read, unknown until the first prune. */
44
+ knownEntries;
45
+ /** Successful appends since the last full read. */
56
46
  appendedSincePrune = 0;
47
+ /** Earliest retained visit's expiry; time can require a prune without any new visit. */
48
+ nextExpiryAt = Infinity;
49
+ /** Changing retention invalidates both the count and the age calculation. */
50
+ limitsChanged = false;
57
51
  maxEntries;
58
52
  maxAgeMs;
59
53
  /**
@@ -76,10 +70,14 @@ export class HistoryStore {
76
70
  * @param limits - the current retention overrides.
77
71
  */
78
72
  updateLimits(limits) {
79
- this.maxEntries = limits.maxEntries ?? DEFAULT_MAX_ENTRIES;
80
- this.maxAgeMs = (limits.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS) * 24 * 60 * 60 * 1000;
81
- // Recomputed rather than left alone: a smaller cap means the next rewrite is sooner.
82
- this.pruneThreshold = Math.max(this.pruneThreshold, this.maxEntries + this.slack());
73
+ const maxEntries = limits.maxEntries ?? DEFAULT_MAX_ENTRIES;
74
+ const maxAgeMs = (limits.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS) * 24 * 60 * 60 * 1000;
75
+ if (maxEntries === this.maxEntries && maxAgeMs === this.maxAgeMs)
76
+ return;
77
+ this.maxEntries = maxEntries;
78
+ this.maxAgeMs = maxAgeMs;
79
+ this.pruneThreshold = this.maxEntries + this.slack();
80
+ this.limitsChanged = true;
83
81
  }
84
82
  /** Whether the history file exists yet (diagnostics and tests). */
85
83
  exists() {
@@ -95,11 +93,12 @@ export class HistoryStore {
95
93
  try {
96
94
  mkdirSync(dirname(this.file), { recursive: true });
97
95
  appendFileSync(this.file, `${JSON.stringify(page)}\n`);
96
+ this.appendedSincePrune++;
97
+ this.nextExpiryAt = Math.min(this.nextExpiryAt, page.at + this.maxAgeMs + 1);
98
98
  }
99
99
  catch {
100
100
  // Best-effort: history is not worth failing a navigation over.
101
101
  }
102
- this.appendedSincePrune++;
103
102
  }
104
103
  /**
105
104
  * Read visits, newest first. Unparseable lines are skipped; entries older
@@ -110,14 +109,15 @@ export class HistoryStore {
110
109
  * @returns the matching visits, newest first.
111
110
  */
112
111
  list(options = {}) {
113
- const all = this.readAll();
112
+ // The on-disk count may include the small batch slack; that is a write optimization,
113
+ // not permission to expose visits beyond the operator's retained-entry limit.
114
114
  const cutoff = Date.now() - this.maxAgeMs;
115
+ const fresh = this.readAll().filter(page => page.at >= cutoff);
116
+ const all = fresh.length > this.maxEntries ? fresh.slice(-this.maxEntries) : fresh;
115
117
  const domain = options.domain?.toLowerCase();
116
118
  const query = options.query?.toLowerCase();
117
119
  const session = options.session;
118
120
  const matches = all.filter(page => {
119
- if (page.at < cutoff)
120
- return false;
121
121
  if (session !== undefined && page.session !== session)
122
122
  return false;
123
123
  if (query !== undefined) {
@@ -137,11 +137,6 @@ export class HistoryStore {
137
137
  matches.reverse();
138
138
  return options.limit === undefined ? matches : matches.slice(0, Math.max(0, options.limit));
139
139
  }
140
- /**
141
- * Enforce retention: drop entries past the age limit, then the oldest beyond
142
- * the count cap. Cheap no-op until the file grows past the cap, so callers can
143
- * run it after every append.
144
- */
145
140
  /**
146
141
  * How far past the cap the file may grow before it is rewritten.
147
142
  *
@@ -154,46 +149,30 @@ export class HistoryStore {
154
149
  return Math.min(PRUNE_SLACK, Math.max(1, Math.floor(this.maxEntries / 2)));
155
150
  }
156
151
  prune() {
157
- // Cheap first: past the cap but without enough new entries to justify a rewrite.
158
- // Reading the file to reach this conclusion was the remaining per-navigation cost.
159
- if (this.appendedSincePrune === 0)
152
+ // Ordinary navigations compare counters and a timestamp only. Read once on startup,
153
+ // when a batch fills, when limits change, or when an existing visit actually expires.
154
+ const now = Date.now();
155
+ if (this.knownEntries !== undefined && !this.limitsChanged
156
+ && this.knownEntries + this.appendedSincePrune < this.pruneThreshold
157
+ && now < this.nextExpiryAt)
160
158
  return;
161
159
  const all = this.readAll();
162
- const cutoff = Date.now() - this.maxAgeMs;
160
+ const cutoff = now - this.maxAgeMs;
163
161
  const fresh = all.filter(page => page.at >= cutoff);
164
162
  const kept = fresh.length > this.maxEntries ? fresh.slice(fresh.length - this.maxEntries) : fresh;
165
- // Every early exit has to retire the count it just spent, or the gate above stops gating.
166
- // It counted appends so that the common "nothing to do" case is a comparison; leaving the
167
- // counter set on the two paths that DO read the file meant it was never zero again, so
168
- // every navigation paid the full parse this was written to avoid.
169
- if (kept.length === all.length) {
170
- this.appendedSincePrune = 0;
171
- return;
172
- }
173
- // Only rewrite once the file has grown PRUNE_SLACK past what we last wrote. Asking
174
- // "is the file over the cap?" instead was true from the first over-cap append
175
- // onwards, so every single navigation after that rewrote the whole file.
176
- if (all.length < this.pruneThreshold) {
177
- // Deliberately NOT reset here: the count is what tracks progress toward the threshold,
178
- // so clearing it would postpone the rewrite indefinitely. The read is the price of
179
- // staying under the threshold, and the threshold is what bounds how often that happens.
180
- return;
181
- }
182
163
  try {
183
- const body = kept.map(page => `${JSON.stringify(page)}\n`).join('');
184
- // Atomic, like the settings document. A plain writeFileSync truncates first, and this is
185
- // the whole history in one call: a TerminateProcess mid-write — the browser host is
186
- // killed exactly that way on Windows — left a partial file, and the reader drops a
187
- // half-written TAIL rather than the middle, so everything after the tear was lost.
188
- writeFileAtomic(this.file, body);
189
- // The file now holds only what was kept, so the next rewrite is due once
190
- // PRUNE_SLACK more entries have been appended.
191
- this.pruneThreshold = kept.length + this.slack();
164
+ if (kept.length !== all.length) {
165
+ writeFileAtomic(this.file, kept.map(page => `${JSON.stringify(page)}\n`).join(''));
166
+ }
167
+ this.knownEntries = kept.length;
192
168
  this.appendedSincePrune = 0;
169
+ this.limitsChanged = false;
170
+ this.nextExpiryAt = kept.reduce((earliest, page) => Math.min(earliest, page.at + this.maxAgeMs + 1), Infinity);
193
171
  }
194
172
  catch {
195
173
  // Best-effort: an unpruned file still reads correctly, and the atomic write leaves the
196
- // previous one in place when it fails.
174
+ // previous one in place when it fails. Keep the next prune eligible to retry.
175
+ this.limitsChanged = true;
197
176
  }
198
177
  }
199
178
  /** Parse the whole file, skipping blank and damaged lines. */
@@ -26,9 +26,18 @@
26
26
  import { app, BrowserWindow, WebContentsView } from 'electron';
27
27
  import { createInterface } from 'node:readline';
28
28
  import { createConnection } from 'node:net';
29
- import { mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
29
+ import { mkdirSync, writeFileSync } from 'node:fs';
30
+ import { writeFileNoReplace } from './file-write.js';
31
+ import { electronRuntimeDiagnosticLines } from './runtime-diagnostics.js';
32
+ import { createRpcLineReader } from './rpc-input.js';
30
33
  import { tmpdir } from 'node:os';
31
- import { dirname, join } from 'node:path';
34
+ import { join } from 'node:path';
35
+ // Report the binary actually running this child, even when ELECTRON_PATH
36
+ // intentionally selects a different version from the plugin's dependency.
37
+ // The parent mirrors stderr to the host log; discovery stays filesystem-only.
38
+ for (const line of electronRuntimeDiagnosticLines(process.versions)) {
39
+ process.stderr.write(line + '\n');
40
+ }
32
41
  /**
33
42
  * The spawn token the parent sent via stdin (first line). Must be echoed in
34
43
  * our hello. Read from stdin so the token never appears in argv (WMI /
@@ -995,22 +1004,7 @@ async function handle(op, msg) {
995
1004
  const detail = result.exceptionDetails;
996
1005
  throw new Error(`download failed: ${detail?.exception?.description ?? 'no data'}`);
997
1006
  }
998
- // Temp file + rename keeps the write atomic-ish: a crash mid-write
999
- // leaves only a `.part` file, never a half-written final file.
1000
- const tmpPath = savePath + '.part';
1001
- mkdirSync(dirname(savePath), { recursive: true });
1002
- writeFileSync(tmpPath, Buffer.from(value, 'base64'));
1003
- try {
1004
- renameSync(tmpPath, savePath);
1005
- }
1006
- catch (error) {
1007
- // A failed rename must not leave a stray .part behind.
1008
- try {
1009
- unlinkSync(tmpPath);
1010
- }
1011
- catch { /* already gone */ }
1012
- throw error;
1013
- }
1007
+ writeFileNoReplace(savePath, Buffer.from(value, 'base64'));
1014
1008
  reply(msg.id, { ok: true, result: { path: savePath } });
1015
1009
  return;
1016
1010
  }
@@ -1171,7 +1165,9 @@ void app.whenReady().then(() => {
1171
1165
  stdinLines.once('close', send);
1172
1166
  }
1173
1167
  }
1174
- const rl = createInterface({ input: socket });
1168
+ const rl = createRpcLineReader(socket, error => {
1169
+ process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`);
1170
+ });
1175
1171
  // Handle messages STRICTLY in order. Ops depend on each other completing:
1176
1172
  // a `command` for a view must not overtake the `createView` that makes it,
1177
1173
  // and the parent's present-barrier (`showView` then `ping`) is only
@@ -1197,9 +1193,6 @@ void app.whenReady().then(() => {
1197
1193
  const op = msg.op;
1198
1194
  queue = queue.then(() => handle(op, msg)).catch(() => { });
1199
1195
  });
1200
- socket.on('error', error => {
1201
- process.stderr.write(`[dsh-browser host] socket error: ${String(error)}\n`);
1202
- });
1203
1196
  // The parent owns our lifetime: when it closes the socket (dispose) or dies
1204
1197
  // without cleanup, exit so no zombie Electron window is left behind.
1205
1198
  socket.on('close', () => {
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The live-view frame endpoint (issue #34): one JPEG per request, for a remote operator watching the
3
+ * page the agent is driving.
4
+ *
5
+ * Deliberately one frame per request rather than a stream. The viewer asks for the next frame after
6
+ * it has decoded and painted the previous one, so a slow link slows the view down instead of
7
+ * queueing images; the design chose this over MJPEG and WebSocket for the first version precisely
8
+ * because it needs no new plumbing and degrades predictably.
9
+ *
10
+ * The path is fixed and the session travels as a query parameter because the host web server only
11
+ * registers exact paths. That is also why the session id is not a `viewId`: a client may name a
12
+ * session the plugin handed out, never a carrier handle, a port, or an arbitrary target.
13
+ * @module dsh-browser/browser-electron/preview-route
14
+ */
15
+ import type { IncomingMessage, ServerResponse } from 'node:http';
16
+ /** Where the frame endpoint lives. The viewer must use exactly this path, same origin. */
17
+ export declare const PREVIEW_ROUTE = "/dsh-builtin-browser/browser-view/frame";
18
+ /**
19
+ * Where the viewer asks which sessions it may watch.
20
+ *
21
+ * The provider names its sessions (`browser:<uuid>`) and only it knows them; the browser page has no
22
+ * way to guess one. Without this the viewer could not build a frame URL at all, and inventing an id
23
+ * is exactly what the design forbids. So the list is served, and it contains nothing but ids of
24
+ * sessions that currently have a page — no URLs, no titles, no target handles.
25
+ */
26
+ export declare const PREVIEW_SESSIONS_ROUTE = "/dsh-builtin-browser/browser-view/sessions";
27
+ /**
28
+ * Where the settings panel asks whether the desktop bridge is installed.
29
+ *
30
+ * Reported as issue #36: a missing bridge was only a log warning, so a user on `channel: sidebar`
31
+ * saw "another window opened again" with nothing connecting that to "the bridge is not installed".
32
+ * The reading is taken from the install tree on disk, so it is true even when the plugin has just
33
+ * started and remembers nothing.
34
+ */
35
+ export declare const BRIDGE_STATUS_ROUTE = "/dsh-builtin-browser/bridge-status";
36
+ /** What the route needs from the settings document. */
37
+ interface PreviewSettings {
38
+ get(): {
39
+ readonly remoteView: {
40
+ readonly enabled: boolean;
41
+ };
42
+ };
43
+ }
44
+ /** What the route needs from the browser service. */
45
+ interface PreviewBrowser {
46
+ exists(session: string): boolean;
47
+ capturePassive(session: string, signal?: AbortSignal): Promise<{
48
+ readonly dataUrl: string;
49
+ }>;
50
+ /** Sessions that currently hold a page. Optional: a service without it reports none. */
51
+ watchableSessions?(): readonly string[];
52
+ }
53
+ /**
54
+ * List the sessions a viewer may watch.
55
+ *
56
+ * Ids only. The whole point of this endpoint is to give the page something it cannot guess; adding a
57
+ * URL or title here would leak the very content the frame endpoint is careful not to describe in its
58
+ * refusals.
59
+ * @param request - the incoming request.
60
+ * @param response - the response to write.
61
+ * @param settings - the settings document, for the share switch.
62
+ * @param browser - the browser service.
63
+ */
64
+ export declare function handlePreviewSessions(request: IncomingMessage, response: ServerResponse, settings: PreviewSettings, browser: PreviewBrowser): Promise<void>;
65
+ /**
66
+ * Serve one frame, or say precisely why not.
67
+ *
68
+ * Every refusal is a status the viewer can act on: 403 when watching is switched off (the host has
69
+ * not agreed), 404 when that session has no page (nothing to watch, and nothing is opened on its
70
+ * behalf), 503 when the page cannot produce an image right now (hidden window, capture timeout) —
71
+ * which the viewer shows as paused rather than as an error.
72
+ * @param request - the incoming request.
73
+ * @param response - the response to write.
74
+ * @param settings - the settings document, for the host's share switch.
75
+ * @param browser - the browser service, for passive capture.
76
+ */
77
+ export declare function handlePreviewFrame(request: IncomingMessage, response: ServerResponse, settings: PreviewSettings, browser: PreviewBrowser): Promise<void>;
78
+ /**
79
+ * Report whether the desktop bridge is installed, for the settings panel.
80
+ *
81
+ * Read-only and same-origin like the rest: it names a directory and a state, nothing that could be
82
+ * used to reach anything else. The command it returns is for a human to run — executing it here
83
+ * would let a page decide to close the desktop shell.
84
+ * @param request - the incoming request.
85
+ * @param response - the response to write.
86
+ * @param localAppData - the base directory to probe; injected so a test can point at a fixture.
87
+ */
88
+ export declare function handleBridgeStatus(request: IncomingMessage, response: ServerResponse, localAppData?: string): Promise<void>;
89
+ export {};