dsh-builtin-browser 0.4.14 → 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.
- package/CHANGELOG.md +72 -0
- package/README.en.md +17 -9
- package/README.md +48 -10
- package/client.js +410 -6
- package/desktop-bridge/install-and-start.cmd +36 -0
- package/desktop-bridge/install.mjs +166 -3
- package/desktop-bridge/plugin-browser-bridge.js +133 -11
- package/docs/development.md +19 -0
- package/docs/limitations.md +7 -3
- package/docs/user-guide.md +46 -18
- package/lib/browser/runtime.d.ts +21 -2
- package/lib/browser/runtime.js +30 -0
- package/lib/browser/types.d.ts +54 -0
- package/lib/browser-electron/bridge-status.d.ts +41 -0
- package/lib/browser-electron/bridge-status.js +164 -0
- package/lib/browser-electron/desktop-bridge-host.d.ts +15 -2
- package/lib/browser-electron/desktop-bridge-host.js +75 -44
- package/lib/browser-electron/entry.js +130 -11
- package/lib/browser-electron/file-write.d.ts +2 -0
- package/lib/browser-electron/file-write.js +39 -0
- package/lib/browser-electron/history-store.d.ts +8 -19
- package/lib/browser-electron/history-store.js +37 -58
- package/lib/browser-electron/host-main.js +15 -22
- package/lib/browser-electron/preview-route.d.ts +89 -0
- package/lib/browser-electron/preview-route.js +172 -0
- package/lib/browser-electron/provider.d.ts +62 -3
- package/lib/browser-electron/provider.js +246 -12
- package/lib/browser-electron/remote-host.js +5 -1
- package/lib/browser-electron/rpc-input.d.ts +4 -0
- package/lib/browser-electron/rpc-input.js +11 -0
- package/lib/browser-electron/runtime-diagnostics.d.ts +12 -0
- package/lib/browser-electron/runtime-diagnostics.js +29 -0
- package/lib/browser-electron/settings-store.d.ts +15 -2
- package/lib/browser-electron/settings-store.js +25 -5
- package/lib/browser-electron/system-browser.d.ts +18 -0
- package/lib/browser-electron/system-browser.js +158 -37
- package/lib/tool-browser/index.js +10 -1
- package/package.json +8 -3
- package/scripts/install-electron.mjs +66 -0
- package/scripts/verify-preview-route.mjs +150 -0
- package/src/browser/runtime.ts +36 -0
- package/src/browser/types.ts +55 -0
- package/src/browser-electron/bridge-status.ts +180 -0
- package/src/browser-electron/desktop-bridge-host.ts +75 -41
- package/src/browser-electron/entry.ts +119 -11
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/history-store.ts +36 -57
- package/src/browser-electron/host-main.ts +16 -18
- package/src/browser-electron/preview-route.ts +222 -0
- package/src/browser-electron/provider.ts +286 -16
- package/src/browser-electron/remote-host.ts +5 -1
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/settings-store.ts +37 -5
- package/src/browser-electron/system-browser.ts +149 -32
- package/src/tool-browser/index.ts +13 -1
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { sameOrigin } from './settings-route.js';
|
|
2
|
+
import { findDesktopInstall, readBridgeStatus } from './bridge-status.js';
|
|
3
|
+
/** Where the frame endpoint lives. The viewer must use exactly this path, same origin. */
|
|
4
|
+
export const PREVIEW_ROUTE = '/dsh-builtin-browser/browser-view/frame';
|
|
5
|
+
/**
|
|
6
|
+
* Where the viewer asks which sessions it may watch.
|
|
7
|
+
*
|
|
8
|
+
* The provider names its sessions (`browser:<uuid>`) and only it knows them; the browser page has no
|
|
9
|
+
* way to guess one. Without this the viewer could not build a frame URL at all, and inventing an id
|
|
10
|
+
* is exactly what the design forbids. So the list is served, and it contains nothing but ids of
|
|
11
|
+
* sessions that currently have a page — no URLs, no titles, no target handles.
|
|
12
|
+
*/
|
|
13
|
+
export const PREVIEW_SESSIONS_ROUTE = '/dsh-builtin-browser/browser-view/sessions';
|
|
14
|
+
/**
|
|
15
|
+
* Where the settings panel asks whether the desktop bridge is installed.
|
|
16
|
+
*
|
|
17
|
+
* Reported as issue #36: a missing bridge was only a log warning, so a user on `channel: sidebar`
|
|
18
|
+
* saw "another window opened again" with nothing connecting that to "the bridge is not installed".
|
|
19
|
+
* The reading is taken from the install tree on disk, so it is true even when the plugin has just
|
|
20
|
+
* started and remembers nothing.
|
|
21
|
+
*/
|
|
22
|
+
export const BRIDGE_STATUS_ROUTE = '/dsh-builtin-browser/bridge-status';
|
|
23
|
+
/**
|
|
24
|
+
* List the sessions a viewer may watch.
|
|
25
|
+
*
|
|
26
|
+
* Ids only. The whole point of this endpoint is to give the page something it cannot guess; adding a
|
|
27
|
+
* URL or title here would leak the very content the frame endpoint is careful not to describe in its
|
|
28
|
+
* refusals.
|
|
29
|
+
* @param request - the incoming request.
|
|
30
|
+
* @param response - the response to write.
|
|
31
|
+
* @param settings - the settings document, for the share switch.
|
|
32
|
+
* @param browser - the browser service.
|
|
33
|
+
*/
|
|
34
|
+
export async function handlePreviewSessions(request, response, settings, browser) {
|
|
35
|
+
if (request.method !== 'GET') {
|
|
36
|
+
replyJson(response, 405, { error: 'method-not-allowed' });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (!sameOrigin(request)) {
|
|
40
|
+
replyJson(response, 403, { error: 'not-same-origin' });
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (settings.get().remoteView.enabled !== true) {
|
|
44
|
+
// An empty list rather than a refusal: the panel asks this before it knows whether sharing is
|
|
45
|
+
// on, and "nothing to watch" is the honest answer to give a client that is not allowed to watch.
|
|
46
|
+
replyJson(response, 200, { enabled: false, sessions: [] });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const sessions = browser.watchableSessions?.() ?? [];
|
|
50
|
+
replyJson(response, 200, { enabled: true, sessions: [...sessions] });
|
|
51
|
+
}
|
|
52
|
+
/** Write one JSON body with no caching and no sniffing. */
|
|
53
|
+
function replyJson(response, status, body) {
|
|
54
|
+
const text = JSON.stringify(body);
|
|
55
|
+
response.writeHead(status, {
|
|
56
|
+
'content-type': 'application/json; charset=utf-8',
|
|
57
|
+
'content-length': Buffer.byteLength(text),
|
|
58
|
+
'cache-control': 'no-store, private',
|
|
59
|
+
'x-content-type-options': 'nosniff',
|
|
60
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
61
|
+
});
|
|
62
|
+
response.end(text);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Serve one frame, or say precisely why not.
|
|
66
|
+
*
|
|
67
|
+
* Every refusal is a status the viewer can act on: 403 when watching is switched off (the host has
|
|
68
|
+
* not agreed), 404 when that session has no page (nothing to watch, and nothing is opened on its
|
|
69
|
+
* behalf), 503 when the page cannot produce an image right now (hidden window, capture timeout) —
|
|
70
|
+
* which the viewer shows as paused rather than as an error.
|
|
71
|
+
* @param request - the incoming request.
|
|
72
|
+
* @param response - the response to write.
|
|
73
|
+
* @param settings - the settings document, for the host's share switch.
|
|
74
|
+
* @param browser - the browser service, for passive capture.
|
|
75
|
+
*/
|
|
76
|
+
export async function handlePreviewFrame(request, response, settings, browser) {
|
|
77
|
+
if (request.method !== 'GET') {
|
|
78
|
+
replyJson(response, 405, { error: 'method-not-allowed' });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
// The host's own pages only. A live browser frame can contain a CAPTCHA or logged-in content, so
|
|
82
|
+
// the endpoint is not something a cross-origin page may pull even with the switch on.
|
|
83
|
+
if (!sameOrigin(request)) {
|
|
84
|
+
replyJson(response, 403, { error: 'not-same-origin' });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
// The host's consent, checked per request rather than cached: switching sharing off must take
|
|
88
|
+
// effect on the next frame, not on the next restart.
|
|
89
|
+
if (settings.get().remoteView.enabled !== true) {
|
|
90
|
+
replyJson(response, 403, { error: 'remote-view-disabled' });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const url = new URL(request.url ?? '/', 'http://localhost');
|
|
94
|
+
const session = url.searchParams.get('session') ?? '';
|
|
95
|
+
if (session === '') {
|
|
96
|
+
replyJson(response, 400, { error: 'session-required' });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
// A session the plugin did not hand out is not a session. This is the only identifier a caller
|
|
100
|
+
// may supply; no carrier handle, view id, port or CDP target is accepted anywhere.
|
|
101
|
+
if (!browser.exists(session)) {
|
|
102
|
+
replyJson(response, 404, { error: 'no-such-session' });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const frame = await browser.capturePassive(session);
|
|
107
|
+
const comma = frame.dataUrl.indexOf(',');
|
|
108
|
+
if (comma === -1) {
|
|
109
|
+
replyJson(response, 503, { error: 'preview-unavailable', retryable: true });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const header = frame.dataUrl.slice(0, comma);
|
|
113
|
+
const base64 = frame.dataUrl.slice(comma + 1);
|
|
114
|
+
const mime = /^data:([^;]+)/.exec(header)?.[1] ?? 'image/jpeg';
|
|
115
|
+
const bytes = Buffer.from(base64, 'base64');
|
|
116
|
+
if (bytes.length === 0) {
|
|
117
|
+
replyJson(response, 503, { error: 'preview-unavailable', retryable: true });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
response.writeHead(200, {
|
|
121
|
+
'content-type': mime,
|
|
122
|
+
'content-length': bytes.length,
|
|
123
|
+
// A frame is a moment, never a cached answer: replaying the last one would show the viewer a
|
|
124
|
+
// picture that claims to be live.
|
|
125
|
+
'cache-control': 'no-store, private',
|
|
126
|
+
'x-content-type-options': 'nosniff',
|
|
127
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
128
|
+
'x-captured-at': String(Date.now()),
|
|
129
|
+
});
|
|
130
|
+
response.end(bytes);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
// BROWSER_PREVIEW_UNAVAILABLE is the expected "cannot draw this right now" (hidden or minimized
|
|
134
|
+
// window, capture timeout). Anything else is still a refusal to serve an image, and the viewer
|
|
135
|
+
// treats both the same way: show paused, do not retry in a tight loop.
|
|
136
|
+
const code = error?.code;
|
|
137
|
+
replyJson(response, 503, {
|
|
138
|
+
error: code === 'BROWSER_PREVIEW_UNAVAILABLE' ? 'preview-unavailable' : 'capture-failed',
|
|
139
|
+
retryable: true,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Report whether the desktop bridge is installed, for the settings panel.
|
|
145
|
+
*
|
|
146
|
+
* Read-only and same-origin like the rest: it names a directory and a state, nothing that could be
|
|
147
|
+
* used to reach anything else. The command it returns is for a human to run — executing it here
|
|
148
|
+
* would let a page decide to close the desktop shell.
|
|
149
|
+
* @param request - the incoming request.
|
|
150
|
+
* @param response - the response to write.
|
|
151
|
+
* @param localAppData - the base directory to probe; injected so a test can point at a fixture.
|
|
152
|
+
*/
|
|
153
|
+
export async function handleBridgeStatus(request, response, localAppData) {
|
|
154
|
+
if (request.method !== 'GET') {
|
|
155
|
+
replyJson(response, 405, { error: 'method-not-allowed' });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (!sameOrigin(request)) {
|
|
159
|
+
replyJson(response, 403, { error: 'not-same-origin' });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const installRoot = findDesktopInstall(localAppData);
|
|
163
|
+
const status = installRoot === undefined
|
|
164
|
+
? {
|
|
165
|
+
state: 'missing',
|
|
166
|
+
present: false,
|
|
167
|
+
archivePresent: false,
|
|
168
|
+
detail: 'no DSH Desktop install found under LOCALAPPDATA\\Programs',
|
|
169
|
+
}
|
|
170
|
+
: readBridgeStatus(installRoot);
|
|
171
|
+
replyJson(response, 200, { ok: true, bridge: status });
|
|
172
|
+
}
|
|
@@ -76,9 +76,24 @@ export interface ElectronBrowserViewHost {
|
|
|
76
76
|
* twice. Measured on the sidebar carrier: three clicks produced three webview guests while
|
|
77
77
|
* `dsh_browser_list_tabs` reported one tab; on the installed-browser carrier the window held four
|
|
78
78
|
* pages and the tool reported one.
|
|
79
|
-
* @
|
|
79
|
+
* @param owner - the calling task/conversation; shared sidebar hosts must scope to it.
|
|
80
|
+
* @returns every page this conversation's carrier holds that this host did not open.
|
|
80
81
|
*/
|
|
81
|
-
listPages?(): Promise<readonly CarrierPage[]>;
|
|
82
|
+
listPages?(owner?: string): Promise<readonly CarrierPage[]>;
|
|
83
|
+
/**
|
|
84
|
+
* Optional: take over one page reported by {@link listPages}, so it becomes a page this provider
|
|
85
|
+
* drives rather than one it can only see.
|
|
86
|
+
*
|
|
87
|
+
* Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
|
|
88
|
+
* produced a SECOND page — the human's own tab was listed (under `page:`) and closable, but not
|
|
89
|
+
* readable, which is the opposite of "the page you are looking at". A carrier that cannot do this
|
|
90
|
+
* must leave it undefined rather than pretend: a switch that reported success and then read
|
|
91
|
+
* nothing is the failure this removes.
|
|
92
|
+
* @param viewId - the view to bind the page to.
|
|
93
|
+
* @param id - the carrier's own page id, as {@link listPages} reported it.
|
|
94
|
+
* @returns a handle for that page, usable for commands like any other view's.
|
|
95
|
+
*/
|
|
96
|
+
adoptPage?(id: string): Promise<ElectronViewHandle>;
|
|
82
97
|
/**
|
|
83
98
|
* Optional: close one page reported by {@link listPages}.
|
|
84
99
|
*
|
|
@@ -86,8 +101,9 @@ export interface ElectronBrowserViewHost {
|
|
|
86
101
|
* `dsh_browser_list_tabs` would report pages that `dsh_browser_close_tab` answers "not open in
|
|
87
102
|
* this session" about, which reads as a contradiction rather than a boundary.
|
|
88
103
|
* @param id - the carrier's own page id, as {@link listPages} reported it.
|
|
104
|
+
* @param owner - the same task/conversation used for listing; never a global fallback.
|
|
89
105
|
*/
|
|
90
|
-
closePage?(id: string): Promise<void>;
|
|
106
|
+
closePage?(id: string, owner?: string): Promise<void>;
|
|
91
107
|
/**
|
|
92
108
|
* Optional cheap usability probe (no network): whether the host can back
|
|
93
109
|
* views at all right now. The self-hosted host checks for a usable Electron
|
|
@@ -456,6 +472,18 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
|
|
|
456
472
|
open(label?: string): Promise<BrowserSessionId>;
|
|
457
473
|
/** Open a URL in the active tab (default) or a new tab. */
|
|
458
474
|
openUrl(session: BrowserSessionId, request: BrowserOpenRequest, signal?: AbortSignal): Promise<void>;
|
|
475
|
+
/**
|
|
476
|
+
* Bind the carrier page that already shows this URL, if there is one.
|
|
477
|
+
*
|
|
478
|
+
* Compare the part of a URL that says WHICH page it is: scheme, host, path and query. A hash is a
|
|
479
|
+
* position inside a document, and a trailing slash is spelling, so neither makes a different page.
|
|
480
|
+
* @param s - the session to bind the page into.
|
|
481
|
+
* @param url - the URL being opened.
|
|
482
|
+
* @returns whether an existing page was taken over.
|
|
483
|
+
*/
|
|
484
|
+
private adoptMatchingPage;
|
|
485
|
+
/** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
|
|
486
|
+
private comparableUrl;
|
|
459
487
|
/** List the session's tabs with their titles. */
|
|
460
488
|
listTabs(session: BrowserSessionId): Promise<readonly BrowserTab[]>;
|
|
461
489
|
/** Switch to a tab by id, making its view visible. */
|
|
@@ -694,6 +722,27 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
|
|
|
694
722
|
flushAuth(session: BrowserSessionId): Promise<readonly ExportedCookie[]>;
|
|
695
723
|
/** Import cookies into the session (restore login state). Self-hosted only. */
|
|
696
724
|
restoreAuth(session: BrowserSessionId, cookies: readonly ExportedCookie[]): Promise<number>;
|
|
725
|
+
/**
|
|
726
|
+
* Capture the active page WITHOUT presenting it.
|
|
727
|
+
*
|
|
728
|
+
* `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
|
|
729
|
+
* that the human sees what the model just captured. It is also what makes that path unusable for a
|
|
730
|
+
* live preview: presenting on every frame would move focus, switch tabs and expand windows on the
|
|
731
|
+
* host's screen — exactly the side effects a viewer must not cause (issue #34).
|
|
732
|
+
*
|
|
733
|
+
* So this does the capture and nothing else. Deliberately narrow: viewport only, JPEG at the
|
|
734
|
+
* preview defaults, a short timeout, no save path, no history entry, no carrier recovery. A
|
|
735
|
+
* preview that rebuilt a vanished carrier would make watching a way to start a browser, which the
|
|
736
|
+
* design forbids: no page means "nothing to watch", not "open one".
|
|
737
|
+
* @param session - the session whose active page to capture.
|
|
738
|
+
* @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
|
|
739
|
+
* is not painted, which the caller turns into a "paused" state rather than an error.
|
|
740
|
+
*/
|
|
741
|
+
capturePassive(session: BrowserSessionId): Promise<{
|
|
742
|
+
readonly dataUrl: string;
|
|
743
|
+
readonly width?: number;
|
|
744
|
+
readonly height?: number;
|
|
745
|
+
}>;
|
|
697
746
|
/** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
|
|
698
747
|
screenshot(session: BrowserSessionId, request?: BrowserScreenshotRequest, signal?: AbortSignal): Promise<{
|
|
699
748
|
readonly dataUrl: string;
|
|
@@ -783,6 +832,16 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
|
|
|
783
832
|
* @param session - the session id to test.
|
|
784
833
|
*/
|
|
785
834
|
exists(session: BrowserSessionId): boolean;
|
|
835
|
+
/**
|
|
836
|
+
* The sessions a viewer may watch, which is exactly the sessions that exist.
|
|
837
|
+
*
|
|
838
|
+
* Served so the browser page can build a frame URL without guessing: the provider names its
|
|
839
|
+
* sessions, and an id invented by a client is refused at the route. Ids only — no URL, no title,
|
|
840
|
+
* no target handle — because the point is to let the panel address a session, not to describe
|
|
841
|
+
* what is in it.
|
|
842
|
+
* @returns the live session ids.
|
|
843
|
+
*/
|
|
844
|
+
watchableSessions(): readonly BrowserSessionId[];
|
|
786
845
|
/**
|
|
787
846
|
* The human closed a browser window: the session that window showed is over.
|
|
788
847
|
* Ending it here is what makes the next call a clean start rather than a
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
* @module dsh-browser/browser-electron
|
|
8
8
|
*/
|
|
9
9
|
import { randomUUID } from 'node:crypto';
|
|
10
|
-
import { existsSync, lstatSync, mkdirSync, realpathSync
|
|
10
|
+
import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
|
|
11
|
+
import { writeFileNoReplace } from './file-write.js';
|
|
11
12
|
import { homedir } from 'node:os';
|
|
12
13
|
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
13
14
|
import { HistoryStore } from './history-store.js';
|
|
@@ -181,7 +182,15 @@ export const CDP_PAGE_NAVIGATE = 'Page.navigate';
|
|
|
181
182
|
const SNAPSHOT_LABEL_MAX = 120;
|
|
182
183
|
/** Named-key table for `key()`: CDP key/code names + Windows virtual key codes. */
|
|
183
184
|
const KEY_SPECS = {
|
|
184
|
-
|
|
185
|
+
// `text` is what makes a key produce CHARACTER INPUT rather than only a key event, and form
|
|
186
|
+
// submission depends on the character: pressing Enter in a text field submits the form because
|
|
187
|
+
// the browser processes a carriage return, not because a key went down. Without `text` the event
|
|
188
|
+
// still reaches the page, a `keydown` listener still fires, and nothing happens — reported as
|
|
189
|
+
// issue #36, where `requestSubmit()` worked and this did not.
|
|
190
|
+
//
|
|
191
|
+
// The same omission is why Space used to pass only its key event; that one was already fixed and
|
|
192
|
+
// is the reason the table has a `text` column at all.
|
|
193
|
+
Enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
|
|
185
194
|
Tab: { key: 'Tab', code: 'Tab', vk: 9 },
|
|
186
195
|
Escape: { key: 'Escape', code: 'Escape', vk: 27 },
|
|
187
196
|
Backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
|
|
@@ -361,8 +370,70 @@ export class ElectronBrowserProvider {
|
|
|
361
370
|
if (request.newTab === true) {
|
|
362
371
|
this.newTab(s);
|
|
363
372
|
}
|
|
373
|
+
// A page the human already has, at the URL being asked for, is the page they mean.
|
|
374
|
+
//
|
|
375
|
+
// Reported as a defect: they opened a page by hand, then a tool call drove the plugin's own
|
|
376
|
+
// blank tab instead and reported nothing about the page on screen — so the obvious conclusion
|
|
377
|
+
// was "the page is broken", and opening the same URL again produced a SECOND tab. Reusing the
|
|
378
|
+
// existing page is both what the request says and what a person expects.
|
|
379
|
+
//
|
|
380
|
+
// Only an exact match after normalisation: a deliberate navigation to a different URL must not
|
|
381
|
+
// be redirected to whatever page happens to be open.
|
|
382
|
+
if (request.newTab !== true && await this.adoptMatchingPage(s, request.url))
|
|
383
|
+
return;
|
|
364
384
|
await this.navigate(session, { url: request.url }, signal);
|
|
365
385
|
}
|
|
386
|
+
/**
|
|
387
|
+
* Bind the carrier page that already shows this URL, if there is one.
|
|
388
|
+
*
|
|
389
|
+
* Compare the part of a URL that says WHICH page it is: scheme, host, path and query. A hash is a
|
|
390
|
+
* position inside a document, and a trailing slash is spelling, so neither makes a different page.
|
|
391
|
+
* @param s - the session to bind the page into.
|
|
392
|
+
* @param url - the URL being opened.
|
|
393
|
+
* @returns whether an existing page was taken over.
|
|
394
|
+
*/
|
|
395
|
+
async adoptMatchingPage(s, url) {
|
|
396
|
+
if (this.host.adoptPage === undefined || this.host.listPages === undefined)
|
|
397
|
+
return false;
|
|
398
|
+
const wanted = this.comparableUrl(url);
|
|
399
|
+
if (wanted === undefined)
|
|
400
|
+
return false;
|
|
401
|
+
let pages;
|
|
402
|
+
try {
|
|
403
|
+
pages = await this.host.listPages(s.label);
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
// A listing must not turn "nothing to reuse" into "open failed".
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
const match = pages.find(page => this.comparableUrl(page.url) === wanted);
|
|
410
|
+
if (match === undefined)
|
|
411
|
+
return false;
|
|
412
|
+
try {
|
|
413
|
+
const handle = await this.host.adoptPage(match.id);
|
|
414
|
+
const tab = { id: `page:${match.id}`, handle, url: match.url };
|
|
415
|
+
s.tabs.push(tab);
|
|
416
|
+
s.activeIndex = s.tabs.length - 1;
|
|
417
|
+
this.showActive(s);
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
// The page went away between listing and adopting: fall through to an ordinary navigation.
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
|
|
426
|
+
comparableUrl(url) {
|
|
427
|
+
if (url === '' || url === 'about:blank')
|
|
428
|
+
return undefined;
|
|
429
|
+
try {
|
|
430
|
+
const parsed = new URL(url);
|
|
431
|
+
return `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}${parsed.search}`;
|
|
432
|
+
}
|
|
433
|
+
catch {
|
|
434
|
+
return undefined;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
366
437
|
/** List the session's tabs with their titles. */
|
|
367
438
|
async listTabs(session) {
|
|
368
439
|
const s = this.session(session);
|
|
@@ -398,7 +469,7 @@ export class ElectronBrowserProvider {
|
|
|
398
469
|
//
|
|
399
470
|
// They are appended under a `page:` prefix so a caller can tell the two kinds apart — the
|
|
400
471
|
// prefix is also what `closeTab` uses to decide whether to close a view or a carrier page.
|
|
401
|
-
const pages = await this.host.listPages?.(
|
|
472
|
+
const pages = await this.host.listPages?.(s.label) ?? [];
|
|
402
473
|
for (const page of pages) {
|
|
403
474
|
// A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
|
|
404
475
|
// caller to act on nothing, and the blank normalisation already closes those.
|
|
@@ -409,14 +480,31 @@ export class ElectronBrowserProvider {
|
|
|
409
480
|
return result;
|
|
410
481
|
}
|
|
411
482
|
/** Switch to a tab by id, making its view visible. */
|
|
412
|
-
switchTab(session, tabId) {
|
|
483
|
+
async switchTab(session, tabId) {
|
|
484
|
+
const s = this.session(session);
|
|
485
|
+
// A page the carrier owns. Before this, switching to one threw "not open in this session" —
|
|
486
|
+
// while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
|
|
487
|
+
// page the human was looking at could not be reached (reported as a defect).
|
|
488
|
+
if (tabId.startsWith('page:')) {
|
|
489
|
+
const id = tabId.slice('page:'.length);
|
|
490
|
+
if (this.host.adoptPage === undefined) {
|
|
491
|
+
throw new BrowserError('browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
|
|
492
|
+
+ 'Open the URL through dsh_browser_open instead — that creates a page this plugin owns.', 'BROWSER_TAB_NOT_FOUND');
|
|
493
|
+
}
|
|
494
|
+
const handle = await this.host.adoptPage(id);
|
|
495
|
+
const tab = { id: tabId, handle, url: '' };
|
|
496
|
+
s.tabs.push(tab);
|
|
497
|
+
s.activeIndex = s.tabs.length - 1;
|
|
498
|
+
this.showActive(s);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
413
501
|
const found = this.locateTab(session, tabId);
|
|
414
502
|
found.s.activeIndex = found.index;
|
|
415
503
|
this.showActive(found.s);
|
|
416
|
-
return Promise.resolve();
|
|
417
504
|
}
|
|
418
505
|
/** Close one tab; closing the active tab activates the next. */
|
|
419
506
|
closeTab(session, tabId) {
|
|
507
|
+
const owner = this.session(session).label;
|
|
420
508
|
// A page the carrier owns rather than a view we created. It was reported by `listTabs` under
|
|
421
509
|
// this prefix, so closing it here is what keeps the two tools consistent — a page that can be
|
|
422
510
|
// listed must be closable, or the listing reads as a contradiction.
|
|
@@ -425,7 +513,7 @@ export class ElectronBrowserProvider {
|
|
|
425
513
|
if (this.host.closePage === undefined) {
|
|
426
514
|
return Promise.reject(new BrowserError('browser: this carrier does not expose the pages it opens on its own, so that page cannot be closed', 'BROWSER_TAB_NOT_FOUND'));
|
|
427
515
|
}
|
|
428
|
-
return this.host.closePage(id);
|
|
516
|
+
return this.host.closePage(id, owner);
|
|
429
517
|
}
|
|
430
518
|
const found = this.locateTab(session, tabId);
|
|
431
519
|
const s = found.s;
|
|
@@ -856,8 +944,23 @@ export class ElectronBrowserProvider {
|
|
|
856
944
|
// A tab that has never navigated is a blank, uncommitted view. The collector cannot answer in
|
|
857
945
|
// it — there is no document to commit — so the call would sit out its whole budget before
|
|
858
946
|
// saying anything. Answering the empty page immediately is both faster and more truthful.
|
|
859
|
-
|
|
860
|
-
|
|
947
|
+
//
|
|
948
|
+
// `about:blank` needs the same answer for a different reason: it HAS a document, so the collector
|
|
949
|
+
// runs, finds nothing, and returns zero elements — indistinguishable from a real page with nothing
|
|
950
|
+
// interactive. A caller then acts on it and receives success values, which is how a carrier swap
|
|
951
|
+
// that started a fresh window looked like working tools operating on the wrong page (issue #37).
|
|
952
|
+
const blankUrl = tab.url === '' || tab.url === 'about:blank';
|
|
953
|
+
if (blankUrl) {
|
|
954
|
+
return {
|
|
955
|
+
url: tab.url,
|
|
956
|
+
elements: [],
|
|
957
|
+
truncated: false,
|
|
958
|
+
blank: true,
|
|
959
|
+
note: tab.url === ''
|
|
960
|
+
? 'no page has been opened in this browser yet'
|
|
961
|
+
: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
|
|
962
|
+
};
|
|
963
|
+
}
|
|
861
964
|
const script = `(() => {
|
|
862
965
|
const cap = ${String(this.snapshotMaxElements)}
|
|
863
966
|
const url = location.href
|
|
@@ -911,7 +1014,14 @@ export class ElectronBrowserProvider {
|
|
|
911
1014
|
: el.tagName === 'SELECT' ? 'select'
|
|
912
1015
|
: el.tagName === 'BUTTON' ? 'button'
|
|
913
1016
|
: el.tagName === 'A' ? 'link' : 'other'
|
|
914
|
-
|
|
1017
|
+
// An anchor wrapping only an image has no text: 4399.com's 1608 game links are all
|
|
1018
|
+
// <a href><img alt="名字"></a>, so every label came out empty and the whole page read as
|
|
1019
|
+
// "no interactive elements" while it was full of them.
|
|
1020
|
+
const imageAlt = el.tagName === 'A' || el.tagName === 'BUTTON'
|
|
1021
|
+
? (el.querySelector('img[alt]')?.getAttribute('alt') ?? '')
|
|
1022
|
+
: ''
|
|
1023
|
+
const label = (el.getAttribute('aria-label') || el.placeholder || el.textContent || imageAlt
|
|
1024
|
+
|| el.value || el.name || el.id || '').toString().replace(/\\s+/g, ' ').trim().slice(0, ${String(SNAPSHOT_LABEL_MAX)})
|
|
915
1025
|
if (!label && kind !== 'link') continue
|
|
916
1026
|
const a = absRect(el, el.ownerDocument)
|
|
917
1027
|
out.push({
|
|
@@ -925,7 +1035,52 @@ export class ElectronBrowserProvider {
|
|
|
925
1035
|
})
|
|
926
1036
|
}
|
|
927
1037
|
const challenge = ${CHALLENGE_DETECT_EXPRESSION}
|
|
928
|
-
|
|
1038
|
+
// The page's own URL is the authority on whether there is a document. The tracked tab.url is
|
|
1039
|
+
// a bookkeeping copy that can lag behind a navigation the browser performed itself, and a
|
|
1040
|
+
// stale copy made this check miss on a real about:blank tab.
|
|
1041
|
+
const blankPage = out.length === 0 && (url === '' || url === 'about:blank')
|
|
1042
|
+
// Independent of the element list: a page can mix DOM controls with a canvas that holds the
|
|
1043
|
+
// part the caller actually needs. Measured on sudoku.com — 60 links were collected and the
|
|
1044
|
+
// board, drawn on a canvas, was invisible in the same result.
|
|
1045
|
+
//
|
|
1046
|
+
// The thresholds keep a decorative canvas from claiming a page: at least 80x80 per canvas and
|
|
1047
|
+
// 10% of the viewport in total. Anything smaller is reported by nothing, which is right.
|
|
1048
|
+
let canvas
|
|
1049
|
+
if (blankPage !== true) {
|
|
1050
|
+
let area = 0
|
|
1051
|
+
let count = 0
|
|
1052
|
+
for (const c of document.querySelectorAll('canvas')) {
|
|
1053
|
+
const r = c.getBoundingClientRect()
|
|
1054
|
+
if (r.width < 80 || r.height < 80) continue
|
|
1055
|
+
count += 1
|
|
1056
|
+
area += r.width * r.height
|
|
1057
|
+
}
|
|
1058
|
+
const view = window.innerWidth * window.innerHeight
|
|
1059
|
+
if (count > 0 && view > 0 && area / view >= 0.1) canvas = true
|
|
1060
|
+
}
|
|
1061
|
+
return {
|
|
1062
|
+
url,
|
|
1063
|
+
title,
|
|
1064
|
+
elements: out,
|
|
1065
|
+
truncated: out.length >= cap,
|
|
1066
|
+
challenge,
|
|
1067
|
+
...blankPage === true
|
|
1068
|
+
? {
|
|
1069
|
+
blank: true,
|
|
1070
|
+
note: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
|
|
1071
|
+
}
|
|
1072
|
+
: {},
|
|
1073
|
+
...canvas === true
|
|
1074
|
+
? {
|
|
1075
|
+
canvas: true,
|
|
1076
|
+
note: out.length === 0
|
|
1077
|
+
? 'this page draws its interface on a canvas, so there is no DOM content for a snapshot. '
|
|
1078
|
+
+ 'Use dsh_browser_screenshot to see it, and coordinates with dsh_browser_click to act on it.'
|
|
1079
|
+
: 'part of this page is drawn on a canvas, which no element list can describe. The elements '
|
|
1080
|
+
+ 'below are real; anything inside the canvas is only visible in dsh_browser_screenshot.',
|
|
1081
|
+
}
|
|
1082
|
+
: {},
|
|
1083
|
+
}
|
|
929
1084
|
})()`;
|
|
930
1085
|
// Same hang guard as execute: a renderer that has not committed after
|
|
931
1086
|
// navigate would otherwise block snapshot forever.
|
|
@@ -2349,6 +2504,62 @@ export class ElectronBrowserProvider {
|
|
|
2349
2504
|
this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` });
|
|
2350
2505
|
return restored;
|
|
2351
2506
|
}
|
|
2507
|
+
/**
|
|
2508
|
+
* Capture the active page WITHOUT presenting it.
|
|
2509
|
+
*
|
|
2510
|
+
* `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
|
|
2511
|
+
* that the human sees what the model just captured. It is also what makes that path unusable for a
|
|
2512
|
+
* live preview: presenting on every frame would move focus, switch tabs and expand windows on the
|
|
2513
|
+
* host's screen — exactly the side effects a viewer must not cause (issue #34).
|
|
2514
|
+
*
|
|
2515
|
+
* So this does the capture and nothing else. Deliberately narrow: viewport only, JPEG at the
|
|
2516
|
+
* preview defaults, a short timeout, no save path, no history entry, no carrier recovery. A
|
|
2517
|
+
* preview that rebuilt a vanished carrier would make watching a way to start a browser, which the
|
|
2518
|
+
* design forbids: no page means "nothing to watch", not "open one".
|
|
2519
|
+
* @param session - the session whose active page to capture.
|
|
2520
|
+
* @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
|
|
2521
|
+
* is not painted, which the caller turns into a "paused" state rather than an error.
|
|
2522
|
+
*/
|
|
2523
|
+
async capturePassive(session) {
|
|
2524
|
+
const s = this.session(session);
|
|
2525
|
+
const { handle } = this.activeTab(s);
|
|
2526
|
+
const timeoutMs = PREVIEW_CAPTURE_MS;
|
|
2527
|
+
const timeoutMessage = `browser: preview capture timed out after ${timeoutMs}ms`;
|
|
2528
|
+
// The self-hosted carrier encodes in the child from a NativeImage; it is the only path that can
|
|
2529
|
+
// produce JPEG under Electron 43, whose CDP JPEG encoder hangs.
|
|
2530
|
+
if (typeof handle.capture === 'function') {
|
|
2531
|
+
const shot = await withTimeout(handle.capture({
|
|
2532
|
+
format: 'jpeg',
|
|
2533
|
+
quality: PREVIEW_QUALITY,
|
|
2534
|
+
maxWidth: PREVIEW_MAX_WIDTH,
|
|
2535
|
+
maxHeight: PREVIEW_MAX_HEIGHT,
|
|
2536
|
+
}), timeoutMs, undefined, timeoutMessage);
|
|
2537
|
+
if (shot.base64 === '') {
|
|
2538
|
+
// A hidden or minimized window is not a failure to report as one: the design says the
|
|
2539
|
+
// viewer shows pause and does not open a window to fix it.
|
|
2540
|
+
throw new BrowserError('browser: preview unavailable (the page is not painted; the window may be hidden or minimized)', 'BROWSER_PREVIEW_UNAVAILABLE');
|
|
2541
|
+
}
|
|
2542
|
+
return {
|
|
2543
|
+
dataUrl: `data:${shot.mime};base64,${shot.base64}`,
|
|
2544
|
+
...shot.width !== undefined && shot.height !== undefined
|
|
2545
|
+
? { width: shot.width, height: shot.height }
|
|
2546
|
+
: {},
|
|
2547
|
+
};
|
|
2548
|
+
}
|
|
2549
|
+
// Real Chrome/Edge (and the sidebar): CDP. Viewport only — `captureBeyondViewport` would pull
|
|
2550
|
+
// the whole document, which is neither what a viewer shows nor bounded in size.
|
|
2551
|
+
const result = await withTimeout(handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, {
|
|
2552
|
+
format: 'jpeg',
|
|
2553
|
+
quality: PREVIEW_QUALITY,
|
|
2554
|
+
fromSurface: true,
|
|
2555
|
+
captureBeyondViewport: false,
|
|
2556
|
+
}), timeoutMs, undefined, timeoutMessage);
|
|
2557
|
+
const base64 = typeof result?.data === 'string' ? result.data : '';
|
|
2558
|
+
if (base64 === '') {
|
|
2559
|
+
throw new BrowserError('browser: preview unavailable (the carrier returned no image)', 'BROWSER_PREVIEW_UNAVAILABLE');
|
|
2560
|
+
}
|
|
2561
|
+
return { dataUrl: `data:image/jpeg;base64,${base64}` };
|
|
2562
|
+
}
|
|
2352
2563
|
/** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
|
|
2353
2564
|
async screenshot(session, request, signal) {
|
|
2354
2565
|
const s = this.session(session);
|
|
@@ -2451,8 +2662,7 @@ export class ElectronBrowserProvider {
|
|
|
2451
2662
|
// path, not a disk problem.
|
|
2452
2663
|
const target = this.admitSavePath(savePath, 'screenshot');
|
|
2453
2664
|
try {
|
|
2454
|
-
|
|
2455
|
-
writeFileSync(target, Buffer.from(base64, 'base64'));
|
|
2665
|
+
writeFileNoReplace(target, Buffer.from(base64, 'base64'));
|
|
2456
2666
|
return { dataUrl: `data:${mime};base64,${base64}`, path: target, ...rendered };
|
|
2457
2667
|
}
|
|
2458
2668
|
catch (error) {
|
|
@@ -2709,6 +2919,18 @@ export class ElectronBrowserProvider {
|
|
|
2709
2919
|
exists(session) {
|
|
2710
2920
|
return this.sessions.has(session);
|
|
2711
2921
|
}
|
|
2922
|
+
/**
|
|
2923
|
+
* The sessions a viewer may watch, which is exactly the sessions that exist.
|
|
2924
|
+
*
|
|
2925
|
+
* Served so the browser page can build a frame URL without guessing: the provider names its
|
|
2926
|
+
* sessions, and an id invented by a client is refused at the route. Ids only — no URL, no title,
|
|
2927
|
+
* no target handle — because the point is to let the panel address a session, not to describe
|
|
2928
|
+
* what is in it.
|
|
2929
|
+
* @returns the live session ids.
|
|
2930
|
+
*/
|
|
2931
|
+
watchableSessions() {
|
|
2932
|
+
return [...this.sessions.keys()];
|
|
2933
|
+
}
|
|
2712
2934
|
/**
|
|
2713
2935
|
* The human closed a browser window: the session that window showed is over.
|
|
2714
2936
|
* Ending it here is what makes the next call a clean start rather than a
|
|
@@ -2841,6 +3063,18 @@ export class ElectronBrowserProvider {
|
|
|
2841
3063
|
* best-effort: a page that never settles must not fail the navigation.
|
|
2842
3064
|
*/
|
|
2843
3065
|
const SETTLE_TIMEOUT_MS = 5_000;
|
|
3066
|
+
/**
|
|
3067
|
+
* Bounds for one passive preview frame.
|
|
3068
|
+
*
|
|
3069
|
+
* The design's numbers (issue #34): viewport only, JPEG quality 70, fit inside 1280x720 without
|
|
3070
|
+
* enlarging, and a 2 s capture ceiling so a stuck frame ends the viewer's wait instead of piling up
|
|
3071
|
+
* behind the control queue. These are deliberately not configurable in v1 — one canonical spec per
|
|
3072
|
+
* target is what lets several viewers share a single capture.
|
|
3073
|
+
*/
|
|
3074
|
+
const PREVIEW_CAPTURE_MS = 2_000;
|
|
3075
|
+
const PREVIEW_QUALITY = 70;
|
|
3076
|
+
const PREVIEW_MAX_WIDTH = 1280;
|
|
3077
|
+
const PREVIEW_MAX_HEIGHT = 720;
|
|
2844
3078
|
/**
|
|
2845
3079
|
* When the document already looks settled but its identity has NOT changed
|
|
2846
3080
|
* (same-document navigation, or the outgoing document still answering), wait
|
|
@@ -412,13 +412,17 @@ class ElectronChildClient {
|
|
|
412
412
|
this.onViewClosed = onViewClosed;
|
|
413
413
|
this.executable = executable;
|
|
414
414
|
const electron = this.executable ?? resolveElectronPath();
|
|
415
|
+
const source = this.executable !== undefined
|
|
416
|
+
? 'provided'
|
|
417
|
+
: electron === process.env.ELECTRON_PATH ? 'ELECTRON_PATH' : 'auto';
|
|
415
418
|
// Record what is about to be spawned — with existence checks — BEFORE the
|
|
416
419
|
// attempt. When Electron cannot load the app entry it exits 1 with EMPTY
|
|
417
420
|
// stderr, and that signature is otherwise indistinguishable from a missing
|
|
418
421
|
// binary: writing both paths (and whether they exist) in advance is what
|
|
419
422
|
// turns the next occurrence into a named cause instead of a guess.
|
|
420
|
-
process.stderr.write(`[dsh-browser host] spawning electron: ${electron}\n`);
|
|
423
|
+
process.stderr.write(`[dsh-browser host] spawning electron: ${electron} source=${source}\n`);
|
|
421
424
|
appendHostLog(`${hostStamp()} spawning: electron=${electron} (exists=${String(existsSync(electron))})`
|
|
425
|
+
+ ` source=${source}`
|
|
422
426
|
+ ` hostMain=${this.hostMainPath} (exists=${String(existsSync(this.hostMainPath))})`
|
|
423
427
|
+ ` port=${String(this.port)}\n`);
|
|
424
428
|
// ELECTRON_RUN_AS_NODE (even an empty string) makes Electron run as plain
|