dsh-builtin-browser 0.2.0 → 0.3.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 (34) hide show
  1. package/README.en.md +50 -5
  2. package/README.md +62 -10
  3. package/client.js +44 -8
  4. package/desktop-bridge/install.mjs +98 -0
  5. package/desktop-bridge/plugin-browser-bridge.js +385 -0
  6. package/lib/browser-electron/bridge-connection.d.ts +58 -0
  7. package/lib/browser-electron/bridge-connection.js +133 -0
  8. package/lib/browser-electron/desktop-bridge-host.d.ts +124 -0
  9. package/lib/browser-electron/desktop-bridge-host.js +297 -0
  10. package/lib/browser-electron/entry.js +81 -13
  11. package/lib/browser-electron/history-store.d.ts +5 -1
  12. package/lib/browser-electron/history-store.js +12 -1
  13. package/lib/browser-electron/provider.d.ts +42 -1
  14. package/lib/browser-electron/provider.js +96 -24
  15. package/lib/browser-electron/remote-host.d.ts +9 -1
  16. package/lib/browser-electron/remote-host.js +17 -3
  17. package/lib/browser-electron/settings-store.d.ts +5 -0
  18. package/lib/browser-electron/settings-store.js +24 -1
  19. package/lib/browser-electron/system-browser.d.ts +132 -0
  20. package/lib/browser-electron/system-browser.js +380 -0
  21. package/lib/browser-electron/virtual-cursor.d.ts +27 -2
  22. package/lib/browser-electron/virtual-cursor.js +77 -7
  23. package/lib/tool-browser/index.js +51 -15
  24. package/package.json +2 -1
  25. package/src/browser-electron/bridge-connection.ts +145 -0
  26. package/src/browser-electron/desktop-bridge-host.ts +305 -0
  27. package/src/browser-electron/entry.ts +84 -13
  28. package/src/browser-electron/history-store.ts +11 -2
  29. package/src/browser-electron/provider.ts +124 -25
  30. package/src/browser-electron/remote-host.ts +17 -2
  31. package/src/browser-electron/settings-store.ts +30 -1
  32. package/src/browser-electron/system-browser.ts +371 -0
  33. package/src/browser-electron/virtual-cursor.ts +76 -6
  34. package/src/tool-browser/index.ts +51 -15
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Drive the browser the user already has (Chrome / Edge / any Chromium) instead of
3
+ * the Electron we ship — the same approach Codex Browser Use takes.
4
+ *
5
+ * WHY
6
+ * The bundled Electron is a private copy with its own profile, so it can never see
7
+ * the logins the user already has in Chrome, and on a managed machine the user may
8
+ * simply prefer their own browser. Launching their browser with a *separate*
9
+ * `--user-data-dir` gives us a real Chromium we can drive over CDP without touching
10
+ * their everyday profile, bookmarks or windows: nothing of theirs is opened, locked
11
+ * or modified, and closing us never closes them.
12
+ *
13
+ * HOW
14
+ * Chromium exposes CDP on `--remote-debugging-port=0`, and writes the port it chose
15
+ * into `<profile>/DevToolsActivePort`. That file is the discovery mechanism — no
16
+ * port guessing, no collisions. From there everything is CDP over one WebSocket:
17
+ * `Target.createTarget` makes a page, `Target.attachToTarget` (flattened) gives a
18
+ * session for it, and the plugin's commands ride that session. Node 22 ships a global
19
+ * `WebSocket`, so this needs no dependency at all.
20
+ *
21
+ * WHAT IT IMPLEMENTS
22
+ * The same `ElectronBrowserViewHost` seam as the self-hosted and sidebar hosts, so
23
+ * the provider, the tools, history, the cursor and teardown rules are unchanged —
24
+ * only the carrier differs.
25
+ * @module dsh-browser/browser-electron/system-browser
26
+ */
27
+ import { readFileSync, rmSync } from 'node:fs';
28
+ import { existsSync } from 'node:fs';
29
+ import { join } from 'node:path';
30
+ import { spawn } from 'node:child_process';
31
+ import { randomUUID } from 'node:crypto';
32
+ /**
33
+ * Where each Chromium product installs on Windows, plus the registry paths that
34
+ * survive a non-default install location. Only paths that exist are returned, so a
35
+ * caller can tell "not installed" from "installed elsewhere".
36
+ */
37
+ const WINDOWS_LOCATIONS = {
38
+ chrome: [
39
+ String.raw `C:\Program Files\Google\Chrome\Application\chrome.exe`,
40
+ String.raw `C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
41
+ ],
42
+ edge: [
43
+ String.raw `C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
44
+ String.raw `C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
45
+ ],
46
+ brave: [
47
+ String.raw `C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe`,
48
+ String.raw `C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\brave.exe`,
49
+ ],
50
+ };
51
+ /**
52
+ * Find an installed Chromium browser.
53
+ *
54
+ * `auto` prefers Chrome, then Edge, then Brave — the order reflects how likely each
55
+ * is to be the browser a user actually chose rather than one Windows shipped.
56
+ * @param channel - the configured choice; `bundled` never resolves to a system browser.
57
+ * @param env - environment lookup, injected so tests need no real machine.
58
+ * @returns the detected browser, or undefined when the choice is unavailable.
59
+ */
60
+ export function detectBrowser(channel, env = process.env) {
61
+ if (channel === 'bundled')
62
+ return undefined;
63
+ const order = channel === 'auto' ? ['chrome', 'edge', 'brave'] : [channel];
64
+ for (const kind of order) {
65
+ const fromEnv = (kind === 'chrome' ? env.DSH_BROWSER_CHROME_PATH : kind === 'edge' ? env.DSH_BROWSER_EDGE_PATH : undefined);
66
+ if (fromEnv !== undefined && fromEnv !== '' && existsSync(fromEnv))
67
+ return { kind, path: fromEnv };
68
+ for (const candidate of WINDOWS_LOCATIONS[kind] ?? []) {
69
+ if (existsSync(candidate))
70
+ return { kind, path: candidate };
71
+ }
72
+ }
73
+ return undefined;
74
+ }
75
+ /** One CDP connection to a browser-level WebSocket, with flattened sessions. */
76
+ class CdpClient {
77
+ url;
78
+ nextId = 1;
79
+ pending = new Map();
80
+ ready;
81
+ /**
82
+ * @param url - the browser's `webSocketDebuggerUrl`.
83
+ */
84
+ constructor(url) {
85
+ this.url = url;
86
+ // Node 22 provides WebSocket globally; no dependency is added for this.
87
+ const socket = new WebSocket(url);
88
+ this.socket = socket;
89
+ this.ready = new Promise((resolve, reject) => {
90
+ socket.addEventListener('open', () => resolve());
91
+ socket.addEventListener('error', () => reject(new Error('dsh-builtin-browser: could not reach the browser over CDP')));
92
+ });
93
+ socket.addEventListener('message', event => this.onMessage(String(event.data)));
94
+ socket.addEventListener('close', () => this.fail(new Error('dsh-builtin-browser: the browser closed the CDP connection')));
95
+ }
96
+ socket;
97
+ /** Resolve once the socket is open. */
98
+ async whenReady() {
99
+ await this.ready;
100
+ }
101
+ /**
102
+ * Send one CDP command, optionally on an attached session.
103
+ * @param method - the CDP method.
104
+ * @param params - its parameters.
105
+ * @param sessionId - the flattened session to target, when this is a page command.
106
+ * @returns the CDP result.
107
+ */
108
+ async send(method, params, sessionId) {
109
+ await this.ready;
110
+ const id = this.nextId++;
111
+ const message = { id, method, ...params !== undefined ? { params } : {}, ...sessionId !== undefined ? { sessionId } : {} };
112
+ return await new Promise((resolve, reject) => {
113
+ this.pending.set(id, { resolve, reject });
114
+ this.socket.send(JSON.stringify(message));
115
+ setTimeout(() => {
116
+ if (this.pending.delete(id))
117
+ reject(new Error(`dsh-builtin-browser: ${method} timed out`));
118
+ }, 30_000).unref?.();
119
+ });
120
+ }
121
+ /** Close the socket. */
122
+ close() {
123
+ try {
124
+ this.socket.close();
125
+ }
126
+ catch { /* already closed */ }
127
+ }
128
+ /** Route one CDP message to its waiter. */
129
+ onMessage(raw) {
130
+ let message;
131
+ try {
132
+ message = JSON.parse(raw);
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ if (message.id === undefined)
138
+ return;
139
+ const entry = this.pending.get(message.id);
140
+ if (entry === undefined)
141
+ return;
142
+ this.pending.delete(message.id);
143
+ if (message.error !== undefined)
144
+ entry.reject(new Error(`dsh-builtin-browser: CDP error: ${message.error.message ?? 'unknown'}`));
145
+ else
146
+ entry.resolve(message.result);
147
+ }
148
+ /** Fail everything in flight. */
149
+ fail(error) {
150
+ const pending = [...this.pending.values()];
151
+ this.pending.clear();
152
+ for (const entry of pending)
153
+ entry.reject(error);
154
+ }
155
+ }
156
+ /** A system browser driven over CDP, presented as a browser view host. */
157
+ export class SystemBrowserViewHost {
158
+ browser;
159
+ profileDir;
160
+ extraArgs;
161
+ ephemeralDir;
162
+ views = new Map();
163
+ disposed = false;
164
+ /**
165
+ * The browser is started on FIRST USE, never on construction.
166
+ *
167
+ * A plugin that launches Chrome the moment its host loads is a plugin that takes
168
+ * over the machine before anyone asked it to: simply starting DSH would spawn a
169
+ * browser window. Registration must therefore be inert, and the process is only
170
+ * spawned when a view is actually needed.
171
+ */
172
+ client;
173
+ child;
174
+ starting;
175
+ /**
176
+ * @param browser - the detected installation to launch on first use.
177
+ * @param profileDir - a plugin-owned directory; the user's own profile is never touched.
178
+ * @param extraArgs - additional Chromium switches.
179
+ * @param ephemeralDir - a directory to delete on release, when the user has turned
180
+ * persistence off so no login state outlives the session.
181
+ */
182
+ constructor(browser, profileDir, extraArgs = [], ephemeralDir) {
183
+ this.browser = browser;
184
+ this.profileDir = profileDir;
185
+ this.extraArgs = extraArgs;
186
+ this.ephemeralDir = ephemeralDir;
187
+ }
188
+ /** Which product this host would drive (for diagnostics). */
189
+ get kind() {
190
+ return this.browser.kind;
191
+ }
192
+ /** Whether the browser has actually been started yet (diagnostics and tests). */
193
+ get started() {
194
+ return this.child !== undefined;
195
+ }
196
+ /**
197
+ * The CDP client, starting the browser on first use.
198
+ * @returns the connected client.
199
+ */
200
+ async ensureClient() {
201
+ if (this.client !== undefined)
202
+ return this.client;
203
+ // Concurrent first calls share one startup rather than racing two browsers.
204
+ this.starting ??= this.start().finally(() => { this.starting = undefined; });
205
+ return await this.starting;
206
+ }
207
+ /**
208
+ * Launch the browser with a private profile and connect over CDP.
209
+ *
210
+ * `--remote-debugging-port=0` plus the `DevToolsActivePort` file is the only
211
+ * reliable way to learn the port: a fixed port collides with whatever else the
212
+ * machine is running, and parsing stderr is fragile across versions.
213
+ * @returns the connected client.
214
+ */
215
+ async start() {
216
+ const args = [
217
+ '--remote-debugging-port=0',
218
+ `--user-data-dir=${this.profileDir}`,
219
+ // Behave like a fresh, unattended browser: no first-run UI, no default-browser
220
+ // prompt, no restore bubble, and no "Chrome is being controlled" infobar.
221
+ '--no-first-run',
222
+ '--no-default-browser-check',
223
+ '--disable-features=Translate,MediaRouter',
224
+ '--disable-session-crashed-bubble',
225
+ '--hide-crash-restore-bubble',
226
+ ...this.extraArgs,
227
+ 'about:blank',
228
+ ];
229
+ const child = spawn(this.browser.path, args, { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: false });
230
+ this.child = child;
231
+ const portFile = join(this.profileDir, 'DevToolsActivePort');
232
+ const deadline = Date.now() + 30_000;
233
+ for (;;) {
234
+ if (Date.now() > deadline) {
235
+ child.kill();
236
+ this.child = undefined;
237
+ break;
238
+ }
239
+ if (child.exitCode !== null) {
240
+ this.child = undefined;
241
+ break;
242
+ }
243
+ if (existsSync(portFile)) {
244
+ try {
245
+ const port = readFileSync(portFile, 'utf8').split('\n')[0]?.trim() ?? '';
246
+ if (port !== '') {
247
+ const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json();
248
+ if (typeof version.webSocketDebuggerUrl === 'string') {
249
+ const client = new CdpClient(version.webSocketDebuggerUrl);
250
+ await client.whenReady();
251
+ this.client = client;
252
+ return client;
253
+ }
254
+ }
255
+ }
256
+ catch {
257
+ // The file can exist a moment before the port answers; poll again.
258
+ }
259
+ }
260
+ await new Promise(resolve => setTimeout(resolve, 250));
261
+ }
262
+ throw new Error(`dsh-builtin-browser: ${this.browser.kind} did not expose CDP within 30s (${this.browser.path})`);
263
+ }
264
+ /**
265
+ * Whether this host can back views.
266
+ *
267
+ * True while the host is usable — including before the browser has been started,
268
+ * since the first command is what starts it. Reporting "unavailable" here would
269
+ * make the plugin fall back for no reason.
270
+ */
271
+ available() {
272
+ return !this.disposed;
273
+ }
274
+ createView() {
275
+ const viewId = randomUUID();
276
+ return {
277
+ id: viewId,
278
+ sendCommand: async (method, params) => {
279
+ const client = await this.ensureClient();
280
+ const session = this.views.get(viewId) ?? await this.ensureSession(viewId);
281
+ const result = await client.send(method, params, session);
282
+ return (result ?? {});
283
+ },
284
+ };
285
+ }
286
+ destroyView(handle) {
287
+ const session = this.views.get(handle.id);
288
+ this.views.delete(handle.id);
289
+ if (session === undefined)
290
+ return;
291
+ // A session id is not a target id: closing the page needs the target the session
292
+ // was attached to, which is why they are tracked separately.
293
+ const targetId = this.sessions.get(session);
294
+ this.sessions.delete(session);
295
+ // Nothing to close if the browser was never started.
296
+ if (targetId !== undefined && this.client !== undefined) {
297
+ // Best-effort: a page that is already gone is not an error.
298
+ void this.client.send('Target.closeTarget', { targetId }).catch(() => undefined);
299
+ }
300
+ }
301
+ /** Nothing to show: the browser owns its own windows. */
302
+ showView() { }
303
+ /** Same as {@link showView}. */
304
+ async presentView() { }
305
+ /** The browser owns window grouping. */
306
+ groupView() { }
307
+ /**
308
+ * Bring the browser's window forward.
309
+ *
310
+ * The browser is a separate application, so there is no view to raise; focusing
311
+ * the process is the closest honest equivalent, and failing to do so (a minimized
312
+ * window, a locked session) is never worth an error.
313
+ */
314
+ async focus() {
315
+ try {
316
+ this.child?.kill('SIGCONT');
317
+ }
318
+ catch { /* not supported on Windows; harmless */ }
319
+ }
320
+ /** The browser reports its own window lifecycle. */
321
+ onUserAction() { }
322
+ /** The browser reports its own window lifecycle. */
323
+ onViewClosed() { }
324
+ /**
325
+ * Close the browser we launched, if we ever launched one.
326
+ *
327
+ * The user's own windows belong to a different process and are never touched. A
328
+ * host whose browser was never started (the common case when nobody used the
329
+ * browser) simply tears down its bookkeeping.
330
+ */
331
+ dispose() {
332
+ if (this.disposed)
333
+ return;
334
+ this.disposed = true;
335
+ this.views.clear();
336
+ this.sessions.clear();
337
+ this.client?.close();
338
+ try {
339
+ this.child?.kill();
340
+ }
341
+ catch { /* already gone */ }
342
+ const ephemeral = this.ephemeralDir;
343
+ if (ephemeral !== undefined && this.child !== undefined) {
344
+ // The browser flushes its profile while shutting down, so deleting later avoids
345
+ // racing it. Leftovers are only a stray temp directory, never a live credential.
346
+ setTimeout(() => { try {
347
+ rmSync(ephemeral, { recursive: true, force: true });
348
+ }
349
+ catch { /* best effort */ } }, 3_000).unref?.();
350
+ }
351
+ else if (ephemeral !== undefined) {
352
+ // Never started, so nothing can be holding it open.
353
+ try {
354
+ rmSync(ephemeral, { recursive: true, force: true });
355
+ }
356
+ catch { /* best effort */ }
357
+ }
358
+ }
359
+ /** The flattened session for a view, creating its page on first use. */
360
+ async ensureSession(viewId) {
361
+ const existing = this.views.get(viewId);
362
+ if (existing !== undefined)
363
+ return existing;
364
+ const client = await this.ensureClient();
365
+ const created = await client.send('Target.createTarget', { url: 'about:blank' });
366
+ const targetId = created?.targetId;
367
+ if (typeof targetId !== 'string')
368
+ throw new Error('dsh-builtin-browser: the browser did not create a page');
369
+ const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
370
+ const sessionId = attached?.sessionId;
371
+ if (typeof sessionId !== 'string')
372
+ throw new Error('dsh-builtin-browser: the browser did not attach to the new page');
373
+ // The session id is what page commands ride; the target id is what closes it.
374
+ this.sessions.set(sessionId, targetId);
375
+ this.views.set(viewId, sessionId);
376
+ return sessionId;
377
+ }
378
+ /** sessionId -> targetId, so a destroyed view can close the right page. */
379
+ sessions = new Map();
380
+ }
@@ -17,15 +17,39 @@
17
17
  */
18
18
  /** What the pointer is doing at the reported point. */
19
19
  export type CursorAction = 'move' | 'click';
20
+ /**
21
+ * Whether a paint at this position would change anything on screen.
22
+ * @param handle - the view the overlay belongs to.
23
+ * @param x - viewport x in CSS pixels.
24
+ * @param y - viewport y in CSS pixels.
25
+ * @param action - the action being reported.
26
+ * @param force - paint even when unchanged (a click ripple must always fire).
27
+ * @returns true when the overlay should be painted.
28
+ */
29
+ export declare function cursorNeedsPaint<TView>(handle: TView, x: number, y: number, action: CursorAction, force?: boolean): boolean;
20
30
  /**
21
31
  * The in-page expression that materializes or moves the overlay. Idempotent: the
22
32
  * first call creates the nodes, later calls only move them (and pulse).
23
33
  * @param x - viewport x in CSS pixels.
24
34
  * @param y - viewport y in CSS pixels.
25
35
  * @param action - whether to pulse a click ripple at the point.
36
+ * @param label - optional short description of the operation, shown beside the
37
+ * pointer. The overlay is the only "the agent has taken over this tab" signal, so
38
+ * saying *what* it is doing is what turns it from a decoration into an account of
39
+ * the agent's actions that a human can follow without reading the tool log.
26
40
  * @returns a self-contained expression that evaluates to `true`.
27
41
  */
28
- export declare function cursorScript(x: number, y: number, action: CursorAction): string;
42
+ export declare function cursorScript(x: number, y: number, action: CursorAction, label?: string): string;
43
+ /**
44
+ * Forget the remembered position for a view.
45
+ *
46
+ * Called when the document is replaced: the overlay lived in the old document and
47
+ * went with it, so the cache would otherwise claim the pointer is already where it
48
+ * needs to be and skip every later paint — the pointer would simply never return
49
+ * after a navigation.
50
+ * @param handle - the view whose cache should be dropped.
51
+ */
52
+ export declare function forgetCursor<TView>(handle: TView): void;
29
53
  /**
30
54
  * Draw (or move) the pointer overlay on one view's page.
31
55
  *
@@ -38,5 +62,6 @@ export declare function cursorScript(x: number, y: number, action: CursorAction)
38
62
  * @param y - viewport y in CSS pixels.
39
63
  * @param action - whether to pulse a click ripple.
40
64
  * @param evaluate - the provider's evaluate bridge (keeps the CDP coupling in one place).
65
+ * @param label - optional short description of the operation, shown beside the pointer.
41
66
  */
42
- export declare function paintCursor<TView>(handle: TView, x: number, y: number, action: CursorAction, evaluate: (handle: TView, expression: string) => Promise<unknown>): void;
67
+ export declare function paintCursor<TView>(handle: TView, x: number, y: number, action: CursorAction, evaluate: (handle: TView, expression: string) => Promise<unknown>, label?: string, force?: boolean): void;
@@ -17,15 +17,46 @@
17
17
  */
18
18
  /** Element id of the overlay root, stable so repeat calls update one node. */
19
19
  const CURSOR_ID = '__dsh_agent_cursor__';
20
+ /**
21
+ * Where the overlay was last placed, so an unchanged position is not repainted.
22
+ *
23
+ * A single tool call issues several CDP commands (locate, click, cursor), and the
24
+ * cursor is repainted for each one that moves it. Repainting to the same pixel is a
25
+ * wasted round-trip *and* a visible flicker: the transition restarts from the same
26
+ * place, which reads as a stutter rather than as movement.
27
+ */
28
+ const lastPlaced = new WeakMap();
29
+ /**
30
+ * Whether a paint at this position would change anything on screen.
31
+ * @param handle - the view the overlay belongs to.
32
+ * @param x - viewport x in CSS pixels.
33
+ * @param y - viewport y in CSS pixels.
34
+ * @param action - the action being reported.
35
+ * @param force - paint even when unchanged (a click ripple must always fire).
36
+ * @returns true when the overlay should be painted.
37
+ */
38
+ export function cursorNeedsPaint(handle, x, y, action, force = false) {
39
+ if (force)
40
+ return true;
41
+ const key = handle;
42
+ if (key === null || typeof key !== 'object')
43
+ return true;
44
+ const previous = lastPlaced.get(key);
45
+ return previous === undefined || previous.x !== x || previous.y !== y || previous.action !== action;
46
+ }
20
47
  /**
21
48
  * The in-page expression that materializes or moves the overlay. Idempotent: the
22
49
  * first call creates the nodes, later calls only move them (and pulse).
23
50
  * @param x - viewport x in CSS pixels.
24
51
  * @param y - viewport y in CSS pixels.
25
52
  * @param action - whether to pulse a click ripple at the point.
53
+ * @param label - optional short description of the operation, shown beside the
54
+ * pointer. The overlay is the only "the agent has taken over this tab" signal, so
55
+ * saying *what* it is doing is what turns it from a decoration into an account of
56
+ * the agent's actions that a human can follow without reading the tool log.
26
57
  * @returns a self-contained expression that evaluates to `true`.
27
58
  */
28
- export function cursorScript(x, y, action) {
59
+ export function cursorScript(x, y, action, label) {
29
60
  return `(() => {
30
61
  const id = ${JSON.stringify(CURSOR_ID)}
31
62
  let root = document.getElementById(id)
@@ -33,24 +64,55 @@ export function cursorScript(x, y, action) {
33
64
  root = document.createElement('div')
34
65
  root.id = id
35
66
  root.setAttribute('aria-hidden', 'true')
36
- root.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;pointer-events:none;transition:transform 120ms ease-out;will-change:transform'
67
+ root.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;pointer-events:none;transition:transform 190ms cubic-bezier(.22,.85,.24,1);will-change:transform'
37
68
  const svg = '<svg width="22" height="22" viewBox="0 0 22 22" style="position:absolute;left:-2px;top:-2px;filter:drop-shadow(0 1px 2px rgba(0,0,0,.45))">'
38
69
  + '<path d="M4 2 L4 18 L8.4 13.8 L11.2 19.6 L13.8 18.4 L11 12.8 L17 12.6 Z" fill="#ffffff" stroke="#111111" stroke-width="1.4" stroke-linejoin="round"/></svg>'
39
- const ripple = '<span style="position:absolute;left:0;top:0;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:2px solid rgba(64,160,255,.9);opacity:0"></span>'
40
- root.innerHTML = svg + ripple
70
+ const ripple = '<span data-dsh-role="ripple" style="position:absolute;left:0;top:0;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:2px solid rgba(64,160,255,.9);opacity:0"></span>'
71
+ // The bubble sits below-right of the pointer tip and is capped in width so a long
72
+ // label cannot cover the page it is describing.
73
+ const bubble = '<span data-dsh-role="bubble" style="position:absolute;left:18px;top:16px;max-width:280px;padding:3px 8px;border-radius:5px;background:rgba(17,17,17,.92);color:#fff;font:12px/1.45 -apple-system,Segoe UI,Roboto,sans-serif;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;box-shadow:0 1px 3px rgba(0,0,0,.4)"></span>'
74
+ root.innerHTML = svg + ripple + bubble
41
75
  ;(document.body || document.documentElement).appendChild(root)
42
76
  }
43
77
  root.style.transform = 'translate(${x}px, ${y}px)'
44
- ${action === 'click' ? `const ripple = root.lastElementChild
78
+ ${action === 'click' ? `const ripple = root.querySelector('[data-dsh-role="ripple"]')
45
79
  if (ripple && typeof ripple.animate === 'function') {
46
80
  ripple.animate(
47
81
  [{ transform: 'scale(.25)', opacity: 0.95 }, { transform: 'scale(1.6)', opacity: 0 }],
48
82
  { duration: 550, easing: 'ease-out' },
49
83
  )
50
84
  }` : ''}
85
+ ${label !== undefined && label !== '' ? `const bubble = root.querySelector('[data-dsh-role="bubble"]')
86
+ if (bubble) {
87
+ bubble.textContent = ${JSON.stringify(label)}
88
+ if (typeof bubble.animate === 'function') {
89
+ // Fade in, hold, fade out: the label is a narration of the action, not a
90
+ // permanent caption, so a stale one never lingers over later work.
91
+ bubble.animate(
92
+ [{ opacity: 0, transform: 'translateY(-3px)' }, { opacity: 1, transform: 'translateY(0)' }, { opacity: 1, offset: 0.6 }, { opacity: 0 }],
93
+ { duration: 2200, easing: 'ease-out', fill: 'forwards' },
94
+ )
95
+ } else {
96
+ bubble.style.opacity = '1'
97
+ }
98
+ }` : ''}
51
99
  return true
52
100
  })()`;
53
101
  }
102
+ /**
103
+ * Forget the remembered position for a view.
104
+ *
105
+ * Called when the document is replaced: the overlay lived in the old document and
106
+ * went with it, so the cache would otherwise claim the pointer is already where it
107
+ * needs to be and skip every later paint — the pointer would simply never return
108
+ * after a navigation.
109
+ * @param handle - the view whose cache should be dropped.
110
+ */
111
+ export function forgetCursor(handle) {
112
+ const key = handle;
113
+ if (key !== null && typeof key === 'object')
114
+ lastPlaced.delete(key);
115
+ }
54
116
  /**
55
117
  * Draw (or move) the pointer overlay on one view's page.
56
118
  *
@@ -63,9 +125,17 @@ export function cursorScript(x, y, action) {
63
125
  * @param y - viewport y in CSS pixels.
64
126
  * @param action - whether to pulse a click ripple.
65
127
  * @param evaluate - the provider's evaluate bridge (keeps the CDP coupling in one place).
128
+ * @param label - optional short description of the operation, shown beside the pointer.
66
129
  */
67
- export function paintCursor(handle, x, y, action, evaluate) {
130
+ export function paintCursor(handle, x, y, action, evaluate, label, force = false) {
68
131
  if (!Number.isFinite(x) || !Number.isFinite(y))
69
132
  return;
70
- void evaluate(handle, cursorScript(Math.round(x), Math.round(y), action)).catch(() => { });
133
+ const roundedX = Math.round(x);
134
+ const roundedY = Math.round(y);
135
+ if (!cursorNeedsPaint(handle, roundedX, roundedY, action, force))
136
+ return;
137
+ const key = handle;
138
+ if (key !== null && typeof key === 'object')
139
+ lastPlaced.set(key, { x: roundedX, y: roundedY, action });
140
+ void evaluate(handle, cursorScript(roundedX, roundedY, action, label)).catch(() => { });
71
141
  }