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,23 @@
1
+ # Batching with dsh_browser_do
2
+
3
+ One call, one result, and it stops at the first step that cannot proceed:
4
+
5
+ ```json
6
+ {"steps": [
7
+ {"open": "https://example.com/search"},
8
+ {"field": {"target": {"by": "css", "value": "#q"}, "text": "invoice"}},
9
+ {"key": "Enter"},
10
+ {"wait_idle": {}},
11
+ {"check": {"text": "3 results"}}
12
+ ]}
13
+ ```
14
+
15
+ Rules that keep a batch honest:
16
+
17
+ - Give each step exactly one key; anything else is refused before the first action runs.
18
+ - Put a `check` after the steps that change server state — the batch then fails at the step where
19
+ the outcome was already wrong, not three steps later.
20
+ - `wait_idle` waits for in-flight requests to drain and the page to go quiet for 300 ms; use it
21
+ instead of `sleep_ms` unless the page genuinely needs wall-clock time.
22
+ - A failed batch reports `stoppedAt`, `completed` and a per-step log, so re-running only the
23
+ remainder is a deliberate choice, and it starts with a fresh `state`.
@@ -0,0 +1,31 @@
1
+ # Delivering a file somewhere else
2
+
3
+ The browser's job ends with a file on disk. Sending it to Feishu (Lark) drive, Baidu Netdisk or any
4
+ other storage is a separate capability the user connects as an MCP server — both platforms ship an
5
+ official one (`lark_drive_upload`, `baidu-netdisk/mcp`'s upload tool). The plugin does not hold
6
+ their credentials and should not.
7
+
8
+ ## The path
9
+
10
+ 1. `dsh_browser_download` saves the URL through the directory admission gate and returns an
11
+ **absolute path**. It never overwrites an existing file; if the name is taken, ask for another.
12
+ 2. Hand that exact path to the upload tool the user connected, e.g.
13
+ `lark_drive_upload({ file_path: "<returned path>", folder_token: "<the user's folder>" })`.
14
+ 3. Report both facts: where the file now sits locally, and what the upload tool answered.
15
+
16
+ ## Rules
17
+
18
+ - **Never** report "saved to Feishu" from the download alone. The download proves a local file; only
19
+ the upload tool's reply proves the remote copy.
20
+ - If the upload tool fails or is not connected, say so plainly and leave the local path — the file
21
+ is still usable and the human can move it by hand. Do not silently retry somewhere else.
22
+ - A folder id / token belongs to the user's workspace: ask for it, or read it from the tool's own
23
+ documentation, instead of guessing a default.
24
+ - Before uploading something sensitive (an invoice, a screenshot with an account name), say what is
25
+ about to leave the machine.
26
+
27
+ ## When the user wants this to happen automatically
28
+
29
+ A per-call handoff (`dsh_browser_download` with a `handoff` argument) and a settings field for the
30
+ default tool are planned; until they exist, the two-step form above is the supported path and it
31
+ keeps the human in control of where their files go.
@@ -0,0 +1,11 @@
1
+ # Locating things
2
+
3
+ - Prefer roles and names (`dsh_browser_a11y`) over CSS when the page is a normal app: a label
4
+ survives a re-render, a generated class does not.
5
+ - `dsh_browser_snapshot` numbers every interactive element and appends `{#id}` / `{[name=x]}`
6
+ when it can derive one — copy that straight into `{by:"css", value:"#id"}`.
7
+ - Text targets match the element's own visible text or aria-label; if two match, pass `index`.
8
+ - `dsh_browser_find` searches the page text and returns viewport points — use it to find a table
9
+ row or a sentence, then click at the point or scroll the element into view.
10
+ - An element inside an iframe or shadow root is reachable, but only when same-origin; a
11
+ cross-origin frame is a wall — report it instead of guessing coordinates at random.
@@ -0,0 +1,11 @@
1
+ # Recovering
2
+
3
+ - Page stuck or a script half-applied: `dsh_browser_refresh`.
4
+ - Session wedged after a carrier loss: `dsh_browser_reset_session` (this task only), then re-open
5
+ and re-read the page. A lost carrier means the page context is gone — nothing you knew about it
6
+ still holds.
7
+ - A call fails with a reason you cannot place: `dsh_browser_doctor` (session, page state, probe
8
+ buffers, which tools this task restricted away), then `dsh_browser_help` for the topic.
9
+ - Everything is refused with "restricted": the task restricted its own tools. `dsh_browser_restrict`
10
+ with the needed names lifts it; observation tools are never blocked.
11
+ - Do not retry a state-changing call blindly after an error. Read first, decide second.
@@ -0,0 +1,13 @@
1
+ # Verifying
2
+
3
+ | Question | Tool |
4
+ | --- | --- |
5
+ | Is the element there / the text there / the URL changed? | `dsh_browser_assert` |
6
+ | Did a request reach the server? | `dsh_browser_wait_for_response` |
7
+ | What did the page log or fetch? | `dsh_browser_console`, `dsh_browser_network` |
8
+ | Did a field take the value? | `dsh_browser_get_value` |
9
+
10
+ A submit is the dangerous case. After clicking submit: wait for the response, assert the visible
11
+ outcome, and if the call died before either answer arrived, **read the site's own record** (the
12
+ list page, the order history) before acting again. "Result unknown" is an acceptable answer to
13
+ report; a second submit is not.
@@ -7,6 +7,7 @@
7
7
  * @module dsh-browser/browser
8
8
  */
9
9
 
10
+ import { pageOperationScript } from '../tool-browser/page-probe.js'
10
11
  import { Context, Service } from '@deepseek-ai/cordis'
11
12
  import z from '@deepseek-ai/schemastery'
12
13
  import type {
@@ -22,6 +23,7 @@ import type {
22
23
  BrowserDownloadRequest,
23
24
  BrowserElementTarget,
24
25
  BrowserExecuteRequest,
26
+ BrowserPageOperationRequest,
25
27
  BrowserExecuteResult,
26
28
  BrowserFillRequest,
27
29
  BrowserFillResult,
@@ -247,6 +249,15 @@ export class BrowserRuntime extends Service {
247
249
  return this.resolveProvider().execute(session, request, signal)
248
250
  }
249
251
 
252
+ /** Execute one provider-owned page operation with validated operation names. */
253
+ async pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
254
+ const provider = this.resolveProvider()
255
+ // Legacy providers retain their execute permission checks.
256
+ return provider.pageOperation
257
+ ? provider.pageOperation(session, request, signal)
258
+ : provider.execute(session, { script: pageOperationScript(request) }, signal)
259
+ }
260
+
250
261
  /** Wait until the session's page is ready (and optional URL/selector match). */
251
262
  async waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult> {
252
263
  return this.resolveProvider().waitFor(session, request, signal)
@@ -359,6 +359,22 @@ export interface BrowserExecuteRequest {
359
359
  readonly timeoutMs?: number
360
360
  }
361
361
 
362
+ /**
363
+ * Fixed page operations implemented by the provider. Strings are serialized as data.
364
+ * Arbitrary JavaScript is handled only by BrowserExecuteRequest.
365
+ */
366
+ export type BrowserPageOperationRequest =
367
+ | { readonly operation: 'install' }
368
+ | { readonly operation: 'probe'; readonly method: BrowserProbeMethod; readonly args?: readonly unknown[] }
369
+ | { readonly operation: 'text'; readonly text: string }
370
+ | { readonly operation: 'url' }
371
+ | { readonly operation: 'drag'; readonly from: { x: number; y: number }; readonly to: { x: number; y: number }; readonly steps: number }
372
+ | { readonly operation: 'upload'; readonly target: { by: 'css' | 'text' | 'xpath'; value: string }; readonly file: { name: string; mime: string; base64: string } }
373
+
374
+ /** Provider-owned probe operations; JavaScript properties such as constructor are excluded. */
375
+ export type BrowserProbeMethod = 'read' | 'clear' | 'settle' | 'find' | 'overlayAt' | 'summary'
376
+ | 'findText' | 'hoverAt' | 'setDialogPolicy' | 'dialogStatus' | 'networkCursor'
377
+
362
378
  /**
363
379
  * Result of an execute. Mirrors CDP `Runtime.evaluate` semantics: either a
364
380
  * value (by value, not by reference) or the exception thrown.
@@ -632,6 +648,9 @@ export interface BrowserProvider {
632
648
  navigate(session: BrowserSessionId, request: BrowserNavigateRequest, signal?: AbortSignal): Promise<void>
633
649
  /** Execute JS in the active tab's page context. */
634
650
  execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>
651
+
652
+ /** Execute one fixed browser operation without granting arbitrary page scripting. */
653
+ pageOperation?(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>
635
654
  /** Wait until the page is ready (and optional URL/selector match). Honor `signal` for cancellation. */
636
655
  waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult>
637
656
  /** Produce an AI-friendly snapshot of the active tab. */
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Authenticate plugin HTTP routes with the browser session owned by DSH.
3
+ * The connection service verifies its signed cookie and completes denied responses.
4
+ * @module dsh-browser/browser-electron/authenticated-route
5
+ */
6
+ import type { IncomingMessage, ServerResponse } from 'node:http'
7
+ import { replyJson } from './json-reply.js'
8
+
9
+ /** The host authentication method shared with its application and inspector routes. */
10
+ export interface BrowserConnection {
11
+ authorizeIndex(request: IncomingMessage, response: ServerResponse): boolean
12
+ }
13
+
14
+ /** An exact HTTP route registered with the DSH web server. */
15
+ export type BrowserHttpHandler = (request: IncomingMessage, response: ServerResponse) => void | Promise<void>
16
+
17
+ /**
18
+ * Check the current host credential on every request before reading settings, capturing a frame,
19
+ * or starting a write. Origin checks remain inside the handler as an additional browser boundary.
20
+ * @param connection - resolves the host's current connection service.
21
+ * @param handler - the operation to run after authentication.
22
+ * @returns an authenticated route handler.
23
+ */
24
+ export function authenticatedRoute(
25
+ connection: () => BrowserConnection | undefined,
26
+ handler: BrowserHttpHandler,
27
+ ): BrowserHttpHandler {
28
+ return (request, response) => {
29
+ let host: BrowserConnection | undefined
30
+ try {
31
+ host = connection()
32
+ } catch {
33
+ // A disposed host cannot authorize new work.
34
+ }
35
+ if (typeof host?.authorizeIndex !== 'function') {
36
+ replyJson(response, 503, { error: 'browser-auth-unavailable' })
37
+ return
38
+ }
39
+ // A false result owns the response. Preserving it also preserves host-specific login behavior.
40
+ if (!host.authorizeIndex(request, response)) return
41
+ return handler(request, response)
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Admit machine-wide installation changes from a direct loopback connection.
47
+ * Forwarded requests belong to their remote operator even when the last hop is loopback.
48
+ * @param request - request received by the host.
49
+ * @returns true for direct loopback requests.
50
+ */
51
+ export function isDirectLoopback(request: IncomingMessage): boolean {
52
+ const address = request.socket.remoteAddress
53
+ const local = address === '::1' || address === '127.0.0.1' || address === '::ffff:127.0.0.1'
54
+ return local && !['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-real-ip']
55
+ .some(name => request.headers[name] !== undefined)
56
+ }
@@ -78,6 +78,13 @@ export function readBridgeEndpoint(
78
78
  let raw: { port?: unknown; token?: unknown; pid?: unknown; updatedAt?: unknown }
79
79
  try {
80
80
  raw = JSON.parse(readFileSync(path, 'utf8')) as typeof raw
81
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
82
+ || !Number.isInteger(raw.port) || Number(raw.port) < 1 || Number(raw.port) > 65535
83
+ || typeof raw.token !== 'string' || raw.token.trim() === ''
84
+ || !Number.isSafeInteger(raw.pid) || Number(raw.pid) <= 0
85
+ || (raw.updatedAt !== undefined && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt))))) {
86
+ throw new Error('expected a port, a nonempty token, a positive pid and an optional timestamp')
87
+ }
81
88
  } catch (error) {
82
89
  return {
83
90
  present: true,
@@ -0,0 +1,122 @@
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
+ /** What the panel may ask for. */
18
+ export type BridgeAction = 'install' | 'uninstall'
19
+
20
+ /** Everything this module touches from outside, so a test can drive it without spawning. */
21
+ export interface BridgeActionDeps {
22
+ /** Runs the installer; resolves with an exit code and the tail of its output. */
23
+ readonly run: (command: string, argv: readonly string[]) => Promise<{ readonly code: number | null; readonly output: string }>
24
+ /** Absolute path of the packaged installer. */
25
+ readonly installer: () => string
26
+ /** Node executable used to run it (the host's own, so no PATH surprises). */
27
+ readonly node: () => string
28
+ }
29
+
30
+ /** What the panel is told. */
31
+ export interface BridgeActionResult {
32
+ /** Whether the installer exited 0. */
33
+ readonly ok: boolean
34
+ /** Its exit code, or null when it was killed. */
35
+ readonly code: number | null
36
+ /** The tail of its output, for the one line the panel shows. */
37
+ readonly output: string
38
+ /** The exact command line, so a failure can be reproduced by hand. */
39
+ readonly command: string
40
+ }
41
+
42
+ /**
43
+ * The argv the installer expects, in one place so the panel and a human run the same thing.
44
+ *
45
+ * `--restart --yes` is not a convenience: the shell holds `app.asar` open, so an install with the
46
+ * app running fails with EBUSY, and a prompt would block an unattended click.
47
+ * @param action - install/repair, or restore the pre-bridge state.
48
+ * @param installRoot - the desktop install directory that was discovered.
49
+ * @returns argv for the installer.
50
+ */
51
+ export function bridgeActionArgv(action: BridgeAction, installRoot: string): string[] {
52
+ const argv = [installRoot]
53
+ if (action === 'uninstall') argv.push('--revert')
54
+ argv.push('--restart', '--yes')
55
+ return argv
56
+ }
57
+
58
+ /** The packaged installer, resolved from this module rather than from a build-time path. */
59
+ export function defaultInstallerPath(): string {
60
+ return fileURLToPath(new URL('../../desktop-bridge/install.mjs', import.meta.url))
61
+ }
62
+
63
+ /** One line from a long output: the tail is what names the failure. */
64
+ function tail(text: string, limit = 600): string {
65
+ const trimmed = text.trim()
66
+ return trimmed.length > limit ? '…' + trimmed.slice(-limit) : trimmed
67
+ }
68
+
69
+ /** Default runner: the host's own node, a bounded wait, and no shell (so a path with spaces is data). */
70
+ function defaultRun(command: string, argv: readonly string[]): Promise<{ code: number | null; output: string }> {
71
+ return new Promise(resolve => {
72
+ const child = spawn(command, [...argv], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
73
+ let output = ''
74
+ const collect = (chunk: unknown): void => { output += String(chunk); if (output.length > 20_000) output = output.slice(-20_000) }
75
+ child.stdout?.on('data', collect)
76
+ child.stderr?.on('data', collect)
77
+ const timer = setTimeout(() => { try { child.kill() } catch { /* already gone */ } }, 180_000)
78
+ child.on('error', error => { clearTimeout(timer); resolve({ code: null, output: `${output}\nfailed to start: ${String(error)}` }) })
79
+ child.on('exit', code => { clearTimeout(timer); resolve({ code, output }) })
80
+ })
81
+ }
82
+
83
+ /**
84
+ * Run one bridge action.
85
+ *
86
+ * Never throws for an installer failure: the panel needs the exit code and the line that explains it,
87
+ * and an exception would lose both.
88
+ * @param action - install/repair or uninstall.
89
+ * @param installRoot - the desktop install directory.
90
+ * @param deps - effects; defaulted to this process's.
91
+ * @returns the outcome, with the command line for reproduction.
92
+ */
93
+ export async function runBridgeAction(
94
+ action: BridgeAction,
95
+ installRoot: string,
96
+ deps: BridgeActionDeps = { run: defaultRun, installer: defaultInstallerPath, node: () => process.execPath },
97
+ ): Promise<BridgeActionResult> {
98
+ const command = deps.node()
99
+ const argv = [deps.installer(), ...bridgeActionArgv(action, installRoot)]
100
+ const printable = [command, ...argv].map(part => (/\s/.test(part) ? `"${part}"` : part)).join(' ')
101
+ try {
102
+ // Ask the installer to check identity FIRST, without touching anything. It is the same preflight
103
+ // a human can run, and it turns "the button did nothing" into a named reason.
104
+ const preflight = await deps.run(command, [argv[0] as string, installRoot, '--preflight'])
105
+ const verdict = (() => {
106
+ try { return JSON.parse(preflight.output.trim().split('\n').at(-1) ?? '{}') as { ok?: boolean; reason?: string } }
107
+ catch { return {} as { ok?: boolean; reason?: string } }
108
+ })()
109
+ if (preflight.code !== 0 || verdict.ok !== true) {
110
+ return {
111
+ ok: false,
112
+ code: preflight.code,
113
+ output: tail(String(verdict.reason ?? preflight.output)),
114
+ command: printable,
115
+ }
116
+ }
117
+ const result = await deps.run(command, argv)
118
+ return { ok: result.code === 0, code: result.code, output: tail(result.output), command: printable }
119
+ } catch (error) {
120
+ return { ok: false, code: null, output: tail(String(error)), command: printable }
121
+ }
122
+ }
@@ -36,7 +36,12 @@ import { readDesktopIdentity } from './desktop-identity.js'
36
36
  export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''): string | undefined {
37
37
  if (localAppData === '') return undefined
38
38
  const programs = join(localAppData, 'Programs')
39
- const isDesktop = (candidate: string): boolean => readDesktopIdentity(candidate).ok
39
+ // An archive-only layout is still a DSH Desktop install: a desktop update repacks `resources/app`
40
+ // into `resources/app.asar`, and the identity rule (which reads the unpacked main entry) then has
41
+ // nothing to read. Treating that as "no desktop here" hid the repair command exactly when it was
42
+ // needed most — measured on this machine after an update.
43
+ const isDesktop = (candidate: string): boolean =>
44
+ readDesktopIdentity(candidate).ok || safeExists(join(candidate, 'resources', 'app.asar'))
40
45
  for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
41
46
  const candidate = join(programs, named)
42
47
  if (isDesktop(candidate)) return candidate
@@ -136,11 +141,26 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
136
141
  // aimed at an application that merely looked like Electron.
137
142
  const identity = readDesktopIdentity(installRoot)
138
143
  if (!identity.ok) {
144
+ // The identity rule reads the unpacked main entry. When the archive is what exists, the tree it
145
+ // wants is gone — the signature of a desktop update that restored app.asar and took the bridge
146
+ // with it. Reporting `absent` there was wrong twice over: the desktop is installed, and the
147
+ // user needs the repair command.
148
+ if (safeExists(archivePath)) {
149
+ return {
150
+ state: 'stale',
151
+ present: true,
152
+ installRoot,
153
+ archivePresent: true,
154
+ command: repairCommand(installRoot),
155
+ detail: 'the desktop is packed (resources/app.asar) and the unpacked tree the bridge lives in '
156
+ + 'is gone — most likely a desktop update restored the archive: re-run the installer to repair',
157
+ }
158
+ }
139
159
  return {
140
160
  state: 'missing',
141
161
  present: false,
142
162
  installRoot,
143
- archivePresent: safeExists(archivePath),
163
+ archivePresent: false,
144
164
  detail: `not a DSH Desktop install: ${identity.reason}`,
145
165
  }
146
166
  }
@@ -49,6 +49,7 @@ export function bridgeEndpointPath(): string {
49
49
  * blank — losing the page the user had open.
50
50
  */
51
51
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
52
+ const PANEL_INITIALIZING = 'panel-initializing'
52
53
 
53
54
  /**
54
55
  * How many times a display-state refusal is retried, and how long each retry waits.
@@ -71,12 +72,12 @@ const PANEL_DISPLAY_RETRY_MS = 400
71
72
  * this host retries while it renders — so reaching here means the shell did not render it at all.
72
73
  */
73
74
  export class BrowserPanelNotDisplayedError extends Error {
74
- readonly code = PANEL_NOT_DISPLAYED
75
+ readonly code: string
75
76
 
76
77
  /**
77
78
  * @param detail - the bridge's own explanation, appended so the message says why.
78
79
  */
79
- constructor(detail: string) {
80
+ constructor(detail: string, code = PANEL_NOT_DISPLAYED) {
80
81
  super(
81
82
  'dsh-builtin-browser: this conversation\'s sidebar page did not attach — the shell was asked to '
82
83
  + 'show this conversation and its panel still did not render. Nothing was lost, and the page '
@@ -84,6 +85,7 @@ export class BrowserPanelNotDisplayedError extends Error {
84
85
  + `(${detail})`,
85
86
  )
86
87
  this.name = 'BrowserPanelNotDisplayedError'
88
+ this.code = code
87
89
  }
88
90
  }
89
91
 
@@ -177,7 +179,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
177
179
  /**
178
180
  * @param endpoint - the shell's published bridge endpoint.
179
181
  */
180
- private constructor(endpoint: BridgeEndpoint, sessionId?: string) {
182
+ private constructor(endpoint: BridgeEndpoint, sessionId?: string, private readonly isQuiet: () => boolean = () => false) {
181
183
  this.owner = sessionId !== undefined && sessionId !== String.fromCharCode(39,39) ? sessionId : randomUUID()
182
184
  // The transport reaches this only by concluding the shell stopped refreshing its endpoint, which
183
185
  // is `shell-exited`.
@@ -212,7 +214,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
212
214
  * caller falls back to self-hosting, which always works.
213
215
  * @returns the host, or undefined when no bridge is available.
214
216
  */
215
- static async discover(sessionId?: string): Promise<DesktopBridgeViewHost | undefined> {
217
+ static async discover(sessionId?: string, isQuiet?: () => boolean): Promise<DesktopBridgeViewHost | undefined> {
216
218
  let endpoint: BridgeEndpoint
217
219
  try {
218
220
  const raw = JSON.parse(readFileSync(bridgeEndpointPath(), 'utf8')) as Partial<BridgeEndpoint>
@@ -246,7 +248,7 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
246
248
  DesktopBridgeViewHost.refuseIframe = true
247
249
  return undefined
248
250
  }
249
- return new DesktopBridgeViewHost(endpoint, sessionId)
251
+ return new DesktopBridgeViewHost(endpoint, sessionId, isQuiet)
250
252
  } finally {
251
253
  probe.close()
252
254
  }
@@ -356,6 +358,9 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
356
358
  // command. A guest that has gone away is detected by the command itself failing,
357
359
  // and `createView`'s sendCommand then discards the cache and calls back in here.
358
360
  if (entry?.guest !== undefined) return entry.guest
361
+ if (options?.initialize === false) {
362
+ throw new BrowserPanelNotDisplayedError('this view has no attached guest yet', PANEL_INITIALIZING)
363
+ }
359
364
 
360
365
  // The conversation THIS VIEW serves — read from the view, never from the process.
361
366
  //
@@ -373,7 +378,8 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
373
378
  // 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
374
379
  // and wrong for "let me look at it". A page that is not on screen therefore reports as a display
375
380
  // state, and the preview route turns that into the panel's paused state.
376
- if (options?.present === false) {
381
+ const quiet = this.isQuiet()
382
+ if (options?.present === false || quiet) {
377
383
  // `list` and NOT `ensureSidebar`. This is deliberate and it is the whole fix: every version of
378
384
  // `ensureSidebar` can drive the shell — the current one asks the renderer to display the
379
385
  // conversation, and the pre-#37 one literally pressed the sidebar shortcut and typed into the
@@ -385,14 +391,17 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
385
391
  ? listed.sidebar.filter(page => page !== null && typeof page === 'object' && page.type === 'webview')
386
392
  : []
387
393
  const wanted = url !== undefined && url !== '' ? url : undefined
388
- const match = wanted === undefined
389
- ? pages[0]
390
- : pages.find(page => typeof page.url === 'string' && (page.url === wanted || page.url.startsWith(wanted))) ?? pages[0]
394
+ const matchedUrl = pages.find(page => wanted !== undefined && page.url === wanted)
395
+ const match = quiet && wanted !== undefined
396
+ ? matchedUrl
397
+ : pages.find(page => wanted !== undefined && typeof page.url === 'string' && page.url.startsWith(wanted)) ?? pages[0]
391
398
  const id = match !== undefined ? Number(match.id) : Number.NaN
392
399
  if (!Number.isFinite(id) || id <= 0) {
393
400
  throw new BrowserPanelNotDisplayedError(
394
- 'the preview asked for this conversation\'s page without presenting it, and no page is attached '
395
- + `(the shell holds ${pages.length})`,
401
+ quiet
402
+ ? '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'
403
+ : 'the preview asked for this conversation\'s page without presenting it, and no page is attached '
404
+ + `(the shell holds ${pages.length})`,
396
405
  )
397
406
  }
398
407
  this.views.set(viewId, { guest: id, owner })
@@ -432,12 +441,15 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
432
441
  // wording:
433
442
  // panel-not-displayed -> the shell was asked to show the conversation (client half's
434
443
  // `openSession`) and did not render it in ~1.6 s: no loss, no swap.
435
- // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
436
- // fall back, because otherwise every call fails forever.
444
+ // A missing guest within a time budget is still initialization, including on old bridges
445
+ // that only returned text. It is not evidence that this shell uses an undrivable iframe.
437
446
  const code = String(answer.code ?? '')
438
447
  const detail = String(answer.error)
439
448
  if (code === PANEL_NOT_DISPLAYED) throw new BrowserPanelNotDisplayedError(detail)
440
- if (detail.includes('produced no page')) this.reportLost('panel-unusable')
449
+ if (code === PANEL_INITIALIZING || (code === '' && detail.includes('produced no page'))) {
450
+ throw new BrowserPanelNotDisplayedError(detail, PANEL_INITIALIZING)
451
+ }
452
+ if (code === 'panel-unusable') this.reportLost('panel-unusable')
441
453
  throw new Error(`dsh-builtin-browser: sidebar unavailable (${detail})`)
442
454
  }
443
455
  const id = Number(answer.id)
@@ -514,7 +526,13 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
514
526
  * it must not fail the navigation that has already happened.
515
527
  * @param handle - the view to bring forward.
516
528
  */
517
- showView(handle: ElectronViewHandle): void {
529
+ showView(handle: ElectronViewHandle, _label?: string, options?: { readonly quiet?: boolean }): void {
530
+ // Quiet mode (`ui.quiet`) means "do not take my screen". On this carrier showing a page means
531
+ // asking the shell to switch the displayed conversation — precisely the takeover the switch
532
+ // forbids. So honour it by asking for nothing: a page that is already displayed keeps working,
533
+ // and one that is not fails with the documented display-state error instead of moving the
534
+ // user's view. Measured before this: the setting was on and every call still switched.
535
+ if (options?.quiet === true) return
518
536
  // `owner` is required: the bridge refuses to bring forward a guest held by another session.
519
537
  // It comes from the view, not the process — with several conversations live, a process-wide
520
538
  // owner would raise the wrong conversation's tab.
@@ -94,7 +94,7 @@ export interface ProvisionDeps {
94
94
  /** The installed electron package's own installer script, or undefined when it is not there. */
95
95
  readonly installerScript: () => string | undefined
96
96
  /** Runs the installer; resolves to an exit code, or rejects/returns null on failure. */
97
- readonly run: (script: string) => Promise<{ code: number | null; detail?: string }>
97
+ readonly run: (script: string, signal?: AbortSignal) => Promise<{ code: number | null; detail?: string }>
98
98
  /** Where the outcome goes. */
99
99
  readonly log: (message: string) => void
100
100
  /** Opt-out honoured exactly like the install script honours it. */
@@ -150,21 +150,35 @@ function electronVersion(): string {
150
150
  }
151
151
  }
152
152
 
153
+ let runningInstaller: Promise<{ code: number | null; detail?: string }> | undefined
154
+
153
155
  /** The real dependencies: this process's spawn, fs and logger. */
154
156
  export function defaultDeps(log: (message: string) => void = () => {}): ProvisionDeps {
155
157
  return {
156
158
  hasBinary: hasElectronRuntime,
157
159
  installerScript: electronInstallerScript,
158
- run: async script => {
159
- const child = spawn(process.execPath, [script], {
160
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
161
- stdio: ['ignore', 'ignore', 'ignore'],
162
- windowsHide: true,
163
- })
164
- return await new Promise(resolve => {
165
- child.once('error', error => resolve({ code: null, detail: String(error) }))
166
- child.once('close', code => resolve({ code, detail: undefined }))
160
+ run: (script, signal) => {
161
+ if (runningInstaller !== undefined) return runningInstaller
162
+ const run = new Promise<{ code: number | null; detail?: string }>(resolve => {
163
+ const child = spawn(process.execPath, [script], {
164
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
165
+ stdio: ['ignore', 'ignore', 'ignore'],
166
+ windowsHide: true,
167
+ })
168
+ let failure: string | undefined
169
+ const abort = (): void => { child.kill('SIGKILL') }
170
+ signal?.addEventListener('abort', abort, { once: true })
171
+ if (signal?.aborted) abort()
172
+ child.once('error', error => { failure = String(error) })
173
+ child.once('close', code => {
174
+ signal?.removeEventListener('abort', abort)
175
+ resolve({ code, detail: failure })
176
+ })
167
177
  })
178
+ runningInstaller = run
179
+ const clear = (): void => { if (runningInstaller === run) runningInstaller = undefined }
180
+ void run.then(clear, clear)
181
+ return run
168
182
  },
169
183
  log,
170
184
  skip: () => typeof process.env.ELECTRON_SKIP_BINARY_DOWNLOAD === 'string'
@@ -202,15 +216,19 @@ export async function ensureElectronRuntime(deps: ProvisionDeps = defaultDeps())
202
216
  // this path failed with "Promise resolution is still pending but the event loop has already
203
217
  // resolved". Keep it referenced, and clear it so a success does not leave a 180 s handle behind.
204
218
  let timer: ReturnType<typeof setTimeout> | undefined
219
+ const controller = new AbortController()
205
220
  const timeout = new Promise<{ code: number | null; detail: string }>(resolve => {
206
221
  timer = setTimeout(
207
- () => resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` }),
222
+ () => {
223
+ controller.abort()
224
+ resolve({ code: null, detail: `gave up after ${Math.round(deps.timeoutMs / 1000)}s` })
225
+ },
208
226
  deps.timeoutMs,
209
227
  )
210
228
  })
211
229
  let outcome: { code: number | null; detail?: string }
212
230
  try {
213
- outcome = await Promise.race([deps.run(script), timeout])
231
+ outcome = await Promise.race([deps.run(script, controller.signal), timeout])
214
232
  } catch (error) {
215
233
  return record({ status: 'failed', detail: `the download failed: ${String(error)}` })
216
234
  } finally {