dsh-builtin-browser 0.5.1 → 0.5.3

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 (44) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/README.en.md +68 -67
  3. package/README.md +63 -91
  4. package/client.js +235 -11
  5. package/desktop-bridge/desktop-identity.json +9 -0
  6. package/desktop-bridge/install.mjs +220 -1
  7. package/docs/README.md +1 -1
  8. package/docs/architecture.md +1 -1
  9. package/docs/limitations.md +19 -1
  10. package/docs/tool-reference.md +2 -1
  11. package/lib/browser/runtime.d.ts +4 -2
  12. package/lib/browser/runtime.js +4 -0
  13. package/lib/browser/types.d.ts +37 -0
  14. package/lib/browser-electron/bridge-status.d.ts +5 -3
  15. package/lib/browser-electron/bridge-status.js +25 -8
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -3
  17. package/lib/browser-electron/desktop-bridge-host.js +47 -13
  18. package/lib/browser-electron/desktop-identity.d.ts +58 -0
  19. package/lib/browser-electron/desktop-identity.js +236 -0
  20. package/lib/browser-electron/electron-provision.d.ts +59 -0
  21. package/lib/browser-electron/electron-provision.js +164 -0
  22. package/lib/browser-electron/entry.js +61 -2
  23. package/lib/browser-electron/host-main.js +68 -14
  24. package/lib/browser-electron/provider.d.ts +51 -3
  25. package/lib/browser-electron/provider.js +77 -4
  26. package/lib/browser-electron/remote-host.d.ts +3 -3
  27. package/lib/browser-electron/remote-host.js +25 -11
  28. package/lib/browser-electron/settings-store.d.ts +19 -0
  29. package/lib/browser-electron/settings-store.js +5 -1
  30. package/lib/tool-browser/index.js +49 -0
  31. package/package.json +2 -3
  32. package/src/browser/runtime.ts +8 -0
  33. package/src/browser/types.ts +36 -0
  34. package/src/browser-electron/bridge-status.ts +28 -9
  35. package/src/browser-electron/desktop-bridge-host.ts +49 -13
  36. package/src/browser-electron/desktop-identity.ts +260 -0
  37. package/src/browser-electron/electron-provision.ts +195 -0
  38. package/src/browser-electron/entry.ts +49 -2
  39. package/src/browser-electron/host-main.ts +62 -12
  40. package/src/browser-electron/provider.ts +118 -6
  41. package/src/browser-electron/remote-host.ts +26 -12
  42. package/src/browser-electron/settings-store.ts +24 -1
  43. package/src/tool-browser/index.ts +49 -0
  44. package/src/types/electron-shim.d.ts +8 -0
@@ -26,7 +26,7 @@
26
26
  * unauthenticated peer can neither read traffic nor drive a session.
27
27
  * @module dsh-browser/browser-electron/remote-host
28
28
  */
29
- import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle } from './provider.js';
29
+ import type { BrowserUserAction, ElectronBrowserViewHost, ElectronViewHandle, PresentOptions } from './provider.js';
30
30
  /**
31
31
  * Locate a SPAWNABLE Electron binary — one that runs a script given as an
32
32
  * argument, i.e. a BARE electron, never a packaged app executable:
@@ -209,7 +209,7 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
209
209
  private onChildExit;
210
210
  createView(): ElectronViewHandle;
211
211
  private ensureView;
212
- showView(handle: ElectronViewHandle, label?: string): void;
212
+ showView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void;
213
213
  /**
214
214
  * (Re)present a view and WAIT for the child to confirm it, so the provider
215
215
  * can dispatch CDP `Input.*` knowing the view has a display surface.
@@ -225,7 +225,7 @@ export declare class RemoteElectronViewHost implements ElectronBrowserViewHost {
225
225
  * in order: its reply is queued behind the showView and so only arrives once
226
226
  * the visibility change has been applied.
227
227
  */
228
- presentView(handle: ElectronViewHandle, label?: string): Promise<void>;
228
+ presentView(handle: ElectronViewHandle, label?: string, options?: PresentOptions): Promise<void>;
229
229
  /** Route a view into its session's own window (one window per session). */
230
230
  groupView(handle: ElectronViewHandle, windowId: string, label?: string): void;
231
231
  /** Register the provider's handler for user-initiated toolbar actions. */
@@ -95,13 +95,13 @@ function resolveElectronPathImpl(inputs) {
95
95
  if (hostExe !== undefined)
96
96
  return hostExe;
97
97
  throw new Error('dsh-builtin-browser: cannot locate a spawnable Electron binary. ' +
98
- 'The electron package ships with the plugin (0.1.18+); Electron 44+ downloads its binary on first use, ' +
99
- 'so if the package is installed but the binary is missing, run `npx install-electron` once (needs network) ' +
100
- 'in the profile that installed the plugin, then retry. Alternatively set ELECTRON_PATH to an electron ' +
101
- 'executable. On installs from before electron became a dependency, add it to the active profile ' +
102
- '(`dsh plugin --profile <your-profile> add electron`; on DSH Desktop the profile is `desktop`). ' +
103
- 'Note: the host\'s own executable cannot be reused when it is a packaged Electron app (e.g. DSH Desktop.exe) ' +
104
- '— only a real electron binary can be spawned.');
98
+ 'The electron package ships with the plugin and its binary is downloaded on first use, not at install time ' +
99
+ '(issue #41: an install-time download made default profiles refuse the plugin). The plugin prepares it ' +
100
+ 'automatically when the bundled carrier is selected; to do it by hand, run ' +
101
+ '`npx --no dsh-browser-install-electron` in the profile that installed the plugin, then retry. ' +
102
+ 'Alternatively set ELECTRON_PATH to an electron executable. Note: the host\'s own executable cannot be ' +
103
+ 'reused when it is a packaged Electron app (e.g. DSH Desktop.exe) — only a real electron binary can be ' +
104
+ 'spawned.');
105
105
  }
106
106
  /** DSH install anchors: electron installed separately (profile / global prefix), newest wins. */
107
107
  function anchoredElectronBinary() {
@@ -1154,13 +1154,19 @@ export class RemoteElectronViewHost {
1154
1154
  this.views.set(id, view);
1155
1155
  return view;
1156
1156
  }
1157
- showView(handle, label) {
1157
+ showView(handle, label, options) {
1158
1158
  // Fire-and-forget by design (visibility is best-effort), but a rejected
1159
1159
  // promise must not become an unhandled rejection (crash on Node >= 15).
1160
1160
  // The label (session/task id) rides along so the child can show it in the
1161
1161
  // window title — a human can then tell which task's page is visible.
1162
+ // `quiet` is only sent when it is on: the child's default is the documented
1163
+ // "present and raise" behaviour, so an old child keeps working either way.
1162
1164
  void this.ready()
1163
- .then(() => this.client?.call('showView', { viewId: handle.id, ...label !== undefined ? { label } : {} }))
1165
+ .then(() => this.client?.call('showView', {
1166
+ viewId: handle.id,
1167
+ ...label !== undefined ? { label } : {},
1168
+ ...options?.quiet === true ? { quiet: true } : {},
1169
+ }))
1164
1170
  .catch(() => { });
1165
1171
  }
1166
1172
  /**
@@ -1178,7 +1184,7 @@ export class RemoteElectronViewHost {
1178
1184
  * in order: its reply is queued behind the showView and so only arrives once
1179
1185
  * the visibility change has been applied.
1180
1186
  */
1181
- async presentView(handle, label) {
1187
+ async presentView(handle, label, options) {
1182
1188
  await this.ready();
1183
1189
  const client = this.client;
1184
1190
  if (client === undefined)
@@ -1189,7 +1195,15 @@ export class RemoteElectronViewHost {
1189
1195
  if (handle instanceof DeferredRemoteView) {
1190
1196
  await withTimeout(handle.ensureMaterialized(), PRESENT_TIMEOUT_MS, 'browser host did not materialize the view');
1191
1197
  }
1192
- await withTimeout(client.call('showView', { viewId: handle.id, ...label !== undefined ? { label } : {} }), PRESENT_TIMEOUT_MS, 'browser host did not confirm the view presentation');
1198
+ await withTimeout(client.call('showView', {
1199
+ viewId: handle.id,
1200
+ ...label !== undefined ? { label } : {},
1201
+ // `needSurface` tells the child this is the pre-input barrier: under quiet mode this
1202
+ // is the only presentation allowed to un-minimize a window, because Chromium drops
1203
+ // `Input.*` without a display surface. One line below in the child, and only read
1204
+ // there when `quiet` is set.
1205
+ ...options?.quiet === true ? { quiet: true, needSurface: true } : {},
1206
+ }), PRESENT_TIMEOUT_MS, 'browser host did not confirm the view presentation');
1193
1207
  await withTimeout(client.call('ping'), PRESENT_TIMEOUT_MS, 'browser host stopped answering');
1194
1208
  }
1195
1209
  /** Route a view into its session's own window (one window per session). */
@@ -40,6 +40,25 @@ export interface BrowserSettings {
40
40
  readonly closeWithSession: boolean;
41
41
  /** Show the synthetic cursor/click feedback while the agent operates. */
42
42
  readonly virtualCursor: boolean;
43
+ /**
44
+ * Quiet mode: drive the page without taking over the screen.
45
+ *
46
+ * Off (the default) keeps the contract this plugin is built on — human and agent share one
47
+ * window, so an operation raises it and the user can see what is being driven. On, the
48
+ * carrier never activates the application and never steals keyboard focus:
49
+ * - screenshots of a minimized or hidden window go through CDP `Page.captureScreenshot`
50
+ * instead of `capturePage()`, so grabbing an image stops being a reason to show a window;
51
+ * - navigation and tab switching only change which view is visible INSIDE the window; a
52
+ * minimized window stays minimized;
53
+ * - synthesized input still needs a display surface (Chromium drops `Input.*` for a view
54
+ * without one), so that one barrier may restore a minimized window — with
55
+ * `showInactive()`, which shows it without becoming the key window, and without
56
+ * `moveTop()`.
57
+ *
58
+ * Reported as issue #35: a minimized browser window was restored and focused by the next
59
+ * screenshot or click, pulling the user out of whatever they were typing in.
60
+ */
61
+ readonly quiet: boolean;
43
62
  };
44
63
  /** Visual vs non-visual operation strategy. */
45
64
  readonly vision: {
@@ -17,7 +17,7 @@ export const HEADLESS_MODES = ['auto', 'headless', 'windowed'];
17
17
  export const DEFAULT_SETTINGS = {
18
18
  history: { enabled: true, maxEntries: 5_000, maxAgeDays: 90 },
19
19
  cookies: { persist: true },
20
- ui: { autoExpandOnce: true, closeWithSession: false, virtualCursor: true },
20
+ ui: { autoExpandOnce: true, closeWithSession: false, virtualCursor: true, quiet: false },
21
21
  vision: { strategy: 'auto' },
22
22
  // Bundled by default: it needs nothing installed, and on the desktop the carrier
23
23
  // is the sidebar anyway. Choosing a system browser is an explicit opt-in because
@@ -197,6 +197,10 @@ export function resolveSettings(raw, warn) {
197
197
  autoExpandOnce: bool(ui?.autoExpandOnce, DEFAULT_SETTINGS.ui.autoExpandOnce),
198
198
  closeWithSession: bool(ui?.closeWithSession, DEFAULT_SETTINGS.ui.closeWithSession),
199
199
  virtualCursor: bool(ui?.virtualCursor, DEFAULT_SETTINGS.ui.virtualCursor),
200
+ // Presentation preference, not a capability gate: a mistyped value keeps the documented
201
+ // default (off) instead of being read as "on", because quiet mode changes how every
202
+ // operation presents itself and should never be the accidental result of a bad edit.
203
+ quiet: bool(ui?.quiet, DEFAULT_SETTINGS.ui.quiet),
200
204
  },
201
205
  vision: { strategy: vision?.strategy === 'nonVisual' ? 'nonVisual' : DEFAULT_SETTINGS.vision.strategy },
202
206
  browser: {
@@ -806,6 +806,55 @@ export function apply(ctx, config = {}) {
806
806
  return { clicked: true };
807
807
  },
808
808
  }));
809
+ registerSafely(defineTool({
810
+ name: 'dsh_browser_click_sequence',
811
+ description: 'Click many points in order, in one call. Use this instead of repeated dsh_browser_click when a page needs a run of coordinate clicks — a canvas board, a map, a drawing surface. Each point is clicked with the same real input sequence the single click uses; between points the call waits intervalMs (default 40 ms), which is what stops a page from reading two presses as a double click. Stops at the first point that fails and says where, so a run that half-landed is reported rather than looking complete.',
812
+ parameters: {
813
+ points: {
814
+ type: 'array',
815
+ required: true,
816
+ description: 'Points to click, in order, in viewport CSS pixels — the same space dsh_browser_screenshot reports.',
817
+ items: {
818
+ type: 'object',
819
+ additionalProperties: false,
820
+ properties: {
821
+ x: { type: 'number', required: true, description: 'Viewport x in CSS px.' },
822
+ y: { type: 'number', required: true, description: 'Viewport y in CSS px.' },
823
+ },
824
+ },
825
+ },
826
+ intervalMs: { type: 'number', description: 'Milliseconds between points (default 40).' },
827
+ },
828
+ output: {
829
+ schema: {
830
+ type: 'object',
831
+ additionalProperties: false,
832
+ properties: {
833
+ clicked: { type: 'number', required: true, description: 'How many points landed.' },
834
+ failedAt: { type: 'number', description: 'Index of the point that failed, when one did.' },
835
+ error: { type: 'string', description: 'Why that point failed.' },
836
+ },
837
+ },
838
+ render: (_args, value) => [{
839
+ type: 'text',
840
+ text: value.failedAt === undefined
841
+ ? `Clicked ${String(value.clicked)} point(s).`
842
+ : `Clicked ${String(value.clicked)} point(s), then stopped at index ${String(value.failedAt)}: ${String(value.error ?? 'unknown')}`,
843
+ }],
844
+ },
845
+ timeoutMs,
846
+ isConcurrencySafe: () => false,
847
+ async execute(args, exec) {
848
+ assertAllowed(state, 'dsh_browser_click_sequence', taskKey(exec));
849
+ const browser = ctx.get('browser');
850
+ if (browser === undefined)
851
+ throw new Error('tool-browser: browser service unavailable');
852
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
853
+ const points = Array.isArray(args.points) ? args.points : [];
854
+ const intervalMs = typeof args.intervalMs === 'number' ? args.intervalMs : undefined;
855
+ return browser.clickSequence(session, { points, ...intervalMs === undefined ? {} : { intervalMs } });
856
+ },
857
+ }));
809
858
  registerSafely(defineTool({
810
859
  name: 'dsh_browser_type',
811
860
  description: 'Type text into the focused element of the shared browser, or into a located element (pass target {by: css|text|xpath, value, index?} to focus it first). Text is inserted at the focus via CDP Input.insertText. For setting whole field values (and React-controlled inputs) prefer dsh_browser_set_value; use dsh_browser_key for Enter/Tab/arrows.',
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-builtin-browser",
3
- "version": "0.5.1",
4
- "description": "Shared real browser plugin for DeepSeek Harness: install-and-use — a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
3
+ "version": "0.5.3",
4
+ "description": "Shared real browser plugin for DeepSeek Harness: install-and-use 鈥?a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -50,7 +50,6 @@
50
50
  "scripts": {
51
51
  "build": "tsc -p tsconfig.json",
52
52
  "test": "tsc -p tsconfig.json && node --test \"tests/*.test.mjs\"",
53
- "postinstall": "node scripts/install-electron.mjs",
54
53
  "prepack": "npm run build"
55
54
  },
56
55
  "keywords": [
@@ -15,6 +15,8 @@ import type {
15
15
  BrowserCheckRequest,
16
16
  BrowserClearRequest,
17
17
  BrowserClickRequest,
18
+ BrowserClickSequenceRequest,
19
+ BrowserClickSequenceResult,
18
20
  BrowserContentRequest,
19
21
  BrowserContentResult,
20
22
  BrowserDownloadRequest,
@@ -63,6 +65,8 @@ export type {
63
65
  BrowserCheckRequest,
64
66
  BrowserClearRequest,
65
67
  BrowserClickRequest,
68
+ BrowserClickSequenceRequest,
69
+ BrowserClickSequenceResult,
66
70
  BrowserContentFormat,
67
71
  BrowserElementTarget,
68
72
  BrowserGetValueRequest,
@@ -273,6 +277,10 @@ export class BrowserRuntime extends Service {
273
277
  return this.resolveProvider().click(session, request, signal)
274
278
  }
275
279
 
280
+ /** Click several points in order through the selected provider. */
281
+ async clickSequence(session: BrowserSessionId, request: BrowserClickSequenceRequest, signal?: AbortSignal): Promise<BrowserClickSequenceResult> {
282
+ return this.resolveProvider().clickSequence(session, request, signal)
283
+ }
276
284
  /** Type into the focused element (or a located one) through the selected provider. */
277
285
  async type(session: BrowserSessionId, request: BrowserTypeRequest | { readonly target: BrowserElementTarget }, signal?: AbortSignal): Promise<void> {
278
286
  return this.resolveProvider().type(session, request, signal)
@@ -43,6 +43,31 @@ export interface BrowserClickRequest {
43
43
  readonly y: number
44
44
  }
45
45
 
46
+ /**
47
+ * A run of coordinate clicks in one call.
48
+ *
49
+ * Each point is clicked in order with the same real CDP sequence the single click uses. Between
50
+ * points the call waits `intervalMs`, because a canvas that receives two presses inside one frame
51
+ * treats them as a double click — or drops the second entirely, which looks like a silently wrong
52
+ * board rather than an error.
53
+ */
54
+ export interface BrowserClickSequenceRequest {
55
+ /** Points to click, in order, in viewport CSS pixels. */
56
+ readonly points: readonly { readonly x: number; readonly y: number }[]
57
+ /** Milliseconds to wait between points; defaults to 40. */
58
+ readonly intervalMs?: number
59
+ }
60
+
61
+ /** Result of a click run: how many landed, and where it stopped if it did not finish. */
62
+ export interface BrowserClickSequenceResult {
63
+ /** Points that were clicked successfully. */
64
+ readonly clicked: number
65
+ /** Index of the point that failed, when one did. */
66
+ readonly failedAt?: number
67
+ /** Why that point failed. */
68
+ readonly error?: string
69
+ }
70
+
46
71
  /** Type text into the focused element. */
47
72
  export interface BrowserTypeRequest {
48
73
  /** The text to insert. */
@@ -624,6 +649,17 @@ export interface BrowserProvider {
624
649
  * request carries a `target`. Honor `signal` for cancellation.
625
650
  */
626
651
  click(session: BrowserSessionId, request: BrowserClickRequest | { readonly target: BrowserElementTarget }, signal?: AbortSignal): Promise<void>
652
+ /**
653
+ * Click several points in order, in one round trip.
654
+ *
655
+ * Exists because a canvas page accepts only genuine input: one click per call meant two calls
656
+ * per cell on a 9x9 board. Stops at the first point that fails rather than pressing through a
657
+ * page that has moved under it, and reports how far it got.
658
+ * @param session - the session to click in.
659
+ * @param request - the points and the interval between them.
660
+ * @param signal - cancellation between points.
661
+ */
662
+ clickSequence(session: BrowserSessionId, request: BrowserClickSequenceRequest, signal?: AbortSignal): Promise<BrowserClickSequenceResult>
627
663
  /**
628
664
  * Type into the focused element, or focus a located element first when the
629
665
  * request carries a `target`. Honor `signal` for cancellation.
@@ -19,29 +19,32 @@
19
19
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
20
20
  import { join } from 'node:path'
21
21
 
22
+ import { readDesktopIdentity } from './desktop-identity.js'
23
+
22
24
  /**
23
25
  * Find the desktop install to report on.
24
26
  *
25
- * The same shape probe the installer uses, repeated here because the two run in different processes
26
- * and neither can import the other: the product directory is `DeepSeek Harness` on some builds and
27
- * `DSH Desktop` on others, and the shape that identifies an install is stable across both.
27
+ * Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
28
+ * directory that had one. Any Electron app has that layout, so a stranger's app was reported as
29
+ * "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
30
+ * probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
31
+ * answer is about DSH Desktop and nothing else.
28
32
  * @param localAppData - the base directory; defaults to the environment's.
29
33
  * @returns the install directory, or undefined when nothing matches.
30
34
  */
31
35
  export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''): string | undefined {
32
36
  if (localAppData === '') return undefined
33
37
  const programs = join(localAppData, 'Programs')
34
- const looksInstalled = (candidate: string): boolean => existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
35
- || existsSync(join(candidate, 'resources', 'app.asar'))
38
+ const isDesktop = (candidate: string): boolean => readDesktopIdentity(candidate).ok
36
39
  for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
37
40
  const candidate = join(programs, named)
38
- if (looksInstalled(candidate)) return candidate
41
+ if (isDesktop(candidate)) return candidate
39
42
  }
40
43
  try {
41
44
  for (const entry of readdirSync(programs, { withFileTypes: true })) {
42
45
  if (!entry.isDirectory()) continue
43
46
  const candidate = join(programs, entry.name)
44
- if (looksInstalled(candidate)) return candidate
47
+ if (isDesktop(candidate)) return candidate
45
48
  }
46
49
  } catch {
47
50
  // No Programs directory: nothing to report on, which is a state rather than an error.
@@ -100,16 +103,32 @@ export function readBridgeStatus(installRoot: string): BridgeStatus {
100
103
  const archivePath = join(resources, 'app.asar')
101
104
  const backupPath = `${mainPath}.before-bridge`
102
105
 
106
+ // Identity first, and before any other reading. Two reasons, both measured in issue #40: a
107
+ // stranger's app must not be reported as DSH Desktop, and this status also carries a *command* —
108
+ // pointing that command at a directory whose identity was never verified is how the installer got
109
+ // aimed at an application that merely looked like Electron.
110
+ const identity = readDesktopIdentity(installRoot)
111
+ if (!identity.ok) {
112
+ return {
113
+ state: 'missing',
114
+ present: false,
115
+ installRoot,
116
+ archivePresent: safeExists(archivePath),
117
+ detail: `not a DSH Desktop install: ${identity.reason}`,
118
+ }
119
+ }
120
+
103
121
  const archivePresent = safeExists(archivePath)
104
122
  const mainPresent = safeExists(mainPath)
105
123
  if (!mainPresent && !archivePresent) {
124
+ // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
125
+ // fail-closed branch for a tree that changed between the two reads.
106
126
  return {
107
127
  state: 'missing',
108
128
  present: false,
109
129
  installRoot,
110
130
  archivePresent,
111
- command: repairCommand(installRoot),
112
- detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
131
+ detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
113
132
  }
114
133
  }
115
134
  let backupAt
@@ -51,10 +51,24 @@ export function bridgeEndpointPath(): string {
51
51
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
52
52
 
53
53
  /**
54
- * A failure worth showing as-is: the carrier is alive and this is a condition the user can change.
54
+ * How many times a display-state refusal is retried, and how long each retry waits.
55
55
  *
56
- * Thrown instead of a plain Error so callers can distinguish "wait for the conversation to be shown"
57
- * from "the browser broke", which is exactly the distinction issue #37 says was missing.
56
+ * The retry exists because the same call now asks the shell to SHOW the conversation (the client
57
+ * half's `openSession` step). React renders that on the next pass, so the refusal the first call
58
+ * sees is true-but-stale. 4 x 400 ms is ~1.6 s: long enough for a render on a busy conversation,
59
+ * short enough that a shell which genuinely cannot render a panel still fails inside one tool call
60
+ * instead of stalling for the bridge's own 20 s budget.
61
+ */
62
+ const PANEL_DISPLAY_RETRIES = 4
63
+ const PANEL_DISPLAY_RETRY_MS = 400
64
+
65
+ /**
66
+ * A failure worth showing as-is: the carrier is alive and this is a condition the shell can change.
67
+ *
68
+ * Thrown instead of a plain Error so callers can distinguish "the panel did not render" from "the
69
+ * browser broke", which is exactly the distinction issue #37 says was missing. The plugin no longer
70
+ * waits for a human to show the conversation — the client half asks the shell to (`openSession`) and
71
+ * this host retries while it renders — so reaching here means the shell did not render it at all.
58
72
  */
59
73
  export class BrowserPanelNotDisplayedError extends Error {
60
74
  readonly code = PANEL_NOT_DISPLAYED
@@ -64,8 +78,9 @@ export class BrowserPanelNotDisplayedError extends Error {
64
78
  */
65
79
  constructor(detail: string) {
66
80
  super(
67
- 'dsh-builtin-browser: this conversation\'s sidebar page is not attached because the conversation '
68
- + 'is not the one displayed. Show it and the page appears; nothing was lost. '
81
+ 'dsh-builtin-browser: this conversation\'s sidebar page did not attach — the shell was asked to '
82
+ + 'show this conversation and its panel still did not render. Nothing was lost, and the page '
83
+ + 'appears as soon as the panel mounts. '
69
84
  + `(${detail})`,
70
85
  )
71
86
  this.name = 'BrowserPanelNotDisplayedError'
@@ -354,19 +369,40 @@ export class DesktopBridgeViewHost implements ElectronBrowserViewHost {
354
369
  // conversation's own panel by id through the renderer, rather than by pressing the shell's
355
370
  // shortcut or clicking its card, both of which the shell delivers to whatever it displays.
356
371
  const owner = entry?.owner ?? this.owner
357
- const answer = await this.connection.call({
372
+ const ask = (): Promise<Record<string, unknown>> => this.connection.call({
358
373
  op: 'ensureSidebar',
359
374
  owner,
360
375
  ...url !== undefined && url !== '' ? { url } : {},
361
376
  }, 30_000)
377
+ let answer = await ask()
378
+ // A refusal is retried when it describes a DISPLAY state rather than a dead carrier, because the
379
+ // plugin's client half asks the shell to show this conversation inside the very call that
380
+ // produced it. Two shapes come back from that first round:
381
+ // panel-not-displayed - the conversation exists but is not the one on screen;
382
+ // "is not mounted" - its surface store was not minted when the tab was placed.
383
+ // Both are gone one render later. Measured, this is the whole difference between "the sidebar
384
+ // works once I click over to that conversation" and "it works" — the page is real either way,
385
+ // and failing the call while the shell is already switching away from it just reported a
386
+ // problem the plugin had already fixed.
387
+ const displayRefusal = (value: Record<string, unknown>): boolean =>
388
+ value.ok !== true
389
+ && (String(value.code ?? '') === PANEL_NOT_DISPLAYED
390
+ || String(value.error ?? '').includes('not mounted')
391
+ // Bridges installed before issue #37 send the same refusal with NO code — the installed copy
392
+ // on this machine is one of them (`panel-not-displayed` appears nowhere in it). Reading only
393
+ // the code therefore turned a retryable display state into a hard failure for exactly the
394
+ // users who had the old bridge, which is the majority until it is reinstalled. The wording
395
+ // is stable across both versions; the code is not.
396
+ || String(value.error ?? '').includes('can only attach'))
397
+ for (let attempt = 0; attempt < PANEL_DISPLAY_RETRIES && displayRefusal(answer); attempt += 1) {
398
+ await new Promise(resolve => setTimeout(resolve, PANEL_DISPLAY_RETRY_MS))
399
+ answer = await ask()
400
+ }
362
401
  if (answer.ok !== true) {
363
- // A bridge that answers but cannot produce a page is as usable as one that has exited ONLY when
364
- // the panel can never work here. "The conversation is not displayed" is the opposite case: the
365
- // panel is fine, the shell simply is not rendering it right now, and it will the moment the
366
- // user shows that conversation (issue #37).
367
- //
368
- // So the code decides, not the wording:
369
- // panel-not-displayed -> a transient display state; no loss, no retry, nothing swapped.
402
+ // Reachable only after the retries above have run out, and the code still decides — not the
403
+ // wording:
404
+ // panel-not-displayed -> the shell was asked to show the conversation (client half's
405
+ // `openSession`) and did not render it in ~1.6 s: no loss, no swap.
370
406
  // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
371
407
  // fall back, because otherwise every call fails forever.
372
408
  const code = String(answer.code ?? '')