dsh-builtin-browser 0.5.6 → 0.5.7

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 (63) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.en.md +67 -99
  3. package/README.md +67 -100
  4. package/client.js +381 -322
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/tool-reference.md +20 -1
  8. package/lib/browser/runtime.d.ts +3 -1
  9. package/lib/browser/runtime.js +9 -0
  10. package/lib/browser/types.d.ts +42 -0
  11. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  12. package/lib/browser-electron/authenticated-route.js +39 -0
  13. package/lib/browser-electron/bridge-endpoint.js +7 -0
  14. package/lib/browser-electron/bridge-install.d.ts +48 -0
  15. package/lib/browser-electron/bridge-install.js +98 -0
  16. package/lib/browser-electron/bridge-status.js +21 -2
  17. package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
  18. package/lib/browser-electron/desktop-bridge-host.js +36 -15
  19. package/lib/browser-electron/electron-provision.d.ts +1 -1
  20. package/lib/browser-electron/electron-provision.js +31 -11
  21. package/lib/browser-electron/entry.js +84 -8
  22. package/lib/browser-electron/host-main.js +48 -27
  23. package/lib/browser-electron/provider.d.ts +9 -2
  24. package/lib/browser-electron/provider.js +76 -6
  25. package/lib/browser-electron/remote-host.js +4 -4
  26. package/lib/browser-electron/runtime-route.d.ts +3 -5
  27. package/lib/browser-electron/runtime-status.js +4 -2
  28. package/lib/browser-electron/settings-route.d.ts +5 -18
  29. package/lib/browser-electron/settings-route.js +4 -14
  30. package/lib/browser-electron/settings-store.d.ts +17 -0
  31. package/lib/browser-electron/settings-store.js +24 -0
  32. package/lib/browser-electron/system-browser.d.ts +5 -2
  33. package/lib/browser-electron/system-browser.js +12 -4
  34. package/lib/tool-browser/index.js +1041 -4
  35. package/lib/tool-browser/page-probe.d.ts +86 -0
  36. package/lib/tool-browser/page-probe.js +460 -0
  37. package/package.json +4 -2
  38. package/scripts/verify-runtime-status.mjs +14 -0
  39. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  40. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  41. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  42. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  43. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  44. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  45. package/src/browser/runtime.ts +11 -0
  46. package/src/browser/types.ts +19 -0
  47. package/src/browser-electron/authenticated-route.ts +56 -0
  48. package/src/browser-electron/bridge-endpoint.ts +7 -0
  49. package/src/browser-electron/bridge-install.ts +122 -0
  50. package/src/browser-electron/bridge-status.ts +22 -2
  51. package/src/browser-electron/desktop-bridge-host.ts +33 -15
  52. package/src/browser-electron/electron-provision.ts +30 -12
  53. package/src/browser-electron/entry.ts +76 -8
  54. package/src/browser-electron/host-main.ts +41 -22
  55. package/src/browser-electron/provider.ts +90 -6
  56. package/src/browser-electron/remote-host.ts +4 -4
  57. package/src/browser-electron/runtime-route.ts +3 -5
  58. package/src/browser-electron/runtime-status.ts +4 -2
  59. package/src/browser-electron/settings-route.ts +9 -32
  60. package/src/browser-electron/settings-store.ts +39 -0
  61. package/src/browser-electron/system-browser.ts +9 -3
  62. package/src/tool-browser/index.ts +991 -7
  63. package/src/tool-browser/page-probe.ts +474 -0
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Install, repair or remove the desktop bridge from the settings panel.
3
+ *
4
+ * The panel used to print a command and leave the user to copy it into a terminal. That is a defect
5
+ * for this plugin specifically: the command closes and reopens the desktop app, so a half-done manual
6
+ * run (wrong cwd, wrong node, wrong quoting on a path with spaces) leaves the shell in a state the
7
+ * user has to diagnose. The installer already knows how to do the whole dance unattended
8
+ * (`--restart --yes`), so the panel calls it and reports what happened.
9
+ *
10
+ * What this deliberately does NOT do: invent its own patching. Every path, backup and identity check
11
+ * stays inside `desktop-bridge/install.mjs`, which is the same file a human would run.
12
+ * @module dsh-browser/browser-electron/bridge-install
13
+ */
14
+ import { spawn } from 'node:child_process';
15
+ import { fileURLToPath } from 'node:url';
16
+ /**
17
+ * The argv the installer expects, in one place so the panel and a human run the same thing.
18
+ *
19
+ * `--restart --yes` is not a convenience: the shell holds `app.asar` open, so an install with the
20
+ * app running fails with EBUSY, and a prompt would block an unattended click.
21
+ * @param action - install/repair, or restore the pre-bridge state.
22
+ * @param installRoot - the desktop install directory that was discovered.
23
+ * @returns argv for the installer.
24
+ */
25
+ export function bridgeActionArgv(action, installRoot) {
26
+ const argv = [installRoot];
27
+ if (action === 'uninstall')
28
+ argv.push('--revert');
29
+ argv.push('--restart', '--yes');
30
+ return argv;
31
+ }
32
+ /** The packaged installer, resolved from this module rather than from a build-time path. */
33
+ export function defaultInstallerPath() {
34
+ return fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url));
35
+ }
36
+ /** One line from a long output: the tail is what names the failure. */
37
+ function tail(text, limit = 600) {
38
+ const trimmed = text.trim();
39
+ return trimmed.length > limit ? '…' + trimmed.slice(-limit) : trimmed;
40
+ }
41
+ /** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
42
+ function defaultRun(command, argv) {
43
+ return new Promise(resolve => {
44
+ const child = spawn(command, [...argv], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
45
+ let output = '';
46
+ const collect = (chunk) => { output += String(chunk); if (output.length > 20_000)
47
+ output = output.slice(-20_000); };
48
+ child.stdout?.on('data', collect);
49
+ child.stderr?.on('data', collect);
50
+ const timer = setTimeout(() => { try {
51
+ child.kill();
52
+ }
53
+ catch { /* already gone */ } }, 180_000);
54
+ child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }); });
55
+ child.on('exit', code => { clearTimeout(timer); resolve({ code, output }); });
56
+ });
57
+ }
58
+ /**
59
+ * Run one bridge action.
60
+ *
61
+ * Never throws for an installer failure: the panel needs the exit code and the line that explains it,
62
+ * and an exception would lose both.
63
+ * @param action - install/repair or uninstall.
64
+ * @param installRoot - the desktop install directory.
65
+ * @param deps - effects; defaulted to this process's.
66
+ * @returns the outcome, with the command line for reproduction.
67
+ */
68
+ export async function runBridgeAction(action, installRoot, deps = { run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath }) {
69
+ const command = deps.node();
70
+ const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)];
71
+ const printable = [command, ...argv].map(part => (/\s/.test(part) ? `"${part}"` : part)).join(' ');
72
+ try {
73
+ // Ask the installer to check identity FIRST, without touching anything. It is the same preflight
74
+ // a human can run, and it turns "the button did nothing" into a named reason.
75
+ const preflight = await deps.run(command, [argv[0], installRoot, '--preflight']);
76
+ const verdict = (() => {
77
+ try {
78
+ return JSON.parse(preflight.output.trim().split('\n').at(-1) ?? '{}');
79
+ }
80
+ catch {
81
+ return {};
82
+ }
83
+ })();
84
+ if (preflight.code !== 0 || verdict.ok !== true) {
85
+ return {
86
+ ok: false,
87
+ code: preflight.code,
88
+ output: tail(String(verdict.reason ?? preflight.output)),
89
+ command: printable,
90
+ };
91
+ }
92
+ const result = await deps.run(command, argv);
93
+ return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable };
94
+ }
95
+ catch (error) {
96
+ return { ok: false, code: null, output: tail(String(error)), command: printable };
97
+ }
98
+ }
@@ -35,7 +35,11 @@ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''
35
35
  if (localAppData === '')
36
36
  return undefined;
37
37
  const programs = join(localAppData, 'Programs');
38
- const isDesktop = (candidate) => readDesktopIdentity(candidate).ok;
38
+ // An archive-only layout is still a DSH Desktop install: a desktop update repacks `resources/app`
39
+ // into `resources/app.asar`, and the identity rule (which reads the unpacked main entry) then has
40
+ // nothing to read. Treating that as "no desktop here" hid the repair command exactly when it was
41
+ // needed most — measured on this machine after an update.
42
+ const isDesktop = (candidate) => readDesktopIdentity(candidate).ok || safeExists(join(candidate, 'resources', 'app.asar'));
39
43
  for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
40
44
  const candidate = join(programs, named);
41
45
  if (isDesktop(candidate))
@@ -113,11 +117,26 @@ export function readBridgeStatus(installRoot) {
113
117
  // aimed at an application that merely looked like Electron.
114
118
  const identity = readDesktopIdentity(installRoot);
115
119
  if (!identity.ok) {
120
+ // The identity rule reads the unpacked main entry. When the archive is what exists, the tree it
121
+ // wants is gone — the signature of a desktop update that restored app.asar and took the bridge
122
+ // with it. Reporting `absent` there was wrong twice over: the desktop is installed, and the
123
+ // user needs the repair command.
124
+ if (safeExists(archivePath)) {
125
+ return {
126
+ state: 'stale',
127
+ present: true,
128
+ installRoot,
129
+ archivePresent: true,
130
+ command: repairCommand(installRoot),
131
+ detail: 'the desktop is packed (resources/app.asar) and the unpacked tree the bridge lives in '
132
+ + 'is gone — most likely a desktop update restored the archive: re-run the installer to repair',
133
+ };
134
+ }
116
135
  return {
117
136
  state: 'missing',
118
137
  present: false,
119
138
  installRoot,
120
- archivePresent: safeExists(archivePath),
139
+ archivePresent: false,
121
140
  detail: `not a DSH Desktop install: ${identity.reason}`,
122
141
  };
123
142
  }
@@ -36,11 +36,11 @@ export declare function bridgeEndpointPath(): string;
36
36
  * this host retries while it renders — so reaching here means the shell did not render it at all.
37
37
  */
38
38
  export declare class BrowserPanelNotDisplayedError extends Error {
39
- readonly code = "panel-not-displayed";
39
+ readonly code: string;
40
40
  /**
41
41
  * @param detail - the bridge's own explanation, appended so the message says why.
42
42
  */
43
- constructor(detail: string);
43
+ constructor(detail: string, code?: string);
44
44
  }
45
45
  /**
46
46
  * The desktop sidebar, presented as a browser view host.
@@ -51,6 +51,7 @@ export declare class BrowserPanelNotDisplayedError extends Error {
51
51
  * point is a single page both parties can see.
52
52
  */
53
53
  export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
54
+ private readonly isQuiet;
54
55
  private readonly connection;
55
56
  /**
56
57
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
@@ -134,7 +135,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
134
135
  * caller falls back to self-hosting, which always works.
135
136
  * @returns the host, or undefined when no bridge is available.
136
137
  */
137
- static discover(sessionId?: string): Promise<DesktopBridgeViewHost | undefined>;
138
+ static discover(sessionId?: string, isQuiet?: () => boolean): Promise<DesktopBridgeViewHost | undefined>;
138
139
  /**
139
140
  * Whether the last discovery refused a bridge because its sidebar panel is an iframe.
140
141
  *
@@ -217,7 +218,9 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
217
218
  * it must not fail the navigation that has already happened.
218
219
  * @param handle - the view to bring forward.
219
220
  */
220
- showView(handle: ElectronViewHandle): void;
221
+ showView(handle: ElectronViewHandle, _label?: string, options?: {
222
+ readonly quiet?: boolean;
223
+ }): void;
221
224
  onUserAction(handler: (action: BrowserUserAction) => void): void;
222
225
  /**
223
226
  * Release the sidebar's browser pages (requirements 搂3, `ui.closeWithSession`).
@@ -42,6 +42,7 @@ export function bridgeEndpointPath() {
42
42
  * blank — losing the page the user had open.
43
43
  */
44
44
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed';
45
+ const PANEL_INITIALIZING = 'panel-initializing';
45
46
  /**
46
47
  * How many times a display-state refusal is retried, and how long each retry waits.
47
48
  *
@@ -62,16 +63,17 @@ const PANEL_DISPLAY_RETRY_MS = 400;
62
63
  * this host retries while it renders — so reaching here means the shell did not render it at all.
63
64
  */
64
65
  export class BrowserPanelNotDisplayedError extends Error {
65
- code = PANEL_NOT_DISPLAYED;
66
+ code;
66
67
  /**
67
68
  * @param detail - the bridge's own explanation, appended so the message says why.
68
69
  */
69
- constructor(detail) {
70
+ constructor(detail, code = PANEL_NOT_DISPLAYED) {
70
71
  super('dsh-builtin-browser: this conversation\'s sidebar page did not attach — the shell was asked to '
71
72
  + 'show this conversation and its panel still did not render. Nothing was lost, and the page '
72
73
  + 'appears as soon as the panel mounts. '
73
74
  + `(${detail})`);
74
75
  this.name = 'BrowserPanelNotDisplayedError';
76
+ this.code = code;
75
77
  }
76
78
  }
77
79
  /**
@@ -99,6 +101,7 @@ function isGuestGone(error) {
99
101
  * point is a single page both parties can see.
100
102
  */
101
103
  export class DesktopBridgeViewHost {
104
+ isQuiet;
102
105
  connection;
103
106
  /**
104
107
  * One entry per view this host handed out: the conversation it serves, and the guest backing it.
@@ -163,7 +166,8 @@ export class DesktopBridgeViewHost {
163
166
  /**
164
167
  * @param endpoint - the shell's published bridge endpoint.
165
168
  */
166
- constructor(endpoint, sessionId) {
169
+ constructor(endpoint, sessionId, isQuiet = () => false) {
170
+ this.isQuiet = isQuiet;
167
171
  this.owner = sessionId !== undefined && sessionId !== String.fromCharCode(39, 39) ? sessionId : randomUUID();
168
172
  // The transport reaches this only by concluding the shell stopped refreshing its endpoint, which
169
173
  // is `shell-exited`.
@@ -196,7 +200,7 @@ export class DesktopBridgeViewHost {
196
200
  * caller falls back to self-hosting, which always works.
197
201
  * @returns the host, or undefined when no bridge is available.
198
202
  */
199
- static async discover(sessionId) {
203
+ static async discover(sessionId, isQuiet) {
200
204
  let endpoint;
201
205
  try {
202
206
  const raw = JSON.parse(readFileSync(bridgeEndpointPath(), 'utf8'));
@@ -233,7 +237,7 @@ export class DesktopBridgeViewHost {
233
237
  DesktopBridgeViewHost.refuseIframe = true;
234
238
  return undefined;
235
239
  }
236
- return new DesktopBridgeViewHost(endpoint, sessionId);
240
+ return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet);
237
241
  }
238
242
  finally {
239
243
  probe.close();
@@ -342,6 +346,9 @@ export class DesktopBridgeViewHost {
342
346
  // and `createView`'s sendCommand then discards the cache and calls back in here.
343
347
  if (entry?.guest !== undefined)
344
348
  return entry.guest;
349
+ if (options?.initialize === false) {
350
+ throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING);
351
+ }
345
352
  // The conversation THIS VIEW serves — read from the view, never from the process.
346
353
  //
347
354
  // The difference is the whole bug. This host is one instance shared by every conversation, so
@@ -358,7 +365,8 @@ export class DesktopBridgeViewHost {
358
365
  // It asks the bridge what this conversation ALREADY has and never enters the retry loop below — // that loop is what asks the shell to display the conversation, which is right for a tool call
359
366
  // and wrong for "let me look at it". A page that is not on screen therefore reports as a display
360
367
  // state, and the preview route turns that into the panel's paused state.
361
- if (options?.present === false) {
368
+ const quiet = this.isQuiet();
369
+ if (options?.present === false || quiet) {
362
370
  // `list` and NOT `ensureSidebar`. This is deliberate and it is the whole fix: every version of
363
371
  // `ensureSidebar` can drive the shell — the current one asks the renderer to display the
364
372
  // conversation, and the pre-#37 one literally pressed the sidebar shortcut and typed into the
@@ -370,13 +378,16 @@ export class DesktopBridgeViewHost {
370
378
  ? listed.sidebar.filter(page => page !== null && typeof page === 'object' && page.type === 'webview')
371
379
  : [];
372
380
  const wanted = url !== undefined && url !== '' ? url : undefined;
373
- const match = wanted === undefined
374
- ? pages[0]
375
- : pages.find(page => typeof page.url === 'string' && (page.url === wanted || page.url.startsWith(wanted))) ?? pages[0];
381
+ const matchedUrl = pages.find(page => wanted !== undefined && page.url === wanted);
382
+ const match = quiet && wanted !== undefined
383
+ ? matchedUrl
384
+ : pages.find(page => wanted !== undefined && typeof page.url === 'string' && page.url.startsWith(wanted)) ?? pages[0];
376
385
  const id = match !== undefined ? Number(match.id) : Number.NaN;
377
386
  if (!Number.isFinite(id) || id <= 0) {
378
- throw new BrowserPanelNotDisplayedError('the preview asked for this conversation\'s page without presenting it, and no page is attached '
379
- + `(the shell holds ${pages.length})`);
387
+ throw new BrowserPanelNotDisplayedError(quiet
388
+ ? 'quiet mode will not open a sidebar or switch conversations; open this URL in the sidebar yourself or select the bundled browser for background work'
389
+ : 'the preview asked for this conversation\'s page without presenting it, and no page is attached '
390
+ + `(the shell holds ${pages.length})`);
380
391
  }
381
392
  this.views.set(viewId, { guest: id, owner });
382
393
  return id;
@@ -414,13 +425,16 @@ export class DesktopBridgeViewHost {
414
425
  // wording:
415
426
  // panel-not-displayed -> the shell was asked to show the conversation (client half's
416
427
  // `openSession`) and did not render it in ~1.6 s: no loss, no swap.
417
- // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
418
- // fall back, because otherwise every call fails forever.
428
+ // A missing guest within a time budget is still initialization, including on old bridges
429
+ // that only returned text. It is not evidence that this shell uses an undrivable iframe.
419
430
  const code = String(answer.code ?? '');
420
431
  const detail = String(answer.error);
421
432
  if (code === PANEL_NOT_DISPLAYED)
422
433
  throw new BrowserPanelNotDisplayedError(detail);
423
- if (detail.includes('produced no page'))
434
+ if (code === PANEL_INITIALIZING || (code === '' && detail.includes('produced no page'))) {
435
+ throw new BrowserPanelNotDisplayedError(detail, PANEL_INITIALIZING);
436
+ }
437
+ if (code === 'panel-unusable')
424
438
  this.reportLost('panel-unusable');
425
439
  throw new Error(`dsh-builtin-browser: sidebar unavailable (${detail})`);
426
440
  }
@@ -499,7 +513,14 @@ export class DesktopBridgeViewHost {
499
513
  * it must not fail the navigation that has already happened.
500
514
  * @param handle - the view to bring forward.
501
515
  */
502
- showView(handle) {
516
+ showView(handle, _label, options) {
517
+ // Quiet mode (`ui.quiet`) means "do not take my screen". On this carrier showing a page means
518
+ // asking the shell to switch the displayed conversation — precisely the takeover the switch
519
+ // forbids. So honour it by asking for nothing: a page that is already displayed keeps working,
520
+ // and one that is not fails with the documented display-state error instead of moving the
521
+ // user's view. Measured before this: the setting was on and every call still switched.
522
+ if (options?.quiet === true)
523
+ return;
503
524
  // `owner` is required: the bridge refuses to bring forward a guest held by another session.
504
525
  // It comes from the view, not the process — with several conversations live, a process-wide
505
526
  // owner would raise the wrong conversation's tab.
@@ -38,7 +38,7 @@ export interface ProvisionDeps {
38
38
  /** The installed electron package's own installer script, or undefined when it is not there. */
39
39
  readonly installerScript: () => string | undefined;
40
40
  /** Runs the installer; resolves to an exit code, or rejects/returns null on failure. */
41
- readonly run: (script: string) => Promise<{
41
+ readonly run: (script: string, signal?: AbortSignal) => Promise<{
42
42
  code: number | null;
43
43
  detail?: string;
44
44
  }>;
@@ -102,21 +102,37 @@ function electronVersion() {
102
102
  return 'unknown';
103
103
  }
104
104
  }
105
+ let runningInstaller;
105
106
  /** The real dependencies: this process's spawn, fs and logger. */
106
107
  export function defaultDeps(log = () => { }) {
107
108
  return {
108
109
  hasBinary: hasElectronRuntime,
109
110
  installerScript: electronInstallerScript,
110
- run: async (script) => {
111
- const child = spawn(process.execPath, [script], {
112
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
113
- stdio: ['ignore', 'ignore', 'ignore'],
114
- windowsHide: true,
115
- });
116
- return await new Promise(resolve => {
117
- child.once('error', error => resolve({ code: null, detail: String(error) }));
118
- child.once('close', code => resolve({ code, detail: undefined }));
111
+ run: (script, signal) => {
112
+ if (runningInstaller !== undefined)
113
+ return runningInstaller;
114
+ const run = new Promise(resolve => {
115
+ const child = spawn(process.execPath, [script], {
116
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
117
+ stdio: ['ignore', 'ignore', 'ignore'],
118
+ windowsHide: true,
119
+ });
120
+ let failure;
121
+ const abort = () => { child.kill('SIGKILL'); };
122
+ signal?.addEventListener('abort', abort, { once: true });
123
+ if (signal?.aborted)
124
+ abort();
125
+ child.once('error', error => { failure = String(error); });
126
+ child.once('close', code => {
127
+ signal?.removeEventListener('abort', abort);
128
+ resolve({ code, detail: failure });
129
+ });
119
130
  });
131
+ runningInstaller = run;
132
+ const clear = () => { if (runningInstaller === run)
133
+ runningInstaller = undefined; };
134
+ void run.then(clear, clear);
135
+ return run;
120
136
  },
121
137
  log,
122
138
  skip: () => typeof process.env.ELECTRON_SKIP_BINARY_DOWNLOAD === 'string'
@@ -155,12 +171,16 @@ export async function ensureElectronRuntime(deps = defaultDeps()) {
155
171
  // this path failed with "Promise resolution is still pending but the event loop has already
156
172
  // resolved". Keep it referenced, and clear it so a success does not leave a 180 s handle behind.
157
173
  let timer;
174
+ const controller = new AbortController();
158
175
  const timeout = new Promise(resolve => {
159
- timer = setTimeout(() => resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` }), deps.timeoutMs);
176
+ timer = setTimeout(() => {
177
+ controller.abort();
178
+ resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` });
179
+ }, deps.timeoutMs);
160
180
  });
161
181
  let outcome;
162
182
  try {
163
- outcome = await Promise.race([deps.run(script), timeout]);
183
+ outcome = await Promise.race([deps.run(script, controller.signal), timeout]);
164
184
  }
165
185
  catch (error) {
166
186
  return record({ status: 'failed', detail: `the download failed: ${String(error)}` });
@@ -24,9 +24,12 @@ import { claimEphemeralProfile, ephemeralProfileName, sweepAbandonedEphemeralPro
24
24
  import { MissingSystemBrowserHost } from './missing-system-browser.js';
25
25
  import { SettingsStore, settingsPath } from './settings-store.js';
26
26
  import { sameOrigin } from './settings-route.js';
27
+ import { authenticatedRoute, isDirectLoopback } from './authenticated-route.js';
27
28
  import { handleBridgeStatus, handlePreviewFrame, handlePreviewSessions, BRIDGE_STATUS_ROUTE, PREVIEW_ROUTE, PREVIEW_SESSIONS_ROUTE } from './preview-route.js';
28
29
  import { findDesktopInstall, readBridgeStatus } from './bridge-status.js';
29
30
  import { readBridgeEndpoint } from './bridge-endpoint.js';
31
+ import { runBridgeAction } from './bridge-install.js';
32
+ import { replyJson } from './json-reply.js';
30
33
  import { readRuntimeStatus } from './runtime-status.js';
31
34
  import { handleRuntimeProvision, handleRuntimeStatus, RUNTIME_PROVISION_ROUTE, RUNTIME_STATUS_ROUTE } from './runtime-route.js';
32
35
  export { ELECTRON_BROWSER_PROVIDER_ID, ElectronBrowserProvider, } from './provider.js';
@@ -348,7 +351,7 @@ export function apply(ctx, config) {
348
351
  }
349
352
  // The headless mode rides along so a display-less host (systemd, container, SSH-only server)
350
353
  // still gets a working browser instead of "exited immediately after launch" — issue #32.
351
- adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir, undefined, settings.get().browser.headless), `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`);
354
+ adopt(new SystemBrowserViewHost(detected, profileDir, [], persist ? undefined : profileDir, undefined, settings.get().browser.headless, () => settings.get().ui.quiet), `will drive the installed ${detected.kind} (${detected.path}${persist ? '' : ', ephemeral profile'})`);
352
355
  }
353
356
  }
354
357
  else if (adoptedCarrier !== undefined) {
@@ -384,7 +387,7 @@ export function apply(ctx, config) {
384
387
  return;
385
388
  let sidebar;
386
389
  try {
387
- sidebar = await DesktopBridgeViewHost.discover(sessionId);
390
+ sidebar = await DesktopBridgeViewHost.discover(sessionId, () => settings.get().ui.quiet);
388
391
  }
389
392
  catch {
390
393
  sidebar = undefined; // discovery is documented not to throw; never let it stop the retries
@@ -451,13 +454,13 @@ export function apply(ctx, config) {
451
454
  host.effect(() => host.webServer.register({
452
455
  kind: 'exact',
453
456
  path: PREVIEW_ROUTE,
454
- handler: (request, response) => handlePreviewFrame(request, response, settings, browser),
457
+ handler: authenticated(ctx, (request, response) => handlePreviewFrame(request, response, settings, browser)),
455
458
  }, 'dsh-builtin-browser: live view frame'));
456
459
  // The list the panel needs before it can build a frame URL at all: session ids only.
457
460
  host.effect(() => host.webServer.register({
458
461
  kind: 'exact',
459
462
  path: PREVIEW_SESSIONS_ROUTE,
460
- handler: (request, response) => handlePreviewSessions(request, response, settings, browser),
463
+ handler: authenticated(ctx, (request, response) => handlePreviewSessions(request, response, settings, browser)),
461
464
  }, 'dsh-builtin-browser: live view sessions'));
462
465
  });
463
466
  }
@@ -473,6 +476,65 @@ export function apply(ctx, config) {
473
476
  * exactly like the other two.
474
477
  * @param ctx - the plugin context.
475
478
  */
479
+ /** Where the panel asks to install or remove the bridge. */
480
+ const BRIDGE_ACTION_ROUTE = '/dsh-builtin-browser/bridge-action';
481
+ let bridgeActionRunning = false;
482
+ /**
483
+ * Install, repair or remove the bridge, from a button.
484
+ *
485
+ * The panel used to print a command. This step closes and reopens the desktop app, so a
486
+ * half-finished manual run leaves the shell in a state the user then has to diagnose — the
487
+ * packaged installer already handles the whole sequence unattended, and this hands it the one
488
+ * decision that is not its own: which action the user pressed.
489
+ * @param request - the incoming request (POST, JSON body `{action}`).
490
+ * @param response - the response to write.
491
+ */
492
+ async function handleBridgeAction(request, response) {
493
+ if (request.method !== 'POST') {
494
+ replyJson(response, 405, { error: 'method-not-allowed' });
495
+ return;
496
+ }
497
+ // A write: it stops the shell. Same admission as a settings write, not the read rule.
498
+ if (!sameOrigin(request, true)) {
499
+ replyJson(response, 403, { error: 'not-same-origin' });
500
+ return;
501
+ }
502
+ if (!isDirectLoopback(request)) {
503
+ replyJson(response, 403, { error: 'local-request-required' });
504
+ return;
505
+ }
506
+ let action;
507
+ try {
508
+ const body = await readBody(request);
509
+ action = JSON.parse(body === '' ? '{}' : body).action;
510
+ }
511
+ catch (error) {
512
+ replyJson(response, 400, { ok: false, error: `unreadable body: ${String(error)}` });
513
+ return;
514
+ }
515
+ if (action !== 'install' && action !== 'uninstall') {
516
+ replyJson(response, 400, { ok: false, error: 'action must be "install" or "uninstall"' });
517
+ return;
518
+ }
519
+ const root = findDesktopInstall();
520
+ if (root === undefined) {
521
+ // Nothing to patch: say so instead of running an installer against a guess.
522
+ replyJson(response, 409, { ok: false, error: 'no DSH Desktop install was found on this machine' });
523
+ return;
524
+ }
525
+ if (bridgeActionRunning) {
526
+ replyJson(response, 409, { ok: false, error: 'bridge-action-in-progress' });
527
+ return;
528
+ }
529
+ bridgeActionRunning = true;
530
+ try {
531
+ const result = await runBridgeAction(action, root);
532
+ replyJson(response, 200, { ok: result.ok, action, code: result.code, output: result.output, command: result.command });
533
+ }
534
+ finally {
535
+ bridgeActionRunning = false;
536
+ }
537
+ }
476
538
  function installBridgeStatusRoute(ctx) {
477
539
  const injectStatus = ctx.inject;
478
540
  if (typeof injectStatus !== 'function')
@@ -482,8 +544,15 @@ export function apply(ctx, config) {
482
544
  host.effect(() => host.webServer.register({
483
545
  kind: 'exact',
484
546
  path: BRIDGE_STATUS_ROUTE,
485
- handler: (request, response) => handleBridgeStatus(request, response),
547
+ handler: authenticated(ctx, (request, response) => handleBridgeStatus(request, response)),
486
548
  }, 'dsh-builtin-browser: bridge status'));
549
+ // The same information, one action later: install/repair or remove the bridge without the
550
+ // user opening a terminal. Admitted as a write, because it closes and restarts the shell.
551
+ host.effect(() => host.webServer.register({
552
+ kind: 'exact',
553
+ path: BRIDGE_ACTION_ROUTE,
554
+ handler: authenticated(ctx, (request, response) => handleBridgeAction(request, response)),
555
+ }, 'dsh-builtin-browser: bridge action'));
487
556
  });
488
557
  }
489
558
  catch {
@@ -534,12 +603,12 @@ export function apply(ctx, config) {
534
603
  host.effect(() => host.webServer.register({
535
604
  kind: 'exact',
536
605
  path: RUNTIME_STATUS_ROUTE,
537
- handler: (request, response) => handleRuntimeStatus(request, response, deps),
606
+ handler: authenticated(ctx, (request, response) => handleRuntimeStatus(request, response, deps)),
538
607
  }, 'dsh-builtin-browser: runtime status'));
539
608
  host.effect(() => host.webServer.register({
540
609
  kind: 'exact',
541
610
  path: RUNTIME_PROVISION_ROUTE,
542
- handler: (request, response) => handleRuntimeProvision(request, response, deps),
611
+ handler: authenticated(ctx, (request, response) => handleRuntimeProvision(request, response, deps)),
543
612
  }, 'dsh-builtin-browser: runtime provision'));
544
613
  });
545
614
  }
@@ -642,6 +711,13 @@ export function adoptLegacyProfileRoot(profileRoot, legacyRoot = join(homedir(),
642
711
  // Nothing here is worth failing an apply over; the fallback is the pre-existing behaviour.
643
712
  }
644
713
  }
714
+ /** Bind the host's signed browser-session authentication to a plugin route. */
715
+ function authenticated(ctx, handler) {
716
+ return authenticatedRoute(() => {
717
+ const surface = ctx;
718
+ return surface.get('connection');
719
+ }, handler);
720
+ }
645
721
  /**
646
722
  * Expose the settings document over the host's web server, which is how the
647
723
  * settings panel reads and writes it. A host without that service (headless /
@@ -659,7 +735,7 @@ function installSettingsRoute(ctx, settings, onChannelChange) {
659
735
  host.effect(() => host.webServer.register({
660
736
  kind: 'exact',
661
737
  path: SETTINGS_ROUTE,
662
- handler: (request, response) => handleSettingsRequest(request, response, settings, onChannelChange),
738
+ handler: authenticated(ctx, (request, response) => handleSettingsRequest(request, response, settings, onChannelChange)),
663
739
  }, 'dsh-builtin-browser: settings'));
664
740
  });
665
741
  }