dsh-builtin-browser 0.1.23 → 0.3.0
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/README.en.md +91 -3
- package/README.md +98 -4
- package/client.js +334 -0
- package/cordis.patch.yml +24 -5
- package/desktop-bridge/install.mjs +98 -0
- package/desktop-bridge/plugin-browser-bridge.js +385 -0
- package/docs/README.md +1 -1
- package/docs/architecture.md +1 -1
- package/docs/tool-reference.md +2 -1
- package/lib/browser/runtime.d.ts +18 -1
- package/lib/browser/runtime.js +19 -0
- package/lib/browser/types.d.ts +33 -0
- package/lib/browser-electron/bridge-connection.d.ts +58 -0
- package/lib/browser-electron/bridge-connection.js +133 -0
- package/lib/browser-electron/desktop-bridge-host.d.ts +124 -0
- package/lib/browser-electron/desktop-bridge-host.js +297 -0
- package/lib/browser-electron/entry.js +195 -11
- package/lib/browser-electron/history-store.d.ts +75 -0
- package/lib/browser-electron/history-store.js +162 -0
- package/lib/browser-electron/host-main.js +28 -1
- package/lib/browser-electron/provider.d.ts +122 -1
- package/lib/browser-electron/provider.js +233 -21
- package/lib/browser-electron/remote-host.d.ts +17 -1
- package/lib/browser-electron/remote-host.js +81 -9
- package/lib/browser-electron/settings-store.d.ts +92 -0
- package/lib/browser-electron/settings-store.js +183 -0
- package/lib/browser-electron/system-browser.d.ts +100 -0
- package/lib/browser-electron/system-browser.js +322 -0
- package/lib/browser-electron/virtual-cursor.d.ts +67 -0
- package/lib/browser-electron/virtual-cursor.js +141 -0
- package/lib/index.d.ts +16 -2
- package/lib/index.js +18 -2
- package/lib/tool-browser/index.js +122 -16
- package/package.json +14 -1
- package/src/browser/runtime.ts +22 -0
- package/src/browser/types.ts +31 -0
- package/src/browser-electron/bridge-connection.ts +145 -0
- package/src/browser-electron/desktop-bridge-host.ts +305 -0
- package/src/browser-electron/entry.ts +217 -11
- package/src/browser-electron/history-store.ts +171 -0
- package/src/browser-electron/host-main.ts +26 -1
- package/src/browser-electron/provider.ts +284 -21
- package/src/browser-electron/remote-host.ts +84 -7
- package/src/browser-electron/settings-store.ts +227 -0
- package/src/browser-electron/system-browser.ts +318 -0
- package/src/browser-electron/virtual-cursor.ts +152 -0
- package/src/index.ts +20 -2
- package/src/tool-browser/index.ts +121 -15
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport for the desktop shell's browser bridge: one long-lived connection to a
|
|
3
|
+
* loopback TCP service.
|
|
4
|
+
*
|
|
5
|
+
* WHY THIS IS ITS OWN MODULE
|
|
6
|
+
* The bridge used to be reached with a fresh connection per request, which measured
|
|
7
|
+
* at ~25ms per call (TCP handshake + token exchange) against ~0.2ms when the socket
|
|
8
|
+
* is reused. A single browser action issues several CDP commands, so that cost was
|
|
9
|
+
* multiplied on every tool call — the difference between a snappy agent and a
|
|
10
|
+
* visibly sluggish one. Reuse is therefore a property of the transport, and keeping
|
|
11
|
+
* it here means the view host above does not have to think about sockets at all.
|
|
12
|
+
*
|
|
13
|
+
* PROTOCOL
|
|
14
|
+
* The first line on a connection carries the token; the service marks the socket
|
|
15
|
+
* authenticated and ignores that line as a command. Requests and answers are then
|
|
16
|
+
* newline-delimited JSON, one answer per request, in order.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-browser/browser-electron/bridge-connection
|
|
19
|
+
*/
|
|
20
|
+
import { connect } from 'node:net';
|
|
21
|
+
/**
|
|
22
|
+
* A reusable connection to the bridge.
|
|
23
|
+
*
|
|
24
|
+
* Requests are serialised by construction: one socket, one in-flight request at a
|
|
25
|
+
* time, answered in order. A broken socket is discarded so the next call dials
|
|
26
|
+
* again — a dead connection must never become a dead plugin.
|
|
27
|
+
*/
|
|
28
|
+
export class BridgeConnection {
|
|
29
|
+
endpoint;
|
|
30
|
+
socket;
|
|
31
|
+
buffer = '';
|
|
32
|
+
queue = [];
|
|
33
|
+
/**
|
|
34
|
+
* @param endpoint - the shell's published bridge endpoint.
|
|
35
|
+
*/
|
|
36
|
+
constructor(endpoint) {
|
|
37
|
+
this.endpoint = endpoint;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Send one request, reusing the socket if it is still healthy.
|
|
41
|
+
* @param request - the request body (the token is added here).
|
|
42
|
+
* @param timeoutMs - how long to wait for the answer before dropping the socket.
|
|
43
|
+
* @returns the bridge's answer.
|
|
44
|
+
*/
|
|
45
|
+
async call(request, timeoutMs = 20_000) {
|
|
46
|
+
const socket = this.ensureSocket();
|
|
47
|
+
return await new Promise((resolve, reject) => {
|
|
48
|
+
const timer = setTimeout(() => {
|
|
49
|
+
const index = this.queue.findIndex(entry => entry.resolve === resolve);
|
|
50
|
+
if (index !== -1)
|
|
51
|
+
this.queue.splice(index, 1);
|
|
52
|
+
const error = new Error(`dsh-builtin-browser: bridge timed out after ${timeoutMs}ms`);
|
|
53
|
+
this.reset(error);
|
|
54
|
+
reject(error);
|
|
55
|
+
}, timeoutMs);
|
|
56
|
+
this.queue.push({
|
|
57
|
+
resolve: answer => { clearTimeout(timer); resolve(answer); },
|
|
58
|
+
reject: error => { clearTimeout(timer); reject(error); },
|
|
59
|
+
});
|
|
60
|
+
try {
|
|
61
|
+
socket.write(JSON.stringify({ token: this.endpoint.token, ...request }) + '\n');
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
this.queue.pop();
|
|
66
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
67
|
+
this.reset(failure);
|
|
68
|
+
reject(failure);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Close the socket and fail anything still waiting on it. */
|
|
73
|
+
close() {
|
|
74
|
+
this.reset(new Error('dsh-builtin-browser: bridge closed'));
|
|
75
|
+
}
|
|
76
|
+
/** The live socket, connecting and authenticating it on first use. */
|
|
77
|
+
ensureSocket() {
|
|
78
|
+
if (this.socket !== undefined)
|
|
79
|
+
return this.socket;
|
|
80
|
+
const socket = connect({ host: '127.0.0.1', port: this.endpoint.port });
|
|
81
|
+
socket.setEncoding('utf8');
|
|
82
|
+
socket.on('data', chunk => this.onData(String(chunk)));
|
|
83
|
+
socket.on('error', error => this.reset(error));
|
|
84
|
+
socket.on('close', () => this.reset(new Error('dsh-builtin-browser: bridge connection closed')));
|
|
85
|
+
this.buffer = '';
|
|
86
|
+
this.socket = socket;
|
|
87
|
+
socket.write(JSON.stringify({ token: this.endpoint.token }) + '\n');
|
|
88
|
+
return socket;
|
|
89
|
+
}
|
|
90
|
+
/** Resolve queued requests in order as answers arrive. */
|
|
91
|
+
onData(chunk) {
|
|
92
|
+
this.buffer += chunk;
|
|
93
|
+
let newline = this.buffer.indexOf('\n');
|
|
94
|
+
while (newline !== -1) {
|
|
95
|
+
const line = this.buffer.slice(0, newline).trim();
|
|
96
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
97
|
+
newline = this.buffer.indexOf('\n');
|
|
98
|
+
if (line === '')
|
|
99
|
+
continue;
|
|
100
|
+
const entry = this.queue.shift();
|
|
101
|
+
if (entry === undefined)
|
|
102
|
+
continue;
|
|
103
|
+
try {
|
|
104
|
+
const answer = JSON.parse(line);
|
|
105
|
+
// A rejected token means the shell restarted with a new one, so this socket
|
|
106
|
+
// can never succeed again: answer (the caller needs the error) and drop it,
|
|
107
|
+
// so the next call dials afresh instead of retrying a doomed credential.
|
|
108
|
+
if (answer.ok === false && answer.error === 'bad token') {
|
|
109
|
+
entry.resolve(answer);
|
|
110
|
+
this.reset(new Error('dsh-builtin-browser: the bridge rejected our token'));
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
entry.resolve(answer);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
entry.reject(new Error(`dsh-builtin-browser: malformed bridge answer (${String(error)})`));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Tear the socket down, failing pending work. */
|
|
121
|
+
reset(error) {
|
|
122
|
+
if (this.socket !== undefined) {
|
|
123
|
+
const socket = this.socket;
|
|
124
|
+
this.socket = undefined;
|
|
125
|
+
socket.removeAllListeners();
|
|
126
|
+
socket.destroy();
|
|
127
|
+
}
|
|
128
|
+
this.buffer = '';
|
|
129
|
+
const pending = this.queue.splice(0, this.queue.length);
|
|
130
|
+
for (const entry of pending)
|
|
131
|
+
entry.reject(error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Desktop-sidebar browser host: drive the page the desktop shell shows in its
|
|
3
|
+
* sidebar, instead of spawning a second, parallel Electron window.
|
|
4
|
+
*
|
|
5
|
+
* WHY
|
|
6
|
+
* The plugin runs inside the desktop's Node-mode host, where there is no Electron
|
|
7
|
+
* API — which is why it self-hosts a whole browser today. The shell, however, can
|
|
8
|
+
* own views, and its sidebar already displays real web pages. This host borrows
|
|
9
|
+
* that page over the shell's bridge (see apps/desktop/bridge/plugin-browser-bridge.js),
|
|
10
|
+
* so the agent and the human end up on ONE page instead of two.
|
|
11
|
+
*
|
|
12
|
+
* CONTRACT
|
|
13
|
+
* It implements the same `ElectronBrowserViewHost` seam the self-hosted host does,
|
|
14
|
+
* so the provider, the tools, browsing history, the synthetic cursor and the
|
|
15
|
+
* teardown rules are all unchanged: only the carrier differs. Everything is
|
|
16
|
+
* lazily materialized — a fresh shell has no sidebar guest until something asks
|
|
17
|
+
* for a page, and the bridge creates one on demand.
|
|
18
|
+
*
|
|
19
|
+
* FALLBACK
|
|
20
|
+
* `discover()` returns undefined whenever the shell offers no usable bridge
|
|
21
|
+
* (older desktop build, plain `dsh web`, bridge not started), and the entry point
|
|
22
|
+
* then keeps the self-hosted Electron it has always used.
|
|
23
|
+
* @module dsh-browser/browser-electron/desktop-bridge-host
|
|
24
|
+
*/
|
|
25
|
+
import type { ElectronBrowserViewHost, ElectronViewHandle } from './provider.js';
|
|
26
|
+
import type { BrowserUserAction } from './provider.js';
|
|
27
|
+
/** Absolute path of the endpoint file the shell writes. */
|
|
28
|
+
export declare function bridgeEndpointPath(): string;
|
|
29
|
+
/**
|
|
30
|
+
* The desktop sidebar, presented as a browser view host.
|
|
31
|
+
*
|
|
32
|
+
* One sidebar exists per shell window, so every view this host hands out refers
|
|
33
|
+
* to the same guest: the provider keeps its tab bookkeeping, and the tabs simply
|
|
34
|
+
* share the visible page. That is the intended behaviour for this carrier — the
|
|
35
|
+
* point is a single page both parties can see.
|
|
36
|
+
*/
|
|
37
|
+
export declare class DesktopBridgeViewHost implements ElectronBrowserViewHost {
|
|
38
|
+
private readonly endpoint;
|
|
39
|
+
private readonly connection;
|
|
40
|
+
private readonly views;
|
|
41
|
+
/**
|
|
42
|
+
* Guests whose view is gone but whose page may still be open in the sidebar.
|
|
43
|
+
*
|
|
44
|
+
* The provider destroys its view handles before it asks for a release, so the
|
|
45
|
+
* mapping is dropped by then — keeping the guest ids here is what lets us close
|
|
46
|
+
* only our own tabs when several sessions are running (requirements §4: each
|
|
47
|
+
* session gets its own page).
|
|
48
|
+
*/
|
|
49
|
+
private readonly orphaned;
|
|
50
|
+
private userActionHandler;
|
|
51
|
+
/**
|
|
52
|
+
* @param endpoint - the shell's published bridge endpoint.
|
|
53
|
+
*/
|
|
54
|
+
private constructor();
|
|
55
|
+
/**
|
|
56
|
+
* Find a usable desktop bridge, if this surface has one.
|
|
57
|
+
*
|
|
58
|
+
* A stale endpoint (a shell that already exited, leaving its file behind) is
|
|
59
|
+
* rejected here rather than surfacing later as a mysterious ECONNREFUSED: the
|
|
60
|
+
* caller falls back to self-hosting, which always works.
|
|
61
|
+
* @returns the host, or undefined when no bridge is available.
|
|
62
|
+
*/
|
|
63
|
+
static discover(): Promise<DesktopBridgeViewHost | undefined>;
|
|
64
|
+
/** Whether this host can back views: the bridge already answered `list`. */
|
|
65
|
+
available(): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* The guest id backing a view, materialized on first use.
|
|
68
|
+
*
|
|
69
|
+
* The sidebar browser is itself a multi-tab surface, so each view gets its own
|
|
70
|
+
* tab's guest: the provider's tab bookkeeping then maps onto real tabs the human
|
|
71
|
+
* can see and switch between. Two rules keep that honest:
|
|
72
|
+
* - a cached guest is used as-is: probing it first cost a round-trip on every
|
|
73
|
+
* command, so liveness is established by the command failing instead;
|
|
74
|
+
* - a fresh view takes an unclaimed guest, growing the tab strip only when
|
|
75
|
+
* every existing guest is already spoken for.
|
|
76
|
+
* @param viewId - the view whose guest is wanted.
|
|
77
|
+
* @param url - address to use when a sidebar browser has to be opened first.
|
|
78
|
+
*/
|
|
79
|
+
private guestFor;
|
|
80
|
+
/**
|
|
81
|
+
* Ask for at least `count` sidebar tabs and return their guest ids.
|
|
82
|
+
* @param count - minimum number of tabs.
|
|
83
|
+
*/
|
|
84
|
+
private guestIds;
|
|
85
|
+
createView(): ElectronViewHandle;
|
|
86
|
+
destroyView(handle: ElectronViewHandle): void;
|
|
87
|
+
/**
|
|
88
|
+
* Nothing to show: the sidebar is already on screen, and showing it again is
|
|
89
|
+
* the shell's business (it owns the tab strip and the visibility toggle).
|
|
90
|
+
*/
|
|
91
|
+
showView(): void;
|
|
92
|
+
/** Same as {@link showView}: the page is already presented by the shell. */
|
|
93
|
+
presentView(): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* The shell owns window grouping, and one sidebar serves every view, so there
|
|
96
|
+
* is nothing to record here. (It must not write a placeholder guest id either:
|
|
97
|
+
* a view whose guest is not yet materialized has to stay absent from the map,
|
|
98
|
+
* or the first real command would be sent to the placeholder.)
|
|
99
|
+
*/
|
|
100
|
+
groupView(): void;
|
|
101
|
+
/** Focus is the shell's to manage, and there is no separate window to raise. */
|
|
102
|
+
focus(): Promise<void>;
|
|
103
|
+
onUserAction(handler: (action: BrowserUserAction) => void): void;
|
|
104
|
+
/** The shell reports its own window lifecycle; nothing to subscribe to here. */
|
|
105
|
+
onViewClosed(): void;
|
|
106
|
+
/**
|
|
107
|
+
* Release the sidebar's browser pages (requirements §3, `ui.closeWithSession`).
|
|
108
|
+
*
|
|
109
|
+
* Destroying our own view handles is not enough on this carrier: the sidebar
|
|
110
|
+
* belongs to the shell and would happily keep the page (and its renderer) alive.
|
|
111
|
+
* Closing the tabs is what actually ends the page — and only the page: cookies
|
|
112
|
+
* live in the partition, history on disk, so both survive.
|
|
113
|
+
* @returns a promise that settles once the shell has been asked.
|
|
114
|
+
*/
|
|
115
|
+
releasePage(): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Fold the sidebar away without ending the page (`ui.autoExpandOnce` is off, or
|
|
118
|
+
* the caller wants the screen back while work continues).
|
|
119
|
+
* @returns a promise that settles once the shell has been asked.
|
|
120
|
+
*/
|
|
121
|
+
collapse(): Promise<void>;
|
|
122
|
+
/** No child process of our own to stop; close the shared connection instead. */
|
|
123
|
+
dispose(): void;
|
|
124
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Desktop-sidebar browser host: drive the page the desktop shell shows in its
|
|
3
|
+
* sidebar, instead of spawning a second, parallel Electron window.
|
|
4
|
+
*
|
|
5
|
+
* WHY
|
|
6
|
+
* The plugin runs inside the desktop's Node-mode host, where there is no Electron
|
|
7
|
+
* API — which is why it self-hosts a whole browser today. The shell, however, can
|
|
8
|
+
* own views, and its sidebar already displays real web pages. This host borrows
|
|
9
|
+
* that page over the shell's bridge (see apps/desktop/bridge/plugin-browser-bridge.js),
|
|
10
|
+
* so the agent and the human end up on ONE page instead of two.
|
|
11
|
+
*
|
|
12
|
+
* CONTRACT
|
|
13
|
+
* It implements the same `ElectronBrowserViewHost` seam the self-hosted host does,
|
|
14
|
+
* so the provider, the tools, browsing history, the synthetic cursor and the
|
|
15
|
+
* teardown rules are all unchanged: only the carrier differs. Everything is
|
|
16
|
+
* lazily materialized — a fresh shell has no sidebar guest until something asks
|
|
17
|
+
* for a page, and the bridge creates one on demand.
|
|
18
|
+
*
|
|
19
|
+
* FALLBACK
|
|
20
|
+
* `discover()` returns undefined whenever the shell offers no usable bridge
|
|
21
|
+
* (older desktop build, plain `dsh web`, bridge not started), and the entry point
|
|
22
|
+
* then keeps the self-hosted Electron it has always used.
|
|
23
|
+
* @module dsh-browser/browser-electron/desktop-bridge-host
|
|
24
|
+
*/
|
|
25
|
+
import { BridgeConnection } from './bridge-connection.js';
|
|
26
|
+
import { readFileSync } from 'node:fs';
|
|
27
|
+
import { homedir } from 'node:os';
|
|
28
|
+
import { join } from 'node:path';
|
|
29
|
+
import { randomUUID } from 'node:crypto';
|
|
30
|
+
/** Absolute path of the endpoint file the shell writes. */
|
|
31
|
+
export function bridgeEndpointPath() {
|
|
32
|
+
const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
|
|
33
|
+
return join(home, 'dsh-builtin-browser-bridge.json');
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Whether a command failed because the page is no longer there (as opposed to
|
|
37
|
+
* failing on its own merits). Only these are worth retrying on a fresh guest.
|
|
38
|
+
* @param error - the failure to classify.
|
|
39
|
+
*/
|
|
40
|
+
function isGuestGone(error) {
|
|
41
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
42
|
+
return /guest \d+ is not available|sidebar unavailable|did not create a browser guest/i.test(message);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The desktop sidebar, presented as a browser view host.
|
|
46
|
+
*
|
|
47
|
+
* One sidebar exists per shell window, so every view this host hands out refers
|
|
48
|
+
* to the same guest: the provider keeps its tab bookkeeping, and the tabs simply
|
|
49
|
+
* share the visible page. That is the intended behaviour for this carrier — the
|
|
50
|
+
* point is a single page both parties can see.
|
|
51
|
+
*/
|
|
52
|
+
export class DesktopBridgeViewHost {
|
|
53
|
+
endpoint;
|
|
54
|
+
connection;
|
|
55
|
+
views = new Map();
|
|
56
|
+
/**
|
|
57
|
+
* Guests whose view is gone but whose page may still be open in the sidebar.
|
|
58
|
+
*
|
|
59
|
+
* The provider destroys its view handles before it asks for a release, so the
|
|
60
|
+
* mapping is dropped by then — keeping the guest ids here is what lets us close
|
|
61
|
+
* only our own tabs when several sessions are running (requirements §4: each
|
|
62
|
+
* session gets its own page).
|
|
63
|
+
*/
|
|
64
|
+
orphaned = new Set();
|
|
65
|
+
userActionHandler;
|
|
66
|
+
/**
|
|
67
|
+
* @param endpoint - the shell's published bridge endpoint.
|
|
68
|
+
*/
|
|
69
|
+
constructor(endpoint) {
|
|
70
|
+
this.endpoint = endpoint;
|
|
71
|
+
this.connection = new BridgeConnection(endpoint);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Find a usable desktop bridge, if this surface has one.
|
|
75
|
+
*
|
|
76
|
+
* A stale endpoint (a shell that already exited, leaving its file behind) is
|
|
77
|
+
* rejected here rather than surfacing later as a mysterious ECONNREFUSED: the
|
|
78
|
+
* caller falls back to self-hosting, which always works.
|
|
79
|
+
* @returns the host, or undefined when no bridge is available.
|
|
80
|
+
*/
|
|
81
|
+
static async discover() {
|
|
82
|
+
let endpoint;
|
|
83
|
+
try {
|
|
84
|
+
const raw = JSON.parse(readFileSync(bridgeEndpointPath(), 'utf8'));
|
|
85
|
+
if (typeof raw.port !== 'number' || typeof raw.token !== 'string' || typeof raw.pid !== 'number')
|
|
86
|
+
return undefined;
|
|
87
|
+
endpoint = { port: raw.port, token: raw.token, pid: raw.pid, ...raw.updatedAt !== undefined ? { updatedAt: raw.updatedAt } : {} };
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
// A throwaway connection for discovery: the adopted host opens its own, and a
|
|
94
|
+
// rejected endpoint must not leave a socket behind.
|
|
95
|
+
const probe = new BridgeConnection(endpoint);
|
|
96
|
+
try {
|
|
97
|
+
const answer = await probe.call({ op: 'list' }, 5_000);
|
|
98
|
+
return answer.ok === true ? new DesktopBridgeViewHost(endpoint) : undefined;
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
probe.close();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Dead endpoint or an older bridge: self-hosting remains the answer.
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Whether this host can back views: the bridge already answered `list`. */
|
|
110
|
+
available() {
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The guest id backing a view, materialized on first use.
|
|
115
|
+
*
|
|
116
|
+
* The sidebar browser is itself a multi-tab surface, so each view gets its own
|
|
117
|
+
* tab's guest: the provider's tab bookkeeping then maps onto real tabs the human
|
|
118
|
+
* can see and switch between. Two rules keep that honest:
|
|
119
|
+
* - a cached guest is used as-is: probing it first cost a round-trip on every
|
|
120
|
+
* command, so liveness is established by the command failing instead;
|
|
121
|
+
* - a fresh view takes an unclaimed guest, growing the tab strip only when
|
|
122
|
+
* every existing guest is already spoken for.
|
|
123
|
+
* @param viewId - the view whose guest is wanted.
|
|
124
|
+
* @param url - address to use when a sidebar browser has to be opened first.
|
|
125
|
+
*/
|
|
126
|
+
async guestFor(viewId, url) {
|
|
127
|
+
const existing = this.views.get(viewId);
|
|
128
|
+
// No liveness check here: verifying the cached guest cost a round-trip on every
|
|
129
|
+
// command. A guest that has gone away is detected by the command itself failing,
|
|
130
|
+
// and `createView`'s sendCommand then discards the cache and calls back in here.
|
|
131
|
+
if (existing !== undefined)
|
|
132
|
+
return existing;
|
|
133
|
+
// The browser tab must exist before its strip can be extended: `ensureSidebar`
|
|
134
|
+
// opens the sidebar (and, on a fresh shell, materializes the first guest).
|
|
135
|
+
const sidebar = await this.connection.call({
|
|
136
|
+
op: 'ensureSidebar',
|
|
137
|
+
...url !== undefined ? { url } : {},
|
|
138
|
+
});
|
|
139
|
+
if (sidebar.ok !== true)
|
|
140
|
+
throw new Error(`dsh-builtin-browser: sidebar unavailable (${String(sidebar.error)})`);
|
|
141
|
+
const wanted = this.views.size + 1;
|
|
142
|
+
let ids = await this.guestIds(Math.max(1, wanted));
|
|
143
|
+
const taken = new Set(this.views.values());
|
|
144
|
+
let free = ids.find(id => !taken.has(id));
|
|
145
|
+
if (free === undefined) {
|
|
146
|
+
// Every tab is already driving something: the strip has to grow.
|
|
147
|
+
ids = await this.guestIds(ids.length + 1);
|
|
148
|
+
free = ids.find(id => !taken.has(id));
|
|
149
|
+
}
|
|
150
|
+
if (free === undefined)
|
|
151
|
+
throw new Error('dsh-builtin-browser: the sidebar reported no free browser tab');
|
|
152
|
+
this.views.set(viewId, free);
|
|
153
|
+
return free;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Ask for at least `count` sidebar tabs and return their guest ids.
|
|
157
|
+
* @param count - minimum number of tabs.
|
|
158
|
+
*/
|
|
159
|
+
async guestIds(count) {
|
|
160
|
+
const answer = await this.connection.call({ op: 'ensureTabs', count });
|
|
161
|
+
if (answer.ok !== true)
|
|
162
|
+
throw new Error(`dsh-builtin-browser: could not open a sidebar tab (${String(answer.error)})`);
|
|
163
|
+
const ids = Array.isArray(answer.ids) ? answer.ids.map(Number).filter(Number.isFinite) : [];
|
|
164
|
+
if (ids.length === 0)
|
|
165
|
+
throw new Error('dsh-builtin-browser: the sidebar reported no browser tabs');
|
|
166
|
+
return ids;
|
|
167
|
+
}
|
|
168
|
+
createView() {
|
|
169
|
+
const viewId = randomUUID();
|
|
170
|
+
const navigateUrl = (method, params) => method === 'Page.navigate' ? String(params?.url ?? '') : undefined;
|
|
171
|
+
const run = async (guest, method, params) => {
|
|
172
|
+
const answer = await this.connection.call({ op: 'cdp', id: guest, method, params });
|
|
173
|
+
if (answer.ok !== true)
|
|
174
|
+
throw new Error(`dsh-builtin-browser: sidebar command failed: ${String(answer.error)}`);
|
|
175
|
+
// The bridge forwards whatever CDP answered; the seam expects an object.
|
|
176
|
+
return (answer.result ?? {});
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
id: viewId,
|
|
180
|
+
sendCommand: async (method, params) => {
|
|
181
|
+
// No liveness probe up front. Checking first cost a whole round-trip on
|
|
182
|
+
// every command; instead the command runs and its failure is what triggers
|
|
183
|
+
// recovery. Only a genuinely missing guest is retried, so a real error (a
|
|
184
|
+
// bad selector, a timeout) still surfaces unchanged.
|
|
185
|
+
const url = navigateUrl(method, params);
|
|
186
|
+
let guest = await this.guestFor(viewId, url);
|
|
187
|
+
try {
|
|
188
|
+
return await run(guest, method, params);
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (!isGuestGone(error))
|
|
192
|
+
throw error;
|
|
193
|
+
// The human closed the tab: the page is gone, so take a fresh one and
|
|
194
|
+
// replay the command once. This is the "closing the interface ends the
|
|
195
|
+
// session" rule, now paid for only when it actually happens.
|
|
196
|
+
this.views.delete(viewId);
|
|
197
|
+
guest = await this.guestFor(viewId, url);
|
|
198
|
+
return await run(guest, method, params);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
destroyView(handle) {
|
|
204
|
+
const guest = this.views.get(handle.id);
|
|
205
|
+
if (guest !== undefined) {
|
|
206
|
+
// Remember it: the page outlives our handle, and a later release must be able
|
|
207
|
+
// to name exactly the tabs this plugin opened.
|
|
208
|
+
this.orphaned.add(guest);
|
|
209
|
+
this.views.delete(handle.id);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Nothing to show: the sidebar is already on screen, and showing it again is
|
|
214
|
+
* the shell's business (it owns the tab strip and the visibility toggle).
|
|
215
|
+
*/
|
|
216
|
+
showView() { }
|
|
217
|
+
/** Same as {@link showView}: the page is already presented by the shell. */
|
|
218
|
+
async presentView() { }
|
|
219
|
+
/**
|
|
220
|
+
* The shell owns window grouping, and one sidebar serves every view, so there
|
|
221
|
+
* is nothing to record here. (It must not write a placeholder guest id either:
|
|
222
|
+
* a view whose guest is not yet materialized has to stay absent from the map,
|
|
223
|
+
* or the first real command would be sent to the placeholder.)
|
|
224
|
+
*/
|
|
225
|
+
groupView() { }
|
|
226
|
+
/** Focus is the shell's to manage, and there is no separate window to raise. */
|
|
227
|
+
async focus() { }
|
|
228
|
+
onUserAction(handler) {
|
|
229
|
+
this.userActionHandler = handler;
|
|
230
|
+
}
|
|
231
|
+
/** The shell reports its own window lifecycle; nothing to subscribe to here. */
|
|
232
|
+
onViewClosed() { }
|
|
233
|
+
/**
|
|
234
|
+
* Release the sidebar's browser pages (requirements §3, `ui.closeWithSession`).
|
|
235
|
+
*
|
|
236
|
+
* Destroying our own view handles is not enough on this carrier: the sidebar
|
|
237
|
+
* belongs to the shell and would happily keep the page (and its renderer) alive.
|
|
238
|
+
* Closing the tabs is what actually ends the page — and only the page: cookies
|
|
239
|
+
* live in the partition, history on disk, so both survive.
|
|
240
|
+
* @returns a promise that settles once the shell has been asked.
|
|
241
|
+
*/
|
|
242
|
+
async releasePage() {
|
|
243
|
+
// Only our own tabs: the ids come from the views we handed out (and their
|
|
244
|
+
// orphans), never from "every webview currently visible". With two sessions
|
|
245
|
+
// live, releasing one must leave the other's page alone.
|
|
246
|
+
const mine = [...this.views.values(), ...this.orphaned];
|
|
247
|
+
this.views.clear();
|
|
248
|
+
this.orphaned.clear();
|
|
249
|
+
// Nothing of ours is open: release nothing. Falling through to an unfiltered
|
|
250
|
+
// release here would close tabs a human opened, or another session's page.
|
|
251
|
+
if (mine.length === 0)
|
|
252
|
+
return;
|
|
253
|
+
let titles;
|
|
254
|
+
try {
|
|
255
|
+
const answer = await this.connection.call({ op: 'list' }, 5_000);
|
|
256
|
+
const sidebar = Array.isArray(answer.sidebar) ? answer.sidebar : [];
|
|
257
|
+
titles = sidebar
|
|
258
|
+
.filter(guest => mine.includes(Number(guest.id)))
|
|
259
|
+
.map(guest => String(guest.title ?? ''))
|
|
260
|
+
.filter(title => title !== '');
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// Could not read the titles back; releasing nothing is safer than closing
|
|
264
|
+
// tabs that belong to somebody else.
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (titles.length === 0)
|
|
268
|
+
return;
|
|
269
|
+
try {
|
|
270
|
+
await this.connection.call({ op: 'closeSidebarBrowser', titles }, 10_000);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// Best effort: the setting expresses a preference, and a shell that cannot
|
|
274
|
+
// be reached is no reason to fail the session teardown that called us.
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Fold the sidebar away without ending the page (`ui.autoExpandOnce` is off, or
|
|
279
|
+
* the caller wants the screen back while work continues).
|
|
280
|
+
* @returns a promise that settles once the shell has been asked.
|
|
281
|
+
*/
|
|
282
|
+
async collapse() {
|
|
283
|
+
try {
|
|
284
|
+
await this.connection.call({ op: 'collapseSidebar' }, 10_000);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
// Presentation only; failing to fold is never worth an error.
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** No child process of our own to stop; close the shared connection instead. */
|
|
291
|
+
dispose() {
|
|
292
|
+
this.connection.close();
|
|
293
|
+
this.views.clear();
|
|
294
|
+
this.orphaned.clear();
|
|
295
|
+
this.userActionHandler = undefined;
|
|
296
|
+
}
|
|
297
|
+
}
|