dsh-builtin-browser 0.4.15 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.en.md +17 -9
  3. package/README.md +48 -10
  4. package/client.js +410 -6
  5. package/desktop-bridge/install-and-start.cmd +36 -0
  6. package/desktop-bridge/install.mjs +166 -3
  7. package/desktop-bridge/plugin-browser-bridge.js +133 -11
  8. package/docs/development.md +19 -0
  9. package/docs/limitations.md +7 -3
  10. package/docs/user-guide.md +46 -18
  11. package/lib/browser/runtime.d.ts +21 -2
  12. package/lib/browser/runtime.js +30 -0
  13. package/lib/browser/types.d.ts +54 -0
  14. package/lib/browser-electron/bridge-status.d.ts +41 -0
  15. package/lib/browser-electron/bridge-status.js +164 -0
  16. package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
  17. package/lib/browser-electron/desktop-bridge-host.js +75 -44
  18. package/lib/browser-electron/entry.js +130 -11
  19. package/lib/browser-electron/file-write.d.ts +2 -0
  20. package/lib/browser-electron/file-write.js +39 -0
  21. package/lib/browser-electron/history-store.d.ts +8 -19
  22. package/lib/browser-electron/history-store.js +37 -58
  23. package/lib/browser-electron/host-main.js +15 -22
  24. package/lib/browser-electron/preview-route.d.ts +89 -0
  25. package/lib/browser-electron/preview-route.js +172 -0
  26. package/lib/browser-electron/provider.d.ts +62 -3
  27. package/lib/browser-electron/provider.js +246 -12
  28. package/lib/browser-electron/remote-host.js +5 -1
  29. package/lib/browser-electron/rpc-input.d.ts +4 -0
  30. package/lib/browser-electron/rpc-input.js +11 -0
  31. package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
  32. package/lib/browser-electron/runtime-diagnostics.js +29 -0
  33. package/lib/browser-electron/settings-store.d.ts +15 -2
  34. package/lib/browser-electron/settings-store.js +25 -5
  35. package/lib/browser-electron/system-browser.d.ts +18 -0
  36. package/lib/browser-electron/system-browser.js +116 -33
  37. package/lib/tool-browser/index.js +10 -1
  38. package/package.json +8 -3
  39. package/scripts/install-electron.mjs +66 -0
  40. package/scripts/verify-preview-route.mjs +150 -0
  41. package/src/browser/runtime.ts +36 -0
  42. package/src/browser/types.ts +55 -0
  43. package/src/browser-electron/bridge-status.ts +180 -0
  44. package/src/browser-electron/desktop-bridge-host.ts +75 -41
  45. package/src/browser-electron/entry.ts +119 -11
  46. package/src/browser-electron/file-write.ts +31 -0
  47. package/src/browser-electron/history-store.ts +36 -57
  48. package/src/browser-electron/host-main.ts +16 -18
  49. package/src/browser-electron/preview-route.ts +222 -0
  50. package/src/browser-electron/provider.ts +286 -16
  51. package/src/browser-electron/remote-host.ts +5 -1
  52. package/src/browser-electron/rpc-input.ts +13 -0
  53. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  54. package/src/browser-electron/settings-store.ts +37 -5
  55. package/src/browser-electron/system-browser.ts +108 -29
  56. package/src/tool-browser/index.ts +13 -1
@@ -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, 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, 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, BrowserProvider, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSessionId, BrowserSnapshotElement, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, ExportedCookie, } 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';
14
14
  declare module '@deepseek-ai/cordis' {
15
15
  interface Context {
16
16
  browser: BrowserRuntime;
@@ -114,6 +114,17 @@ export declare class BrowserRuntime extends Service {
114
114
  scrape(session: BrowserSessionId, request: BrowserScrapeRequest, signal?: AbortSignal): Promise<BrowserScrapeResult>;
115
115
  /** Capture the current page through the selected provider. */
116
116
  screenshot(session: BrowserSessionId, request?: BrowserScreenshotRequest, signal?: AbortSignal): Promise<BrowserScreenshotResult>;
117
+ /**
118
+ * Capture the active page without presenting it, through the selected provider.
119
+ *
120
+ * Optional throughout: a provider that cannot do this keeps working for every other tool, and the
121
+ * caller gets exactly one error code meaning "watching is not available here" — which the viewer
122
+ * renders as paused rather than as a failure of the browser.
123
+ * @param session - the session whose active page to capture.
124
+ * @param signal - cancellation for the wait, never for the capture itself.
125
+ * @returns the encoded frame.
126
+ */
127
+ capturePassive(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserPreviewFrame>;
117
128
  /** Check for a human-verification challenge on the active tab. */
118
129
  detectChallenge(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserChallenge>;
119
130
  /** Return the session's chronological operation log through the provider. */
@@ -135,6 +146,14 @@ export declare class BrowserRuntime extends Service {
135
146
  * @param session - the session id to test.
136
147
  */
137
148
  exists(session: BrowserSessionId): boolean;
149
+ /**
150
+ * The sessions a viewer may watch, through the selected provider.
151
+ *
152
+ * Empty when the provider cannot preview at all: a viewer then has nothing to offer, which is the
153
+ * honest answer rather than an error.
154
+ * @returns the live session ids.
155
+ */
156
+ watchableSessions(): readonly BrowserSessionId[];
138
157
  /** Replay one recorded operation by sequence number through the provider. */
139
158
  replay(session: BrowserSessionId, seq: number): Promise<void>;
140
159
  /** Download a URL to a local file through the provider. */
@@ -194,6 +194,23 @@ export class BrowserRuntime extends Service {
194
194
  async screenshot(session, request, signal) {
195
195
  return this.resolveProvider().screenshot(session, request, signal);
196
196
  }
197
+ /**
198
+ * Capture the active page without presenting it, through the selected provider.
199
+ *
200
+ * Optional throughout: a provider that cannot do this keeps working for every other tool, and the
201
+ * caller gets exactly one error code meaning "watching is not available here" — which the viewer
202
+ * renders as paused rather than as a failure of the browser.
203
+ * @param session - the session whose active page to capture.
204
+ * @param signal - cancellation for the wait, never for the capture itself.
205
+ * @returns the encoded frame.
206
+ */
207
+ async capturePassive(session, signal) {
208
+ const provider = this.resolveProvider();
209
+ if (typeof provider.capturePassive !== 'function') {
210
+ throw new BrowserError('browser: this carrier cannot provide a passive preview (watching is unavailable here)', 'BROWSER_PREVIEW_UNAVAILABLE');
211
+ }
212
+ return provider.capturePassive(session, signal);
213
+ }
197
214
  /** Check for a human-verification challenge on the active tab. */
198
215
  async detectChallenge(session, signal) {
199
216
  return this.resolveProvider().detectChallenge(session, signal);
@@ -221,6 +238,19 @@ export class BrowserRuntime extends Service {
221
238
  const provider = this.resolveProvider();
222
239
  return provider.exists === undefined ? true : provider.exists(session);
223
240
  }
241
+ /**
242
+ * The sessions a viewer may watch, through the selected provider.
243
+ *
244
+ * Empty when the provider cannot preview at all: a viewer then has nothing to offer, which is the
245
+ * honest answer rather than an error.
246
+ * @returns the live session ids.
247
+ */
248
+ watchableSessions() {
249
+ const provider = this.resolveProvider();
250
+ if (typeof provider.capturePassive !== 'function')
251
+ return [];
252
+ return provider.watchableSessions?.() ?? [];
253
+ }
224
254
  /** Replay one recorded operation by sequence number through the provider. */
225
255
  async replay(session, seq) {
226
256
  return this.resolveProvider().replay(session, seq);
@@ -352,6 +352,27 @@ export interface BrowserSnapshotResult {
352
352
  readonly truncated: boolean;
353
353
  /** Human-verification challenge blocking the page, when one is detected. */
354
354
  readonly challenge?: BrowserChallenge;
355
+ /**
356
+ * True when this is a blank page — no document to read, nothing to drive.
357
+ *
358
+ * Zero elements means two very different things: a page that genuinely has nothing interactive,
359
+ * and a browser that has not opened anything at all. Without this flag they look identical, so a
360
+ * caller can act on a blank page and get a success value back — reported as issue #37, where every
361
+ * tool after a carrier swap answered against `about:blank` while appearing to work.
362
+ *
363
+ * Set for `about:blank` and for a view that has never navigated. A caller seeing it should treat
364
+ * the page as absent, not as empty.
365
+ */
366
+ readonly blank?: boolean;
367
+ /** A sentence a caller can show instead of reporting an empty page as a successful read. */
368
+ readonly note?: string;
369
+ /**
370
+ * True when the page draws its interface on a canvas, so no DOM element exists to collect.
371
+ *
372
+ * Distinct from `blank`: the page is fully rendered and interactive, just not as elements. A
373
+ * caller must switch to a screenshot and coordinate input rather than conclude the page is empty.
374
+ */
375
+ readonly canvas?: boolean;
355
376
  }
356
377
  /**
357
378
  * One node of the accessibility tree, with a stable reference number the
@@ -465,6 +486,17 @@ export interface BrowserTab {
465
486
  /** Whether this tab is the active one. */
466
487
  readonly active: boolean;
467
488
  }
489
+ /**
490
+ * One passive preview frame: an encoded image plus its dimensions.
491
+ *
492
+ * The image is a data URL so it travels the existing JSON seam unchanged; the media type is part of
493
+ * the URL rather than a separate field because every consumer needs them together.
494
+ */
495
+ export interface BrowserPreviewFrame {
496
+ readonly dataUrl: string;
497
+ readonly width?: number;
498
+ readonly height?: number;
499
+ }
468
500
  /** One page a carrier holds, whether or not this plugin created it. */
469
501
  export interface CarrierPage {
470
502
  /** Stable within one carrier session; used to address the page. */
@@ -587,6 +619,28 @@ export interface BrowserProvider {
587
619
  fillForm(session: BrowserSessionId, request: BrowserFillRequest, signal?: AbortSignal): Promise<BrowserFillResult>;
588
620
  /** Capture the current page. Honor `signal` for cancellation. */
589
621
  screenshot(session: BrowserSessionId, request?: BrowserScreenshotRequest, signal?: AbortSignal): Promise<BrowserScreenshotResult>;
622
+ /**
623
+ * Capture the active page WITHOUT presenting it, for a remote live view (issue #34).
624
+ *
625
+ * Optional, and it must stay optional: a third-party provider that cannot do this simply does not
626
+ * offer watching, while every existing tool keeps working. That is the design's requirement, not
627
+ * a convenience — a mandatory member would make every provider implement a feature most never
628
+ * need.
629
+ *
630
+ * The contract is narrower than {@link screenshot} in every direction: viewport only, no save
631
+ * path, no full page, and no side effects on what the host displays. A provider that would have to
632
+ * focus, restore, expand or recreate anything to produce a frame must throw
633
+ * BROWSER_PREVIEW_UNAVAILABLE instead — the viewer shows a paused state, it does not rearrange the
634
+ * host's screen.
635
+ */
636
+ capturePassive?(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserPreviewFrame>;
637
+ /**
638
+ * The sessions a viewer may watch. Only meaningful alongside {@link capturePassive}.
639
+ *
640
+ * Exists because the provider names its sessions and the browser page cannot know one; served as
641
+ * ids only, so the panel can address a session without being told what is in it.
642
+ */
643
+ watchableSessions?(): readonly BrowserSessionId[];
590
644
  /** Download a URL to a local file. Honor `signal` for cancellation. */
591
645
  download(session: BrowserSessionId, request: BrowserDownloadRequest, signal?: AbortSignal): Promise<{
592
646
  readonly path: string;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Find the desktop install to report on.
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.
7
+ * @param localAppData - the base directory; defaults to the environment's.
8
+ * @returns the install directory, or undefined when nothing matches.
9
+ */
10
+ export declare function findDesktopInstall(localAppData?: string): string | undefined;
11
+ /** One reading of the install tree. */
12
+ export interface BridgeStatus {
13
+ /** `installed`, `missing` or `stale`; see the module comment for what each means. */
14
+ readonly state: 'installed' | 'missing' | 'stale';
15
+ /** Whether the install directory looks like a DSH Desktop install at all. */
16
+ readonly present: boolean;
17
+ /** The directory that was inspected, when one was found. */
18
+ readonly installRoot?: string;
19
+ /** Whether `resources/app.asar` exists — the archive the shell actually loads. */
20
+ readonly archivePresent: boolean;
21
+ /** When the pre-bridge backup was written, if there is one. */
22
+ readonly backupAt?: string;
23
+ /** A one-line explanation for the panel, in the plugin's own words. */
24
+ readonly detail: string;
25
+ /**
26
+ * The command that installs or repairs the bridge.
27
+ *
28
+ * Shown rather than run. Executing it from a web request would mean a page can decide to close the
29
+ * desktop shell, and no amount of same-origin checking makes that a good idea; the user runs it.
30
+ */
31
+ readonly command?: string;
32
+ }
33
+ /**
34
+ * Read the bridge's state from an install directory.
35
+ *
36
+ * Never throws: a caller showing this in a settings panel must get an answer even when the directory
37
+ * is unreadable or the user pointed at something that is not an install.
38
+ * @param installRoot - the desktop install directory.
39
+ * @returns the current state.
40
+ */
41
+ export declare function readBridgeStatus(installRoot: string): BridgeStatus;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Whether the desktop bridge is installed, and what state its files are in.
3
+ *
4
+ * Reported as issue #36: when the bridge is missing the plugin only logs a warning, so a user who
5
+ * chose `channel: sidebar` sees "another window opened again" and has no way to connect that with
6
+ * "the bridge is not installed". This module answers the question the panel needs to show, from the
7
+ * install tree on disk rather than from anything the plugin remembers.
8
+ *
9
+ * The states are the three that actually occur:
10
+ *
11
+ * - `installed` — the shell's main.js carries our marker and the archive is still moved aside.
12
+ * - `missing` — no marker. Either never installed, or the shell was upgraded (which restores
13
+ * `app.asar` and replaces `lib/main.js`) and the bridge went with it.
14
+ * - `stale` — the marker is present but `app.asar` is back. That is the signature of a desktop
15
+ * update that restored the archive without removing our patch: the shell loads the archive, so the
16
+ * patch inside the unpacked tree has no effect. This is the case that looks installed and is not.
17
+ * @module dsh-browser/browser-electron/bridge-status
18
+ */
19
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
20
+ import { join } from 'node:path';
21
+ /**
22
+ * Find the desktop install to report on.
23
+ *
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.
27
+ * @param localAppData - the base directory; defaults to the environment's.
28
+ * @returns the install directory, or undefined when nothing matches.
29
+ */
30
+ export function findDesktopInstall(localAppData = process.env.LOCALAPPDATA ?? '') {
31
+ if (localAppData === '')
32
+ return undefined;
33
+ const programs = join(localAppData, 'Programs');
34
+ const looksInstalled = (candidate) => existsSync(join(candidate, 'resources', 'app', 'lib', 'main.js'))
35
+ || existsSync(join(candidate, 'resources', 'app.asar'));
36
+ for (const named of ['DSH Desktop', 'DeepSeek Harness']) {
37
+ const candidate = join(programs, named);
38
+ if (looksInstalled(candidate))
39
+ return candidate;
40
+ }
41
+ try {
42
+ for (const entry of readdirSync(programs, { withFileTypes: true })) {
43
+ if (!entry.isDirectory())
44
+ continue;
45
+ const candidate = join(programs, entry.name);
46
+ if (looksInstalled(candidate))
47
+ return candidate;
48
+ }
49
+ }
50
+ catch {
51
+ // No Programs directory: nothing to report on, which is a state rather than an error.
52
+ }
53
+ return undefined;
54
+ }
55
+ /** The marker the installer inserts into the shell's main.js. */
56
+ const MARKER = '// dsh-builtin-browser: hand the plugin a way to drive the sidebar';
57
+ /**
58
+ * The command a user should run for this state, quoted so it survives a path with spaces.
59
+ * @param installRoot - the install directory, or undefined when none was found.
60
+ * @returns the command line, or undefined when there is nothing useful to suggest.
61
+ */
62
+ function repairCommand(installRoot) {
63
+ if (installRoot === undefined)
64
+ return undefined;
65
+ return `node desktop-bridge/install.mjs "${installRoot}" --restart`;
66
+ }
67
+ /**
68
+ * Read the bridge's state from an install directory.
69
+ *
70
+ * Never throws: a caller showing this in a settings panel must get an answer even when the directory
71
+ * is unreadable or the user pointed at something that is not an install.
72
+ * @param installRoot - the desktop install directory.
73
+ * @returns the current state.
74
+ */
75
+ export function readBridgeStatus(installRoot) {
76
+ const resources = join(installRoot, 'resources');
77
+ const appDir = join(resources, 'app');
78
+ const mainPath = join(appDir, 'lib', 'main.js');
79
+ const archivePath = join(resources, 'app.asar');
80
+ const backupPath = `${mainPath}.before-bridge`;
81
+ const archivePresent = safeExists(archivePath);
82
+ const mainPresent = safeExists(mainPath);
83
+ if (!mainPresent && !archivePresent) {
84
+ return {
85
+ state: 'missing',
86
+ present: false,
87
+ installRoot,
88
+ archivePresent,
89
+ command: repairCommand(installRoot),
90
+ detail: 'not a DSH Desktop install: no resources/app/lib/main.js and no resources/app.asar',
91
+ };
92
+ }
93
+ let backupAt;
94
+ try {
95
+ if (existsSync(backupPath))
96
+ backupAt = statSync(backupPath).mtime.toISOString();
97
+ }
98
+ catch {
99
+ // A backup we cannot stat is simply not reported; it does not change the state.
100
+ }
101
+ if (archivePresent && !safeIncludes(mainPath, MARKER)) {
102
+ // The archive is what the shell loads, so an unpacked tree without our marker is not in effect
103
+ // even if it were patched.
104
+ return {
105
+ state: 'missing',
106
+ present: true,
107
+ installRoot,
108
+ archivePresent,
109
+ ...backupAt === undefined ? {} : { backupAt },
110
+ command: repairCommand(installRoot),
111
+ detail: 'packed layout with no bridge in the loaded tree: the bridge is not installed',
112
+ };
113
+ }
114
+ if (archivePresent) {
115
+ return {
116
+ state: 'stale',
117
+ present: true,
118
+ installRoot,
119
+ archivePresent,
120
+ ...backupAt === undefined ? {} : { backupAt },
121
+ command: repairCommand(installRoot),
122
+ detail: 'the archive is back alongside the patched tree, so the shell loads the archive: '
123
+ + 'a desktop update restored it. Re-run the installer to repair.',
124
+ };
125
+ }
126
+ if (!safeIncludes(mainPath, MARKER)) {
127
+ return {
128
+ state: 'missing',
129
+ present: true,
130
+ installRoot,
131
+ archivePresent,
132
+ ...backupAt === undefined ? {} : { backupAt },
133
+ command: repairCommand(installRoot),
134
+ detail: 'unpacked layout without the bridge patch: the bridge is not installed',
135
+ };
136
+ }
137
+ return {
138
+ state: 'installed',
139
+ present: true,
140
+ installRoot,
141
+ archivePresent,
142
+ ...backupAt === undefined ? {} : { backupAt },
143
+ command: repairCommand(installRoot),
144
+ detail: 'the shell loads the patched tree and the bridge is in it',
145
+ };
146
+ }
147
+ /** Whether a path exists, treating any error as absence. */
148
+ function safeExists(path) {
149
+ try {
150
+ return existsSync(path);
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ /** Whether a file contains a string, treating any error as absence. */
157
+ function safeIncludes(path, needle) {
158
+ try {
159
+ return existsSync(path) && statSync(path).isFile() && readFileSync(path, 'utf8').includes(needle);
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
@@ -27,6 +27,19 @@ import type { BrowserUserAction } from './provider.js';
27
27
  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
+ /**
31
+ * A failure worth showing as-is: the carrier is alive and this is a condition the user can change.
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.
35
+ */
36
+ export declare class BrowserPanelNotDisplayedError extends Error {
37
+ readonly code = "panel-not-displayed";
38
+ /**
39
+ * @param detail - the bridge's own explanation, appended so the message says why.
40
+ */
41
+ constructor(detail: string);
42
+ }
30
43
  /**
31
44
  * The desktop sidebar, presented as a browser view host.
32
45
  *
@@ -159,7 +172,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
159
172
  * possible exists only here.
160
173
  * @returns the panel's pages that are not ours, or an empty list when the bridge cannot answer.
161
174
  */
162
- listPages(): Promise<readonly CarrierPage[]>;
175
+ listPages(owner?: string): Promise<readonly CarrierPage[]>;
163
176
  /**
164
177
  * Close one sidebar page by the id {@link listPages} reported.
165
178
  *
@@ -169,7 +182,7 @@ export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
169
182
  * than as an error: the caller asked for it to be closed, and it is.
170
183
  * @param id - the sidebar guest id, as a string.
171
184
  */
172
- closePage(id: string): Promise<void>;
185
+ closePage(id: string, owner?: string): Promise<void>;
173
186
  /**
174
187
  * The guest backing a view, materialized on first use.
175
188
  *
@@ -32,12 +32,45 @@ export function bridgeEndpointPath() {
32
32
  const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
33
33
  return join(home, 'dsh-builtin-browser-bridge.json');
34
34
  }
35
+ /**
36
+ * The error code the bridge uses when the conversation's panel exists but the shell is not showing
37
+ * that conversation, so no webview has attached yet (issue #37).
38
+ *
39
+ * A display state, not a dead carrier. It must never reach `reportLost`, and it must never be
40
+ * retried as though a guest had vanished: retrying cannot attach a webview the shell has not
41
+ * rendered, and treating it as loss swapped the surface to a fresh self-hosted window whose page was
42
+ * blank — losing the page the user had open.
43
+ */
44
+ const PANEL_NOT_DISPLAYED = 'panel-not-displayed';
45
+ /**
46
+ * A failure worth showing as-is: the carrier is alive and this is a condition the user can change.
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.
50
+ */
51
+ export class BrowserPanelNotDisplayedError extends Error {
52
+ code = PANEL_NOT_DISPLAYED;
53
+ /**
54
+ * @param detail - the bridge's own explanation, appended so the message says why.
55
+ */
56
+ 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. '
59
+ + `(${detail})`);
60
+ this.name = 'BrowserPanelNotDisplayedError';
61
+ }
62
+ }
35
63
  /**
36
64
  * Whether a command failed because the page is no longer there (as opposed to
37
65
  * failing on its own merits). Only these are worth retrying on a fresh guest.
38
66
  * @param error - the failure to classify.
39
67
  */
40
68
  function isGuestGone(error) {
69
+ // "The conversation is not displayed" is NOT a vanished guest. It is listed here as a negative
70
+ // because retrying it wastes the only thing it can produce: the same answer, slower. Issue #37 was
71
+ // this classification being too broad.
72
+ if (error instanceof BrowserPanelNotDisplayedError)
73
+ return false;
41
74
  const message = error instanceof Error ? error.message : String(error);
42
75
  // The panel path reports its own failure when the renderer never produced a page, and that is the
43
76
  // same class as a vanished guest — worth one retry on a fresh panel — so it is listed here too.
@@ -240,28 +273,23 @@ export class DesktopBridgeViewHost {
240
273
  * possible exists only here.
241
274
  * @returns the panel's pages that are not ours, or an empty list when the bridge cannot answer.
242
275
  */
243
- async listPages() {
244
- try {
245
- const answer = await this.connection.call({ op: 'list', owner: this.owner }, 5_000);
246
- const guests = Array.isArray(answer.sidebar) ? answer.sidebar : [];
247
- const ours = new Set();
248
- for (const view of this.views.values()) {
249
- if (typeof view.guest === 'number')
250
- ours.add(view.guest);
251
- }
252
- return guests
253
- .filter((guest) => typeof guest?.id === 'number')
254
- .filter(guest => !ours.has(guest.id))
255
- .map(guest => ({
256
- id: String(guest.id),
257
- url: typeof guest.url === 'string' ? guest.url : '',
258
- }));
259
- }
260
- catch {
261
- // A bridge that cannot answer has a real problem, and the next command reports it. Failing
262
- // the tab LIST here would make a listing worse than the driving it exists to describe.
263
- return [];
276
+ async listPages(owner = this.owner) {
277
+ const answer = await this.connection.call({ op: 'list', owner }, 5_000);
278
+ if (answer.ok !== true)
279
+ throw new Error(String(answer.error ?? 'sidebar page listing failed'));
280
+ const guests = Array.isArray(answer.sidebar) ? answer.sidebar : [];
281
+ const ours = new Set();
282
+ for (const view of this.views.values()) {
283
+ if (typeof view.guest === 'number')
284
+ ours.add(view.guest);
264
285
  }
286
+ return guests
287
+ .filter((guest) => typeof guest?.id === 'number')
288
+ .filter(guest => !ours.has(guest.id))
289
+ .map(guest => ({
290
+ id: String(guest.id),
291
+ url: typeof guest.url === 'string' ? guest.url : '',
292
+ }));
265
293
  }
266
294
  /**
267
295
  * Close one sidebar page by the id {@link listPages} reported.
@@ -272,19 +300,14 @@ export class DesktopBridgeViewHost {
272
300
  * than as an error: the caller asked for it to be closed, and it is.
273
301
  * @param id - the sidebar guest id, as a string.
274
302
  */
275
- async closePage(id) {
303
+ async closePage(id, owner = this.owner) {
276
304
  const numeric = Number(id);
277
- if (!Number.isFinite(numeric))
305
+ if (!Number.isSafeInteger(numeric) || numeric <= 0)
278
306
  throw new Error(`not a sidebar page id: ${id}`);
279
- const answer = await this.connection.call({ op: 'list', owner: this.owner }, 5_000);
280
- const guests = Array.isArray(answer.sidebar) ? answer.sidebar : [];
281
- const title = guests
282
- .filter((guest) => Number(guest?.id) === numeric)
283
- .map(guest => String(guest.title ?? ''))
284
- .find(candidate => candidate !== '');
285
- if (title === undefined)
286
- return;
287
- await this.connection.call({ op: 'closeSidebarBrowser', titles: [title], owner: this.owner }, 10_000);
307
+ const answer = await this.connection.call({ op: 'closePage', id: numeric, owner }, 10_000);
308
+ if (answer.ok !== true || answer.closed !== 1) {
309
+ throw new Error(`dsh-builtin-browser: could not close sidebar page ${id}: ${String(answer.error ?? 'the shell did not close the requested page; refresh or upgrade the desktop bridge')}`);
310
+ }
288
311
  }
289
312
  /**
290
313
  * The guest backing a view, materialized on first use.
@@ -323,19 +346,22 @@ export class DesktopBridgeViewHost {
323
346
  ...url !== undefined && url !== '' ? { url } : {},
324
347
  }, 30_000);
325
348
  if (answer.ok !== true) {
326
- // A bridge that answers but cannot produce a page is as unusable as one that has exited, and
327
- // the difference matters here: `onLost` is what returns the surface to the self-hosted
328
- // browser. Without this the same failure repeats on every call until DSH is restarted — on a
329
- // shell whose sidebar panel is an iframe, that is every call forever. Reported as "installing
330
- // the bridge made it worse than not installing it": the carrier was switched to one that
331
- // cannot work, with no path back to the one that does.
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).
332
353
  //
333
- // `panel-unusable`, not `shell-exited`: the shell is alive and answered this very request. The
334
- // fallback's message used to announce an exiting shell unconditionally, which told the user
335
- // their desktop had crashed when it was running normally.
336
- if (String(answer.error).includes('produced no page'))
354
+ // So the code decides, not the wording:
355
+ // panel-not-displayed -> a transient display state; no loss, no retry, nothing swapped.
356
+ // produced no page -> this shell cannot drive a panel at all (an iframe shell, issue #30);
357
+ // fall back, because otherwise every call fails forever.
358
+ const code = String(answer.code ?? '');
359
+ const detail = String(answer.error);
360
+ if (code === PANEL_NOT_DISPLAYED)
361
+ throw new BrowserPanelNotDisplayedError(detail);
362
+ if (detail.includes('produced no page'))
337
363
  this.reportLost('panel-unusable');
338
- throw new Error(`dsh-builtin-browser: sidebar unavailable (${String(answer.error)})`);
364
+ throw new Error(`dsh-builtin-browser: sidebar unavailable (${detail})`);
339
365
  }
340
366
  const id = Number(answer.id);
341
367
  if (!Number.isFinite(id) || id <= 0) {
@@ -417,7 +443,12 @@ export class DesktopBridgeViewHost {
417
443
  // It comes from the view, not the process — with several conversations live, a process-wide
418
444
  // owner would raise the wrong conversation's tab.
419
445
  const owner = this.views.get(handle.id)?.owner ?? this.owner;
420
- void this.connection.call({ op: 'showTab', viewId: Number(handle.id), owner }, 5_000).catch(() => undefined);
446
+ const guest = this.views.get(handle.id)?.guest;
447
+ // showActive also runs before a view has navigated; do not materialize a blank page just to
448
+ // present it. Once materialized, only the shell's numeric guest id can name its tab.
449
+ if (guest === undefined)
450
+ return;
451
+ void this.connection.call({ op: 'showTab', viewId: guest, owner }, 5_000).catch(() => undefined);
421
452
  }
422
453
  onUserAction(handler) {
423
454
  this.userActionHandler = handler;