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
@@ -1,6 +1,6 @@
1
1
  # 工具参考
2
2
 
3
- 全部 34 个 `dsh_browser_*` 工具。守卫列:✅ 表示该动作受 `dsh_browser_restrict` 白名单约束;**「– 豁免」表示无论白名单怎么写都不拦截**(豁免集合为 `READ_ONLY_TOOLS`,`src/tool-browser/index.ts` 导出:**只观察的工具** —— `snapshot`/`a11y`/`content`/`scrape`/`screenshot`/`get_value`/`wait`/`challenge`/`list_tabs`/`session`/`history`/`visited` —— 加上 **解除限制 / 从坏状态恢复的工具** `restrict`/`reset_session`/`reset`;`restrict` 在其中,否则限制到空的任务再也解不开);**「–」表示该工具只观察、不做动作**,故没有可拦的东西。两者之外的工具都受白名单约束 —— 例如 `dsh_browser_close_tab`、`dsh_browser_auth` 都不属于豁免集合(`dsh_browser_auth` 的 `restore` 会向任意域写 cookie,是动作,不是观察)。
3
+ 全部 35 个 `dsh_browser_*` 工具。守卫列:✅ 表示该动作受 `dsh_browser_restrict` 白名单约束;**「– 豁免」表示无论白名单怎么写都不拦截**(豁免集合为 `READ_ONLY_TOOLS`,`src/tool-browser/index.ts` 导出:**只观察的工具** —— `snapshot`/`a11y`/`content`/`scrape`/`screenshot`/`get_value`/`wait`/`challenge`/`list_tabs`/`session`/`history`/`visited` —— 加上 **解除限制 / 从坏状态恢复的工具** `restrict`/`reset_session`/`reset`;`restrict` 在其中,否则限制到空的任务再也解不开);**「–」表示该工具只观察、不做动作**,故没有可拦的东西。两者之外的工具都受白名单约束 —— 例如 `dsh_browser_close_tab`、`dsh_browser_auth` 都不属于豁免集合(`dsh_browser_auth` 的 `restore` 会向任意域写 cookie,是动作,不是观察)。
4
4
 
5
5
  ## 页面与导航
6
6
 
@@ -19,6 +19,7 @@
19
19
  | --- | --- | --- | --- | --- |
20
20
  | `dsh_browser_execute` | `script`(必填), `args?` | `{ ok, value? / exception? }` | ✅ | 在页面执行 JS;脚本以 `return` 开头或作为表达式;`args` 以 `arguments[0..n]` 传入。**返回值上限 50 000 字符**,超出时结果里写明"截断于 50 000 / 实际 N 字符"(要完整内容请让表达式返回更小的值)。受设置「Agent 能做什么 → 允许在页面里执行脚本」门控,关闭后一律被拒(`BROWSER_EXECUTE_DISABLED`),且没有任何工具能把它打开 |
21
21
  | `dsh_browser_click` | `target?`(css/text/xpath), `x?`, `y?`(target 与坐标二选一) | `{ clicked }` | ✅ | 语义目标点击:按 `target` 定位、滚动到视口中央再点中心;或视口坐标点击(配合截图做视觉定位) |
22
+ | `dsh_browser_click_sequence` | `points`(必填,`{x,y}[]`), `intervalMs?`(默认 40) | `{ clicked, failedAt?, error? }` | ✅ | 一次调用打一串**视口坐标**点击:只 `present()` 一次,每点走 `mouseMoved`/`mousePressed`/`mouseReleased`;点间默认 40 ms(低于此值页面会把两次按下读成双击或丢弃)。**首点失败即停**并回报 `failedAt`。用于 canvas 页面——它们不采信脚本派发的 `MouseEvent`/`PointerEvent`/`element.click()`,只认 `isTrusted` 的真实输入(实测:sudoku.com 一盘 84 点一次打完) |
22
23
  | `dsh_browser_type` | `text`(必填), `target?` | `{ typed }` | ✅ | 输入文本;传 `target` 先聚焦该元素(CDP `Input.insertText`) |
23
24
  | `dsh_browser_key` | `key`(必填,枚举) | `{ pressed }` | ✅ | 按命名按键:Enter/Tab/Escape/Backspace/Delete/方向键/Home/End/PageUp/PageDown/Space |
24
25
  | `dsh_browser_scroll` | `deltaX?`, `deltaY?`, `selector?`, `toTop?`, `toBottom?` | `{ scrolled }` | ✅ | 滚动页面:像素增量 / 选择器定位 / 顶部底部 |
@@ -8,9 +8,9 @@
8
8
  */
9
9
  import { Context, Service } from '@deepseek-ai/cordis';
10
10
  import z from '@deepseek-ai/schemastery';
11
- import type { BrowserA11yRequest, BrowserA11yResult, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserElementTarget, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserChallenge, ExportedCookie, VisitedPage } from './types.js';
11
+ import type { BrowserA11yRequest, BrowserA11yResult, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserElementTarget, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserChallenge, ExportedCookie, VisitedPage } from './types.js';
12
12
  export { BrowserError, } from './types.js';
13
- export type { BrowserA11yNode, BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserContentFormat, BrowserElementTarget, BrowserGetValueRequest, BrowserGetValueResult, BrowserScrapeField, BrowserScrapeRequest, BrowserScrapeResult, BrowserSelectRequest, BrowserSelectResult, BrowserSetValueRequest, BrowserSetValueResult, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillField, BrowserFillRequest, BrowserFillResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSessionId, BrowserSnapshotElement, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, ExportedCookie, } from './types.js';
13
+ export type { BrowserA11yNode, BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentFormat, BrowserElementTarget, BrowserGetValueRequest, BrowserGetValueResult, BrowserScrapeField, BrowserScrapeRequest, BrowserScrapeResult, BrowserSelectRequest, BrowserSelectResult, BrowserSetValueRequest, BrowserSetValueResult, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillField, BrowserFillRequest, BrowserFillResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSessionId, BrowserSnapshotElement, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, ExportedCookie, } from './types.js';
14
14
  declare module '@deepseek-ai/cordis' {
15
15
  interface Context {
16
16
  browser: BrowserRuntime;
@@ -82,6 +82,8 @@ export declare class BrowserRuntime extends Service {
82
82
  click(session: BrowserSessionId, request: BrowserClickRequest | {
83
83
  readonly target: BrowserElementTarget;
84
84
  }, signal?: AbortSignal): Promise<void>;
85
+ /** Click several points in order through the selected provider. */
86
+ clickSequence(session: BrowserSessionId, request: BrowserClickSequenceRequest, signal?: AbortSignal): Promise<BrowserClickSequenceResult>;
85
87
  /** Type into the focused element (or a located one) through the selected provider. */
86
88
  type(session: BrowserSessionId, request: BrowserTypeRequest | {
87
89
  readonly target: BrowserElementTarget;
@@ -142,6 +142,10 @@ export class BrowserRuntime extends Service {
142
142
  async click(session, request, signal) {
143
143
  return this.resolveProvider().click(session, request, signal);
144
144
  }
145
+ /** Click several points in order through the selected provider. */
146
+ async clickSequence(session, request, signal) {
147
+ return this.resolveProvider().clickSequence(session, request, signal);
148
+ }
145
149
  /** Type into the focused element (or a located one) through the selected provider. */
146
150
  async type(session, request, signal) {
147
151
  return this.resolveProvider().type(session, request, signal);
@@ -38,6 +38,32 @@ export interface BrowserClickRequest {
38
38
  /** Viewport-relative y in CSS pixels. */
39
39
  readonly y: number;
40
40
  }
41
+ /**
42
+ * A run of coordinate clicks in one call.
43
+ *
44
+ * Each point is clicked in order with the same real CDP sequence the single click uses. Between
45
+ * points the call waits `intervalMs`, because a canvas that receives two presses inside one frame
46
+ * treats them as a double click — or drops the second entirely, which looks like a silently wrong
47
+ * board rather than an error.
48
+ */
49
+ export interface BrowserClickSequenceRequest {
50
+ /** Points to click, in order, in viewport CSS pixels. */
51
+ readonly points: readonly {
52
+ readonly x: number;
53
+ readonly y: number;
54
+ }[];
55
+ /** Milliseconds to wait between points; defaults to 40. */
56
+ readonly intervalMs?: number;
57
+ }
58
+ /** Result of a click run: how many landed, and where it stopped if it did not finish. */
59
+ export interface BrowserClickSequenceResult {
60
+ /** Points that were clicked successfully. */
61
+ readonly clicked: number;
62
+ /** Index of the point that failed, when one did. */
63
+ readonly failedAt?: number;
64
+ /** Why that point failed. */
65
+ readonly error?: string;
66
+ }
41
67
  /** Type text into the focused element. */
42
68
  export interface BrowserTypeRequest {
43
69
  /** The text to insert. */
@@ -584,6 +610,17 @@ export interface BrowserProvider {
584
610
  click(session: BrowserSessionId, request: BrowserClickRequest | {
585
611
  readonly target: BrowserElementTarget;
586
612
  }, signal?: AbortSignal): Promise<void>;
613
+ /**
614
+ * Click several points in order, in one round trip.
615
+ *
616
+ * Exists because a canvas page accepts only genuine input: one click per call meant two calls
617
+ * per cell on a 9x9 board. Stops at the first point that fails rather than pressing through a
618
+ * page that has moved under it, and reports how far it got.
619
+ * @param session - the session to click in.
620
+ * @param request - the points and the interval between them.
621
+ * @param signal - cancellation between points.
622
+ */
623
+ clickSequence(session: BrowserSessionId, request: BrowserClickSequenceRequest, signal?: AbortSignal): Promise<BrowserClickSequenceResult>;
587
624
  /**
588
625
  * Type into the focused element, or focus a located element first when the
589
626
  * request carries a `target`. Honor `signal` for cancellation.
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Find the desktop install to report on.
3
3
  *
4
- * The same shape probe the installer uses, repeated here because the two run in different processes
5
- * and neither can import the other: the product directory is `DeepSeek Harness` on some builds and
6
- * `DSH Desktop` on others, and the shape that identifies an install is stable across both.
4
+ * Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
5
+ * directory that had one. Any Electron app has that layout, so a stranger's app was reported as
6
+ * "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
7
+ * probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
8
+ * answer is about DSH Desktop and nothing else.
7
9
  * @param localAppData - the base directory; defaults to the environment's.
8
10
  * @returns the install directory, or undefined when nothing matches.
9
11
  */
@@ -18,12 +18,15 @@
18
18
  */
19
19
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
20
20
  import { join } from 'node:path';
21
+ import { readDesktopIdentity } from './desktop-identity.js';
21
22
  /**
22
23
  * Find the desktop install to report on.
23
24
  *
24
- * The same shape probe the installer uses, repeated here because the two run in different processes
25
- * and neither can import the other: the product directory is `DeepSeek Harness` on some builds and
26
- * `DSH Desktop` on others, and the shape that identifies an install is stable across both.
25
+ * Reported as issue #40: this used to probe for a *generic* Electron layout and return the first
26
+ * directory that had one. Any Electron app has that layout, so a stranger's app was reported as
27
+ * "DSH Desktop, bridge missing" — together with a ready-to-run installer command aimed at it. The
28
+ * probe now verifies the same identity the installer does (see `desktop-identity.js`), so the
29
+ * answer is about DSH Desktop and nothing else.
27
30
  * @param localAppData - the base directory; defaults to the environment's.
28
31
  * @returns the install directory, or undefined when nothing matches.
29
32
  */
@@ -31,11 +34,10 @@ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''
31
34
  if (localAppData === '')
32
35
  return undefined;
33
36
  const programs = join(localAppData, 'Programs');
34
- const looksInstalled = (candidate) => existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
35
- || existsSync(join(candidate, 'resources', 'app.asar'));
37
+ const isDesktop = (candidate) => readDesktopIdentity(candidate).ok;
36
38
  for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
37
39
  const candidate = join(programs, named);
38
- if (looksInstalled(candidate))
40
+ if (isDesktop(candidate))
39
41
  return candidate;
40
42
  }
41
43
  try {
@@ -43,7 +45,7 @@ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? ''
43
45
  if (!entry.isDirectory())
44
46
  continue;
45
47
  const candidate = join(programs, entry.name);
46
- if (looksInstalled(candidate))
48
+ if (isDesktop(candidate))
47
49
  return candidate;
48
50
  }
49
51
  }
@@ -78,15 +80,30 @@ export function readBridgeStatus(installRoot) {
78
80
  const mainPath = join(appDir, 'lib', 'main.js');
79
81
  const archivePath = join(resources, 'app.asar');
80
82
  const backupPath = `${mainPath}.before-bridge`;
83
+ // Identity first, and before any other reading. Two reasons, both measured in issue #40: a
84
+ // stranger's app must not be reported as DSH Desktop, and this status also carries a *command* —
85
+ // pointing that command at a directory whose identity was never verified is how the installer got
86
+ // aimed at an application that merely looked like Electron.
87
+ const identity = readDesktopIdentity(installRoot);
88
+ if (!identity.ok) {
89
+ return {
90
+ state: 'missing',
91
+ present: false,
92
+ installRoot,
93
+ archivePresent: safeExists(archivePath),
94
+ detail: `not a DSH Desktop install: ${identity.reason}`,
95
+ };
96
+ }
81
97
  const archivePresent = safeExists(archivePath);
82
98
  const mainPresent = safeExists(mainPath);
83
99
  if (!mainPresent && !archivePresent) {
100
+ // Unreachable once identity has passed (identity requires the loaded main entry), kept as the
101
+ // fail-closed branch for a tree that changed between the two reads.
84
102
  return {
85
103
  state: 'missing',
86
104
  present: false,
87
105
  installRoot,
88
106
  archivePresent,
89
- command: repairCommand(installRoot),
90
107
  detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
91
108
  };
92
109
  }
@@ -28,10 +28,12 @@ import type { CarrierPage, CarrierLossReason } from '../browser/types.js';
28
28
  /** Absolute path of the endpoint file the shell writes. */
29
29
  export declare function bridgeEndpointPath(): string;
30
30
  /**
31
- * A failure worth showing as-is: the carrier is alive and this is a condition the user can change.
31
+ * A failure worth showing as-is: the carrier is alive and this is a condition the shell can change.
32
32
  *
33
- * Thrown instead of a plain Error so callers can distinguish "wait for the conversation to be shown"
34
- * from "the browser broke", which is exactly the distinction issue #37 says was missing.
33
+ * Thrown instead of a plain Error so callers can distinguish "the panel did not render" from "the
34
+ * browser broke", which is exactly the distinction issue #37 says was missing. The plugin no longer
35
+ * waits for a human to show the conversation — the client half asks the shell to (`openSession`) and
36
+ * this host retries while it renders — so reaching here means the shell did not render it at all.
35
37
  */
36
38
  export declare class BrowserPanelNotDisplayedError extends Error {
37
39
  readonly code = "panel-not-displayed";
@@ -43,10 +43,23 @@ export function bridgeEndpointPath() {
43
43
  */
44
44
  const PANEL_NOT_DISPLAYED = 'panel-not-displayed';
45
45
  /**
46
- * A failure worth showing as-is: the carrier is alive and this is a condition the user can change.
46
+ * How many times a display-state refusal is retried, and how long each retry waits.
47
47
  *
48
- * Thrown instead of a plain Error so callers can distinguish "wait for the conversation to be shown"
49
- * from "the browser broke", which is exactly the distinction issue #37 says was missing.
48
+ * The retry exists because the same call now asks the shell to SHOW the conversation (the client
49
+ * half's `openSession` step). React renders that on the next pass, so the refusal the first call
50
+ * sees is true-but-stale. 4 x 400 ms is ~1.6 s: long enough for a render on a busy conversation,
51
+ * short enough that a shell which genuinely cannot render a panel still fails inside one tool call
52
+ * instead of stalling for the bridge's own 20 s budget.
53
+ */
54
+ const PANEL_DISPLAY_RETRIES = 4;
55
+ const PANEL_DISPLAY_RETRY_MS = 400;
56
+ /**
57
+ * A failure worth showing as-is: the carrier is alive and this is a condition the shell can change.
58
+ *
59
+ * Thrown instead of a plain Error so callers can distinguish "the panel did not render" from "the
60
+ * browser broke", which is exactly the distinction issue #37 says was missing. The plugin no longer
61
+ * waits for a human to show the conversation — the client half asks the shell to (`openSession`) and
62
+ * this host retries while it renders — so reaching here means the shell did not render it at all.
50
63
  */
51
64
  export class BrowserPanelNotDisplayedError extends Error {
52
65
  code = PANEL_NOT_DISPLAYED;
@@ -54,8 +67,9 @@ export class BrowserPanelNotDisplayedError extends Error {
54
67
  * @param detail - the bridge's own explanation, appended so the message says why.
55
68
  */
56
69
  constructor(detail) {
57
- super('dsh-builtin-browser: this conversation\'s sidebar page is not attached because the conversation '
58
- + 'is not the one displayed. Show it and the page appears; nothing was lost. '
70
+ super('dsh-builtin-browser: this conversation\'s sidebar page did not attach — the shell was asked to '
71
+ + 'show this conversation and its panel still did not render. Nothing was lost, and the page '
72
+ + 'appears as soon as the panel mounts. '
59
73
  + `(${detail})`);
60
74
  this.name = 'BrowserPanelNotDisplayedError';
61
75
  }
@@ -340,19 +354,39 @@ export class DesktopBridgeViewHost {
340
354
  // conversation's own panel by id through the renderer, rather than by pressing the shell's
341
355
  // shortcut or clicking its card, both of which the shell delivers to whatever it displays.
342
356
  const owner = entry?.owner ?? this.owner;
343
- const answer = await this.connection.call({
357
+ const ask = () => this.connection.call({
344
358
  op: 'ensureSidebar',
345
359
  owner,
346
360
  ...url !== undefined && url !== '' ? { url } : {},
347
361
  }, 30_000);
362
+ let answer = await ask();
363
+ // A refusal is retried when it describes a DISPLAY state rather than a dead carrier, because the
364
+ // plugin's client half asks the shell to show this conversation inside the very call that
365
+ // produced it. Two shapes come back from that first round:
366
+ // panel-not-displayed - the conversation exists but is not the one on screen;
367
+ // "is not mounted" - its surface store was not minted when the tab was placed.
368
+ // Both are gone one render later. Measured, this is the whole difference between "the sidebar
369
+ // works once I click over to that conversation" and "it works" — the page is real either way,
370
+ // and failing the call while the shell is already switching away from it just reported a
371
+ // problem the plugin had already fixed.
372
+ const displayRefusal = (value) => value.ok !== true
373
+ && (String(value.code ?? '') === PANEL_NOT_DISPLAYED
374
+ || String(value.error ?? '').includes('not mounted')
375
+ // Bridges installed before issue #37 send the same refusal with NO code — the installed copy
376
+ // on this machine is one of them (`panel-not-displayed` appears nowhere in it). Reading only
377
+ // the code therefore turned a retryable display state into a hard failure for exactly the
378
+ // users who had the old bridge, which is the majority until it is reinstalled. The wording
379
+ // is stable across both versions; the code is not.
380
+ || String(value.error ?? '').includes('can only attach'));
381
+ for (let attempt = 0; attempt < PANEL_DISPLAY_RETRIES && displayRefusal(answer); attempt += 1) {
382
+ await new Promise(resolve => setTimeout(resolve, PANEL_DISPLAY_RETRY_MS));
383
+ answer = await ask();
384
+ }
348
385
  if (answer.ok !== true) {
349
- // A bridge that answers but cannot produce a page is as usable as one that has exited ONLY when
350
- // the panel can never work here. "The conversation is not displayed" is the opposite case: the
351
- // panel is fine, the shell simply is not rendering it right now, and it will the moment the
352
- // user shows that conversation (issue #37).
353
- //
354
- // So the code decides, not the wording:
355
- // panel-not-displayed -> a transient display state; no loss, no retry, nothing swapped.
386
+ // Reachable only after the retries above have run out, and the code still decides — not the
387
+ // wording:
388
+ // panel-not-displayed -> the shell was asked to show the conversation (client half's
389
+ // `openSession`) and did not render it in ~1.6 s: no loss, no swap.
356
390
  // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
357
391
  // fall back, because otherwise every call fails forever.
358
392
  const code = String(answer.code ?? '');
@@ -0,0 +1,58 @@
1
+ /** The identity rule, as data. */
2
+ interface IdentityRule {
3
+ readonly packageNames: readonly string[];
4
+ readonly mainEntry: string;
5
+ }
6
+ /**
7
+ * The rule shipped in `desktop-bridge/desktop-identity.json`, used when the file cannot be read.
8
+ *
9
+ * A copy exists here only as a fallback for a broken package layout; the test suite asserts that it
10
+ * equals the JSON, so the two can never drift apart silently.
11
+ */
12
+ export declare const FALLBACK_RULE: IdentityRule;
13
+ /** A verified install. */
14
+ export interface DesktopIdentity {
15
+ readonly ok: true;
16
+ /** The install root that was verified. */
17
+ readonly root: string;
18
+ /** Which shape was verified — the archive when it exists, the extraction only without one. */
19
+ readonly layout: 'packed' | 'unpacked';
20
+ /** `name` from the package the caller will actually run. */
21
+ readonly packageName: string;
22
+ /** `version`, when the package declares one. */
23
+ readonly version?: string;
24
+ }
25
+ /** A refusal, with a reason a human can act on. */
26
+ export interface IdentityRefusal {
27
+ readonly ok: false;
28
+ readonly reason: string;
29
+ }
30
+ /**
31
+ * Read the identity rule.
32
+ *
33
+ * Resolved relative to this module, which in both the repository and the published tarball puts
34
+ * `desktop-bridge/` beside `lib/`. A missing file is not fatal — the fallback is the same rule —
35
+ * but a *malformed* one is an error the caller should not ignore, so it is reported through the
36
+ * refusal path rather than silently swapped for the fallback.
37
+ * @returns the rule, or an error string.
38
+ */
39
+ export declare function readIdentityRule(): IdentityRule | {
40
+ readonly error: string;
41
+ };
42
+ /**
43
+ * Read one file out of an asar archive without extracting the tree.
44
+ * @param archive - the archive path.
45
+ * @param path - a slash-separated path inside the archive.
46
+ * @returns the bytes, or undefined when the entry is absent or unreadable.
47
+ */
48
+ export declare function readAsarFile(archive: string, path: string): Buffer | undefined;
49
+ /**
50
+ * Whether an install directory is DSH Desktop.
51
+ *
52
+ * Everything the caller does next (stop the app, delete a tree, extract, rename, write) depends on
53
+ * this being right, so every uncertainty resolves to a refusal that names what was found.
54
+ * @param installRoot - the directory a user or the discovery probe named.
55
+ * @returns the verified identity, or a refusal with a reason.
56
+ */
57
+ export declare function readDesktopIdentity(installRoot: string): DesktopIdentity | IdentityRefusal;
58
+ export {};
@@ -0,0 +1,236 @@
1
+ /**
2
+ * What proves a directory is a DSH Desktop install.
3
+ *
4
+ * Reported as issue #40. Every reader of an install directory used to accept a *generic* Electron
5
+ * layout (`resources/app/lib/main.js` or `resources/app.asar`) as proof, and that is not proof of
6
+ * anything: any Electron app has it. The consequence was measured — a throwaway app in a temp
7
+ * directory, whose own package.json said `unrelated-meeting-app`, was accepted by discovery, got a
8
+ * "bridge not installed" verdict with a ready-to-run installer command aimed at it, and (with that
9
+ * command) had its entry file rewritten and the bridge copied in.
10
+ *
11
+ * So identity is one rule, in one file (`desktop-bridge/desktop-identity.json`), read by both the
12
+ * installer and this module. Nothing else may decide what a DSH Desktop install is.
13
+ *
14
+ * Two properties are load-bearing and are why this is not a one-line `name ===` check:
15
+ *
16
+ * - **The archive wins.** Electron loads `resources/app.asar` in preference to `resources/app`, and
17
+ * a desktop update leaves the old extraction lying around. Reading identity from the extraction
18
+ * while the archive holds a different build would verify the wrong bytes, so when the archive is
19
+ * present that is what is read — and the sibling directory is not consulted at all.
20
+ * - **Unreadable means not DSH.** Every failure path (missing file, truncated pickle, unsupported
21
+ * archive version, malformed JSON, unreadable name) refuses. There is no "assume yes" branch: the
22
+ * caller is about to write into, or delete from, this directory.
23
+ * @module dsh-browser/browser-electron/desktop-identity
24
+ */
25
+ import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs';
26
+ import { join } from 'node:path';
27
+ /**
28
+ * The rule shipped in `desktop-bridge/desktop-identity.json`, used when the file cannot be read.
29
+ *
30
+ * A copy exists here only as a fallback for a broken package layout; the test suite asserts that it
31
+ * equals the JSON, so the two can never drift apart silently.
32
+ */
33
+ export const FALLBACK_RULE = {
34
+ packageNames: ['@deepseek-ai/dsh-desktop', 'dsh-desktop'],
35
+ mainEntry: 'lib/main.js',
36
+ };
37
+ /**
38
+ * Read the identity rule.
39
+ *
40
+ * Resolved relative to this module, which in both the repository and the published tarball puts
41
+ * `desktop-bridge/` beside `lib/`. A missing file is not fatal — the fallback is the same rule —
42
+ * but a *malformed* one is an error the caller should not ignore, so it is reported through the
43
+ * refusal path rather than silently swapped for the fallback.
44
+ * @returns the rule, or an error string.
45
+ */
46
+ export function readIdentityRule() {
47
+ try {
48
+ const path = new URL('../../desktop-bridge/desktop-identity.json', import.meta.url);
49
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
50
+ const names = raw.packageNames;
51
+ const main = raw.mainEntry;
52
+ if (!Array.isArray(names) || names.length === 0 || names.some(n => typeof n !== 'string')) {
53
+ return { error: 'desktop-identity.json: packageNames must be a non-empty array of strings' };
54
+ }
55
+ if (typeof main !== 'string' || main === '') {
56
+ return { error: 'desktop-identity.json: mainEntry must be a non-empty string' };
57
+ }
58
+ return { packageNames: names, mainEntry: main };
59
+ }
60
+ catch (error) {
61
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
62
+ return FALLBACK_RULE;
63
+ }
64
+ return { error: `desktop-identity.json could not be read: ${String(error)}` };
65
+ }
66
+ }
67
+ /**
68
+ * Parse an asar header, the same way the installer does.
69
+ *
70
+ * Layout, for the next reader: an 8-byte outer pickle (`[size][jsonLength]`), then the header
71
+ * pickle whose first 4 bytes are the JSON length, then the JSON tree. File content starts right
72
+ * after the header pickle.
73
+ * @param archive - the archive path.
74
+ * @returns the header tree and the offset where content starts, or an error string.
75
+ */
76
+ function readAsarHeader(archive) {
77
+ let fd;
78
+ try {
79
+ fd = openSync(archive, 'r');
80
+ const outer = Buffer.alloc(8);
81
+ if (readSync(fd, outer, 0, 8, 0) !== 8)
82
+ return { error: 'the archive header is truncated' };
83
+ const headerSize = outer.readUInt32LE(4);
84
+ if (headerSize < 8 || headerSize > 64 * 1024 * 1024)
85
+ return { error: `implausible archive header size (${headerSize})` };
86
+ const header = Buffer.alloc(headerSize);
87
+ if (readSync(fd, header, 0, headerSize, 8) !== headerSize)
88
+ return { error: 'the archive header is truncated' };
89
+ const jsonLength = header.readUInt32LE(4);
90
+ if (jsonLength <= 0 || jsonLength > headerSize - 8)
91
+ return { error: 'the archive header has an implausible JSON length' };
92
+ return { header: JSON.parse(header.toString('utf8', 8, 8 + jsonLength)), contentBase: 8 + headerSize };
93
+ }
94
+ catch (error) {
95
+ return { error: `the archive header could not be read: ${String(error)}` };
96
+ }
97
+ finally {
98
+ if (fd !== undefined) {
99
+ try {
100
+ closeSync(fd);
101
+ }
102
+ catch { /* already closed */ }
103
+ }
104
+ }
105
+ }
106
+ /**
107
+ * Walk a slash-separated path inside an asar header tree.
108
+ * @param tree - the header's `files` node.
109
+ * @param path - e.g. `lib/main.js`.
110
+ * @returns the entry, or undefined when the path does not exist.
111
+ */
112
+ function entryAt(tree, path) {
113
+ let node;
114
+ let files = tree;
115
+ for (const part of path.split('/')) {
116
+ if (files === undefined)
117
+ return undefined;
118
+ node = files[part];
119
+ if (node === undefined)
120
+ return undefined;
121
+ files = node.files;
122
+ }
123
+ return node;
124
+ }
125
+ /**
126
+ * Read one file out of an asar archive without extracting the tree.
127
+ * @param archive - the archive path.
128
+ * @param path - a slash-separated path inside the archive.
129
+ * @returns the bytes, or undefined when the entry is absent or unreadable.
130
+ */
131
+ export function readAsarFile(archive, path) {
132
+ const parsed = readAsarHeader(archive);
133
+ if ('error' in parsed)
134
+ return undefined;
135
+ const entry = entryAt(parsed.header.files, path);
136
+ if (entry === undefined || entry.files !== undefined || entry.unpacked === true)
137
+ return undefined;
138
+ if (typeof entry.offset !== 'string' || typeof entry.size !== 'number' || entry.size < 0)
139
+ return undefined;
140
+ let fd;
141
+ try {
142
+ fd = openSync(archive, 'r');
143
+ const buffer = Buffer.alloc(entry.size);
144
+ const read = readSync(fd, buffer, 0, entry.size, parsed.contentBase + Number(entry.offset));
145
+ return read === entry.size ? buffer : undefined;
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ finally {
151
+ if (fd !== undefined) {
152
+ try {
153
+ closeSync(fd);
154
+ }
155
+ catch { /* already closed */ }
156
+ }
157
+ }
158
+ }
159
+ /**
160
+ * Whether an install directory is DSH Desktop.
161
+ *
162
+ * Everything the caller does next (stop the app, delete a tree, extract, rename, write) depends on
163
+ * this being right, so every uncertainty resolves to a refusal that names what was found.
164
+ * @param installRoot - the directory a user or the discovery probe named.
165
+ * @returns the verified identity, or a refusal with a reason.
166
+ */
167
+ export function readDesktopIdentity(installRoot) {
168
+ const rule = readIdentityRule();
169
+ if ('error' in rule)
170
+ return { ok: false, reason: rule.error };
171
+ const resources = join(installRoot, 'resources');
172
+ const appDir = join(resources, 'app');
173
+ const archive = join(resources, 'app.asar');
174
+ let archivePresent;
175
+ try {
176
+ archivePresent = existsSync(archive);
177
+ }
178
+ catch {
179
+ return { ok: false, reason: `cannot inspect ${archive}` };
180
+ }
181
+ const layout = archivePresent ? 'packed' : 'unpacked';
182
+ let manifestText;
183
+ let mainPresent;
184
+ if (archivePresent) {
185
+ const parsed = readAsarHeader(archive);
186
+ if ('error' in parsed) {
187
+ return { ok: false, reason: `${archive} could not be read: ${parsed.error}` };
188
+ }
189
+ const manifest = entryAt(parsed.header.files, 'package.json');
190
+ if (manifest === undefined || manifest.files !== undefined || manifest.unpacked === true) {
191
+ return { ok: false, reason: `${archive} has no plain package.json; an archive without one is not proof of identity` };
192
+ }
193
+ manifestText = readAsarFile(archive, 'package.json')?.toString('utf8');
194
+ if (manifestText === undefined) {
195
+ return { ok: false, reason: `${archive}: package.json is listed but its bytes cannot be read` };
196
+ }
197
+ mainPresent = entryAt(parsed.header.files, rule.mainEntry) !== undefined;
198
+ }
199
+ else {
200
+ const manifestPath = join(appDir, 'package.json');
201
+ try {
202
+ manifestText = readFileSync(manifestPath, 'utf8');
203
+ }
204
+ catch {
205
+ return { ok: false, reason: `${manifestPath} is missing; a directory without a package manifest is not a DSH Desktop install` };
206
+ }
207
+ mainPresent = existsSync(join(appDir, ...rule.mainEntry.split('/')));
208
+ }
209
+ let manifest;
210
+ try {
211
+ manifest = JSON.parse(manifestText);
212
+ }
213
+ catch {
214
+ return { ok: false, reason: 'the package manifest is not valid JSON' };
215
+ }
216
+ const name = typeof manifest.name === 'string' ? manifest.name : '';
217
+ if (!rule.packageNames.includes(name)) {
218
+ return {
219
+ ok: false,
220
+ reason: `the app calls itself ${name === '' ? '(no name)' : JSON.stringify(name)}, which is not one of `
221
+ + `${rule.packageNames.join(' / ')} — refusing to touch a different application`,
222
+ };
223
+ }
224
+ // The main entry is the file the installer patches and the shell runs; if it is not there, this
225
+ // is not an install this plugin can reason about even though the manifest looks right.
226
+ if (!mainPresent) {
227
+ return { ok: false, reason: `${rule.mainEntry} is not present under ${archivePresent ? archive : appDir}` };
228
+ }
229
+ return {
230
+ ok: true,
231
+ root: installRoot,
232
+ layout,
233
+ packageName: name,
234
+ ...typeof manifest.version === 'string' ? { version: manifest.version } : {},
235
+ };
236
+ }