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
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The live-view frame endpoint (issue #34): one JPEG per request, for a remote operator watching the
3
+ * page the agent is driving.
4
+ *
5
+ * Deliberately one frame per request rather than a stream. The viewer asks for the next frame after
6
+ * it has decoded and painted the previous one, so a slow link slows the view down instead of
7
+ * queueing images; the design chose this over MJPEG and WebSocket for the first version precisely
8
+ * because it needs no new plumbing and degrades predictably.
9
+ *
10
+ * The path is fixed and the session travels as a query parameter because the host web server only
11
+ * registers exact paths. That is also why the session id is not a `viewId`: a client may name a
12
+ * session the plugin handed out, never a carrier handle, a port, or an arbitrary target.
13
+ * @module dsh-browser/browser-electron/preview-route
14
+ */
15
+ import type { IncomingMessage, ServerResponse } from 'node:http'
16
+ import type { BrowserError } from '../browser/types.js'
17
+ import { sameOrigin } from './settings-route.js'
18
+ import { findDesktopInstall, readBridgeStatus } from './bridge-status.js'
19
+
20
+ /** Where the frame endpoint lives. The viewer must use exactly this path, same origin. */
21
+ export const PREVIEW_ROUTE = '/dsh-builtin-browser/browser-view/frame'
22
+
23
+ /**
24
+ * Where the viewer asks which sessions it may watch.
25
+ *
26
+ * The provider names its sessions (`browser:<uuid>`) and only it knows them; the browser page has no
27
+ * way to guess one. Without this the viewer could not build a frame URL at all, and inventing an id
28
+ * is exactly what the design forbids. So the list is served, and it contains nothing but ids of
29
+ * sessions that currently have a page — no URLs, no titles, no target handles.
30
+ */
31
+ export const PREVIEW_SESSIONS_ROUTE = '/dsh-builtin-browser/browser-view/sessions'
32
+
33
+ /**
34
+ * Where the settings panel asks whether the desktop bridge is installed.
35
+ *
36
+ * Reported as issue #36: a missing bridge was only a log warning, so a user on `channel: sidebar`
37
+ * saw "another window opened again" with nothing connecting that to "the bridge is not installed".
38
+ * The reading is taken from the install tree on disk, so it is true even when the plugin has just
39
+ * started and remembers nothing.
40
+ */
41
+ export const BRIDGE_STATUS_ROUTE = '/dsh-builtin-browser/bridge-status'
42
+
43
+
44
+ /** What the route needs from the settings document. */
45
+ interface PreviewSettings {
46
+ get(): { readonly remoteView: { readonly enabled: boolean } }
47
+ }
48
+
49
+ /** What the route needs from the browser service. */
50
+ interface PreviewBrowser {
51
+ exists(session: string): boolean
52
+ capturePassive(session: string, signal?: AbortSignal): Promise<{ readonly dataUrl: string }>
53
+ /** Sessions that currently hold a page. Optional: a service without it reports none. */
54
+ watchableSessions?(): readonly string[]
55
+ }
56
+
57
+ /**
58
+ * List the sessions a viewer may watch.
59
+ *
60
+ * Ids only. The whole point of this endpoint is to give the page something it cannot guess; adding a
61
+ * URL or title here would leak the very content the frame endpoint is careful not to describe in its
62
+ * refusals.
63
+ * @param request - the incoming request.
64
+ * @param response - the response to write.
65
+ * @param settings - the settings document, for the share switch.
66
+ * @param browser - the browser service.
67
+ */
68
+ export async function handlePreviewSessions(
69
+ request: IncomingMessage,
70
+ response: ServerResponse,
71
+ settings: PreviewSettings,
72
+ browser: PreviewBrowser,
73
+ ): Promise<void> {
74
+ if (request.method !== 'GET') {
75
+ replyJson(response, 405, { error: 'method-not-allowed' })
76
+ return
77
+ }
78
+ if (!sameOrigin(request)) {
79
+ replyJson(response, 403, { error: 'not-same-origin' })
80
+ return
81
+ }
82
+ if (settings.get().remoteView.enabled !== true) {
83
+ // An empty list rather than a refusal: the panel asks this before it knows whether sharing is
84
+ // on, and "nothing to watch" is the honest answer to give a client that is not allowed to watch.
85
+ replyJson(response, 200, { enabled: false, sessions: [] })
86
+ return
87
+ }
88
+ const sessions = browser.watchableSessions?.() ?? []
89
+ replyJson(response, 200, { enabled: true, sessions: [...sessions] })
90
+ }
91
+
92
+ /** Write one JSON body with no caching and no sniffing. */
93
+ function replyJson(response: ServerResponse, status: number, body: unknown): void {
94
+ const text = JSON.stringify(body)
95
+ response.writeHead(status, {
96
+ 'content-type': 'application/json; charset=utf-8',
97
+ 'content-length': Buffer.byteLength(text),
98
+ 'cache-control': 'no-store, private',
99
+ 'x-content-type-options': 'nosniff',
100
+ 'cross-origin-resource-policy': 'same-origin',
101
+ })
102
+ response.end(text)
103
+ }
104
+
105
+ /**
106
+ * Serve one frame, or say precisely why not.
107
+ *
108
+ * Every refusal is a status the viewer can act on: 403 when watching is switched off (the host has
109
+ * not agreed), 404 when that session has no page (nothing to watch, and nothing is opened on its
110
+ * behalf), 503 when the page cannot produce an image right now (hidden window, capture timeout) —
111
+ * which the viewer shows as paused rather than as an error.
112
+ * @param request - the incoming request.
113
+ * @param response - the response to write.
114
+ * @param settings - the settings document, for the host's share switch.
115
+ * @param browser - the browser service, for passive capture.
116
+ */
117
+ export async function handlePreviewFrame(
118
+ request: IncomingMessage,
119
+ response: ServerResponse,
120
+ settings: PreviewSettings,
121
+ browser: PreviewBrowser,
122
+ ): Promise<void> {
123
+ if (request.method !== 'GET') {
124
+ replyJson(response, 405, { error: 'method-not-allowed' })
125
+ return
126
+ }
127
+ // The host's own pages only. A live browser frame can contain a CAPTCHA or logged-in content, so
128
+ // the endpoint is not something a cross-origin page may pull even with the switch on.
129
+ if (!sameOrigin(request)) {
130
+ replyJson(response, 403, { error: 'not-same-origin' })
131
+ return
132
+ }
133
+ // The host's consent, checked per request rather than cached: switching sharing off must take
134
+ // effect on the next frame, not on the next restart.
135
+ if (settings.get().remoteView.enabled !== true) {
136
+ replyJson(response, 403, { error: 'remote-view-disabled' })
137
+ return
138
+ }
139
+ const url = new URL(request.url ?? '/', 'http://localhost')
140
+ const session = url.searchParams.get('session') ?? ''
141
+ if (session === '') {
142
+ replyJson(response, 400, { error: 'session-required' })
143
+ return
144
+ }
145
+ // A session the plugin did not hand out is not a session. This is the only identifier a caller
146
+ // may supply; no carrier handle, view id, port or CDP target is accepted anywhere.
147
+ if (!browser.exists(session)) {
148
+ replyJson(response, 404, { error: 'no-such-session' })
149
+ return
150
+ }
151
+ try {
152
+ const frame = await browser.capturePassive(session)
153
+ const comma = frame.dataUrl.indexOf(',')
154
+ if (comma === -1) {
155
+ replyJson(response, 503, { error: 'preview-unavailable', retryable: true })
156
+ return
157
+ }
158
+ const header = frame.dataUrl.slice(0, comma)
159
+ const base64 = frame.dataUrl.slice(comma + 1)
160
+ const mime = /^data:([^;]+)/.exec(header)?.[1] ?? 'image/jpeg'
161
+ const bytes = Buffer.from(base64, 'base64')
162
+ if (bytes.length === 0) {
163
+ replyJson(response, 503, { error: 'preview-unavailable', retryable: true })
164
+ return
165
+ }
166
+ response.writeHead(200, {
167
+ 'content-type': mime,
168
+ 'content-length': bytes.length,
169
+ // A frame is a moment, never a cached answer: replaying the last one would show the viewer a
170
+ // picture that claims to be live.
171
+ 'cache-control': 'no-store, private',
172
+ 'x-content-type-options': 'nosniff',
173
+ 'cross-origin-resource-policy': 'same-origin',
174
+ 'x-captured-at': String(Date.now()),
175
+ })
176
+ response.end(bytes)
177
+ } catch (error) {
178
+ // BROWSER_PREVIEW_UNAVAILABLE is the expected "cannot draw this right now" (hidden or minimized
179
+ // window, capture timeout). Anything else is still a refusal to serve an image, and the viewer
180
+ // treats both the same way: show paused, do not retry in a tight loop.
181
+ const code = (error as BrowserError)?.code
182
+ replyJson(response, 503, {
183
+ error: code === 'BROWSER_PREVIEW_UNAVAILABLE' ? 'preview-unavailable' : 'capture-failed',
184
+ retryable: true,
185
+ })
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Report whether the desktop bridge is installed, for the settings panel.
191
+ *
192
+ * Read-only and same-origin like the rest: it names a directory and a state, nothing that could be
193
+ * used to reach anything else. The command it returns is for a human to run — executing it here
194
+ * would let a page decide to close the desktop shell.
195
+ * @param request - the incoming request.
196
+ * @param response - the response to write.
197
+ * @param localAppData - the base directory to probe; injected so a test can point at a fixture.
198
+ */
199
+ export async function handleBridgeStatus(
200
+ request: IncomingMessage,
201
+ response: ServerResponse,
202
+ localAppData?: string,
203
+ ): Promise<void> {
204
+ if (request.method !== 'GET') {
205
+ replyJson(response, 405, { error: 'method-not-allowed' })
206
+ return
207
+ }
208
+ if (!sameOrigin(request)) {
209
+ replyJson(response, 403, { error: 'not-same-origin' })
210
+ return
211
+ }
212
+ const installRoot = findDesktopInstall(localAppData)
213
+ const status = installRoot === undefined
214
+ ? {
215
+ state: 'missing' as const,
216
+ present: false,
217
+ archivePresent: false,
218
+ detail: 'no DSH Desktop install found under LOCALAPPDATA\\Programs',
219
+ }
220
+ : readBridgeStatus(installRoot)
221
+ replyJson(response, 200, { ok: true, bridge: status })
222
+ }
@@ -8,7 +8,8 @@
8
8
  */
9
9
 
10
10
  import { randomUUID } from 'node:crypto'
11
- import { existsSync, lstatSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs'
11
+ import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs'
12
+ import { writeFileNoReplace } from './file-write.js'
12
13
  import { homedir } from 'node:os'
13
14
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
14
15
  import { HistoryStore, type VisitedPage } from './history-store.js'
@@ -174,9 +175,24 @@ export interface ElectronBrowserViewHost {
174
175
  * twice. Measured on the sidebar carrier: three clicks produced three webview guests while
175
176
  * `dsh_browser_list_tabs` reported one tab; on the installed-browser carrier the window held four
176
177
  * pages and the tool reported one.
177
- * @returns every page the carrier holds that this host did not open.
178
+ * @param owner - the calling task/conversation; shared sidebar hosts must scope to it.
179
+ * @returns every page this conversation's carrier holds that this host did not open.
178
180
  */
179
- listPages?(): Promise<readonly CarrierPage[]>
181
+ listPages?(owner?: string): Promise<readonly CarrierPage[]>
182
+ /**
183
+ * Optional: take over one page reported by {@link listPages}, so it becomes a page this provider
184
+ * drives rather than one it can only see.
185
+ *
186
+ * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
187
+ * produced a SECOND page — the human's own tab was listed (under `page:`) and closable, but not
188
+ * readable, which is the opposite of "the page you are looking at". A carrier that cannot do this
189
+ * must leave it undefined rather than pretend: a switch that reported success and then read
190
+ * nothing is the failure this removes.
191
+ * @param viewId - the view to bind the page to.
192
+ * @param id - the carrier's own page id, as {@link listPages} reported it.
193
+ * @returns a handle for that page, usable for commands like any other view's.
194
+ */
195
+ adoptPage?(id: string): Promise<ElectronViewHandle>
180
196
  /**
181
197
  * Optional: close one page reported by {@link listPages}.
182
198
  *
@@ -184,8 +200,9 @@ export interface ElectronBrowserViewHost {
184
200
  * `dsh_browser_list_tabs` would report pages that `dsh_browser_close_tab` answers "not open in
185
201
  * this session" about, which reads as a contradiction rather than a boundary.
186
202
  * @param id - the carrier's own page id, as {@link listPages} reported it.
203
+ * @param owner - the same task/conversation used for listing; never a global fallback.
187
204
  */
188
- closePage?(id: string): Promise<void>
205
+ closePage?(id: string, owner?: string): Promise<void>
189
206
  /**
190
207
  * Optional cheap usability probe (no network): whether the host can back
191
208
  * views at all right now. The self-hosted host checks for a usable Electron
@@ -608,7 +625,15 @@ const SNAPSHOT_LABEL_MAX = 120
608
625
 
609
626
  /** Named-key table for `key()`: CDP key/code names + Windows virtual key codes. */
610
627
  const KEY_SPECS: Readonly<Record<string, { readonly key: string; readonly code: string; readonly vk: number; readonly text?: string }>> = {
611
- Enter: { key: 'Enter', code: 'Enter', vk: 13 },
628
+ // `text` is what makes a key produce CHARACTER INPUT rather than only a key event, and form
629
+ // submission depends on the character: pressing Enter in a text field submits the form because
630
+ // the browser processes a carriage return, not because a key went down. Without `text` the event
631
+ // still reaches the page, a `keydown` listener still fires, and nothing happens — reported as
632
+ // issue #36, where `requestSubmit()` worked and this did not.
633
+ //
634
+ // The same omission is why Space used to pass only its key event; that one was already fixed and
635
+ // is the reason the table has a `text` column at all.
636
+ Enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
612
637
  Tab: { key: 'Tab', code: 'Tab', vk: 9 },
613
638
  Escape: { key: 'Escape', code: 'Escape', vk: 27 },
614
639
  Backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
@@ -795,9 +820,65 @@ export class ElectronBrowserProvider implements BrowserProvider {
795
820
  if (request.newTab === true) {
796
821
  this.newTab(s)
797
822
  }
823
+ // A page the human already has, at the URL being asked for, is the page they mean.
824
+ //
825
+ // Reported as a defect: they opened a page by hand, then a tool call drove the plugin's own
826
+ // blank tab instead and reported nothing about the page on screen — so the obvious conclusion
827
+ // was "the page is broken", and opening the same URL again produced a SECOND tab. Reusing the
828
+ // existing page is both what the request says and what a person expects.
829
+ //
830
+ // Only an exact match after normalisation: a deliberate navigation to a different URL must not
831
+ // be redirected to whatever page happens to be open.
832
+ if (request.newTab !== true && await this.adoptMatchingPage(s, request.url)) return
798
833
  await this.navigate(session, { url: request.url }, signal)
799
834
  }
800
835
 
836
+ /**
837
+ * Bind the carrier page that already shows this URL, if there is one.
838
+ *
839
+ * Compare the part of a URL that says WHICH page it is: scheme, host, path and query. A hash is a
840
+ * position inside a document, and a trailing slash is spelling, so neither makes a different page.
841
+ * @param s - the session to bind the page into.
842
+ * @param url - the URL being opened.
843
+ * @returns whether an existing page was taken over.
844
+ */
845
+ private async adoptMatchingPage(s: Session, url: string): Promise<boolean> {
846
+ if (this.host.adoptPage === undefined || this.host.listPages === undefined) return false
847
+ const wanted = this.comparableUrl(url)
848
+ if (wanted === undefined) return false
849
+ let pages: readonly CarrierPage[]
850
+ try {
851
+ pages = await this.host.listPages(s.label)
852
+ } catch {
853
+ // A listing must not turn "nothing to reuse" into "open failed".
854
+ return false
855
+ }
856
+ const match = pages.find(page => this.comparableUrl(page.url) === wanted)
857
+ if (match === undefined) return false
858
+ try {
859
+ const handle = await this.host.adoptPage(match.id)
860
+ const tab: Tab = { id: `page:${match.id}`, handle, url: match.url }
861
+ s.tabs.push(tab)
862
+ s.activeIndex = s.tabs.length - 1
863
+ this.showActive(s)
864
+ return true
865
+ } catch {
866
+ // The page went away between listing and adopting: fall through to an ordinary navigation.
867
+ return false
868
+ }
869
+ }
870
+
871
+ /** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
872
+ private comparableUrl(url: string): string | undefined {
873
+ if (url === '' || url === 'about:blank') return undefined
874
+ try {
875
+ const parsed = new URL(url)
876
+ return `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}${parsed.search}`
877
+ } catch {
878
+ return undefined
879
+ }
880
+ }
881
+
801
882
  /** List the session's tabs with their titles. */
802
883
  async listTabs(session: BrowserSessionId): Promise<readonly BrowserTab[]> {
803
884
  const s = this.session(session)
@@ -831,7 +912,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
831
912
  //
832
913
  // They are appended under a `page:` prefix so a caller can tell the two kinds apart — the
833
914
  // prefix is also what `closeTab` uses to decide whether to close a view or a carrier page.
834
- const pages = await this.host.listPages?.().catch(() => undefined) ?? []
915
+ const pages = await this.host.listPages?.(s.label) ?? []
835
916
  for (const page of pages) {
836
917
  // A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
837
918
  // caller to act on nothing, and the blank normalisation already closes those.
@@ -842,15 +923,35 @@ export class ElectronBrowserProvider implements BrowserProvider {
842
923
  }
843
924
 
844
925
  /** Switch to a tab by id, making its view visible. */
845
- switchTab(session: BrowserSessionId, tabId: string): Promise<void> {
926
+ async switchTab(session: BrowserSessionId, tabId: string): Promise<void> {
927
+ const s = this.session(session)
928
+ // A page the carrier owns. Before this, switching to one threw "not open in this session" —
929
+ // while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
930
+ // page the human was looking at could not be reached (reported as a defect).
931
+ if (tabId.startsWith('page:')) {
932
+ const id = tabId.slice('page:'.length)
933
+ if (this.host.adoptPage === undefined) {
934
+ throw new BrowserError(
935
+ 'browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
936
+ + 'Open the URL through dsh_browser_open instead — that creates a page this plugin owns.',
937
+ 'BROWSER_TAB_NOT_FOUND',
938
+ )
939
+ }
940
+ const handle = await this.host.adoptPage(id)
941
+ const tab: Tab = { id: tabId, handle, url: '' }
942
+ s.tabs.push(tab)
943
+ s.activeIndex = s.tabs.length - 1
944
+ this.showActive(s)
945
+ return
946
+ }
846
947
  const found = this.locateTab(session, tabId)
847
948
  found.s.activeIndex = found.index
848
949
  this.showActive(found.s)
849
- return Promise.resolve()
850
950
  }
851
951
 
852
952
  /** Close one tab; closing the active tab activates the next. */
853
953
  closeTab(session: BrowserSessionId, tabId: string): Promise<void> {
954
+ const owner = this.session(session).label
854
955
  // A page the carrier owns rather than a view we created. It was reported by `listTabs` under
855
956
  // this prefix, so closing it here is what keeps the two tools consistent — a page that can be
856
957
  // listed must be closable, or the listing reads as a contradiction.
@@ -862,7 +963,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
862
963
  'BROWSER_TAB_NOT_FOUND',
863
964
  ))
864
965
  }
865
- return this.host.closePage(id)
966
+ return this.host.closePage(id, owner)
866
967
  }
867
968
  const found = this.locateTab(session, tabId)
868
969
  const s = found.s
@@ -1322,7 +1423,23 @@ export class ElectronBrowserProvider implements BrowserProvider {
1322
1423
  // A tab that has never navigated is a blank, uncommitted view. The collector cannot answer in
1323
1424
  // it — there is no document to commit — so the call would sit out its whole budget before
1324
1425
  // saying anything. Answering the empty page immediately is both faster and more truthful.
1325
- if (tab.url === '') return { url: '', elements: [], truncated: false }
1426
+ //
1427
+ // `about:blank` needs the same answer for a different reason: it HAS a document, so the collector
1428
+ // runs, finds nothing, and returns zero elements — indistinguishable from a real page with nothing
1429
+ // interactive. A caller then acts on it and receives success values, which is how a carrier swap
1430
+ // that started a fresh window looked like working tools operating on the wrong page (issue #37).
1431
+ const blankUrl = tab.url === '' || tab.url === 'about:blank'
1432
+ if (blankUrl) {
1433
+ return {
1434
+ url: tab.url,
1435
+ elements: [],
1436
+ truncated: false,
1437
+ blank: true,
1438
+ note: tab.url === ''
1439
+ ? 'no page has been opened in this browser yet'
1440
+ : 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
1441
+ }
1442
+ }
1326
1443
  const script = `(() => {
1327
1444
  const cap = ${String(this.snapshotMaxElements)}
1328
1445
  const url = location.href
@@ -1376,7 +1493,14 @@ export class ElectronBrowserProvider implements BrowserProvider {
1376
1493
  : el.tagName === 'SELECT' ? 'select'
1377
1494
  : el.tagName === 'BUTTON' ? 'button'
1378
1495
  : el.tagName === 'A' ? 'link' : 'other'
1379
- const label = (el.getAttribute('aria-label') || el.placeholder || el.textContent || el.value || el.name || el.id || '').toString().replace(/\\s+/g, ' ').trim().slice(0, ${String(SNAPSHOT_LABEL_MAX)})
1496
+ // An anchor wrapping only an image has no text: 4399.com's 1608 game links are all
1497
+ // <a href><img alt="名字"></a>, so every label came out empty and the whole page read as
1498
+ // "no interactive elements" while it was full of them.
1499
+ const imageAlt = el.tagName === 'A' || el.tagName === 'BUTTON'
1500
+ ? (el.querySelector('img[alt]')?.getAttribute('alt') ?? '')
1501
+ : ''
1502
+ const label = (el.getAttribute('aria-label') || el.placeholder || el.textContent || imageAlt
1503
+ || el.value || el.name || el.id || '').toString().replace(/\\s+/g, ' ').trim().slice(0, ${String(SNAPSHOT_LABEL_MAX)})
1380
1504
  if (!label && kind !== 'link') continue
1381
1505
  const a = absRect(el, el.ownerDocument)
1382
1506
  out.push({
@@ -1390,7 +1514,52 @@ export class ElectronBrowserProvider implements BrowserProvider {
1390
1514
  })
1391
1515
  }
1392
1516
  const challenge = ${CHALLENGE_DETECT_EXPRESSION}
1393
- return { url, title, elements: out, truncated: out.length >= cap, challenge }
1517
+ // The page's own URL is the authority on whether there is a document. The tracked tab.url is
1518
+ // a bookkeeping copy that can lag behind a navigation the browser performed itself, and a
1519
+ // stale copy made this check miss on a real about:blank tab.
1520
+ const blankPage = out.length === 0 && (url === '' || url === 'about:blank')
1521
+ // Independent of the element list: a page can mix DOM controls with a canvas that holds the
1522
+ // part the caller actually needs. Measured on sudoku.com — 60 links were collected and the
1523
+ // board, drawn on a canvas, was invisible in the same result.
1524
+ //
1525
+ // The thresholds keep a decorative canvas from claiming a page: at least 80x80 per canvas and
1526
+ // 10% of the viewport in total. Anything smaller is reported by nothing, which is right.
1527
+ let canvas
1528
+ if (blankPage !== true) {
1529
+ let area = 0
1530
+ let count = 0
1531
+ for (const c of document.querySelectorAll('canvas')) {
1532
+ const r = c.getBoundingClientRect()
1533
+ if (r.width < 80 || r.height < 80) continue
1534
+ count += 1
1535
+ area += r.width * r.height
1536
+ }
1537
+ const view = window.innerWidth * window.innerHeight
1538
+ if (count > 0 && view > 0 && area / view >= 0.1) canvas = true
1539
+ }
1540
+ return {
1541
+ url,
1542
+ title,
1543
+ elements: out,
1544
+ truncated: out.length >= cap,
1545
+ challenge,
1546
+ ...blankPage === true
1547
+ ? {
1548
+ blank: true,
1549
+ note: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
1550
+ }
1551
+ : {},
1552
+ ...canvas === true
1553
+ ? {
1554
+ canvas: true,
1555
+ note: out.length === 0
1556
+ ? 'this page draws its interface on a canvas, so there is no DOM content for a snapshot. '
1557
+ + 'Use dsh_browser_screenshot to see it, and coordinates with dsh_browser_click to act on it.'
1558
+ : 'part of this page is drawn on a canvas, which no element list can describe. The elements '
1559
+ + 'below are real; anything inside the canvas is only visible in dsh_browser_screenshot.',
1560
+ }
1561
+ : {},
1562
+ }
1394
1563
  })()`
1395
1564
  // Same hang guard as execute: a renderer that has not committed after
1396
1565
  // navigate would otherwise block snapshot forever.
@@ -2929,9 +3098,85 @@ export class ElectronBrowserProvider implements BrowserProvider {
2929
3098
  return restored
2930
3099
  }
2931
3100
 
3101
+ /**
3102
+ * Capture the active page WITHOUT presenting it.
3103
+ *
3104
+ * `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
3105
+ * that the human sees what the model just captured. It is also what makes that path unusable for a
3106
+ * live preview: presenting on every frame would move focus, switch tabs and expand windows on the
3107
+ * host's screen — exactly the side effects a viewer must not cause (issue #34).
3108
+ *
3109
+ * So this does the capture and nothing else. Deliberately narrow: viewport only, JPEG at the
3110
+ * preview defaults, a short timeout, no save path, no history entry, no carrier recovery. A
3111
+ * preview that rebuilt a vanished carrier would make watching a way to start a browser, which the
3112
+ * design forbids: no page means "nothing to watch", not "open one".
3113
+ * @param session - the session whose active page to capture.
3114
+ * @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
3115
+ * is not painted, which the caller turns into a "paused" state rather than an error.
3116
+ */
3117
+ async capturePassive(session: BrowserSessionId): Promise<{
3118
+ readonly dataUrl: string
3119
+ readonly width?: number
3120
+ readonly height?: number
3121
+ }> {
3122
+ const s = this.session(session)
3123
+ const { handle } = this.activeTab(s)
3124
+ const timeoutMs = PREVIEW_CAPTURE_MS
3125
+ const timeoutMessage = `browser: preview capture timed out after ${timeoutMs}ms`
3126
+ // The self-hosted carrier encodes in the child from a NativeImage; it is the only path that can
3127
+ // produce JPEG under Electron 43, whose CDP JPEG encoder hangs.
3128
+ if (typeof handle.capture === 'function') {
3129
+ const shot = await withTimeout(
3130
+ handle.capture({
3131
+ format: 'jpeg',
3132
+ quality: PREVIEW_QUALITY,
3133
+ maxWidth: PREVIEW_MAX_WIDTH,
3134
+ maxHeight: PREVIEW_MAX_HEIGHT,
3135
+ }),
3136
+ timeoutMs,
3137
+ undefined,
3138
+ timeoutMessage,
3139
+ )
3140
+ if (shot.base64 === '') {
3141
+ // A hidden or minimized window is not a failure to report as one: the design says the
3142
+ // viewer shows pause and does not open a window to fix it.
3143
+ throw new BrowserError(
3144
+ 'browser: preview unavailable (the page is not painted; the window may be hidden or minimized)',
3145
+ 'BROWSER_PREVIEW_UNAVAILABLE',
3146
+ )
3147
+ }
3148
+ return {
3149
+ dataUrl: `data:${shot.mime};base64,${shot.base64}`,
3150
+ ...shot.width !== undefined && shot.height !== undefined
3151
+ ? { width: shot.width, height: shot.height }
3152
+ : {},
3153
+ }
3154
+ }
3155
+ // Real Chrome/Edge (and the sidebar): CDP. Viewport only — `captureBeyondViewport` would pull
3156
+ // the whole document, which is neither what a viewer shows nor bounded in size.
3157
+ const result = await withTimeout(
3158
+ handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, {
3159
+ format: 'jpeg',
3160
+ quality: PREVIEW_QUALITY,
3161
+ fromSurface: true,
3162
+ captureBeyondViewport: false,
3163
+ }),
3164
+ timeoutMs,
3165
+ undefined,
3166
+ timeoutMessage,
3167
+ ) as { data?: unknown }
3168
+ const base64 = typeof result?.data === 'string' ? result.data : ''
3169
+ if (base64 === '') {
3170
+ throw new BrowserError(
3171
+ 'browser: preview unavailable (the carrier returned no image)',
3172
+ 'BROWSER_PREVIEW_UNAVAILABLE',
3173
+ )
3174
+ }
3175
+ return { dataUrl: `data:image/jpeg;base64,${base64}` }
3176
+ }
3177
+
2932
3178
  /** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
2933
- async screenshot(
2934
- session: BrowserSessionId,
3179
+ async screenshot( session: BrowserSessionId,
2935
3180
  request?: BrowserScreenshotRequest,
2936
3181
  signal?: AbortSignal,
2937
3182
  ): Promise<{ readonly dataUrl: string; readonly path?: string; readonly width?: number; readonly height?: number }> {
@@ -3059,8 +3304,7 @@ export class ElectronBrowserProvider implements BrowserProvider {
3059
3304
  // path, not a disk problem.
3060
3305
  const target = this.admitSavePath(savePath, 'screenshot')
3061
3306
  try {
3062
- mkdirSync(dirname(target), { recursive: true })
3063
- writeFileSync(target, Buffer.from(base64, 'base64'))
3307
+ writeFileNoReplace(target, Buffer.from(base64, 'base64'))
3064
3308
  return { dataUrl: `data:${mime};base64,${base64}`, path: target, ...rendered }
3065
3309
  } catch (error) {
3066
3310
  // Report the write problem but keep the capture usable.
@@ -3320,6 +3564,19 @@ export class ElectronBrowserProvider implements BrowserProvider {
3320
3564
  return this.sessions.has(session)
3321
3565
  }
3322
3566
 
3567
+ /**
3568
+ * The sessions a viewer may watch, which is exactly the sessions that exist.
3569
+ *
3570
+ * Served so the browser page can build a frame URL without guessing: the provider names its
3571
+ * sessions, and an id invented by a client is refused at the route. Ids only — no URL, no title,
3572
+ * no target handle — because the point is to let the panel address a session, not to describe
3573
+ * what is in it.
3574
+ * @returns the live session ids.
3575
+ */
3576
+ watchableSessions(): readonly BrowserSessionId[] {
3577
+ return [...this.sessions.keys()]
3578
+ }
3579
+
3323
3580
  /**
3324
3581
  * The human closed a browser window: the session that window showed is over.
3325
3582
  * Ending it here is what makes the next call a clean start rather than a
@@ -3456,6 +3713,19 @@ export class ElectronBrowserProvider implements BrowserProvider {
3456
3713
  */
3457
3714
  const SETTLE_TIMEOUT_MS = 5_000
3458
3715
 
3716
+ /**
3717
+ * Bounds for one passive preview frame.
3718
+ *
3719
+ * The design's numbers (issue #34): viewport only, JPEG quality 70, fit inside 1280x720 without
3720
+ * enlarging, and a 2 s capture ceiling so a stuck frame ends the viewer's wait instead of piling up
3721
+ * behind the control queue. These are deliberately not configurable in v1 — one canonical spec per
3722
+ * target is what lets several viewers share a single capture.
3723
+ */
3724
+ const PREVIEW_CAPTURE_MS = 2_000
3725
+ const PREVIEW_QUALITY = 70
3726
+ const PREVIEW_MAX_WIDTH = 1280
3727
+ const PREVIEW_MAX_HEIGHT = 720
3728
+
3459
3729
  /**
3460
3730
  * When the document already looks settled but its identity has NOT changed
3461
3731
  * (same-document navigation, or the outgoing document still answering), wait
@@ -453,14 +453,18 @@ class ElectronChildClient {
453
453
  private readonly executable?: string,
454
454
  ) {
455
455
  const electron = this.executable ?? resolveElectronPath()
456
+ const source = this.executable !== undefined
457
+ ? 'provided'
458
+ : electron === process.env.ELECTRON_PATH ? 'ELECTRON_PATH' : 'auto'
456
459
  // Record what is about to be spawned — with existence checks — BEFORE the
457
460
  // attempt. When Electron cannot load the app entry it exits 1 with EMPTY
458
461
  // stderr, and that signature is otherwise indistinguishable from a missing
459
462
  // binary: writing both paths (and whether they exist) in advance is what
460
463
  // turns the next occurrence into a named cause instead of a guess.
461
- process.stderr.write(`[dsh-browser host] spawning electron: ${electron}\n`)
464
+ process.stderr.write(`[dsh-browser host] spawning electron: ${electron} source=${source}\n`)
462
465
  appendHostLog(
463
466
  `${hostStamp()} spawning: electron=${electron} (exists=${String(existsSync(electron))})`
467
+ + ` source=${source}`
464
468
  + ` hostMain=${this.hostMainPath} (exists=${String(existsSync(this.hostMainPath))})`
465
469
  + ` port=${String(this.port)}\n`,
466
470
  )
@@ -0,0 +1,13 @@
1
+ import type { Socket } from 'node:net'
2
+ import { createInterface, type Interface } from 'node:readline'
3
+
4
+ /** Read RPC lines while keeping transport errors owned by the socket. */
5
+ export function createRpcLineReader(socket: Socket, onError: (error: Error) => void): Interface {
6
+ socket.on('error', onError)
7
+ const reader = createInterface({ input: socket })
8
+ // readline forwards input errors as its own 'error' event. The socket
9
+ // listener above already reports that same error; receive the forwarded
10
+ // event too so a transport failure does not become uncaughtException.
11
+ reader.on('error', () => {})
12
+ return reader
13
+ }