mcp-browser-dev-tools 0.4.1 → 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/README.md CHANGED
@@ -36,7 +36,7 @@ Then ask the agent for browser work, for example "open example.com and check the
36
36
 
37
37
  ![An AI agent sends one run_steps call with five steps to the browser and gets one reply with every result](docs/images/overview.svg)
38
38
 
39
- Your agent gets 45 browser tools over MCP: open or attach to tabs, click, type, drag, upload files, and navigate, read the console and network, block or mock requests, take screenshots, and save and restore sessions. At the center is `run_steps`: the agent sends a whole task, with branches and waits in it, and the server carries it out in the browser and replies once. `run_tabs` does the same in several tabs at the same time.
39
+ Your agent gets 46 browser tools over MCP: open or attach to tabs, click, type, drag, upload files, and navigate, read the console and network, block or mock requests, take screenshots, and save and restore sessions. At the center is `run_steps`: the agent sends a whole task, with branches and waits in it, and the server carries it out in the browser and replies once. `run_tabs` does the same in several tabs at the same time.
40
40
 
41
41
  ## Why This One
42
42
 
@@ -156,12 +156,12 @@ Every form run started with `get_snapshot` and acted by ref, without being told
156
156
 
157
157
  ## Tools
158
158
 
159
- 45 tools, described in [docs/tools.md](docs/tools.md). The server lists the core set by default, since every model turn pays for each tool listed, and `more_tools` lists, describes, and calls the rest; `MCP_BROWSER_TOOLS=all`, or a list of groups such as `network,state`, lists them too ([Tool Sets](docs/tools.md#tool-sets)).
159
+ 47 tools, described in [docs/tools.md](docs/tools.md). The server lists the core set by default, since every model turn pays for each tool listed, and `more_tools` lists, describes, and calls the rest; `MCP_BROWSER_TOOLS=all`, or a list of groups such as `network,state`, lists them too ([Tool Sets](docs/tools.md#tool-sets)).
160
160
 
161
161
  - **Browser and tabs:** `browser_status`, `ensure_browser`, `launch_browser`, `list_tabs`, `new_tab`, `close_tab`, `attach_tab`, `detach_tab`, `list_sessions`
162
- - **Act:** `navigate`, `reload`, `click`, `hover`, `drag`, `type`, `select`, `press_key`, `upload_file`, `scroll`, `set_viewport`
162
+ - **Act:** `navigate`, `reload`, `click`, `hover`, `drag`, `type`, `select`, `press_key`, `upload_file`, `scroll`, `set_viewport`, `set_dialog_answers`
163
163
  - **Wait and batch:** `wait_for`, `run_steps`, `run_tabs`
164
- - **Inspect:** `get_page_state`, `get_snapshot`, `get_document`, `inspect_element`, `read_text`, `take_screenshot`, `evaluate_js`
164
+ - **Inspect:** `get_page_state`, `get_snapshot`, `get_document`, `inspect_element`, `query_elements`, `read_text`, `take_screenshot`, `evaluate_js`
165
165
  - **Console and network:** `get_console_messages`, `get_network_requests`, `get_events`, `get_har`, `set_network`
166
166
  - **Performance:** `get_performance`, `record_trace`, `record_video`
167
167
  - **Session state:** `get_cookies`, `get_storage`, `capture_session_snapshot`, `restore_session_snapshot`, `compare_page_state`, `compare_selector`, `capture_debug_report`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-browser-dev-tools",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Browser MCP server for AI agents: batch actions, waits, and checks into one call on Chrome, Edge, or Firefox (CDP and WebDriver BiDi)",
5
5
  "author": "Hinaser <rindo.hinase@gmail.com>",
6
6
  "license": "MIT",
@@ -26,6 +26,7 @@
26
26
  "src/browser-launcher.mjs",
27
27
  "src/browser-launch-service.mjs",
28
28
  "src/cdp-client.mjs",
29
+ "src/dialog-answers.mjs",
29
30
  "src/cli.mjs",
30
31
  "src/config.mjs",
31
32
  "src/doctor.mjs",
@@ -178,7 +178,9 @@ export class ChangeTracker {
178
178
  // mid-navigation, or blocks scripts), and the action then reports nothing.
179
179
  // With frameKey, the changes are those inside that frame (an action on
180
180
  // an element named by a frame ref).
181
- async begin(sessionId, frameKey = null) {
181
+ // With watchOnly, the baseline takes no snapshot: it serves
182
+ // waitUntilQuiet and ends with stop, never with a report.
183
+ async begin(sessionId, frameKey = null, { watchOnly = false } = {}) {
182
184
  const changeId = crypto.randomUUID();
183
185
  const startedAt = new Date().toISOString();
184
186
  const active = this.activeIds(sessionId);
@@ -192,6 +194,7 @@ export class ChangeTracker {
192
194
  owner: this.owner,
193
195
  active: Array.from(active),
194
196
  ...(frameKey ? { frameKey } : {}),
197
+ ...(watchOnly ? { watchOnly } : {}),
195
198
  },
196
199
  );
197
200
  return { sessionId, changeId, documentId, startedAt, frameKey };
@@ -235,10 +238,20 @@ export class ChangeTracker {
235
238
  }
236
239
  }
237
240
 
238
- // Waits until the DOM is quiet and the action's requests are done, or a
239
- // navigation it started has loaded, within the settle and navigation
240
- // limits; then asks the page for the report.
241
- async settle(baseline) {
241
+ // Waits until the DOM is quiet and the requests and short timers started
242
+ // since the baseline are done, or a navigation has loaded, within the
243
+ // settle and navigation limits.
244
+ //
245
+ // A batch waits like this before a step that reads the page, with:
246
+ // endedAt, when the step that changed the page ended; since, to count
247
+ // requests from before the baseline (a navigation step is watched only
248
+ // once its page has loaded); and signal, which ends the wait when
249
+ // aborted. animations also waits for transitions and animations that are
250
+ // about to end, for a caller whose page is looked at next.
251
+ async waitUntilQuiet(
252
+ baseline,
253
+ { endedAt = Date.now(), since, animations = false, signal } = {},
254
+ ) {
242
255
  const { sessionId, changeId, documentId, startedAt, frameKey } = baseline;
243
256
  const ids = {
244
257
  changeId,
@@ -246,13 +259,18 @@ export class ChangeTracker {
246
259
  owner: this.owner,
247
260
  ...(frameKey ? { frameKey } : {}),
248
261
  };
249
- const actionEndedAt = Date.now();
250
262
  let pending;
263
+ let status;
251
264
  let timedOut = false;
265
+ let polls = 0;
252
266
  while (true) {
253
- const elapsed = Date.now() - actionEndedAt;
254
- pending = await this.pending(sessionId, startedAt);
255
- let status;
267
+ // The caller gave up, as run_tabs does when a tab times out.
268
+ if (signal?.aborted) {
269
+ return { pending: [], timedOut: false, lost: false, polls };
270
+ }
271
+ polls += 1;
272
+ const elapsed = Date.now() - endedAt;
273
+ pending = await this.pending(sessionId, since ?? startedAt);
256
274
  try {
257
275
  status = await this.browserAdapter.trackChanges(
258
276
  sessionId,
@@ -274,6 +292,7 @@ export class ChangeTracker {
274
292
  elapsed >= this.quietMs &&
275
293
  status.quietMs >= this.quietMs &&
276
294
  !(status.timers > 0) &&
295
+ !(animations && status.animations > 0) &&
277
296
  pending.length === 0;
278
297
  if (
279
298
  status.document === "new" &&
@@ -292,6 +311,25 @@ export class ChangeTracker {
292
311
  }
293
312
  await sleep(this.pollMs);
294
313
  }
314
+ // polls is 1 when the page was already quiet.
315
+ return { pending, timedOut, lost: status.lost === true, polls };
316
+ }
317
+
318
+ // Waits for the page to settle after the action, then asks the page for
319
+ // the report.
320
+ async settle(baseline) {
321
+ const { sessionId, changeId, documentId, startedAt, frameKey } = baseline;
322
+ const ids = {
323
+ changeId,
324
+ documentId,
325
+ owner: this.owner,
326
+ ...(frameKey ? { frameKey } : {}),
327
+ };
328
+ // The agent looks at the page next, so a transition about to end is
329
+ // waited for as well.
330
+ const { pending, timedOut } = await this.waitUntilQuiet(baseline, {
331
+ animations: true,
332
+ });
295
333
 
296
334
  let report;
297
335
  try {
package/src/app.mjs CHANGED
@@ -4,6 +4,36 @@ import { createLogger } from "./logger.mjs";
4
4
  import { McpBrowserDevToolsServer } from "./mcp-server.mjs";
5
5
  import { PACKAGE_NAME } from "./package-info.mjs";
6
6
 
7
+ // A fatal error is logged at every level, and an error message can quote a
8
+ // selector, URL, typed text, or page content, so only the error's type, code,
9
+ // and stack frames are kept.
10
+ export function describeFatalError(value) {
11
+ if (!(value instanceof Error)) {
12
+ return `non-Error value (${typeof value})`;
13
+ }
14
+
15
+ const code = value.code === undefined ? "" : ` [${value.code}]`;
16
+ return [`${value.name}${code}`, ...stackFrames(value)].join("\n");
17
+ }
18
+
19
+ // The stack starts with "name: message", and the message can span lines that
20
+ // look like frames, so the frames are what follows that header. A stack that
21
+ // does not start with it gives none.
22
+ function stackFrames(error) {
23
+ const stack = typeof error.stack === "string" ? error.stack : "";
24
+ const message = String(error.message ?? "");
25
+ const header =
26
+ message === "" ? String(error.name) : `${error.name}: ${message}`;
27
+ if (!stack.startsWith(`${header}\n`)) {
28
+ return [];
29
+ }
30
+
31
+ return stack
32
+ .slice(header.length + 1)
33
+ .split("\n")
34
+ .filter((line) => /^\s+at /.test(line));
35
+ }
36
+
7
37
  export function createBrowserDevToolsApp({
8
38
  env = process.env,
9
39
  input = process.stdin,
@@ -93,7 +123,9 @@ export function createBrowserDevToolsApp({
93
123
  if (stream === errorOutput) {
94
124
  logger.disableOutput();
95
125
  }
96
- logger.info(`${name} failed: ${error?.code ?? error?.message ?? error}`);
126
+ logger.info(
127
+ `${name} failed: ${error?.code ?? (error instanceof Error ? error.name : typeof error)}`,
128
+ );
97
129
  // EPIPE means the client closed its end, and without stdout the server
98
130
  // cannot answer it anyway.
99
131
  if (stream === output || error?.code === "EPIPE") {
@@ -120,14 +152,14 @@ export function createBrowserDevToolsApp({
120
152
  process.on("uncaughtException", (error) => {
121
153
  handleFatal(
122
154
  "uncaughtException",
123
- `uncaught exception: ${error?.stack ?? error}`,
155
+ `uncaught exception: ${describeFatalError(error)}`,
124
156
  );
125
157
  });
126
158
 
127
159
  process.on("unhandledRejection", (reason) => {
128
160
  handleFatal(
129
161
  "unhandledRejection",
130
- `unhandled rejection: ${reason instanceof Error ? (reason.stack ?? reason.message) : reason}`,
162
+ `unhandled rejection: ${describeFatalError(reason)}`,
131
163
  );
132
164
  });
133
165
 
@@ -316,6 +316,10 @@ export class MultiBrowserAdapter {
316
316
  return this.delegateSession(sessionId, "setViewport", [options]);
317
317
  }
318
318
 
319
+ setDialogAnswers(sessionId, options) {
320
+ return this.delegateSession(sessionId, "setDialogAnswers", [options]);
321
+ }
322
+
319
323
  evaluate(sessionId, expression, options) {
320
324
  return this.delegateSession(sessionId, "evaluate", [expression, options]);
321
325
  }
@@ -336,6 +340,10 @@ export class MultiBrowserAdapter {
336
340
  return this.delegateSession(sessionId, "readText", [options]);
337
341
  }
338
342
 
343
+ queryElements(sessionId, options) {
344
+ return this.delegateSession(sessionId, "queryElements", [options]);
345
+ }
346
+
339
347
  snapshotControls(sessionId) {
340
348
  return this.delegateSession(sessionId, "snapshotControls");
341
349
  }
@@ -1,5 +1,12 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
- import { mkdir, mkdtemp, readFile, realpath } from "node:fs/promises";
2
+ import {
3
+ mkdir,
4
+ mkdtemp,
5
+ open,
6
+ readFile,
7
+ realpath,
8
+ stat,
9
+ } from "node:fs/promises";
3
10
  import os from "node:os";
4
11
  import process from "node:process";
5
12
  import path from "node:path";
@@ -129,17 +136,58 @@ function mentionsProfile(commandLine, needles) {
129
136
  });
130
137
  }
131
138
 
139
+ // On Windows, a running browser keeps its profile's lock file open, so
140
+ // opening it fails with EBUSY. Chrome and Edge share <profile>\lockfile for
141
+ // reading, so only a write open shows it held, and delete it on exit. Firefox
142
+ // shares <profile>\parent.lock with nobody and leaves it behind, unlocked.
143
+ // The existence check takes no lock, so the brief open, which could get in
144
+ // the way of a browser starting on the profile at that moment, happens only
145
+ // when the file is there. Returns the held file, or null.
146
+ async function findHeldProfileLock(family, userDataDir, { openFn, statFn }) {
147
+ const lockFile = path.join(
148
+ userDataDir,
149
+ family === "firefox" ? "parent.lock" : "lockfile",
150
+ );
151
+ try {
152
+ await statFn(lockFile);
153
+ } catch {
154
+ return null;
155
+ }
156
+ try {
157
+ const handle = await openFn(lockFile, family === "firefox" ? "r" : "r+");
158
+ await handle.close();
159
+ return null;
160
+ } catch (error) {
161
+ return error?.code === "EBUSY" ? lockFile : null;
162
+ }
163
+ }
164
+
132
165
  // Starting a browser binary on a profile that is already open does not start
133
166
  // a second browser: the running instance just opens another window. Callers
134
- // use this to reuse that instance instead.
135
- async function findProfileProcesses(
167
+ // use this to reuse that instance instead. Returns what shows the profile in
168
+ // use: the browser command lines naming it, or on Windows its held lock file.
169
+ export async function findProfileProcesses(
136
170
  family,
137
171
  userDataDir,
138
- { env = process.env, execFileFn = execFileAsync, realpathFn = realpath } = {},
172
+ {
173
+ env = process.env,
174
+ execFileFn = execFileAsync,
175
+ realpathFn = realpath,
176
+ openFn = open,
177
+ statFn = stat,
178
+ platform = detectRuntimePlatform(env),
179
+ } = {},
139
180
  ) {
140
- const platform = detectRuntimePlatform(env);
141
- // Windows process listings do not include command lines, and WSL cannot see
142
- // the command lines of the Windows browsers it launches.
181
+ // Windows can show browser command lines only through slow WMI queries,
182
+ // so the profile's lock file answers there.
183
+ if (platform === "win32") {
184
+ const lockFile = await findHeldProfileLock(family, userDataDir, {
185
+ openFn,
186
+ statFn,
187
+ });
188
+ return lockFile ? [lockFile] : [];
189
+ }
190
+ // WSL cannot see the command lines of the Windows browsers it launches.
143
191
  if (platform !== "darwin" && platform !== "linux") {
144
192
  return [];
145
193
  }
@@ -9,6 +9,12 @@ import {
9
9
  summarizeNetworkRequests,
10
10
  } from "./session-events.mjs";
11
11
  import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
12
+ import {
13
+ answerDialog,
14
+ createDialogAnswers,
15
+ reserveDialogAnswers,
16
+ setDialogAnswers,
17
+ } from "./dialog-answers.mjs";
12
18
  import { waitForPageCondition } from "./wait-for.mjs";
13
19
  import {
14
20
  assertEnabled,
@@ -31,6 +37,7 @@ import {
31
37
  probeScope,
32
38
  restoreFrameSelector,
33
39
  addFrameSnapshots,
40
+ frameElementQuery,
34
41
  frameElementSnapshot,
35
42
  parseFrameRef,
36
43
  shiftFramePoints,
@@ -489,6 +496,8 @@ export class CdpSession {
489
496
  this.lastNavigationAt = null;
490
497
  this.lastReloadAt = null;
491
498
  this.viewportOverride = null;
499
+ // Shared by every session on the tab; see attachToTarget.
500
+ this.dialogAnswers = options.dialogAnswers ?? createDialogAnswers();
492
501
  this.video = null;
493
502
  // Frames: child sessions of cross-site iframes (attached in flatten
494
503
  // mode, by session id), the default execution context of each frame,
@@ -880,7 +889,7 @@ export class CdpSession {
880
889
  }
881
890
 
882
891
  if (method === "Page.javascriptDialogOpening") {
883
- this.autoDismissDialog(params);
892
+ this.answerDialog(params);
884
893
  }
885
894
 
886
895
  if (method === "Fetch.requestPaused") {
@@ -971,9 +980,23 @@ export class CdpSession {
971
980
  }
972
981
  }
973
982
 
974
- autoDismissDialog(params) {
975
- const accept = params.type !== "prompt";
976
- this.send("Page.handleJavaScriptDialog", { accept }).catch(() => {});
983
+ answerDialog(params) {
984
+ const { accept, text } = answerDialog(
985
+ this.dialogAnswers,
986
+ params.type,
987
+ params.defaultPrompt,
988
+ );
989
+ this.send("Page.handleJavaScriptDialog", {
990
+ accept,
991
+ ...(text === undefined ? {} : { promptText: text }),
992
+ }).catch(() => {});
993
+ }
994
+
995
+ setDialogAnswers(options) {
996
+ return {
997
+ sessionId: this.id,
998
+ ...setDialogAnswers(this.dialogAnswers, options),
999
+ };
977
1000
  }
978
1001
 
979
1002
  pushEvent(event) {
@@ -1403,6 +1426,20 @@ export class CdpSession {
1403
1426
  return this.runPageAction({ action: "read_text", ...options });
1404
1427
  }
1405
1428
 
1429
+ async queryElements(options = {}) {
1430
+ const route = parseFrameRef(options.selector);
1431
+ if (route) {
1432
+ return frameElementQuery({
1433
+ route,
1434
+ frameKeys: this.frameKeys,
1435
+ runInFrame: (key, payload, runOptions) =>
1436
+ this.runInFrame(key, payload, runOptions),
1437
+ options,
1438
+ });
1439
+ }
1440
+ return this.runSnapshotAction({ action: "query", ...options });
1441
+ }
1442
+
1406
1443
  async inspectElement(selector, options = {}) {
1407
1444
  return this.runPageAction({
1408
1445
  action: "inspect",
@@ -1503,7 +1540,9 @@ export class CdpSession {
1503
1540
  found: true,
1504
1541
  clicked: true,
1505
1542
  ...(delivery.resent ? { resent: true } : {}),
1506
- ...pointerFields(target, resolved, delivery.node ?? resolved.node),
1543
+ // The element as it was when the click was aimed at it: what it turns
1544
+ // into is in the changes the action reports.
1545
+ ...pointerFields(target, resolved),
1507
1546
  };
1508
1547
  }
1509
1548
 
@@ -2375,6 +2414,7 @@ export class CdpSessionManager {
2375
2414
  constructor(config) {
2376
2415
  this.config = config;
2377
2416
  this.sessions = new Map();
2417
+ this.attachingDialogAnswers = new Map();
2378
2418
  // Sessions that ended while recording a video, kept by id so that stop
2379
2419
  // still encodes their frames, which are on disk.
2380
2420
  this.orphanedVideos = new Map();
@@ -2664,17 +2704,29 @@ export class CdpSessionManager {
2664
2704
  throw new Error(`No page target found for ${targetId}`);
2665
2705
  }
2666
2706
 
2667
- const session = new CdpSession(target, {
2668
- config: this.config,
2669
- eventBufferSize: this.config.eventBufferSize,
2670
- onClosed: (closedSession) => {
2671
- this.sessions.delete(closedSession.id);
2672
- this.orphanVideo(closedSession);
2673
- },
2674
- });
2675
- await session.connect();
2676
- this.sessions.set(session.id, session);
2677
- return session.getSummary();
2707
+ // The tab's sessions share its dialog answers, so whichever session
2708
+ // answers a dialog first answers it as set.
2709
+ const reservation = reserveDialogAnswers(
2710
+ this.sessions,
2711
+ this.attachingDialogAnswers,
2712
+ targetId,
2713
+ );
2714
+ try {
2715
+ const session = new CdpSession(target, {
2716
+ config: this.config,
2717
+ eventBufferSize: this.config.eventBufferSize,
2718
+ dialogAnswers: reservation.answers,
2719
+ onClosed: (closedSession) => {
2720
+ this.sessions.delete(closedSession.id);
2721
+ this.orphanVideo(closedSession);
2722
+ },
2723
+ });
2724
+ await session.connect();
2725
+ this.sessions.set(session.id, session);
2726
+ return session.getSummary();
2727
+ } finally {
2728
+ reservation.release();
2729
+ }
2678
2730
  }
2679
2731
 
2680
2732
  getSession(sessionId) {
@@ -2850,6 +2902,10 @@ export class CdpSessionManager {
2850
2902
  return this.getSession(sessionId).setViewport(options);
2851
2903
  }
2852
2904
 
2905
+ async setDialogAnswers(sessionId, options) {
2906
+ return this.getSession(sessionId).setDialogAnswers(options);
2907
+ }
2908
+
2853
2909
  async takeScreenshot(sessionId, format, options = {}) {
2854
2910
  return this.getSession(sessionId).takeScreenshot(format, options);
2855
2911
  }
@@ -2906,6 +2962,10 @@ export class CdpSessionManager {
2906
2962
  return this.getSession(sessionId).inspectElement(selector, options);
2907
2963
  }
2908
2964
 
2965
+ async queryElements(sessionId, options) {
2966
+ return this.getSession(sessionId).queryElements(options);
2967
+ }
2968
+
2909
2969
  pendingRequests(sessionId) {
2910
2970
  return this.getSession(sessionId).pendingRequests();
2911
2971
  }
@@ -0,0 +1,91 @@
1
+ // How a session answers JavaScript dialogs, which would otherwise block the
2
+ // page. alert and beforeunload are always accepted. confirm is accepted and
3
+ // prompt dismissed unless set_dialog_answers says otherwise; a once answer
4
+ // covers only the next dialog of its type.
5
+ export function createDialogAnswers() {
6
+ return {
7
+ confirm: { accept: true },
8
+ prompt: { accept: false, text: null },
9
+ once: {},
10
+ };
11
+ }
12
+
13
+ function toAnswer(choice, text) {
14
+ return choice === "accept"
15
+ ? { accept: true, text: text ?? null }
16
+ : { accept: false, text: null };
17
+ }
18
+
19
+ export function validateDialogAnswers({ confirm, prompt, promptText }) {
20
+ if (confirm === undefined && prompt === undefined) {
21
+ throw new Error("set_dialog_answers requires confirm or prompt");
22
+ }
23
+ if (promptText !== undefined && prompt !== "accept") {
24
+ throw new Error('set_dialog_answers promptText requires prompt: "accept"');
25
+ }
26
+ }
27
+
28
+ export function setDialogAnswers(answers, options) {
29
+ validateDialogAnswers(options);
30
+ const target = options.once ? answers.once : answers;
31
+ if (options.confirm !== undefined) {
32
+ target.confirm = { accept: options.confirm === "accept" };
33
+ }
34
+ if (options.prompt !== undefined) {
35
+ target.prompt = toAnswer(options.prompt, options.promptText);
36
+ }
37
+ return describeDialogAnswers(answers);
38
+ }
39
+
40
+ function describe({ confirm, prompt }) {
41
+ return {
42
+ ...(confirm ? { confirm: confirm.accept ? "accept" : "dismiss" } : {}),
43
+ ...(prompt ? { prompt: prompt.accept ? "accept" : "dismiss" } : {}),
44
+ ...(prompt?.text != null ? { promptText: prompt.text } : {}),
45
+ };
46
+ }
47
+
48
+ export function describeDialogAnswers(answers) {
49
+ return { ...describe(answers), once: describe(answers.once) };
50
+ }
51
+
52
+ // Dialog answers belong to the tab, so its sessions share one object, also
53
+ // while several of them are still attaching: attaching maps a tab to that
54
+ // object and the number of attaches in progress. Call release once the
55
+ // session is in sessions, or has failed to attach.
56
+ export function reserveDialogAnswers(sessions, attaching, targetId) {
57
+ const entry = attaching.get(targetId);
58
+ const answers =
59
+ [...sessions.values()].find(
60
+ (session) => session.target.targetId === targetId,
61
+ )?.dialogAnswers ??
62
+ entry?.answers ??
63
+ createDialogAnswers();
64
+ attaching.set(targetId, { answers, count: (entry?.count ?? 0) + 1 });
65
+ return {
66
+ answers,
67
+ release() {
68
+ const current = attaching.get(targetId);
69
+ if (current.count > 1) {
70
+ current.count -= 1;
71
+ } else {
72
+ attaching.delete(targetId);
73
+ }
74
+ },
75
+ };
76
+ }
77
+
78
+ // The answer for a dialog of type, using up a once answer for that type. An
79
+ // accepted prompt without promptText keeps the prompt's default value.
80
+ export function answerDialog(answers, type, defaultValue) {
81
+ if (type !== "confirm" && type !== "prompt") {
82
+ return { accept: true };
83
+ }
84
+
85
+ const answer = answers.once[type] ?? answers[type];
86
+ delete answers.once[type];
87
+ if (type === "confirm" || !answer.accept) {
88
+ return { accept: answer.accept };
89
+ }
90
+ return { accept: true, text: answer.text ?? defaultValue ?? "" };
91
+ }