@buoy-gg/mcp 7.0.21 → 7.0.22
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/dist/{chunk-JQ5GZ4LG.mjs → chunk-5C6BLMHY.mjs} +1344 -99
- package/dist/cli.js +1344 -99
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +147 -10
- package/dist/index.d.ts +147 -10
- package/dist/index.js +1344 -99
- package/dist/index.mjs +1 -1
- package/package.json +5 -3
package/dist/cli.js
CHANGED
|
@@ -37,7 +37,12 @@ var import_sync_broker = require("@buoy-gg/sync-broker");
|
|
|
37
37
|
var BROKER_PORT = import_sync_broker.DEFAULT_BROKER_PORT;
|
|
38
38
|
var BROKER_URL = `http://localhost:${BROKER_PORT}`;
|
|
39
39
|
var DEFAULT_ACTION_TIMEOUT_MS = 15e3;
|
|
40
|
+
var UNRESPONSIVE_ACTION_TIMEOUT_MS = 2500;
|
|
41
|
+
var UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS = 1200;
|
|
42
|
+
var RECOVERY_PROBE_MS = 2e4;
|
|
43
|
+
var UNRESPONSIVE_AFTER_MS = 3e4;
|
|
40
44
|
var DEFAULT_SNAPSHOT_TIMEOUT_MS = 5e3;
|
|
45
|
+
var DEVICE_RETENTION_MS = 15 * 6e4;
|
|
41
46
|
var DASHBOARD_NAME = "Dashboard";
|
|
42
47
|
var ALL_DEVICES = "All";
|
|
43
48
|
|
|
@@ -62,6 +67,16 @@ var SyncClient = class {
|
|
|
62
67
|
this.pendingActions = /* @__PURE__ */ new Map();
|
|
63
68
|
/** Callbacks waiting for the next snapshot of `${deviceId}::${toolId}`. */
|
|
64
69
|
this.snapshotWaiters = /* @__PURE__ */ new Map();
|
|
70
|
+
/** When each cached snapshot arrived, keyed by snapKey (staleness reporting). */
|
|
71
|
+
this.snapshotAt = /* @__PURE__ */ new Map();
|
|
72
|
+
/** Liveness per device — see {@link noteTimeout}. */
|
|
73
|
+
this.health = /* @__PURE__ */ new Map();
|
|
74
|
+
/** Dev-server origin per device — see {@link noteDevServerOrigin}. */
|
|
75
|
+
this.devServerOrigins = /* @__PURE__ */ new Map();
|
|
76
|
+
/** Devices whose origin probe already ran (a production bundle has none). */
|
|
77
|
+
this.originProbed = /* @__PURE__ */ new Set();
|
|
78
|
+
/** Last time each device appeared in the broker's device list. */
|
|
79
|
+
this.lastSeen = /* @__PURE__ */ new Map();
|
|
65
80
|
this.port = opts.port ?? BROKER_PORT;
|
|
66
81
|
this.url = opts.url ?? (opts.port ? `http://localhost:${opts.port}` : BROKER_URL);
|
|
67
82
|
this.actionTimeoutMs = opts.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS;
|
|
@@ -121,13 +136,19 @@ var SyncClient = class {
|
|
|
121
136
|
});
|
|
122
137
|
socket.on("devtool-capabilities", (msg) => {
|
|
123
138
|
this.capabilities.set(msg.persistentDeviceId, msg);
|
|
139
|
+
void this.learnDevServerOrigin(msg.persistentDeviceId);
|
|
124
140
|
});
|
|
125
141
|
socket.on("all-devices-update", (list) => {
|
|
126
|
-
if (Array.isArray(list))
|
|
142
|
+
if (!Array.isArray(list)) return;
|
|
143
|
+
this.devices = list;
|
|
144
|
+
const now = Date.now();
|
|
145
|
+
for (const d of list) if (d.deviceId) this.lastSeen.set(d.deviceId, now);
|
|
146
|
+
this.pruneStaleDevices();
|
|
127
147
|
});
|
|
128
148
|
socket.on("devtool-sync", (msg) => {
|
|
129
149
|
const key = snapKey(msg.persistentDeviceId, msg.toolId);
|
|
130
150
|
this.snapshots.set(key, msg.payload);
|
|
151
|
+
this.snapshotAt.set(key, Date.now());
|
|
131
152
|
const waiters = this.snapshotWaiters.get(key);
|
|
132
153
|
if (waiters && waiters.length) {
|
|
133
154
|
this.snapshotWaiters.set(key, []);
|
|
@@ -143,6 +164,37 @@ var SyncClient = class {
|
|
|
143
164
|
});
|
|
144
165
|
});
|
|
145
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* Drop everything remembered about devices that have been gone a while.
|
|
169
|
+
*
|
|
170
|
+
* Deliberately NOT on disconnect: a crashed app often drops off the broker,
|
|
171
|
+
* and its cached console snapshot is the crash evidence — throwing that away
|
|
172
|
+
* the instant it disconnects would delete the answer. But device ids change
|
|
173
|
+
* with every simulator erase and fresh dev client, and each one can hold
|
|
174
|
+
* multi-MB snapshots, so a long-lived server has to forget eventually.
|
|
175
|
+
*/
|
|
176
|
+
pruneStaleDevices() {
|
|
177
|
+
const cutoff = Date.now() - DEVICE_RETENTION_MS;
|
|
178
|
+
for (const [deviceId, seen] of this.lastSeen) {
|
|
179
|
+
if (seen > cutoff) continue;
|
|
180
|
+
if (this.devices.some((d) => d.deviceId === deviceId)) continue;
|
|
181
|
+
this.lastSeen.delete(deviceId);
|
|
182
|
+
this.capabilities.delete(deviceId);
|
|
183
|
+
this.health.delete(deviceId);
|
|
184
|
+
this.devServerOrigins.delete(deviceId);
|
|
185
|
+
this.originProbed.delete(deviceId);
|
|
186
|
+
const prefix = `${deviceId}::`;
|
|
187
|
+
for (const key of [...this.snapshots.keys()]) {
|
|
188
|
+
if (key.startsWith(prefix)) {
|
|
189
|
+
this.snapshots.delete(key);
|
|
190
|
+
this.snapshotAt.delete(key);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
for (const key of [...this.watching.keys()]) {
|
|
194
|
+
if (key.startsWith(prefix)) this.watching.delete(key);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
146
198
|
/** Disconnect and tear down a spawned broker, if any. */
|
|
147
199
|
async stop() {
|
|
148
200
|
for (const [, p] of this.pendingActions) {
|
|
@@ -150,6 +202,8 @@ var SyncClient = class {
|
|
|
150
202
|
p.reject(new Error("SyncClient stopped"));
|
|
151
203
|
}
|
|
152
204
|
this.pendingActions.clear();
|
|
205
|
+
for (const [, waiters] of this.snapshotWaiters) for (const w of waiters) w(void 0);
|
|
206
|
+
this.snapshotWaiters.clear();
|
|
153
207
|
this.socket?.close();
|
|
154
208
|
this.socket = null;
|
|
155
209
|
if (this.broker) {
|
|
@@ -193,11 +247,19 @@ var SyncClient = class {
|
|
|
193
247
|
resolveDevice(deviceId) {
|
|
194
248
|
if (deviceId) return deviceId;
|
|
195
249
|
const connected = this.connectedDevices();
|
|
196
|
-
if (connected.length === 1) return connected[0].deviceId;
|
|
197
250
|
if (connected.length === 0) {
|
|
198
251
|
throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.");
|
|
199
252
|
}
|
|
200
|
-
|
|
253
|
+
if (connected.length === 1) return connected[0].deviceId;
|
|
254
|
+
const usable = connected.filter((d) => d.tools.length > 0);
|
|
255
|
+
if (usable.length === 1) return usable[0].deviceId;
|
|
256
|
+
if (usable.length === 0) {
|
|
257
|
+
const names = connected.map((d) => d.deviceName).join(", ");
|
|
258
|
+
throw new Error(
|
|
259
|
+
`Connected devices (${names}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
const list = usable.map((d) => `${d.deviceName} (${d.deviceId})`).join(", ");
|
|
201
263
|
throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${list}`);
|
|
202
264
|
}
|
|
203
265
|
/**
|
|
@@ -222,6 +284,136 @@ var SyncClient = class {
|
|
|
222
284
|
return target;
|
|
223
285
|
}
|
|
224
286
|
// ----------------------------------------------------------------
|
|
287
|
+
// Device liveness
|
|
288
|
+
// ----------------------------------------------------------------
|
|
289
|
+
healthOf(deviceId) {
|
|
290
|
+
let h = this.health.get(deviceId);
|
|
291
|
+
if (!h) {
|
|
292
|
+
h = { consecutiveTimeouts: 0, lastOkAt: 0, lastFullBudgetAt: 0 };
|
|
293
|
+
this.health.set(deviceId, h);
|
|
294
|
+
}
|
|
295
|
+
return h;
|
|
296
|
+
}
|
|
297
|
+
/** The device answered — it's alive. */
|
|
298
|
+
noteOk(deviceId) {
|
|
299
|
+
const h = this.healthOf(deviceId);
|
|
300
|
+
h.consecutiveTimeouts = 0;
|
|
301
|
+
h.lastOkAt = Date.now();
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* The device didn't answer. A crashed app never answers again, so after the
|
|
305
|
+
* first miss we stop paying the full timeout on every subsequent call.
|
|
306
|
+
*/
|
|
307
|
+
noteTimeout(deviceId) {
|
|
308
|
+
this.healthOf(deviceId).consecutiveTimeouts += 1;
|
|
309
|
+
}
|
|
310
|
+
/** True once a device has missed a call and hasn't answered since. */
|
|
311
|
+
isUnresponsive(deviceId) {
|
|
312
|
+
return this.healthOf(deviceId).consecutiveTimeouts > 0;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Full timeout normally; a short one for a device already not answering.
|
|
316
|
+
*
|
|
317
|
+
* With one escape hatch: every RECOVERY_PROBE_MS a flagged device gets the
|
|
318
|
+
* full budget again. Without it the flag is self-sustaining — a device whose
|
|
319
|
+
* work legitimately takes longer than the short budget (a big snapshot, a
|
|
320
|
+
* slow simulator) can never answer, so it can never clear the flag, and every
|
|
321
|
+
* later reply is a confident "most likely CRASHED" about a healthy app.
|
|
322
|
+
*/
|
|
323
|
+
timeoutFor(deviceId) {
|
|
324
|
+
if (!this.isUnresponsive(deviceId)) return this.actionTimeoutMs;
|
|
325
|
+
const h = this.healthOf(deviceId);
|
|
326
|
+
if (Date.now() - h.lastFullBudgetAt > RECOVERY_PROBE_MS) {
|
|
327
|
+
h.lastFullBudgetAt = Date.now();
|
|
328
|
+
return this.actionTimeoutMs;
|
|
329
|
+
}
|
|
330
|
+
return UNRESPONSIVE_ACTION_TIMEOUT_MS;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Plain-language diagnosis for a device that isn't answering, including the
|
|
334
|
+
* app's last words if the console tool got a crash flush out in time.
|
|
335
|
+
*
|
|
336
|
+
* A silent timeout is the worst possible answer here: the app is on a redbox,
|
|
337
|
+
* the reason is already captured, and without this the caller reads "timed
|
|
338
|
+
* out" and keeps retrying the same dead device.
|
|
339
|
+
*/
|
|
340
|
+
unresponsiveNote(deviceId) {
|
|
341
|
+
const h = this.healthOf(deviceId);
|
|
342
|
+
const since = h.lastOkAt ? Math.round((Date.now() - h.lastOkAt) / 1e3) : null;
|
|
343
|
+
const crashed = h.consecutiveTimeouts >= 2 || h.lastOkAt === 0 || Date.now() - h.lastOkAt > UNRESPONSIVE_AFTER_MS;
|
|
344
|
+
const lines = [
|
|
345
|
+
`The app on "${deviceId}" is not responding (${h.consecutiveTimeouts} call${h.consecutiveTimeouts === 1 ? "" : "s"} unanswered${since != null ? `, last answered ${since}s ago` : ""}).`,
|
|
346
|
+
crashed ? "It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded." : "It may be busy, mid-reload, or crashing."
|
|
347
|
+
];
|
|
348
|
+
const fatal = this.lastFatalFor(deviceId);
|
|
349
|
+
if (fatal) lines.push(`Last captured error: ${fatal}`);
|
|
350
|
+
lines.push(
|
|
351
|
+
fatal ? "Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover." : "Try get_console (served from the last sync) for the app's last words, then reload_app to recover."
|
|
352
|
+
);
|
|
353
|
+
return lines.join(" ");
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* The newest error line the console tool synced for this device, if any.
|
|
357
|
+
* Reads the cached console snapshot rather than the device (which, by the
|
|
358
|
+
* time this matters, is not answering).
|
|
359
|
+
*/
|
|
360
|
+
lastFatalFor(deviceId) {
|
|
361
|
+
const snap = this.snapshots.get(snapKey(deviceId, "console"));
|
|
362
|
+
const entries = snap?.entries;
|
|
363
|
+
if (!Array.isArray(entries)) return null;
|
|
364
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
365
|
+
const e = entries[i];
|
|
366
|
+
if (e?.fatal || e?.level === "error") {
|
|
367
|
+
const msg = (e.message ?? "").split("\n")[0];
|
|
368
|
+
if (msg) return msg.length > 300 ? `${msg.slice(0, 300)}\u2026` : msg;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
/** Age of the cached snapshot for a tool, in ms (null = never received). */
|
|
374
|
+
snapshotAgeMs(toolId, deviceId) {
|
|
375
|
+
const at = this.snapshotAt.get(snapKey(deviceId, toolId));
|
|
376
|
+
return at ? Date.now() - at : null;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Remember where a device's bundle came from, reported by core's `app`
|
|
380
|
+
* adapter while the app is healthy. It is the only way to reload an app that
|
|
381
|
+
* has crashed: the in-app reload needs the React tree that the crash
|
|
382
|
+
* destroyed, but the dev server's reload is handled natively.
|
|
383
|
+
*/
|
|
384
|
+
noteDevServerOrigin(deviceId, origin) {
|
|
385
|
+
if (typeof origin === "string" && /^https?:\/\//.test(origin)) {
|
|
386
|
+
this.devServerOrigins.set(deviceId, origin);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Ask a freshly-announced device where its bundle came from, once.
|
|
391
|
+
*
|
|
392
|
+
* Deliberately eager: this is the piece of information that can ONLY be
|
|
393
|
+
* collected while the app is healthy, and is only ever needed after it has
|
|
394
|
+
* stopped answering. One cheap round-trip per device buys the ability to
|
|
395
|
+
* recover a crashed app instead of telling the caller to go do it by hand.
|
|
396
|
+
*/
|
|
397
|
+
async learnDevServerOrigin(deviceId) {
|
|
398
|
+
if (this.devServerOrigins.has(deviceId) || this.originProbed.has(deviceId)) return;
|
|
399
|
+
this.originProbed.add(deviceId);
|
|
400
|
+
const hasApp = this.capabilities.get(deviceId)?.tools?.some((t) => t.toolId === "app");
|
|
401
|
+
if (!hasApp) return;
|
|
402
|
+
try {
|
|
403
|
+
const { payload } = await this.getSnapshot("app", deviceId, { timeoutMs: 4e3, silent: true });
|
|
404
|
+
this.noteDevServerOrigin(deviceId, payload?.devServerOrigin);
|
|
405
|
+
} catch {
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/** The dev-server origin last reported by this device, if any. */
|
|
409
|
+
devServerOrigin(deviceId) {
|
|
410
|
+
const known = this.devServerOrigins.get(deviceId);
|
|
411
|
+
if (known) return known;
|
|
412
|
+
const snap = this.snapshots.get(snapKey(deviceId, "app"));
|
|
413
|
+
if (typeof snap?.devServerOrigin === "string") return snap.devServerOrigin;
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
// ----------------------------------------------------------------
|
|
225
417
|
// Watch + snapshots
|
|
226
418
|
// ----------------------------------------------------------------
|
|
227
419
|
/**
|
|
@@ -292,13 +484,36 @@ var SyncClient = class {
|
|
|
292
484
|
const target = this.resolveDevice(deviceId);
|
|
293
485
|
const key = snapKey(target, toolId);
|
|
294
486
|
this.ensureWatching(toolId, target);
|
|
295
|
-
|
|
487
|
+
let budget = opts.timeoutMs ?? DEFAULT_SNAPSHOT_TIMEOUT_MS;
|
|
488
|
+
if (opts.timeoutMs === void 0 && this.isUnresponsive(target)) {
|
|
489
|
+
const h = this.healthOf(target);
|
|
490
|
+
if (Date.now() - h.lastFullBudgetAt > RECOVERY_PROBE_MS) {
|
|
491
|
+
h.lastFullBudgetAt = Date.now();
|
|
492
|
+
} else {
|
|
493
|
+
budget = UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const next = this.waitForSnapshot(key, budget);
|
|
296
497
|
this.socket?.emit("request-devtool-state", { toolId, targetDeviceId: target });
|
|
297
498
|
const payload = await next;
|
|
298
|
-
if (payload !== void 0)
|
|
499
|
+
if (payload !== void 0) {
|
|
500
|
+
if (!opts.silent) this.noteOk(target);
|
|
501
|
+
return { deviceId: target, payload };
|
|
502
|
+
}
|
|
503
|
+
if (!opts.silent) this.noteTimeout(target);
|
|
299
504
|
const cached = this.snapshots.get(key);
|
|
300
|
-
if (cached !== void 0)
|
|
301
|
-
|
|
505
|
+
if (cached !== void 0) {
|
|
506
|
+
return { deviceId: target, payload: cached, stale: this.staleNote(toolId, target) };
|
|
507
|
+
}
|
|
508
|
+
throw new Error(
|
|
509
|
+
`Timed out waiting for "${toolId}" state from ${target} (is the tool active?). ${this.unresponsiveNote(target)}`
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
/** Header line for data served from cache because the device went quiet. */
|
|
513
|
+
staleNote(toolId, deviceId) {
|
|
514
|
+
const age = this.snapshotAgeMs(toolId, deviceId);
|
|
515
|
+
const ageText = age == null ? "an earlier sync" : `${Math.round(age / 1e3)}s ago`;
|
|
516
|
+
return `\u26A0\uFE0F Served from the last sync (${ageText}) \u2014 ${this.unresponsiveNote(deviceId)}`;
|
|
302
517
|
}
|
|
303
518
|
waitForSnapshot(key, timeoutMs) {
|
|
304
519
|
return new Promise((resolve) => {
|
|
@@ -327,11 +542,16 @@ var SyncClient = class {
|
|
|
327
542
|
const target = deviceId === ALL_DEVICES ? ALL_DEVICES : this.resolveDevice(deviceId);
|
|
328
543
|
if (!this.socket) throw new Error("SyncClient is not connected");
|
|
329
544
|
const requestId = (0, import_node_crypto.randomUUID)();
|
|
330
|
-
const timeoutMs = opts.timeoutMs ?? this.
|
|
545
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutFor(target);
|
|
331
546
|
const result = await new Promise((resolve, reject) => {
|
|
332
547
|
const timer = setTimeout(() => {
|
|
333
548
|
this.pendingActions.delete(requestId);
|
|
334
|
-
|
|
549
|
+
if (target !== ALL_DEVICES && !opts.silent) this.noteTimeout(target);
|
|
550
|
+
reject(
|
|
551
|
+
new Error(
|
|
552
|
+
`Action "${toolId}.${action}" got no answer in ${timeoutMs}ms. ` + (target === ALL_DEVICES ? "No device responded." : this.unresponsiveNote(target))
|
|
553
|
+
)
|
|
554
|
+
);
|
|
335
555
|
}, timeoutMs);
|
|
336
556
|
this.pendingActions.set(requestId, { resolve, reject, timer });
|
|
337
557
|
this.socket.emit("devtool-action", {
|
|
@@ -342,6 +562,7 @@ var SyncClient = class {
|
|
|
342
562
|
params: params ?? {}
|
|
343
563
|
});
|
|
344
564
|
});
|
|
565
|
+
if (target !== ALL_DEVICES && !opts.silent) this.noteOk(target);
|
|
345
566
|
if (!result.ok) {
|
|
346
567
|
throw new Error(result.error || `Action "${toolId}.${action}" failed on device`);
|
|
347
568
|
}
|
|
@@ -373,7 +594,7 @@ var delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
373
594
|
|
|
374
595
|
// src/server.ts
|
|
375
596
|
var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
376
|
-
var
|
|
597
|
+
var import_zod22 = require("zod");
|
|
377
598
|
|
|
378
599
|
// src/tools/generic.ts
|
|
379
600
|
var import_zod = require("zod");
|
|
@@ -384,7 +605,7 @@ var import_node_os = __toESM(require("os"));
|
|
|
384
605
|
var import_node_path = __toESM(require("path"));
|
|
385
606
|
|
|
386
607
|
// src/version.ts
|
|
387
|
-
var VERSION = "7.0.
|
|
608
|
+
var VERSION = "7.0.22" ? "7.0.22" : "0.0.0-dev";
|
|
388
609
|
var PACKAGE_NAME = "@buoy-gg/mcp";
|
|
389
610
|
|
|
390
611
|
// src/update/checkForUpdate.ts
|
|
@@ -691,6 +912,7 @@ function rankBatchFromIndex(index, batchId, casesOrder, failures = []) {
|
|
|
691
912
|
deltaUiFps: null,
|
|
692
913
|
deltaJsFps: null,
|
|
693
914
|
renderCommits: num(median?.renderCommits),
|
|
915
|
+
renderWasted: median?.renderWasted,
|
|
694
916
|
topRenderers: median?.topRenderers ?? []
|
|
695
917
|
};
|
|
696
918
|
return { ...base, flags: failed ? [] : computeFlags(base) };
|
|
@@ -781,13 +1003,18 @@ function formatRankingMarkdown(ranking) {
|
|
|
781
1003
|
);
|
|
782
1004
|
}
|
|
783
1005
|
const renderLines = ranking.rows.filter((r) => !r.failed && (r.renderCommits != null || r.topRenderers.length > 0)).map((r) => {
|
|
784
|
-
const top = r.topRenderers.map(
|
|
1006
|
+
const top = r.topRenderers.map(
|
|
1007
|
+
(t) => `${t.name} \xD7${t.renders} (${t.totalMs}ms${t.cause ? `, ${t.cause}` : ""})`
|
|
1008
|
+
).join(", ");
|
|
785
1009
|
const commits = r.renderCommits != null ? `${r.renderCommits} commits` : "";
|
|
786
|
-
|
|
1010
|
+
const wasted = r.renderWasted != null ? `${r.renderWasted} wasted` : "";
|
|
1011
|
+
return `- **${r.caseName}** \u2014 ${[commits, wasted, top].filter(Boolean).join(": ")}`;
|
|
787
1012
|
});
|
|
788
1013
|
if (renderLines.length) {
|
|
789
1014
|
lines.push("");
|
|
790
|
-
lines.push(
|
|
1015
|
+
lines.push(
|
|
1016
|
+
"**Renders (median run)** \u2014 `wasted` = parent cascades + identity-only prop churn (removable). Cause per component: `propsUnstable` means a parent handed it a fresh function/object with unchanged values \u2014 fix upstream."
|
|
1017
|
+
);
|
|
791
1018
|
lines.push(...renderLines);
|
|
792
1019
|
}
|
|
793
1020
|
lines.push("");
|
|
@@ -810,7 +1037,20 @@ function compareReportStats(a, b) {
|
|
|
810
1037
|
cpuUsage: ch(a.stats.cpuUsage, b.stats.cpuUsage),
|
|
811
1038
|
memoryUsage: ch(a.stats.memoryUsage, b.stats.memoryUsage),
|
|
812
1039
|
jsJankFrames: { a: a.stats.jsJankFrames, b: b.stats.jsJankFrames, delta: b.stats.jsJankFrames - a.stats.jsJankFrames },
|
|
813
|
-
uiJankFrames: { a: a.stats.uiJankFrames, b: b.stats.uiJankFrames, delta: b.stats.uiJankFrames - a.stats.uiJankFrames }
|
|
1040
|
+
uiJankFrames: { a: a.stats.uiJankFrames, b: b.stats.uiJankFrames, delta: b.stats.uiJankFrames - a.stats.uiJankFrames },
|
|
1041
|
+
...compareRenders(a.renders, b.renders)
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function compareRenders(a, b) {
|
|
1045
|
+
if (!a && !b) return null;
|
|
1046
|
+
const n = (v) => v ?? 0;
|
|
1047
|
+
return {
|
|
1048
|
+
renders: {
|
|
1049
|
+
total: { a: n(a?.totalRenders), b: n(b?.totalRenders), delta: n(b?.totalRenders) - n(a?.totalRenders) },
|
|
1050
|
+
commits: { a: n(a?.totalCommits), b: n(b?.totalCommits), delta: n(b?.totalCommits) - n(a?.totalCommits) },
|
|
1051
|
+
wasted: { a: n(a?.wastedRenders), b: n(b?.wastedRenders), delta: n(b?.wastedRenders) - n(a?.wastedRenders) },
|
|
1052
|
+
causes: { a: a?.causes ?? {}, b: b?.causes ?? {} }
|
|
1053
|
+
}
|
|
814
1054
|
};
|
|
815
1055
|
}
|
|
816
1056
|
function round(n, d) {
|
|
@@ -1060,7 +1300,7 @@ ${JSON.stringify(summary, null, 2)}
|
|
|
1060
1300
|
async ({ deviceId, maxWaitMs }) => {
|
|
1061
1301
|
const log = (m) => process.stderr.write(`[buoy-mcp] ${m}
|
|
1062
1302
|
`);
|
|
1063
|
-
const
|
|
1303
|
+
const cap3 = maxWaitMs ?? 6e5;
|
|
1064
1304
|
try {
|
|
1065
1305
|
const target = sync.requireProDevice(deviceId);
|
|
1066
1306
|
const start = Date.now();
|
|
@@ -1068,7 +1308,7 @@ ${JSON.stringify(summary, null, 2)}
|
|
|
1068
1308
|
let idleStreak = 0;
|
|
1069
1309
|
let lastCount = -1;
|
|
1070
1310
|
let resolved = null;
|
|
1071
|
-
while (Date.now() - start <
|
|
1311
|
+
while (Date.now() - start < cap3) {
|
|
1072
1312
|
let snap2;
|
|
1073
1313
|
try {
|
|
1074
1314
|
snap2 = await readPerfSnapshot(sync, target);
|
|
@@ -1153,7 +1393,7 @@ ${JSON.stringify(ranking, null, 2)}
|
|
|
1153
1393
|
server.registerTool(
|
|
1154
1394
|
"compare_reports",
|
|
1155
1395
|
{
|
|
1156
|
-
description: "Compare two saved benchmark runs head-to-head
|
|
1396
|
+
description: "Compare two saved benchmark runs head-to-head: avg + p95 for FPS/CPU/memory, jank, AND render counts \u2014 total, commits, and wasted (parent cascades + identity-only prop churn) \u2014 each with deltas. Use this to prove a memoization or re-render fix actually landed: the wasted-render delta is the number that says so.",
|
|
1157
1397
|
inputSchema: {
|
|
1158
1398
|
reportIdA: import_zod2.z.string().describe("First (baseline) report id."),
|
|
1159
1399
|
reportIdB: import_zod2.z.string().describe("Second report id to compare against the baseline."),
|
|
@@ -1171,8 +1411,8 @@ ${JSON.stringify(ranking, null, 2)}
|
|
|
1171
1411
|
if (!b) return fail2(`Report "${reportIdB}" not found.`);
|
|
1172
1412
|
return json2(
|
|
1173
1413
|
compareReportStats(
|
|
1174
|
-
{ name: a.metadata.name, stats: a.stats },
|
|
1175
|
-
{ name: b.metadata.name, stats: b.stats }
|
|
1414
|
+
{ name: a.metadata.name, stats: a.stats, renders: a.renders },
|
|
1415
|
+
{ name: b.metadata.name, stats: b.stats, renders: b.renders }
|
|
1176
1416
|
)
|
|
1177
1417
|
);
|
|
1178
1418
|
} catch (e) {
|
|
@@ -2185,13 +2425,13 @@ function registerStorageTools(server, sync) {
|
|
|
2185
2425
|
const target = sync.requireProDevice(args.deviceId);
|
|
2186
2426
|
const pattern = args.pattern?.toLowerCase();
|
|
2187
2427
|
const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 100;
|
|
2188
|
-
const
|
|
2428
|
+
const matches2 = (k) => !pattern || k.toLowerCase().includes(pattern);
|
|
2189
2429
|
const sections = [];
|
|
2190
2430
|
const allKeys = await sync.callAction(STORAGE_TOOL_ID, "async.getAllKeys", {}, target);
|
|
2191
2431
|
if (!Array.isArray(allKeys)) {
|
|
2192
2432
|
return fail9("No storage result from the device. The storage tool may be inactive.");
|
|
2193
2433
|
}
|
|
2194
|
-
const asyncKeys = allKeys.filter(
|
|
2434
|
+
const asyncKeys = allKeys.filter(matches2).slice(0, limit);
|
|
2195
2435
|
if (asyncKeys.length > 0) {
|
|
2196
2436
|
let lines;
|
|
2197
2437
|
if (args.includeValues) {
|
|
@@ -2206,7 +2446,7 @@ ${lines.join("\n")}`);
|
|
|
2206
2446
|
}
|
|
2207
2447
|
const mmkv = await sync.callAction(STORAGE_TOOL_ID, "mmkv.snapshot", {}, target).catch(() => null);
|
|
2208
2448
|
for (const inst of mmkv ?? []) {
|
|
2209
|
-
const entries = inst.entries.filter((e) =>
|
|
2449
|
+
const entries = inst.entries.filter((e) => matches2(e.key)).slice(0, limit);
|
|
2210
2450
|
if (entries.length === 0) continue;
|
|
2211
2451
|
const lines = entries.map(
|
|
2212
2452
|
(e) => args.includeValues ? `- \`${e.key}\` (${e.valueType}) = ${truncate2(e.value)}` : `- \`${e.key}\``
|
|
@@ -2216,7 +2456,7 @@ ${lines.join("\n")}`);
|
|
|
2216
2456
|
${lines.join("\n")}`);
|
|
2217
2457
|
}
|
|
2218
2458
|
const secure = await sync.callAction(STORAGE_TOOL_ID, "secure.keys", {}, target).catch(() => null);
|
|
2219
|
-
const secureKeys = (secure ?? []).filter((d) =>
|
|
2459
|
+
const secureKeys = (secure ?? []).filter((d) => matches2(d.key)).slice(0, limit);
|
|
2220
2460
|
if (secureKeys.length > 0) {
|
|
2221
2461
|
const lines = await Promise.all(
|
|
2222
2462
|
secureKeys.map(async (d) => {
|
|
@@ -2384,7 +2624,10 @@ function registerConsoleTools(server, sync) {
|
|
|
2384
2624
|
async (args) => {
|
|
2385
2625
|
try {
|
|
2386
2626
|
const target = sync.requireProDevice(args.deviceId);
|
|
2387
|
-
const { payload } = await sync.getSnapshot(CONSOLE_TOOL_ID, target);
|
|
2627
|
+
const { payload, stale } = await sync.getSnapshot(CONSOLE_TOOL_ID, target);
|
|
2628
|
+
const staleHeader = stale ? `${stale}
|
|
2629
|
+
|
|
2630
|
+
` : "";
|
|
2388
2631
|
const p = Array.isArray(payload) ? { entries: payload } : payload ?? {};
|
|
2389
2632
|
const all = Array.isArray(p.entries) ? p.entries : [];
|
|
2390
2633
|
const minSev = args.level ? SEVERITY[args.level] : 0;
|
|
@@ -2396,12 +2639,12 @@ function registerConsoleTools(server, sync) {
|
|
|
2396
2639
|
const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 50;
|
|
2397
2640
|
const shown = sorted.slice(-limit);
|
|
2398
2641
|
if (shown.length === 0) {
|
|
2399
|
-
return text10(
|
|
2642
|
+
return text10(`${staleHeader}No console entries${args.level ? ` at level \u2265 ${args.level}` : ""}${pattern ? ` matching "${args.pattern}"` : ""} (${all.length} total captured).`);
|
|
2400
2643
|
}
|
|
2401
2644
|
const lines = shown.map((e) => `${hhmmss(e.timestamp)} [${TAG[e.level] ?? e.level}] ${e.message}`);
|
|
2402
2645
|
const levelNote = args.level ? `, level \u2265 ${args.level}` : "";
|
|
2403
2646
|
const header = `**Console \u2014 ${all.length} entries (showing ${shown.length}${levelNote}):**`;
|
|
2404
|
-
return text10(`${header}
|
|
2647
|
+
return text10(`${staleHeader}${header}
|
|
2405
2648
|
|
|
2406
2649
|
\`\`\`
|
|
2407
2650
|
${lines.join("\n")}
|
|
@@ -2425,13 +2668,19 @@ function kb(bytes) {
|
|
|
2425
2668
|
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
|
2426
2669
|
}
|
|
2427
2670
|
function formatOutcome(outcome) {
|
|
2428
|
-
const lines = Object.entries(outcome.results).map(([sid,
|
|
2429
|
-
const skips =
|
|
2671
|
+
const lines = Object.entries(outcome.results).map(([sid, r2]) => {
|
|
2672
|
+
const skips = r2.skipped.slice(0, 3).map((s) => `
|
|
2430
2673
|
\xB7 ${s.id}: ${s.reason}`).join("");
|
|
2431
|
-
const warns =
|
|
2674
|
+
const warns = r2.warnings.slice(0, 3).map((w) => `
|
|
2432
2675
|
\u26A0 ${w}`).join("");
|
|
2433
|
-
return ` ${
|
|
2676
|
+
return ` ${r2.ok ? "\u2713" : "\u2715"} ${sid} \u2014 applied ${r2.applied}${r2.skipped.length ? `, skipped ${r2.skipped.length}` : ""}${skips}${warns}`;
|
|
2434
2677
|
});
|
|
2678
|
+
const r = outcome.route;
|
|
2679
|
+
if (r) {
|
|
2680
|
+
lines.push(
|
|
2681
|
+
r.status === "navigated" ? ` \u2713 route \u2014 navigated to ${r.href}` : r.status === "deferred" ? ` \u21BB route \u2014 ${r.href} will be opened after the reload` : ` \u2715 route \u2014 ${r.error ?? r.status}`
|
|
2682
|
+
);
|
|
2683
|
+
}
|
|
2435
2684
|
return `Restored "${outcome.snapshotName}" (${outcome.mode}${outcome.willReload ? ", app reloading" : ""}):
|
|
2436
2685
|
${lines.join("\n")}`;
|
|
2437
2686
|
}
|
|
@@ -2439,7 +2688,7 @@ function registerTimeMachineTools(server, sync) {
|
|
|
2439
2688
|
server.registerTool(
|
|
2440
2689
|
"get_time_machine",
|
|
2441
2690
|
{
|
|
2442
|
-
description: "List the app's Time Machine state snapshots (restore points) and which state sources (storage/redux/zustand/jotai/react-query) can currently be captured/restored. Use time_machine_action to capture a snapshot before driving a flow, then restore it to re-run the flow from the same state.",
|
|
2691
|
+
description: "List the app's Time Machine state snapshots (restore points) and which state sources (storage/redux/zustand/jotai/react-query) can currently be captured/restored. Each snapshot also records the route it was captured on (shown as `route`), which a restore can navigate back to. Use time_machine_action to capture a snapshot before driving a flow, then restore it to re-run the flow from the same state.",
|
|
2443
2692
|
inputSchema: {
|
|
2444
2693
|
deviceId: import_zod12.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
2445
2694
|
}
|
|
@@ -2452,13 +2701,19 @@ function registerTimeMachineTools(server, sync) {
|
|
|
2452
2701
|
const snapshots = p.snapshots ?? [];
|
|
2453
2702
|
const providers = p.providers ?? [];
|
|
2454
2703
|
const providerLines = providers.map((pr) => {
|
|
2455
|
-
const
|
|
2456
|
-
return `- ${pr.label} (${pr.id}): ${
|
|
2704
|
+
const cap3 = pr.canCapture ? pr.canRestore ? "capture+restore" : "capture only" : "unavailable";
|
|
2705
|
+
return `- ${pr.label} (${pr.id}): ${cap3}${pr.detail ? ` \u2014 ${pr.detail}` : ""}`;
|
|
2457
2706
|
});
|
|
2707
|
+
if (p.route) {
|
|
2708
|
+
providerLines.push(
|
|
2709
|
+
p.route.available ? `- Route (route): capture+restore \u2014 recorded with every snapshot; pass restoreRoute:true to return to it${p.route.current ? ` (now ${p.route.current})` : ""}` : "- Route (route): unavailable \u2014 no Expo Router on this device, snapshots record no route"
|
|
2710
|
+
);
|
|
2711
|
+
}
|
|
2458
2712
|
const snapLines = snapshots.map((s) => {
|
|
2459
2713
|
const warnings = Object.values(s.sources).reduce((n, src) => n + src.warnings.length, 0);
|
|
2460
2714
|
const desc = s.baseline ? "baseline \u2014 restore wipes to fresh install (always reloads)" : `${kb(s.sizeBytes)} \xB7 ${Object.keys(s.sources).join(", ")}`;
|
|
2461
|
-
|
|
2715
|
+
const route = s.route ? ` \xB7 route ${s.route.href}` : "";
|
|
2716
|
+
return `- \`${s.id}\` **${s.name}** \u2014 ${new Date(s.createdAt).toISOString()} \xB7 ${desc}${route}${warnings ? ` \xB7 \u26A0 ${warnings}` : ""}`;
|
|
2462
2717
|
});
|
|
2463
2718
|
const parts = [
|
|
2464
2719
|
`**Time Machine \u2014 ${snapshots.length} snapshot(s):**`,
|
|
@@ -2477,13 +2732,14 @@ ${formatOutcome(p.lastOutcome)}`);
|
|
|
2477
2732
|
server.registerTool(
|
|
2478
2733
|
"time_machine_action",
|
|
2479
2734
|
{
|
|
2480
|
-
description: "Manage Time Machine state snapshots: capture the app's current state as a named restore point, preview what restoring one would change (per-item added/removed/changed/won't-apply verdicts \u2014 check the blast radius BEFORE restoring), restore one (mode 'live' replaces state in place; 'reload' restores persisted storage then reloads the JS bundle \u2014 baselines always reload), capture_baseline (an empty wipe-to-fresh-install restore point), delete, or rename. The restore result reports per-source applied/skipped counts \u2014 check them rather than assuming success.",
|
|
2735
|
+
description: "Manage Time Machine state snapshots: capture the app's current state as a named restore point, preview what restoring one would change (per-item added/removed/changed/won't-apply verdicts \u2014 check the blast radius BEFORE restoring), restore one (mode 'live' replaces state in place; 'reload' restores persisted storage then reloads the JS bundle \u2014 baselines always reload; pass restoreRoute:true to also return to the screen the snapshot was captured on), capture_baseline (an empty wipe-to-fresh-install restore point), delete, or rename. The restore result reports per-source applied/skipped counts \u2014 check them rather than assuming success.",
|
|
2481
2736
|
inputSchema: {
|
|
2482
2737
|
action: import_zod12.z.enum(["capture", "capture_baseline", "preview", "restore", "delete", "rename"]).describe("What to do."),
|
|
2483
2738
|
id: import_zod12.z.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),
|
|
2484
2739
|
name: import_zod12.z.string().optional().describe("Snapshot name (for capture and rename)."),
|
|
2485
2740
|
mode: import_zod12.z.enum(["live", "reload"]).optional().describe("Restore mode. Default 'live'."),
|
|
2486
2741
|
excludeKeys: import_zod12.z.array(import_zod12.z.string()).optional().describe('Restore only: item keys to LEAVE UNTOUCHED, as "sourceId::itemKey" (itemKey = the key shown by the preview action, e.g. "query::[\\"pokemon\\"]" or "storage::async:@cart").'),
|
|
2742
|
+
restoreRoute: import_zod12.z.boolean().optional().describe("Restore only: also navigate back to the route the snapshot was captured on (shown as `route` by get_time_machine). With mode 'reload' the navigation happens automatically on the next boot. Default false \u2014 state is restored but the app stays on the current screen."),
|
|
2487
2743
|
sourceIds: import_zod12.z.array(import_zod12.z.string()).optional().describe("Capture/restore only these source ids (default all)."),
|
|
2488
2744
|
deviceId: import_zod12.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
2489
2745
|
}
|
|
@@ -2532,7 +2788,8 @@ ${lines.join("\n")}`);
|
|
|
2532
2788
|
const outcome = await call("restore", {
|
|
2533
2789
|
id: args.id,
|
|
2534
2790
|
mode: args.mode ?? "live",
|
|
2535
|
-
excludeKeys: args.excludeKeys
|
|
2791
|
+
excludeKeys: args.excludeKeys,
|
|
2792
|
+
restoreRoute: args.restoreRoute
|
|
2536
2793
|
});
|
|
2537
2794
|
return text11(formatOutcome(outcome));
|
|
2538
2795
|
}
|
|
@@ -2750,11 +3007,14 @@ function formatElement(e) {
|
|
|
2750
3007
|
if (e.nativeTag != null) line += ` #${e.nativeTag}`;
|
|
2751
3008
|
return line;
|
|
2752
3009
|
}
|
|
3010
|
+
var tapCount = 0;
|
|
3011
|
+
var FLOW_TIP_EVERY = 3;
|
|
3012
|
+
var FLOW_TIP = "\n\nTip: driving several steps? `run_flow` does a whole tap/type/wait/assert sequence in ONE call and reports the final screen plus the network and console output it produced.";
|
|
2753
3013
|
function registerInteractTools(server, sync) {
|
|
2754
3014
|
server.registerTool(
|
|
2755
3015
|
"describe_screen",
|
|
2756
3016
|
{
|
|
2757
|
-
description: "List the interactive / labeled elements currently on screen \u2014 the app's live accessibility-style tree walked from the React fiber tree. Each row shows the component name, visible text/label, role, testID, a normalized tap point (tap: x,y in 0\u20131), and its #nativeTag. Rows marked with \u2022 are tappable (have an onPress). Use this to see what's on screen and pick something to tap with tap_element \u2014 no screenshot needed. Re-run after navigating or when the screen changes, since positions move. Requires Buoy Pro.",
|
|
3017
|
+
description: "List the interactive / labeled elements currently on screen \u2014 the app's live accessibility-style tree walked from the React fiber tree. Each row shows the component name, visible text/label, role, testID, a normalized tap point (tap: x,y in 0\u20131), and its #nativeTag. Rows marked with \u2022 are tappable (have an onPress). Use this to see what's on screen and pick something to tap with tap_element \u2014 no screenshot needed. If you already know the sequence you want to drive, `run_flow` does the whole thing (taps, waits, assertions) in one call instead. Re-run after navigating or when the screen changes, since positions move. Requires Buoy Pro.",
|
|
2758
3018
|
inputSchema: {
|
|
2759
3019
|
interactiveOnly: import_zod14.z.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),
|
|
2760
3020
|
deviceId: import_zod14.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
@@ -2783,7 +3043,7 @@ ${elements.map(formatElement).join("\n")}`);
|
|
|
2783
3043
|
server.registerTool(
|
|
2784
3044
|
"tap_element",
|
|
2785
3045
|
{
|
|
2786
|
-
description: "Interact with an on-screen element by invoking its handler directly in JS (no screenshot, no coordinate math, works on real devices). Handles buttons (onPress + onLongPress), toggles/switches and sliders (onValueChange), and text inputs (onChangeText) \u2014 see each element's `control` in describe_screen. Identify the target with an exact `nativeTag` or `testID`, or a fuzzy `query`. Pass `longPress:true` to invoke onLongPress instead of onPress (elements that support it show {long-press} in describe_screen). For a toggle, pass `value:true/false` (omit to flip); for a slider, pass a numeric `value` (omit to jump to the far end); for a text input, pass `text`. If the element is off-screen it's scrolled into view first (scrollIntoView:false to skip). Call describe_screen first to see options + current values. Requires Buoy Pro.",
|
|
3046
|
+
description: "Interact with an on-screen element by invoking its handler directly in JS (no screenshot, no coordinate math, works on real devices). Handles buttons (onPress + onLongPress), toggles/switches and sliders (onValueChange), and text inputs (onChangeText) \u2014 see each element's `control` in describe_screen. Identify the target with an exact `nativeTag` or `testID`, or a fuzzy `query`. Pass `longPress:true` to invoke onLongPress instead of onPress (elements that support it show {long-press} in describe_screen). For a toggle, pass `value:true/false` (omit to flip); for a slider, pass a numeric `value` (omit to jump to the far end); for a text input, pass `text`. If the element is off-screen it's scrolled into view first (scrollIntoView:false to skip). Call describe_screen first to see options + current values. Driving MORE THAN ONE step (reproducing a bug, verifying a fix)? Use `run_flow` instead \u2014 it runs the whole sequence in one call. Requires Buoy Pro.",
|
|
2787
3047
|
inputSchema: {
|
|
2788
3048
|
nativeTag: import_zod14.z.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),
|
|
2789
3049
|
testID: import_zod14.z.string().optional().describe("Exact testID of the element."),
|
|
@@ -2815,13 +3075,15 @@ ${elements.map(formatElement).join("\n")}`);
|
|
|
2815
3075
|
},
|
|
2816
3076
|
target
|
|
2817
3077
|
);
|
|
3078
|
+
tapCount += 1;
|
|
3079
|
+
const flowTip = tapCount >= FLOW_TIP_EVERY && tapCount % FLOW_TIP_EVERY === 0 ? FLOW_TIP : "";
|
|
2818
3080
|
if (res?.tapped && res.matched) {
|
|
2819
3081
|
const m = res.matched;
|
|
2820
3082
|
const label = m.text ?? m.label ?? m.name;
|
|
2821
3083
|
const id = m.testID ? ` [testID=${m.testID}]` : m.nativeTag != null ? ` #${m.nativeTag}` : "";
|
|
2822
3084
|
const scrolledNote = res.scrolled ? " (scrolled into view)" : "";
|
|
2823
3085
|
const verb = m.via === "onValueChange" ? `Set "${label}"${id} \u2192 ${JSON.stringify(m.value)}` : m.via === "onChangeText" ? `Typed ${JSON.stringify(m.value)} into "${label}"${id}` : m.via === "onLongPress" ? `Long-pressed "${label}"${id}` : `Tapped "${label}"${id}`;
|
|
2824
|
-
return text12(`${verb}${scrolledNote}
|
|
3086
|
+
return text12(`${verb}${scrolledNote}.${flowTip}`);
|
|
2825
3087
|
}
|
|
2826
3088
|
let msg = res?.reason ?? "Tap failed.";
|
|
2827
3089
|
if (res?.candidates?.length) {
|
|
@@ -2909,7 +3171,7 @@ function registerJsThreadTools(server, sync) {
|
|
|
2909
3171
|
server.registerTool(
|
|
2910
3172
|
"get_js_thread_top",
|
|
2911
3173
|
{
|
|
2912
|
-
description:
|
|
3174
|
+
description: 'Task Manager for the React Native JS thread: sample for a few seconds and return a ranked table of which task origins (timers, Promise chains, rAF callbacks, bridge call-ins) consumed JS-thread time \u2014 plus thread busy% and freeze (50ms+ block) attribution. Use when JS FPS is low and you need to know WHAT is eating the thread. To profile one specific interaction, pass clearFirst:true, then drive the UI with tap_element while the sample runs. Drill into a row with get_js_thread_origin_detail. NOT the tool for React components re-rendering too often \u2014 this measures TASKS on the thread, not renders; for "the page re-renders constantly / typing lags / tapping one button re-renders everything" use measure_renders. Requires @buoy-gg/js-top on the device.',
|
|
2913
3175
|
inputSchema: {
|
|
2914
3176
|
deviceId: import_zod15.z.string().optional().describe("Target device id (auto-selected if one is connected)."),
|
|
2915
3177
|
durationMs: import_zod15.z.number().optional().describe("How long to sample before reading the table. Default 3000, max 30000."),
|
|
@@ -3489,6 +3751,62 @@ ${JSON.stringify(slim)}
|
|
|
3489
3751
|
|
|
3490
3752
|
// src/tools/packs/reload.ts
|
|
3491
3753
|
var import_zod18 = require("zod");
|
|
3754
|
+
|
|
3755
|
+
// src/capture/devServerReload.ts
|
|
3756
|
+
var import_ws = require("ws");
|
|
3757
|
+
var CONNECT_TIMEOUT_MS = 3e3;
|
|
3758
|
+
function messageSocketUrl(origin) {
|
|
3759
|
+
return `${origin.replace(/^http/, "ws").replace(/\/+$/, "")}/message`;
|
|
3760
|
+
}
|
|
3761
|
+
function reloadViaDevServer(origin) {
|
|
3762
|
+
return new Promise((resolve) => {
|
|
3763
|
+
let settled = false;
|
|
3764
|
+
const done = (result) => {
|
|
3765
|
+
if (settled) return;
|
|
3766
|
+
settled = true;
|
|
3767
|
+
resolve(result);
|
|
3768
|
+
};
|
|
3769
|
+
let socket;
|
|
3770
|
+
try {
|
|
3771
|
+
socket = new import_ws.WebSocket(messageSocketUrl(origin));
|
|
3772
|
+
} catch (e) {
|
|
3773
|
+
done({ ok: false, error: e.message });
|
|
3774
|
+
return;
|
|
3775
|
+
}
|
|
3776
|
+
const timer = setTimeout(() => {
|
|
3777
|
+
try {
|
|
3778
|
+
socket.close();
|
|
3779
|
+
} catch {
|
|
3780
|
+
}
|
|
3781
|
+
done({ ok: false, error: `dev server at ${origin} did not accept a connection` });
|
|
3782
|
+
}, CONNECT_TIMEOUT_MS);
|
|
3783
|
+
let sent = false;
|
|
3784
|
+
socket.on("open", () => {
|
|
3785
|
+
try {
|
|
3786
|
+
socket.send(JSON.stringify({ version: 2, method: "reload" }));
|
|
3787
|
+
sent = true;
|
|
3788
|
+
clearTimeout(timer);
|
|
3789
|
+
setTimeout(() => {
|
|
3790
|
+
try {
|
|
3791
|
+
socket.close();
|
|
3792
|
+
} catch {
|
|
3793
|
+
}
|
|
3794
|
+
done({ ok: true });
|
|
3795
|
+
}, 250);
|
|
3796
|
+
} catch (e) {
|
|
3797
|
+
clearTimeout(timer);
|
|
3798
|
+
done({ ok: false, error: e.message });
|
|
3799
|
+
}
|
|
3800
|
+
});
|
|
3801
|
+
socket.on("error", (e) => {
|
|
3802
|
+
clearTimeout(timer);
|
|
3803
|
+
if (sent) return;
|
|
3804
|
+
done({ ok: false, error: e.message });
|
|
3805
|
+
});
|
|
3806
|
+
});
|
|
3807
|
+
}
|
|
3808
|
+
|
|
3809
|
+
// src/tools/packs/reload.ts
|
|
3492
3810
|
var APP_TOOL_ID = "app";
|
|
3493
3811
|
var RELOAD_ACTION = "reloadApp";
|
|
3494
3812
|
var DEFAULT_WAIT_MS = 3e4;
|
|
@@ -3501,7 +3819,11 @@ var errMsg18 = (e) => e instanceof Error ? e.message : String(e);
|
|
|
3501
3819
|
var delay3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3502
3820
|
async function ping(sync, deviceId, timeoutMs) {
|
|
3503
3821
|
try {
|
|
3504
|
-
const pong = await sync.callAction(APP_TOOL_ID, "ping", {}, deviceId, {
|
|
3822
|
+
const pong = await sync.callAction(APP_TOOL_ID, "ping", {}, deviceId, {
|
|
3823
|
+
timeoutMs,
|
|
3824
|
+
silent: true
|
|
3825
|
+
});
|
|
3826
|
+
sync.noteDevServerOrigin(deviceId, pong?.devServerOrigin);
|
|
3505
3827
|
return typeof pong?.startedAt === "number" ? pong.startedAt : null;
|
|
3506
3828
|
} catch {
|
|
3507
3829
|
return null;
|
|
@@ -3530,7 +3852,7 @@ function registerReloadTools(server, sync) {
|
|
|
3530
3852
|
server.registerTool(
|
|
3531
3853
|
"reload_app",
|
|
3532
3854
|
{
|
|
3533
|
-
description: "Reload the running app's JS bundle (Expo Go, dev client, or RN CLI) \u2014 the equivalent of shaking the device and hitting Reload, but from here. Use it to pick up a change Fast Refresh didn't apply, to clear leaked in-memory state before a measurement,
|
|
3855
|
+
description: "Reload the running app's JS bundle (Expo Go, dev client, or RN CLI) \u2014 the equivalent of shaking the device and hitting Reload, but from here. Use it to pick up a change Fast Refresh didn't apply, to clear leaked in-memory state before a measurement, to re-run app startup, or to RECOVER A CRASHED APP: after a fatal error the other tools stop answering, and reloading is how you get them back (it falls through to the dev server when the app is too broken to reload itself). In dev builds it uses React Native's DevSettings.reload(); otherwise it falls back to expo-updates (if the app installs it). All in-memory state is lost \u2014 read anything you need from get_console/get_storage BEFORE reloading. By default this waits for the app to come back up and reports how long the reload took. Works on any app running @buoy-gg/core \u2014 no particular tool package needed. Requires Buoy Pro.",
|
|
3534
3856
|
inputSchema: {
|
|
3535
3857
|
strategy: import_zod18.z.enum(["auto", "dev-settings", "expo-updates"]).optional().describe(
|
|
3536
3858
|
"Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."
|
|
@@ -3545,13 +3867,27 @@ function registerReloadTools(server, sync) {
|
|
|
3545
3867
|
const target = sync.requireProDevice(args.deviceId);
|
|
3546
3868
|
assertReloadSupported(sync, target);
|
|
3547
3869
|
const previousRealm = args.wait === false ? null : await ping(sync, target, PROBE_TIMEOUT_MS);
|
|
3548
|
-
|
|
3549
|
-
|
|
3550
|
-
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3870
|
+
let ack = null;
|
|
3871
|
+
let recovered = false;
|
|
3872
|
+
try {
|
|
3873
|
+
ack = await sync.callAction(
|
|
3874
|
+
APP_TOOL_ID,
|
|
3875
|
+
RELOAD_ACTION,
|
|
3876
|
+
{ strategy: args.strategy ?? "auto" },
|
|
3877
|
+
target
|
|
3878
|
+
);
|
|
3879
|
+
} catch (inAppError) {
|
|
3880
|
+
const origin = sync.devServerOrigin(target);
|
|
3881
|
+
if (!origin) throw inAppError;
|
|
3882
|
+
const res = await reloadViaDevServer(origin);
|
|
3883
|
+
if (!res.ok) {
|
|
3884
|
+
throw new Error(
|
|
3885
|
+
`The app is not answering (it looks crashed) and the dev server at ${origin} could not be reached either: ${res.error}. Reload the app by hand.`
|
|
3886
|
+
);
|
|
3887
|
+
}
|
|
3888
|
+
recovered = true;
|
|
3889
|
+
}
|
|
3890
|
+
const via = recovered ? ` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)` : ack?.strategy ? ` via ${ack.strategy}` : "";
|
|
3555
3891
|
if (args.wait === false) {
|
|
3556
3892
|
return text16(`Reload requested${via}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`);
|
|
3557
3893
|
}
|
|
@@ -3571,12 +3907,836 @@ function registerReloadTools(server, sync) {
|
|
|
3571
3907
|
);
|
|
3572
3908
|
}
|
|
3573
3909
|
|
|
3910
|
+
// src/tools/packs/triage.ts
|
|
3911
|
+
var import_zod19 = require("zod");
|
|
3912
|
+
var text17 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
3913
|
+
var fail19 = (message) => ({
|
|
3914
|
+
isError: true,
|
|
3915
|
+
content: [{ type: "text", text: message }]
|
|
3916
|
+
});
|
|
3917
|
+
var errMsg19 = (e) => e instanceof Error ? e.message : String(e);
|
|
3918
|
+
var PROBE_TIMEOUT_MS2 = 5e3;
|
|
3919
|
+
var MAX_STORAGE_KEYS = 20;
|
|
3920
|
+
var MAX_STORAGE_VALUE = 400;
|
|
3921
|
+
var STORAGE_VALUE_BUDGET = 1600;
|
|
3922
|
+
var MAX_LINE = 160;
|
|
3923
|
+
var cap = (s, n = MAX_LINE) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
3924
|
+
function hhmmss2(ts) {
|
|
3925
|
+
if (!ts) return "--:--:--";
|
|
3926
|
+
const d = new Date(ts);
|
|
3927
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
3928
|
+
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
3929
|
+
}
|
|
3930
|
+
async function otherBackends(sync, target, opts) {
|
|
3931
|
+
const notes = [];
|
|
3932
|
+
try {
|
|
3933
|
+
const mmkv = await sync.callAction("storage", "mmkv.snapshot", {}, target, opts);
|
|
3934
|
+
for (const inst of mmkv ?? []) {
|
|
3935
|
+
const n = inst.entries?.length ?? 0;
|
|
3936
|
+
if (n > 0) notes.push(`MMKV "${inst.id}": ${n} key${n === 1 ? "" : "s"}`);
|
|
3937
|
+
}
|
|
3938
|
+
} catch {
|
|
3939
|
+
}
|
|
3940
|
+
try {
|
|
3941
|
+
const secure = await sync.callAction("storage", "secure.keys", {}, target, opts);
|
|
3942
|
+
if (secure?.length) notes.push(`SecureStore: ${secure.length} key${secure.length === 1 ? "" : "s"}`);
|
|
3943
|
+
} catch {
|
|
3944
|
+
}
|
|
3945
|
+
return notes.length ? `
|
|
3946
|
+
${notes.join(" \xB7 ")} \u2014 read with get_storage` : "";
|
|
3947
|
+
}
|
|
3948
|
+
async function section(title, run) {
|
|
3949
|
+
try {
|
|
3950
|
+
const body = await run();
|
|
3951
|
+
return body ? `${title}
|
|
3952
|
+
${body}` : null;
|
|
3953
|
+
} catch (e) {
|
|
3954
|
+
const msg = errMsg19(e);
|
|
3955
|
+
if (/not responding|timed out|got no answer/i.test(msg)) {
|
|
3956
|
+
return `${title}
|
|
3957
|
+
(no answer \u2014 see the note above)`;
|
|
3958
|
+
}
|
|
3959
|
+
return `${title}
|
|
3960
|
+
(unavailable: ${cap(msg, 120)})`;
|
|
3961
|
+
}
|
|
3962
|
+
}
|
|
3963
|
+
function registerTriageTools(server, sync) {
|
|
3964
|
+
server.registerTool(
|
|
3965
|
+
"get_triage",
|
|
3966
|
+
{
|
|
3967
|
+
description: "START HERE when debugging a running app. One call = the app's current runtime state: connected device, recent console errors (including [FATAL] crashes), recent network requests with statuses, persisted storage values, and what's on screen right now. Use it as the first step for ANY 'why is the app doing X' question \u2014 it is far cheaper than calling get_console + get_network_requests + get_storage + describe_screen separately, and it tells you which of those to drill into next. If the app has crashed it says so and shows the crash. Requires Buoy Pro.",
|
|
3968
|
+
inputSchema: {
|
|
3969
|
+
deviceId: import_zod19.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
3970
|
+
}
|
|
3971
|
+
},
|
|
3972
|
+
async (args) => {
|
|
3973
|
+
try {
|
|
3974
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
3975
|
+
const device = sync.connectedDevices().find((d) => d.deviceId === target);
|
|
3976
|
+
const toolIds = new Set((device?.tools ?? []).map((t) => t.toolId));
|
|
3977
|
+
const head = `**${device?.deviceName ?? target}** (${device?.platform ?? "?"}, id \`${target}\`) \u2014 tools: ${[...toolIds].join(", ") || "none"}`;
|
|
3978
|
+
const opts = { timeoutMs: PROBE_TIMEOUT_MS2 };
|
|
3979
|
+
const [consoleSec, netSec, storeSec, screenSec] = await Promise.all([
|
|
3980
|
+
section("**Console \u2014 recent errors/warnings:**", async () => {
|
|
3981
|
+
if (!toolIds.has("console")) return null;
|
|
3982
|
+
const { payload } = await sync.getSnapshot("console", target, opts);
|
|
3983
|
+
const p = payload;
|
|
3984
|
+
const entries = Array.isArray(p) ? p : p?.entries ?? [];
|
|
3985
|
+
const bad = entries.filter(
|
|
3986
|
+
(e) => e.level === "error" || e.level === "warning"
|
|
3987
|
+
);
|
|
3988
|
+
const shown = bad.slice(-8);
|
|
3989
|
+
if (shown.length === 0) {
|
|
3990
|
+
return `(none \u2014 ${entries.length} entries captured)`;
|
|
3991
|
+
}
|
|
3992
|
+
return shown.map(
|
|
3993
|
+
(e) => `${hhmmss2(e.timestamp)} [${e.level === "error" ? "ERR" : "warn"}] ${cap(
|
|
3994
|
+
(e.message ?? "").split("\n").map((l) => l.trim()).filter(Boolean).slice(0, 3).join(" \u23CE "),
|
|
3995
|
+
220
|
|
3996
|
+
)}`
|
|
3997
|
+
).join("\n");
|
|
3998
|
+
}),
|
|
3999
|
+
section("**Network \u2014 recent requests:**", async () => {
|
|
4000
|
+
if (!toolIds.has("network")) return null;
|
|
4001
|
+
const { payload } = await sync.getSnapshot("network", target, opts);
|
|
4002
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4003
|
+
if (events.length === 0) return "(no requests captured yet)";
|
|
4004
|
+
const shown = events.slice(-8);
|
|
4005
|
+
return shown.map((e) => {
|
|
4006
|
+
const mark = e.error || (e.status ?? 0) >= 400 ? "\u274C" : "\u2705";
|
|
4007
|
+
const where = e.path ?? e.url ?? "?";
|
|
4008
|
+
const status = e.error ?? e.status ?? "pending";
|
|
4009
|
+
return `${mark} ${e.method ?? "GET"} ${cap(String(where), 80)} \u2192 ${status}${e.duration ? ` (${Math.round(e.duration)}ms)` : ""}`;
|
|
4010
|
+
}).join("\n");
|
|
4011
|
+
}),
|
|
4012
|
+
section("**Storage \u2014 persisted values:**", async () => {
|
|
4013
|
+
if (!toolIds.has("storage")) return null;
|
|
4014
|
+
const keys = await sync.callAction(
|
|
4015
|
+
"storage",
|
|
4016
|
+
"async.getAllKeys",
|
|
4017
|
+
{},
|
|
4018
|
+
target,
|
|
4019
|
+
opts
|
|
4020
|
+
);
|
|
4021
|
+
if (!Array.isArray(keys) || keys.length === 0) {
|
|
4022
|
+
return "(no app keys)";
|
|
4023
|
+
}
|
|
4024
|
+
const head2 = keys.slice(0, MAX_STORAGE_KEYS);
|
|
4025
|
+
let pairs = [];
|
|
4026
|
+
try {
|
|
4027
|
+
pairs = await sync.callAction(
|
|
4028
|
+
"storage",
|
|
4029
|
+
"async.multiGet",
|
|
4030
|
+
{ keys: head2 },
|
|
4031
|
+
target,
|
|
4032
|
+
opts
|
|
4033
|
+
) ?? [];
|
|
4034
|
+
} catch {
|
|
4035
|
+
return `${head2.map((k) => `\`${k}\``).join(", ")}
|
|
4036
|
+
_Values: get_storage includeValues:true_`;
|
|
4037
|
+
}
|
|
4038
|
+
const byKey = new Map(pairs);
|
|
4039
|
+
let budget = STORAGE_VALUE_BUDGET;
|
|
4040
|
+
const lines = head2.map((k) => {
|
|
4041
|
+
const v = byKey.get(k);
|
|
4042
|
+
if (v == null) return `- \`${k}\` = (null)`;
|
|
4043
|
+
if (v.length > MAX_STORAGE_VALUE) {
|
|
4044
|
+
return `- \`${k}\` = (${(v.length / 1024).toFixed(1)} KB \u2014 read with get_storage)`;
|
|
4045
|
+
}
|
|
4046
|
+
if (budget <= 0) return `- \`${k}\` = (not shown \u2014 triage budget spent; read with get_storage)`;
|
|
4047
|
+
budget -= v.length;
|
|
4048
|
+
return `- \`${k}\` = ${v}`;
|
|
4049
|
+
});
|
|
4050
|
+
const more = keys.length - head2.length;
|
|
4051
|
+
const others = await otherBackends(sync, target, opts);
|
|
4052
|
+
return `${lines.join("\n")}${more > 0 ? `
|
|
4053
|
+
\u2026+${more} more keys` : ""}${others}`;
|
|
4054
|
+
}),
|
|
4055
|
+
section("**Screen \u2014 what's visible now:**", async () => {
|
|
4056
|
+
if (!toolIds.has("highlight-updates")) return null;
|
|
4057
|
+
const res = await sync.callAction(
|
|
4058
|
+
"highlight-updates",
|
|
4059
|
+
"describeScreen",
|
|
4060
|
+
{},
|
|
4061
|
+
target,
|
|
4062
|
+
opts
|
|
4063
|
+
);
|
|
4064
|
+
const els = (res?.elements ?? []).filter((e) => e.interactive);
|
|
4065
|
+
if (els.length === 0) return "(nothing interactive on screen)";
|
|
4066
|
+
return els.slice(0, 20).map(
|
|
4067
|
+
(e) => `\u2022 ${e.name}${e.text || e.label ? ` "${cap(e.text ?? e.label ?? "", 60)}"` : ""}${e.testID ? ` [testID=${e.testID}]` : ""}`
|
|
4068
|
+
).join("\n");
|
|
4069
|
+
})
|
|
4070
|
+
]);
|
|
4071
|
+
const crashed = sync.isUnresponsive(target);
|
|
4072
|
+
const banner = crashed ? `
|
|
4073
|
+
|
|
4074
|
+
\u{1F6D1} ${sync.unresponsiveNote(target)}` : "";
|
|
4075
|
+
const body = [consoleSec, netSec, storeSec, screenSec].filter(Boolean).join("\n\n");
|
|
4076
|
+
return text17(
|
|
4077
|
+
`${head}${banner}
|
|
4078
|
+
|
|
4079
|
+
${body}
|
|
4080
|
+
|
|
4081
|
+
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`
|
|
4082
|
+
);
|
|
4083
|
+
} catch (e) {
|
|
4084
|
+
return fail19(errMsg19(e));
|
|
4085
|
+
}
|
|
4086
|
+
}
|
|
4087
|
+
);
|
|
4088
|
+
}
|
|
4089
|
+
|
|
4090
|
+
// src/tools/packs/flow.ts
|
|
4091
|
+
var import_zod20 = require("zod");
|
|
4092
|
+
var UI_TOOL_ID = "highlight-updates";
|
|
4093
|
+
var APP_TOOL_ID2 = "app";
|
|
4094
|
+
var text18 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
4095
|
+
var fail20 = (message) => ({
|
|
4096
|
+
isError: true,
|
|
4097
|
+
content: [{ type: "text", text: message }]
|
|
4098
|
+
});
|
|
4099
|
+
var errMsg20 = (e) => e instanceof Error ? e.message : String(e);
|
|
4100
|
+
var delay4 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4101
|
+
var POLL_MS = 250;
|
|
4102
|
+
var DEFAULT_WAIT_MS2 = 5e3;
|
|
4103
|
+
var ASSERT_SETTLE_MS = 2e3;
|
|
4104
|
+
var TEARDOWN_GRACE_MS2 = 1200;
|
|
4105
|
+
var REALM_PROBE_MS = 1500;
|
|
4106
|
+
var MAX_FLOW_MS = 12e4;
|
|
4107
|
+
function matches(e, needle) {
|
|
4108
|
+
if (e.testID && e.testID === needle) return true;
|
|
4109
|
+
const n = needle.toLowerCase();
|
|
4110
|
+
return [e.testID, e.text, e.label, e.name].filter(Boolean).some((v) => String(v).toLowerCase().includes(n));
|
|
4111
|
+
}
|
|
4112
|
+
function formatElement2(e) {
|
|
4113
|
+
const display = e.text ?? e.label;
|
|
4114
|
+
return `${e.interactive ? "\u2022 " : " "}${e.name}${display ? ` "${display}"` : ""}${e.testID ? ` [testID=${e.testID}]` : ""}`;
|
|
4115
|
+
}
|
|
4116
|
+
var stepSchema = import_zod20.z.object({
|
|
4117
|
+
tap: import_zod20.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),
|
|
4118
|
+
longPress: import_zod20.z.boolean().optional().describe("Make `tap` a long-press instead."),
|
|
4119
|
+
type: import_zod20.z.string().optional().describe("Text to type (needs `into`)."),
|
|
4120
|
+
into: import_zod20.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),
|
|
4121
|
+
set: import_zod20.z.union([import_zod20.z.number(), import_zod20.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),
|
|
4122
|
+
reload: import_zod20.z.boolean().optional().describe("Reload the JS bundle before this step's action."),
|
|
4123
|
+
waitMs: import_zod20.z.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000)."),
|
|
4124
|
+
waitFor: import_zod20.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),
|
|
4125
|
+
waitGone: import_zod20.z.string().optional().describe("Wait until no element matches this (default 5s)."),
|
|
4126
|
+
expect: import_zod20.z.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),
|
|
4127
|
+
expectGone: import_zod20.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),
|
|
4128
|
+
timeoutMs: import_zod20.z.number().min(0).max(6e4).optional().describe("Budget for this step's waitFor/waitGone/expect, max 60000. Default 5000 (2000 for expect).")
|
|
4129
|
+
}).describe("One flow step. Order within a step: reload \u2192 tap/type/set \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect.");
|
|
4130
|
+
function registerFlowTools(server, sync) {
|
|
4131
|
+
server.registerTool(
|
|
4132
|
+
"run_flow",
|
|
4133
|
+
{
|
|
4134
|
+
description: "Run a scripted sequence of UI interactions in ONE call and report what happened: per-step results, the final screen, plus the network requests and console errors the flow produced. Use this instead of alternating describe_screen/tap_element \u2014 reproducing a bug ('open cart, checkout, submit') or verifying a fix after an edit is one call, not a dozen. Steps run in order and stop at the first failure, returning the screen at that point so you can see WHERE it broke. Each step can tap, type, set a toggle/slider, reload, wait for an element, and assert. Requires Buoy Pro.",
|
|
4135
|
+
inputSchema: {
|
|
4136
|
+
steps: import_zod20.z.array(stepSchema).min(1).describe("Steps to run, in order."),
|
|
4137
|
+
include: import_zod20.z.enum(["all", "screen", "none"]).optional().describe("What to report after the flow: 'all' (default) = final screen + network/console produced by the flow; 'screen' = final screen only; 'none' = step results only."),
|
|
4138
|
+
continueOnFailure: import_zod20.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),
|
|
4139
|
+
deviceId: import_zod20.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4140
|
+
}
|
|
4141
|
+
},
|
|
4142
|
+
async (args) => {
|
|
4143
|
+
const started = Date.now();
|
|
4144
|
+
try {
|
|
4145
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4146
|
+
const include = args.include ?? "all";
|
|
4147
|
+
const describe = async () => {
|
|
4148
|
+
const res = await sync.callAction(UI_TOOL_ID, "describeScreen", {}, target);
|
|
4149
|
+
return res?.elements ?? [];
|
|
4150
|
+
};
|
|
4151
|
+
const realmId = async () => {
|
|
4152
|
+
try {
|
|
4153
|
+
const pong = await sync.callAction(APP_TOOL_ID2, "ping", {}, target, {
|
|
4154
|
+
timeoutMs: REALM_PROBE_MS,
|
|
4155
|
+
silent: true
|
|
4156
|
+
// probes across a reload are expected to fail
|
|
4157
|
+
});
|
|
4158
|
+
return typeof pong?.startedAt === "number" ? pong.startedAt : null;
|
|
4159
|
+
} catch {
|
|
4160
|
+
return null;
|
|
4161
|
+
}
|
|
4162
|
+
};
|
|
4163
|
+
const untilNewRealm = async (previous, budgetMs) => {
|
|
4164
|
+
const t0 = Date.now();
|
|
4165
|
+
while (Date.now() - t0 < budgetMs) {
|
|
4166
|
+
const realm = await realmId();
|
|
4167
|
+
if (realm !== null && realm !== previous) return Date.now() - t0;
|
|
4168
|
+
await delay4(POLL_MS);
|
|
4169
|
+
}
|
|
4170
|
+
return null;
|
|
4171
|
+
};
|
|
4172
|
+
const beforeConsole = /* @__PURE__ */ new Set();
|
|
4173
|
+
const beforeNetwork = /* @__PURE__ */ new Set();
|
|
4174
|
+
const toolIds = new Set(
|
|
4175
|
+
(sync.connectedDevices().find((d) => d.deviceId === target)?.tools ?? []).map((t) => t.toolId)
|
|
4176
|
+
);
|
|
4177
|
+
if (include === "all") {
|
|
4178
|
+
if (toolIds.has("console")) {
|
|
4179
|
+
const { payload } = await sync.getSnapshot("console", target).catch(() => ({ payload: null }));
|
|
4180
|
+
const entries = payload?.entries ?? [];
|
|
4181
|
+
for (const e of entries) beforeConsole.add(e.id);
|
|
4182
|
+
}
|
|
4183
|
+
if (toolIds.has("network")) {
|
|
4184
|
+
const { payload } = await sync.getSnapshot("network", target).catch(() => ({ payload: null }));
|
|
4185
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4186
|
+
for (const e of events) beforeNetwork.add(e.id);
|
|
4187
|
+
}
|
|
4188
|
+
}
|
|
4189
|
+
const until = async (predicate, budgetMs) => {
|
|
4190
|
+
const t0 = Date.now();
|
|
4191
|
+
for (; ; ) {
|
|
4192
|
+
if (Date.now() - t0 >= budgetMs || Date.now() - started > MAX_FLOW_MS) {
|
|
4193
|
+
return { ok: false, ms: Date.now() - t0 };
|
|
4194
|
+
}
|
|
4195
|
+
let els = [];
|
|
4196
|
+
try {
|
|
4197
|
+
els = await describe();
|
|
4198
|
+
} catch {
|
|
4199
|
+
}
|
|
4200
|
+
if (predicate(els)) return { ok: true, ms: Date.now() - t0 };
|
|
4201
|
+
await delay4(POLL_MS);
|
|
4202
|
+
}
|
|
4203
|
+
};
|
|
4204
|
+
const lines = [];
|
|
4205
|
+
let failedAt = null;
|
|
4206
|
+
let okCount = 0;
|
|
4207
|
+
for (let i = 0; i < args.steps.length; i++) {
|
|
4208
|
+
const step = args.steps[i];
|
|
4209
|
+
const label = `${i + 1}`;
|
|
4210
|
+
const budget = step.timeoutMs ?? DEFAULT_WAIT_MS2;
|
|
4211
|
+
if (Date.now() - started > MAX_FLOW_MS) {
|
|
4212
|
+
lines.push(`${label} \u2717 flow exceeded ${MAX_FLOW_MS / 1e3}s \u2014 stopped here`);
|
|
4213
|
+
failedAt = i;
|
|
4214
|
+
break;
|
|
4215
|
+
}
|
|
4216
|
+
const stepErrors = [];
|
|
4217
|
+
const done = [];
|
|
4218
|
+
const actionable = step.reload || step.tap || step.type !== void 0 || step.waitMs || step.waitFor || step.waitGone || step.expect || step.expectGone;
|
|
4219
|
+
if (!actionable) {
|
|
4220
|
+
lines.push(`${i + 1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${step.set !== void 0 ? " (`set` needs `tap` naming the control)" : ""}`);
|
|
4221
|
+
failedAt = failedAt ?? i;
|
|
4222
|
+
if (!args.continueOnFailure) break;
|
|
4223
|
+
continue;
|
|
4224
|
+
}
|
|
4225
|
+
try {
|
|
4226
|
+
if (step.reload) {
|
|
4227
|
+
const previousRealm = await realmId();
|
|
4228
|
+
await sync.callAction(APP_TOOL_ID2, "reloadApp", { strategy: "auto" }, target);
|
|
4229
|
+
await delay4(TEARDOWN_GRACE_MS2);
|
|
4230
|
+
const back = await untilNewRealm(previousRealm, Math.max(budget, 2e4));
|
|
4231
|
+
if (back == null) {
|
|
4232
|
+
stepErrors.push("app did not come back after reload");
|
|
4233
|
+
} else {
|
|
4234
|
+
done.push(`reloaded (${back}ms)`);
|
|
4235
|
+
await until((els) => els.length > 0, 1e4);
|
|
4236
|
+
}
|
|
4237
|
+
}
|
|
4238
|
+
if (step.type !== void 0) {
|
|
4239
|
+
const targetSel = step.into ?? step.tap;
|
|
4240
|
+
if (!targetSel) {
|
|
4241
|
+
stepErrors.push("`type` needs `into` (which input to type into)");
|
|
4242
|
+
} else {
|
|
4243
|
+
const res = await sync.callAction(
|
|
4244
|
+
UI_TOOL_ID,
|
|
4245
|
+
"tapElement",
|
|
4246
|
+
{ ...selector(targetSel), text: step.type },
|
|
4247
|
+
target
|
|
4248
|
+
);
|
|
4249
|
+
if (!res?.tapped) {
|
|
4250
|
+
stepErrors.push(res?.reason ?? `could not type into "${targetSel}"`);
|
|
4251
|
+
} else if (res.matched?.via && res.matched.via !== "onChangeText") {
|
|
4252
|
+
stepErrors.push(
|
|
4253
|
+
`"${targetSel}" is not a text input \u2014 it ran ${res.matched.via} instead, and the text was not entered`
|
|
4254
|
+
);
|
|
4255
|
+
} else {
|
|
4256
|
+
done.push(`typed ${JSON.stringify(step.type)} into "${targetSel}"`);
|
|
4257
|
+
}
|
|
4258
|
+
}
|
|
4259
|
+
} else if (step.tap) {
|
|
4260
|
+
const params = { ...selector(step.tap) };
|
|
4261
|
+
if (step.longPress) params.longPress = true;
|
|
4262
|
+
if (step.set !== void 0) params.value = step.set;
|
|
4263
|
+
const res = await sync.callAction(UI_TOOL_ID, "tapElement", params, target);
|
|
4264
|
+
if (!res?.tapped) {
|
|
4265
|
+
stepErrors.push(res?.reason ?? `no element matched "${step.tap}"`);
|
|
4266
|
+
} else {
|
|
4267
|
+
const m = res.matched;
|
|
4268
|
+
const what = m?.text ?? m?.label ?? m?.name ?? step.tap;
|
|
4269
|
+
if (step.set !== void 0 && m?.via && m.via !== "onValueChange") {
|
|
4270
|
+
stepErrors.push(
|
|
4271
|
+
`"${what}" is not a toggle/slider \u2014 it ran ${m.via} instead, so it was not set to ${JSON.stringify(step.set)}`
|
|
4272
|
+
);
|
|
4273
|
+
} else {
|
|
4274
|
+
done.push(
|
|
4275
|
+
step.set !== void 0 ? `set "${what}" \u2192 ${JSON.stringify(m?.value ?? step.set)}` : `${step.longPress ? "long-pressed" : "tapped"} "${what}"`
|
|
4276
|
+
);
|
|
4277
|
+
}
|
|
4278
|
+
}
|
|
4279
|
+
}
|
|
4280
|
+
if (!stepErrors.length && step.waitMs) {
|
|
4281
|
+
await delay4(step.waitMs);
|
|
4282
|
+
done.push(`waited ${step.waitMs}ms`);
|
|
4283
|
+
}
|
|
4284
|
+
if (!stepErrors.length && step.waitFor) {
|
|
4285
|
+
const r = await until((els) => els.some((e) => matches(e, step.waitFor)), budget);
|
|
4286
|
+
if (r.ok) done.push(`"${step.waitFor}" appeared (${r.ms}ms)`);
|
|
4287
|
+
else stepErrors.push(`"${step.waitFor}" never appeared within ${budget}ms`);
|
|
4288
|
+
}
|
|
4289
|
+
if (!stepErrors.length && step.waitGone) {
|
|
4290
|
+
const r = await until((els) => !els.some((e) => matches(e, step.waitGone)), budget);
|
|
4291
|
+
if (r.ok) done.push(`"${step.waitGone}" gone (${r.ms}ms)`);
|
|
4292
|
+
else stepErrors.push(`"${step.waitGone}" was still there after ${budget}ms`);
|
|
4293
|
+
}
|
|
4294
|
+
if (!stepErrors.length && step.expect) {
|
|
4295
|
+
const r = await until(
|
|
4296
|
+
(els) => els.some((e) => matches(e, step.expect)),
|
|
4297
|
+
step.timeoutMs ?? ASSERT_SETTLE_MS
|
|
4298
|
+
);
|
|
4299
|
+
if (r.ok) done.push(`"${step.expect}" is on screen`);
|
|
4300
|
+
else stepErrors.push(`expected "${step.expect}" on screen \u2014 not found`);
|
|
4301
|
+
}
|
|
4302
|
+
if (!stepErrors.length && step.expectGone) {
|
|
4303
|
+
const r = await until(
|
|
4304
|
+
(els) => !els.some((e) => matches(e, step.expectGone)),
|
|
4305
|
+
step.timeoutMs ?? ASSERT_SETTLE_MS
|
|
4306
|
+
);
|
|
4307
|
+
if (r.ok) done.push(`"${step.expectGone}" is gone`);
|
|
4308
|
+
else stepErrors.push(`expected "${step.expectGone}" to be gone \u2014 still on screen`);
|
|
4309
|
+
}
|
|
4310
|
+
} catch (e) {
|
|
4311
|
+
stepErrors.push(errMsg20(e));
|
|
4312
|
+
}
|
|
4313
|
+
if (stepErrors.length) {
|
|
4314
|
+
lines.push(`${label} \u2717 ${describeStep(step)} \u2014 ${stepErrors.join("; ")}`);
|
|
4315
|
+
failedAt = failedAt ?? i;
|
|
4316
|
+
if (!args.continueOnFailure) break;
|
|
4317
|
+
} else {
|
|
4318
|
+
okCount++;
|
|
4319
|
+
lines.push(`${label} \u2713 ${done.join(", ") || describeStep(step)}`);
|
|
4320
|
+
}
|
|
4321
|
+
}
|
|
4322
|
+
const elapsed = ((Date.now() - started) / 1e3).toFixed(1);
|
|
4323
|
+
const header = failedAt === null ? `**Flow: ${okCount}/${args.steps.length} steps OK (${elapsed}s)**` : `**Flow FAILED at step ${failedAt + 1} \u2014 ${okCount}/${args.steps.length} steps OK (${elapsed}s)**`;
|
|
4324
|
+
const parts = [header, lines.join("\n")];
|
|
4325
|
+
if (include !== "none") {
|
|
4326
|
+
try {
|
|
4327
|
+
const els = await describe();
|
|
4328
|
+
const shown = els.filter((e) => e.interactive).slice(0, 30);
|
|
4329
|
+
parts.push(
|
|
4330
|
+
`**Screen now (${shown.length} interactive of ${els.length}):**
|
|
4331
|
+
${shown.map(formatElement2).join("\n")}`
|
|
4332
|
+
);
|
|
4333
|
+
} catch (e) {
|
|
4334
|
+
parts.push(`**Screen now:** unavailable \u2014 ${cap2(errMsg20(e))}`);
|
|
4335
|
+
}
|
|
4336
|
+
}
|
|
4337
|
+
if (include === "all") {
|
|
4338
|
+
if (toolIds.has("network")) {
|
|
4339
|
+
const { payload } = await sync.getSnapshot("network", target).catch(() => ({ payload: null }));
|
|
4340
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4341
|
+
const fresh = events.filter((e) => !beforeNetwork.has(e.id)).slice(-15);
|
|
4342
|
+
if (fresh.length) {
|
|
4343
|
+
parts.push(
|
|
4344
|
+
`**Network during this flow (${fresh.length}):**
|
|
4345
|
+
` + fresh.map(
|
|
4346
|
+
(e) => `${e.error || (e.status ?? 0) >= 400 ? "\u274C" : "\u2705"} ${e.method ?? "GET"} ${e.path ?? e.url ?? "?"} \u2192 ${e.error ?? e.status ?? "pending"}`
|
|
4347
|
+
).join("\n")
|
|
4348
|
+
);
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
if (toolIds.has("console")) {
|
|
4352
|
+
const { payload } = await sync.getSnapshot("console", target).catch(() => ({ payload: null }));
|
|
4353
|
+
const entries = payload?.entries ?? [];
|
|
4354
|
+
const fresh = entries.filter((e) => !beforeConsole.has(e.id) && (e.level === "error" || e.level === "warning")).slice(-10);
|
|
4355
|
+
if (fresh.length) {
|
|
4356
|
+
parts.push(
|
|
4357
|
+
`**Console during this flow (${fresh.length}):**
|
|
4358
|
+
` + fresh.map((e) => `[${e.level === "error" ? "ERR" : "warn"}] ${cap2(firstLines(e.message ?? ""), 220)}`).join("\n")
|
|
4359
|
+
);
|
|
4360
|
+
}
|
|
4361
|
+
}
|
|
4362
|
+
}
|
|
4363
|
+
return text18(parts.join("\n\n"));
|
|
4364
|
+
} catch (e) {
|
|
4365
|
+
return fail20(errMsg20(e));
|
|
4366
|
+
}
|
|
4367
|
+
}
|
|
4368
|
+
);
|
|
4369
|
+
}
|
|
4370
|
+
function selector(needle) {
|
|
4371
|
+
return /\s/.test(needle) ? { query: needle } : { testID: needle, query: needle };
|
|
4372
|
+
}
|
|
4373
|
+
function describeStep(step) {
|
|
4374
|
+
if (step.tap) return `tap "${step.tap}"`;
|
|
4375
|
+
if (step.type !== void 0) return `type into "${step.into ?? "?"}"`;
|
|
4376
|
+
if (step.reload) return "reload";
|
|
4377
|
+
if (step.waitFor) return `waitFor "${step.waitFor}"`;
|
|
4378
|
+
if (step.waitGone) return `waitGone "${step.waitGone}"`;
|
|
4379
|
+
if (step.expect) return `expect "${step.expect}"`;
|
|
4380
|
+
return "step";
|
|
4381
|
+
}
|
|
4382
|
+
var cap2 = (s, n = 160) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
4383
|
+
var firstLines = (s, n = 3) => s.split("\n").map((l) => l.trim()).filter(Boolean).slice(0, n).join(" \u23CE ");
|
|
4384
|
+
|
|
4385
|
+
// src/tools/packs/renders.ts
|
|
4386
|
+
var import_zod21 = require("zod");
|
|
4387
|
+
var UI_TOOL_ID2 = "highlight-updates";
|
|
4388
|
+
var text19 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
4389
|
+
var fail21 = (message) => ({
|
|
4390
|
+
isError: true,
|
|
4391
|
+
content: [{ type: "text", text: message }]
|
|
4392
|
+
});
|
|
4393
|
+
var errMsg21 = (e) => e instanceof Error ? e.message : String(e);
|
|
4394
|
+
var delay5 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4395
|
+
var DEFAULT_IDLE_MS = 3e3;
|
|
4396
|
+
var SETTLE_MS = 400;
|
|
4397
|
+
var DEFAULT_TOP = 12;
|
|
4398
|
+
var lastCapture = /* @__PURE__ */ new Map();
|
|
4399
|
+
var stepSchema2 = import_zod21.z.object({
|
|
4400
|
+
tap: import_zod21.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),
|
|
4401
|
+
type: import_zod21.z.string().optional().describe("Text to type (needs `into`)."),
|
|
4402
|
+
into: import_zod21.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),
|
|
4403
|
+
waitMs: import_zod21.z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),
|
|
4404
|
+
repeat: import_zod21.z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")
|
|
4405
|
+
}).describe("One interaction to measure. Keep it to the thing you're asking about.");
|
|
4406
|
+
function selector2(needle) {
|
|
4407
|
+
return /\s/.test(needle) ? { query: needle } : { testID: needle, query: needle };
|
|
4408
|
+
}
|
|
4409
|
+
function dominant(causes) {
|
|
4410
|
+
if (!causes) return "unknown";
|
|
4411
|
+
let best = "unknown";
|
|
4412
|
+
let n = -1;
|
|
4413
|
+
for (const [k, v] of Object.entries(causes)) {
|
|
4414
|
+
if ((v ?? 0) > n) {
|
|
4415
|
+
n = v ?? 0;
|
|
4416
|
+
best = k;
|
|
4417
|
+
}
|
|
4418
|
+
}
|
|
4419
|
+
return best;
|
|
4420
|
+
}
|
|
4421
|
+
var CAUSE_HINT = {
|
|
4422
|
+
propsUnstable: "props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",
|
|
4423
|
+
parent: "parent re-rendered and nothing of its own changed \u2014 a pure cascade",
|
|
4424
|
+
props: "props genuinely changed value",
|
|
4425
|
+
hooks: "its own state/hooks changed",
|
|
4426
|
+
mount: "first render"
|
|
4427
|
+
};
|
|
4428
|
+
function formatCapture(c, top) {
|
|
4429
|
+
const s = c.summary;
|
|
4430
|
+
const wasted = s.wastedRenders ?? 0;
|
|
4431
|
+
const pct = s.totalRenders > 0 ? Math.round(wasted / s.totalRenders * 100) : 0;
|
|
4432
|
+
const lines = [];
|
|
4433
|
+
const ms = s.totalRenderMs ?? 0;
|
|
4434
|
+
lines.push(
|
|
4435
|
+
`**${s.totalRenders} component renders across ${s.totalCommits} commits in ${(c.windowMs / 1e3).toFixed(1)}s**` + (ms > 0 ? ` \xB7 ${ms.toFixed(1)}ms of render work` : "") + ` \xB7 ${wasted} wasted (${pct}%)`
|
|
4436
|
+
);
|
|
4437
|
+
const causeLine = Object.entries(s.causes ?? {}).filter(([, v]) => (v ?? 0) > 0).sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0)).map(([k, v]) => `${k} ${v}`).join(" \xB7 ");
|
|
4438
|
+
if (causeLine) lines.push(`causes: ${causeLine}`);
|
|
4439
|
+
lines.push("");
|
|
4440
|
+
lines.push("| component | self ms | renders | cause | dragged along by | changed props |");
|
|
4441
|
+
lines.push("|---|---:|---:|---|---|---|");
|
|
4442
|
+
const rows = [...s.topComponents].sort((a, b) => (b.totalMs ?? 0) - (a.totalMs ?? 0) || b.renders - a.renders).slice(0, top);
|
|
4443
|
+
for (const r of rows) {
|
|
4444
|
+
lines.push(
|
|
4445
|
+
`| ${r.name} | ${(r.totalMs ?? 0).toFixed(1)} | ${r.renders} | ${dominant(r.causes)} | ${r.parentName ?? "\u2014"} | ${(r.changedProps ?? []).join(", ") || "\u2014"} |`
|
|
4446
|
+
);
|
|
4447
|
+
}
|
|
4448
|
+
if (s.topComponents.length > top) {
|
|
4449
|
+
lines.push(`_\u2026+${s.topComponents.length - top} more components_`);
|
|
4450
|
+
}
|
|
4451
|
+
const seen = new Set(rows.map((r) => dominant(r.causes)));
|
|
4452
|
+
const hints = [...seen].filter((k) => CAUSE_HINT[k]).map((k) => `\`${k}\` = ${CAUSE_HINT[k]}`);
|
|
4453
|
+
if (hints.length) {
|
|
4454
|
+
lines.push("");
|
|
4455
|
+
lines.push(hints.join(" \xB7 "));
|
|
4456
|
+
}
|
|
4457
|
+
lines.push("");
|
|
4458
|
+
lines.push(
|
|
4459
|
+
"`wasted` = renders that produced nothing new (parent cascades + identity-only prop changes) \u2014 the removable part. Sorted by **self ms**: fix what costs time, not what renders often. Cheap components re-rendering is usually fine, and blanket `memo()` trades real code clarity for a number that was never the problem."
|
|
4460
|
+
);
|
|
4461
|
+
return lines.join("\n");
|
|
4462
|
+
}
|
|
4463
|
+
function formatDelta(before, after) {
|
|
4464
|
+
const d = (a, b) => {
|
|
4465
|
+
const diff = b - a;
|
|
4466
|
+
return `${a} \u2192 ${b} (${diff > 0 ? "+" : ""}${diff})`;
|
|
4467
|
+
};
|
|
4468
|
+
const bs = before.summary;
|
|
4469
|
+
const as_ = after.summary;
|
|
4470
|
+
const lines = [`**vs "${before.label}"**`];
|
|
4471
|
+
lines.push(`- total renders: ${d(bs.totalRenders, as_.totalRenders)}`);
|
|
4472
|
+
lines.push(`- wasted: ${d(bs.wastedRenders ?? 0, as_.wastedRenders ?? 0)}`);
|
|
4473
|
+
const beforeByName = new Map(bs.topComponents.map((r) => [r.name, r.renders]));
|
|
4474
|
+
const moved = [];
|
|
4475
|
+
for (const r of as_.topComponents.slice(0, 20)) {
|
|
4476
|
+
const was = beforeByName.get(r.name) ?? 0;
|
|
4477
|
+
if (was !== r.renders) moved.push(`${r.name} ${d(was, r.renders)}`);
|
|
4478
|
+
beforeByName.delete(r.name);
|
|
4479
|
+
}
|
|
4480
|
+
for (const [name, was] of beforeByName) {
|
|
4481
|
+
if (was > 0) moved.push(`${name} ${d(was, 0)}`);
|
|
4482
|
+
}
|
|
4483
|
+
if (moved.length) lines.push(`- per component: ${moved.slice(0, 10).join(" \xB7 ")}`);
|
|
4484
|
+
const fewer = as_.totalRenders < bs.totalRenders;
|
|
4485
|
+
const more = as_.totalRenders > bs.totalRenders;
|
|
4486
|
+
lines.push(
|
|
4487
|
+
more ? "\n\u26A0\uFE0F MORE renders than before \u2014 this change made this interaction worse. Re-render fixes routinely move cost instead of removing it; check the other interactions too before moving on." : fewer ? "\n\u2705 Fewer renders than before on this interaction. Measure the OTHER interactions too \u2014 a fix that helps typing can cost taps." : "\n\u2796 No change on this interaction."
|
|
4488
|
+
);
|
|
4489
|
+
return lines.join("\n");
|
|
4490
|
+
}
|
|
4491
|
+
function registerRenderTools(server, sync) {
|
|
4492
|
+
server.registerTool(
|
|
4493
|
+
"measure_renders",
|
|
4494
|
+
{
|
|
4495
|
+
description: "Find out WHAT re-rendered on the current screen and WHY, in one call \u2014 no test route, no scaffolding. THE tool for 'this page is slow/laggy/janky', 'typing lags', 'the whole page re-renders when I tap one button'. Give it `steps` to measure a specific interaction (tap a button, type in a field) \u2014 measuring an idle window instead tells you nothing about what taps cost, which is how re-render fixes usually go wrong. Returns per-component render COST in ms (sorted by it \u2014 a component rendering 40x for 0.4ms is noise, one rendering 4x for 38ms is the answer), the CAUSE of each (parent cascade / own state / changed props), which parent dragged it along, and which props changed. `wasted` counts renders that produced nothing new \u2014 that's the removable part. AFTER YOU EDIT, call it again with the same steps and compareToPrevious:true to prove the fix landed and didn't move the cost somewhere else. (For choosing between several implementations of a screen, use run_benchmark_batch instead \u2014 that ranks variants; this explains one screen.) Requires Buoy Pro and @buoy-gg/highlight-updates.",
|
|
4496
|
+
inputSchema: {
|
|
4497
|
+
steps: import_zod21.z.array(stepSchema2).max(20).optional().describe(
|
|
4498
|
+
"The interaction to measure, e.g. [{tap:'favorite-deal-2', repeat:5}] or [{type:'bench', into:'deals-search'}]. Omit to sample the screen idle \u2014 only useful for churn that happens with nobody touching it."
|
|
4499
|
+
),
|
|
4500
|
+
idleMs: import_zod21.z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),
|
|
4501
|
+
label: import_zod21.z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),
|
|
4502
|
+
compareToPrevious: import_zod21.z.boolean().optional().describe("Diff against the previous measure_renders on this device. Use after an edit to prove the fix."),
|
|
4503
|
+
top: import_zod21.z.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),
|
|
4504
|
+
deviceId: import_zod21.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4505
|
+
}
|
|
4506
|
+
},
|
|
4507
|
+
async (args) => {
|
|
4508
|
+
try {
|
|
4509
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4510
|
+
const device = sync.connectedDevices().find((d) => d.deviceId === target);
|
|
4511
|
+
const uiTool = (device?.tools ?? []).find((t) => t.toolId === UI_TOOL_ID2);
|
|
4512
|
+
if (!uiTool) {
|
|
4513
|
+
return fail21(
|
|
4514
|
+
"This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates."
|
|
4515
|
+
);
|
|
4516
|
+
}
|
|
4517
|
+
if (!(uiTool.actions ?? []).includes("beginMeasurement")) {
|
|
4518
|
+
return fail21(
|
|
4519
|
+
"This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route."
|
|
4520
|
+
);
|
|
4521
|
+
}
|
|
4522
|
+
const began = await sync.callAction(UI_TOOL_ID2, "beginMeasurement", {}, target);
|
|
4523
|
+
if (began && began.ok === false) {
|
|
4524
|
+
return fail21(`Can't measure renders: ${began.reason ?? "capture unavailable"}`);
|
|
4525
|
+
}
|
|
4526
|
+
await delay5(SETTLE_MS);
|
|
4527
|
+
const startedAt = Date.now();
|
|
4528
|
+
const notes = [];
|
|
4529
|
+
if (args.steps?.length) {
|
|
4530
|
+
for (const step of args.steps) {
|
|
4531
|
+
const times = step.repeat ?? 1;
|
|
4532
|
+
for (let i = 0; i < times; i++) {
|
|
4533
|
+
if (step.type !== void 0) {
|
|
4534
|
+
const sel = step.into ?? step.tap;
|
|
4535
|
+
if (!sel) {
|
|
4536
|
+
notes.push("a `type` step needs `into`");
|
|
4537
|
+
continue;
|
|
4538
|
+
}
|
|
4539
|
+
const res = await sync.callAction(
|
|
4540
|
+
UI_TOOL_ID2,
|
|
4541
|
+
"tapElement",
|
|
4542
|
+
{ ...selector2(sel), text: step.type },
|
|
4543
|
+
target
|
|
4544
|
+
);
|
|
4545
|
+
if (!res?.tapped) notes.push(res?.reason ?? `could not type into "${sel}"`);
|
|
4546
|
+
else if (res.matched?.via && res.matched.via !== "onChangeText") {
|
|
4547
|
+
notes.push(`"${sel}" is not a text input \u2014 it ran ${res.matched.via}, nothing was typed`);
|
|
4548
|
+
}
|
|
4549
|
+
} else if (step.tap) {
|
|
4550
|
+
const res = await sync.callAction(
|
|
4551
|
+
UI_TOOL_ID2,
|
|
4552
|
+
"tapElement",
|
|
4553
|
+
selector2(step.tap),
|
|
4554
|
+
target
|
|
4555
|
+
);
|
|
4556
|
+
if (!res?.tapped) notes.push(res?.reason ?? `no element matched "${step.tap}"`);
|
|
4557
|
+
}
|
|
4558
|
+
if (step.waitMs) await delay5(step.waitMs);
|
|
4559
|
+
}
|
|
4560
|
+
}
|
|
4561
|
+
await delay5(SETTLE_MS);
|
|
4562
|
+
} else {
|
|
4563
|
+
await delay5(args.idleMs ?? DEFAULT_IDLE_MS);
|
|
4564
|
+
}
|
|
4565
|
+
const windowMs = Date.now() - startedAt;
|
|
4566
|
+
const ended = await sync.callAction(UI_TOOL_ID2, "endMeasurement", {}, target);
|
|
4567
|
+
const summary = ended?.summary;
|
|
4568
|
+
if (!summary) {
|
|
4569
|
+
return fail21(
|
|
4570
|
+
"The capture window closed without returning anything. If the app reloaded mid-measurement, try again."
|
|
4571
|
+
);
|
|
4572
|
+
}
|
|
4573
|
+
const capture = {
|
|
4574
|
+
label: args.label ?? (args.steps?.length ? "interaction" : "idle"),
|
|
4575
|
+
windowMs,
|
|
4576
|
+
summary
|
|
4577
|
+
};
|
|
4578
|
+
const prev = lastCapture.get(target);
|
|
4579
|
+
lastCapture.set(target, capture);
|
|
4580
|
+
const what = args.steps?.length ? args.steps.map((s) => (s.type !== void 0 ? `type "${s.type}"` : `tap "${s.tap}"`) + (s.repeat ? ` \xD7${s.repeat}` : "")).join(", ") : `idle ${(windowMs / 1e3).toFixed(1)}s`;
|
|
4581
|
+
const parts = [`**measure_renders \u2014 ${what}**`, "", formatCapture(capture, args.top ?? DEFAULT_TOP)];
|
|
4582
|
+
if (args.compareToPrevious) {
|
|
4583
|
+
parts.push("", prev ? formatDelta(prev, capture) : "_No previous measurement on this device to compare against._");
|
|
4584
|
+
}
|
|
4585
|
+
if (notes.length) parts.push("", `\u26A0\uFE0F ${notes.join("; ")}`);
|
|
4586
|
+
if (summary.totalRenders === 0) {
|
|
4587
|
+
parts.push(
|
|
4588
|
+
"",
|
|
4589
|
+
"_Nothing re-rendered in this window. If you expected renders, check the app is on the screen you meant and that the steps actually hit something._"
|
|
4590
|
+
);
|
|
4591
|
+
} else if (!args.compareToPrevious) {
|
|
4592
|
+
parts.push("", "_Fixed something? Call this again with the same steps and `compareToPrevious:true` to prove it landed._");
|
|
4593
|
+
}
|
|
4594
|
+
return text19(parts.join("\n"));
|
|
4595
|
+
} catch (e) {
|
|
4596
|
+
return fail21(errMsg21(e));
|
|
4597
|
+
}
|
|
4598
|
+
}
|
|
4599
|
+
);
|
|
4600
|
+
}
|
|
4601
|
+
|
|
4602
|
+
// src/verify/editWatcher.ts
|
|
4603
|
+
var import_node_fs3 = __toESM(require("fs"));
|
|
4604
|
+
var import_node_path3 = __toESM(require("path"));
|
|
4605
|
+
var WATCHED_EXT = /* @__PURE__ */ new Set([
|
|
4606
|
+
".ts",
|
|
4607
|
+
".tsx",
|
|
4608
|
+
".js",
|
|
4609
|
+
".jsx",
|
|
4610
|
+
".mjs",
|
|
4611
|
+
".cjs",
|
|
4612
|
+
".json"
|
|
4613
|
+
]);
|
|
4614
|
+
var IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
4615
|
+
"node_modules",
|
|
4616
|
+
".git",
|
|
4617
|
+
".expo",
|
|
4618
|
+
"ios",
|
|
4619
|
+
"android",
|
|
4620
|
+
"dist",
|
|
4621
|
+
"lib",
|
|
4622
|
+
"build",
|
|
4623
|
+
".next",
|
|
4624
|
+
"coverage",
|
|
4625
|
+
"__snapshots__"
|
|
4626
|
+
]);
|
|
4627
|
+
var DEBOUNCE_MS = 400;
|
|
4628
|
+
function resolveMode(raw) {
|
|
4629
|
+
const v = (raw ?? "").trim().toLowerCase();
|
|
4630
|
+
if (v === "always" || v === "never" || v === "auto") return v;
|
|
4631
|
+
return "auto";
|
|
4632
|
+
}
|
|
4633
|
+
var EditWatcher = class {
|
|
4634
|
+
constructor() {
|
|
4635
|
+
this.watcher = null;
|
|
4636
|
+
this.changed = /* @__PURE__ */ new Set();
|
|
4637
|
+
this.lastEditAt = 0;
|
|
4638
|
+
this.nudgedForCurrentBatch = false;
|
|
4639
|
+
this.mode = "auto";
|
|
4640
|
+
this.started = false;
|
|
4641
|
+
}
|
|
4642
|
+
start(rootDir, mode) {
|
|
4643
|
+
this.mode = mode;
|
|
4644
|
+
if (mode === "never" || this.started) return;
|
|
4645
|
+
this.started = true;
|
|
4646
|
+
try {
|
|
4647
|
+
this.watcher = import_node_fs3.default.watch(
|
|
4648
|
+
rootDir,
|
|
4649
|
+
{ recursive: true },
|
|
4650
|
+
(_event, filename) => {
|
|
4651
|
+
if (!filename) return;
|
|
4652
|
+
const rel2 = String(filename);
|
|
4653
|
+
if (rel2.split(import_node_path3.default.sep).some((seg) => IGNORED_DIRS.has(seg))) return;
|
|
4654
|
+
if (!WATCHED_EXT.has(import_node_path3.default.extname(rel2))) return;
|
|
4655
|
+
this.noteEdit(rel2);
|
|
4656
|
+
}
|
|
4657
|
+
);
|
|
4658
|
+
this.watcher.on("error", () => this.stop());
|
|
4659
|
+
} catch {
|
|
4660
|
+
this.stop();
|
|
4661
|
+
}
|
|
4662
|
+
}
|
|
4663
|
+
/** Record an edit. Public so the nudge policy can be tested without fs.watch. */
|
|
4664
|
+
noteEdit(rel2) {
|
|
4665
|
+
const now = Date.now();
|
|
4666
|
+
if (now - this.lastEditAt > DEBOUNCE_MS) this.nudgedForCurrentBatch = false;
|
|
4667
|
+
this.lastEditAt = now;
|
|
4668
|
+
if (this.changed.size < 50) this.changed.add(rel2);
|
|
4669
|
+
}
|
|
4670
|
+
stop() {
|
|
4671
|
+
try {
|
|
4672
|
+
this.watcher?.close();
|
|
4673
|
+
} catch {
|
|
4674
|
+
}
|
|
4675
|
+
this.watcher = null;
|
|
4676
|
+
}
|
|
4677
|
+
/** Something on the device was actually checked — the edits are accounted for. */
|
|
4678
|
+
markVerified() {
|
|
4679
|
+
this.changed.clear();
|
|
4680
|
+
this.nudgedForCurrentBatch = false;
|
|
4681
|
+
}
|
|
4682
|
+
hasUnverifiedEdits() {
|
|
4683
|
+
return this.changed.size > 0;
|
|
4684
|
+
}
|
|
4685
|
+
/**
|
|
4686
|
+
* The line to append to a tool result, or null to stay quiet.
|
|
4687
|
+
*
|
|
4688
|
+
* `auto` says it once per burst of edits, so it lands when the agent is
|
|
4689
|
+
* mid-loop and then gets out of the way. `always` repeats while anything is
|
|
4690
|
+
* unverified, for people who want the belt and braces.
|
|
4691
|
+
*/
|
|
4692
|
+
nudge() {
|
|
4693
|
+
if (this.mode === "never" || !this.hasUnverifiedEdits()) return null;
|
|
4694
|
+
if (this.mode === "auto") {
|
|
4695
|
+
if (this.nudgedForCurrentBatch) return null;
|
|
4696
|
+
this.nudgedForCurrentBatch = true;
|
|
4697
|
+
}
|
|
4698
|
+
const files = [...this.changed];
|
|
4699
|
+
const shown = files.slice(0, 3).join(", ");
|
|
4700
|
+
const more = files.length > 3 ? ` +${files.length - 3} more` : "";
|
|
4701
|
+
return `
|
|
4702
|
+
|
|
4703
|
+
---
|
|
4704
|
+
\u26A0\uFE0F **${files.length} source file${files.length === 1 ? "" : "s"} changed since anything was last checked on the device** (${shown}${more}).
|
|
4705
|
+
Before reporting this as fixed, observe it working: re-run the same interaction with \`measure_renders\` (\`compareToPrevious: true\`) or \`run_flow\`, and say what the numbers did. A fix nobody watched work is a guess \u2014 and re-render fixes in particular tend to move cost somewhere else rather than remove it.`;
|
|
4706
|
+
}
|
|
4707
|
+
};
|
|
4708
|
+
var editWatcher = new EditWatcher();
|
|
4709
|
+
|
|
3574
4710
|
// src/server.ts
|
|
3575
4711
|
var SERVER_INSTRUCTIONS = `Buoy MCP \u2014 drive Buoy dev tools running in a React Native app from your editor.
|
|
3576
4712
|
|
|
3577
4713
|
Buoy tools live inside the app and sync to a local broker; this server connects to that
|
|
3578
|
-
broker as a dashboard client.
|
|
3579
|
-
|
|
4714
|
+
broker as a dashboard client.
|
|
4715
|
+
|
|
4716
|
+
DEBUGGING A RUNNING APP? Call \`get_triage\` FIRST \u2014 one call returns the connected device,
|
|
4717
|
+
recent console errors (including [FATAL] crashes), recent network requests with statuses,
|
|
4718
|
+
persisted storage keys, and what's on screen. It replaces the usual five-call opening
|
|
4719
|
+
sequence and tells you which tool to drill into. Read runtime facts before hypothesizing
|
|
4720
|
+
from source: the app's actual state beats a guess about what the code should do.
|
|
4721
|
+
|
|
4722
|
+
Routing after triage \u2014 match the SYMPTOM to the tool:
|
|
4723
|
+
- Value wrong/stale/NaN, or broken only after an upgrade \u2192 \`get_storage includeValues:true\`
|
|
4724
|
+
(a bad persisted value is a top root cause, and it survives reinstalls of the JS).
|
|
4725
|
+
- Failed request, wrong data from the API, auth/session bug \u2192 \`get_network_requests
|
|
4726
|
+
includeBodies:true\` and read the response BODY.
|
|
4727
|
+
- Crash or redbox \u2192 \`get_console\` (fatals are captured, and still readable after the app
|
|
4728
|
+
dies), then \`get_storage\` for the state that triggered it.
|
|
4729
|
+
- Data on screen doesn't match the API \u2192 \`get_react_query\` / \`get_zustand_state\` /
|
|
4730
|
+
\`get_redux_state\` / \`get_jotai_state\` for the cache or store between them.
|
|
4731
|
+
|
|
4732
|
+
AFTER YOU EDIT, PROVE IT on the device \u2014 the most common way a fix fails is being incomplete,
|
|
4733
|
+
not being wrong. Reload (\`run_flow\` step \`{reload:true}\`, or \`reload_app\`) and re-drive EVERY
|
|
4734
|
+
screen the symptom could appear on, asserting the corrected value: a price shown in three places
|
|
4735
|
+
has to be right in all three, and a migration only counts if it survives a restart. A fix you
|
|
4736
|
+
haven't watched work is a guess.
|
|
4737
|
+
|
|
4738
|
+
Use \`list_devices\` when you need the full tool/action inventory or several devices are
|
|
4739
|
+
connected (\`get_triage\` already names the active one).
|
|
3580
4740
|
|
|
3581
4741
|
To inspect what's HAPPENING at runtime \u2014 network requests, state changes (redux/zustand/jotai),
|
|
3582
4742
|
react-query updates, storage writes, route changes, renders \u2014 use \`get_events\` with a \`sources\`
|
|
@@ -3595,15 +4755,28 @@ Need to SEE a component (verify a UI change, check styling/layout)? Use \`screen
|
|
|
3595
4755
|
a testID/name \u2014 it locates the live component on-device and returns a cropped screenshot inline.
|
|
3596
4756
|
iOS Simulator only, and only works when this MCP server runs on the same Mac as the booted Simulator.
|
|
3597
4757
|
|
|
3598
|
-
Need to DRIVE the UI
|
|
3599
|
-
|
|
3600
|
-
|
|
3601
|
-
|
|
4758
|
+
Need to DRIVE the UI? Reach for \`run_flow\` FIRST: it runs a whole scripted sequence
|
|
4759
|
+
(tap / type / set / reload / waitFor / expect) in ONE call and reports the per-step result, the
|
|
4760
|
+
final screen, and the network + console output the flow produced. Reproducing a bug and verifying
|
|
4761
|
+
a fix are one call each instead of a dozen alternating reads and taps, and a failed step reports
|
|
4762
|
+
the screen at the point it broke. Drop to \`describe_screen\` (list on-screen elements with testIDs
|
|
4763
|
+
and tap points) + \`tap_element\` only for one-off pokes or when you don't yet know what's there.
|
|
4764
|
+
|
|
4765
|
+
Screen slow / laggy / janky / stutters, typing lags, or "the whole page re-renders when I tap
|
|
4766
|
+
one thing"? Start with \`measure_renders\` \u2014 one call, no test route needed. Pass \`steps\` for the
|
|
4767
|
+
interaction you're actually asking about (a tap, some typing); an idle sample says nothing about
|
|
4768
|
+
what a tap costs. It returns per-component render counts, WHY each rendered (parent cascade / own
|
|
4769
|
+
state / changed props), which parent dragged it along, and \`wasted\` \u2014 the renders that produced
|
|
4770
|
+
nothing new. After you edit, call it again with the same steps and \`compareToPrevious:true\`:
|
|
4771
|
+
re-render fixes routinely move the cost somewhere else instead of removing it, and only a second
|
|
4772
|
+
measurement catches that.
|
|
3602
4773
|
|
|
3603
4774
|
JS FPS low / app hitching and you need to know WHAT is eating the JS thread? Use
|
|
3604
4775
|
\`get_js_thread_top\` (a live "Task Manager" of timers, Promise chains, rAF callbacks and
|
|
3605
4776
|
freezes, ranked by thread time), then \`get_js_thread_origin_detail\` to drill into a row.
|
|
3606
4777
|
Pass clearFirst:true and drive the UI with \`tap_element\` mid-sample to profile one interaction.
|
|
4778
|
+
This is about TASKS on the thread \u2014 for React components re-rendering too often, it's
|
|
4779
|
+
\`measure_renders\`, not this.
|
|
3607
4780
|
|
|
3608
4781
|
Debugging images (not loading, slow, stale cache, memory)? \`get_images\` lists every RN <Image> /
|
|
3609
4782
|
expo-image load with cache verdicts and oversize audits; \`image_action\` reloads, retries, or
|
|
@@ -3639,11 +4812,46 @@ If no device is connected, open the app with Buoy devtools running and try again
|
|
|
3639
4812
|
The Buoy MCP is a Pro feature: \`list_devices\` is always available, but data/action tools
|
|
3640
4813
|
require the connected app to have an active Buoy Pro license. If they error with "Buoy Pro
|
|
3641
4814
|
required", tell the user to upgrade to Buoy Pro in the app \u2014 don't try to work around it.`;
|
|
4815
|
+
var VERIFYING_TOOLS = /* @__PURE__ */ new Set([
|
|
4816
|
+
"measure_renders",
|
|
4817
|
+
"run_flow",
|
|
4818
|
+
"run_benchmark_batch",
|
|
4819
|
+
"get_triage",
|
|
4820
|
+
"tap_element",
|
|
4821
|
+
"describe_screen",
|
|
4822
|
+
"get_console",
|
|
4823
|
+
"get_network_requests",
|
|
4824
|
+
"get_events",
|
|
4825
|
+
"get_snapshot"
|
|
4826
|
+
]);
|
|
3642
4827
|
function createMcpServer(sync) {
|
|
3643
4828
|
const server = new import_mcp.McpServer(
|
|
3644
4829
|
{ name: "buoy", version: VERSION },
|
|
3645
4830
|
{ capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
|
|
3646
4831
|
);
|
|
4832
|
+
editWatcher.start(process.cwd(), resolveMode(process.env.BUOY_VERIFY));
|
|
4833
|
+
const originalRegister = server.registerTool.bind(server);
|
|
4834
|
+
server.registerTool = ((name, config, handler) => originalRegister(name, config, (async (...args) => {
|
|
4835
|
+
const result = await handler(...args);
|
|
4836
|
+
const errored = result?.isError === true;
|
|
4837
|
+
if (VERIFYING_TOOLS.has(name) && !errored) {
|
|
4838
|
+
editWatcher.markVerified();
|
|
4839
|
+
return result;
|
|
4840
|
+
}
|
|
4841
|
+
const note = editWatcher.nudge();
|
|
4842
|
+
if (!note) return result;
|
|
4843
|
+
const r = result;
|
|
4844
|
+
if (Array.isArray(r?.content)) {
|
|
4845
|
+
return {
|
|
4846
|
+
...r,
|
|
4847
|
+
content: [...r.content, { type: "text", text: note }]
|
|
4848
|
+
};
|
|
4849
|
+
}
|
|
4850
|
+
return result;
|
|
4851
|
+
})));
|
|
4852
|
+
registerTriageTools(server, sync);
|
|
4853
|
+
registerFlowTools(server, sync);
|
|
4854
|
+
registerRenderTools(server, sync);
|
|
3647
4855
|
registerGenericTools(server, sync);
|
|
3648
4856
|
registerPerfMonitorTools(server, sync);
|
|
3649
4857
|
registerEventsTools(server, sync);
|
|
@@ -3665,34 +4873,37 @@ function createMcpServer(sync) {
|
|
|
3665
4873
|
return server;
|
|
3666
4874
|
}
|
|
3667
4875
|
var deviceIdField = {
|
|
3668
|
-
deviceId:
|
|
4876
|
+
deviceId: import_zod22.z.string().optional().describe(
|
|
3669
4877
|
'Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.'
|
|
3670
4878
|
)
|
|
3671
4879
|
};
|
|
3672
4880
|
|
|
3673
4881
|
// src/init.ts
|
|
3674
4882
|
var import_node_child_process2 = require("child_process");
|
|
3675
|
-
var
|
|
4883
|
+
var import_node_fs4 = __toESM(require("fs"));
|
|
3676
4884
|
var import_node_os3 = __toESM(require("os"));
|
|
3677
|
-
var
|
|
4885
|
+
var import_node_path4 = __toESM(require("path"));
|
|
4886
|
+
function defaultEnv() {
|
|
4887
|
+
return { BUOY_VERIFY: "auto" };
|
|
4888
|
+
}
|
|
3678
4889
|
var PUBLIC_REGISTRY = "https://registry.npmjs.org";
|
|
3679
|
-
var
|
|
4890
|
+
var PROBE_TIMEOUT_MS3 = 3e3;
|
|
3680
4891
|
function runInit(opts = {}) {
|
|
3681
4892
|
const cwd = opts.cwd ?? process.cwd();
|
|
3682
|
-
const skillSrcDir = opts.skillSrcDir ??
|
|
4893
|
+
const skillSrcDir = opts.skillSrcDir ?? import_node_path4.default.resolve(__dirname, "../skill");
|
|
3683
4894
|
const log = opts.log ?? ((m) => process.stdout.write(m + "\n"));
|
|
3684
4895
|
const entry = resolveEntry(opts, log);
|
|
3685
4896
|
const done = [];
|
|
3686
|
-
upsertMcpConfig(
|
|
3687
|
-
if (
|
|
3688
|
-
upsertMcpConfig(
|
|
4897
|
+
upsertMcpConfig(import_node_path4.default.join(cwd, ".mcp.json"), "mcpServers", entry, cwd, done);
|
|
4898
|
+
if (import_node_fs4.default.existsSync(import_node_path4.default.join(cwd, ".cursor"))) {
|
|
4899
|
+
upsertMcpConfig(import_node_path4.default.join(cwd, ".cursor", "mcp.json"), "mcpServers", entry, cwd, done);
|
|
3689
4900
|
}
|
|
3690
|
-
if (
|
|
3691
|
-
upsertMcpConfig(
|
|
4901
|
+
if (import_node_fs4.default.existsSync(import_node_path4.default.join(cwd, ".vscode"))) {
|
|
4902
|
+
upsertMcpConfig(import_node_path4.default.join(cwd, ".vscode", "mcp.json"), "servers", entry, cwd, done);
|
|
3692
4903
|
}
|
|
3693
4904
|
installSkills(skillSrcDir, cwd, done);
|
|
3694
|
-
appendDebuggingGuide(
|
|
3695
|
-
appendDebuggingGuide(
|
|
4905
|
+
appendDebuggingGuide(import_node_path4.default.join(cwd, "CLAUDE.md"), cwd, done);
|
|
4906
|
+
appendDebuggingGuide(import_node_path4.default.join(cwd, "AGENTS.md"), cwd, done);
|
|
3696
4907
|
log("Buoy MCP installed:");
|
|
3697
4908
|
for (const line of done) log(" \u2022 " + line);
|
|
3698
4909
|
log("");
|
|
@@ -3712,7 +4923,7 @@ function runInit(opts = {}) {
|
|
|
3712
4923
|
}
|
|
3713
4924
|
function resolveEntry(opts, log) {
|
|
3714
4925
|
if (opts.cliPath) {
|
|
3715
|
-
return { type: "stdio", command: "node", args: [opts.cliPath] };
|
|
4926
|
+
return { type: "stdio", command: "node", args: [opts.cliPath], env: defaultEnv() };
|
|
3716
4927
|
}
|
|
3717
4928
|
const mode = opts.mode ?? "auto";
|
|
3718
4929
|
if (mode === "npx") {
|
|
@@ -3731,21 +4942,21 @@ function resolveEntry(opts, log) {
|
|
|
3731
4942
|
return localEntry(opts, log);
|
|
3732
4943
|
}
|
|
3733
4944
|
function npxEntry() {
|
|
3734
|
-
return { type: "stdio", command: "npx", args: ["-y", `${PACKAGE_NAME}@latest`] };
|
|
4945
|
+
return { type: "stdio", command: "npx", args: ["-y", `${PACKAGE_NAME}@latest`], env: defaultEnv() };
|
|
3735
4946
|
}
|
|
3736
4947
|
function localEntry(opts, log) {
|
|
3737
|
-
const installDir = opts.installDir ?? process.env.BUOY_MCP_HOME ??
|
|
4948
|
+
const installDir = opts.installDir ?? process.env.BUOY_MCP_HOME ?? import_node_path4.default.join(import_node_os3.default.homedir(), ".buoy-mcp");
|
|
3738
4949
|
const registry = opts.registry ?? PUBLIC_REGISTRY;
|
|
3739
4950
|
const cliPath = installLocalCopy(installDir, registry, log);
|
|
3740
4951
|
if (cliPath) {
|
|
3741
|
-
return { type: "stdio", command: "node", args: [cliPath] };
|
|
4952
|
+
return { type: "stdio", command: "node", args: [cliPath], env: defaultEnv() };
|
|
3742
4953
|
}
|
|
3743
4954
|
log("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");
|
|
3744
4955
|
return npxEntry();
|
|
3745
4956
|
}
|
|
3746
4957
|
function installLocalCopy(installDir, registry, log) {
|
|
3747
4958
|
const spec = `${PACKAGE_NAME}@${VERSION === "0.0.0-dev" ? "latest" : VERSION}`;
|
|
3748
|
-
|
|
4959
|
+
import_node_fs4.default.mkdirSync(installDir, { recursive: true });
|
|
3749
4960
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
3750
4961
|
log(`Installing ${spec} into ${installDir} from ${registry} \u2026`);
|
|
3751
4962
|
const res = (0, import_node_child_process2.spawnSync)(
|
|
@@ -3768,8 +4979,8 @@ function installLocalCopy(installDir, registry, log) {
|
|
|
3768
4979
|
log(`\u26A0 npm install exited with code ${res.status ?? "?"}${res.error ? ` (${res.error.message})` : ""}.`);
|
|
3769
4980
|
return null;
|
|
3770
4981
|
}
|
|
3771
|
-
const cliPath =
|
|
3772
|
-
if (!
|
|
4982
|
+
const cliPath = import_node_path4.default.join(installDir, "node_modules", PACKAGE_NAME, "dist", "cli.js");
|
|
4983
|
+
if (!import_node_fs4.default.existsSync(cliPath)) {
|
|
3773
4984
|
log(`\u26A0 install finished but ${cliPath} is missing.`);
|
|
3774
4985
|
return null;
|
|
3775
4986
|
}
|
|
@@ -3791,7 +5002,7 @@ function effectiveRegistry() {
|
|
|
3791
5002
|
}
|
|
3792
5003
|
function npmConfigGet(key) {
|
|
3793
5004
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
3794
|
-
const res = (0, import_node_child_process2.spawnSync)(npm, ["config", "get", key], { encoding: "utf8", timeout:
|
|
5005
|
+
const res = (0, import_node_child_process2.spawnSync)(npm, ["config", "get", key], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS3 });
|
|
3795
5006
|
if (res.status !== 0 || typeof res.stdout !== "string") return null;
|
|
3796
5007
|
const val = res.stdout.trim();
|
|
3797
5008
|
if (!val || val === "undefined" || val === "null") return null;
|
|
@@ -3800,8 +5011,8 @@ function npmConfigGet(key) {
|
|
|
3800
5011
|
function hostReachable(registry) {
|
|
3801
5012
|
const done = (0, import_node_child_process2.spawnSync)(
|
|
3802
5013
|
process.execPath,
|
|
3803
|
-
["-e", REACHABILITY_PROBE, registry, String(
|
|
3804
|
-
{ encoding: "utf8", timeout:
|
|
5014
|
+
["-e", REACHABILITY_PROBE, registry, String(PROBE_TIMEOUT_MS3)],
|
|
5015
|
+
{ encoding: "utf8", timeout: PROBE_TIMEOUT_MS3 + 2e3 }
|
|
3805
5016
|
);
|
|
3806
5017
|
return done.status === 0;
|
|
3807
5018
|
}
|
|
@@ -3821,22 +5032,22 @@ fetch(url, { method: 'HEAD', signal: c.signal })
|
|
|
3821
5032
|
`;
|
|
3822
5033
|
function upsertMcpConfig(file, key, entry, cwd, done) {
|
|
3823
5034
|
let json3 = {};
|
|
3824
|
-
if (
|
|
5035
|
+
if (import_node_fs4.default.existsSync(file)) {
|
|
3825
5036
|
try {
|
|
3826
|
-
json3 = JSON.parse(
|
|
5037
|
+
json3 = JSON.parse(import_node_fs4.default.readFileSync(file, "utf8"));
|
|
3827
5038
|
} catch {
|
|
3828
|
-
|
|
5039
|
+
import_node_fs4.default.copyFileSync(file, file + ".bak");
|
|
3829
5040
|
done.push(`existing ${rel(file, cwd)} was invalid JSON \u2014 backed up to ${rel(file, cwd)}.bak`);
|
|
3830
5041
|
json3 = {};
|
|
3831
5042
|
}
|
|
3832
5043
|
} else {
|
|
3833
|
-
|
|
5044
|
+
import_node_fs4.default.mkdirSync(import_node_path4.default.dirname(file), { recursive: true });
|
|
3834
5045
|
}
|
|
3835
5046
|
const servers = json3[key] && typeof json3[key] === "object" ? json3[key] : {};
|
|
3836
5047
|
const existed = "buoy" in servers;
|
|
3837
5048
|
servers.buoy = entry;
|
|
3838
5049
|
json3[key] = servers;
|
|
3839
|
-
|
|
5050
|
+
import_node_fs4.default.writeFileSync(file, JSON.stringify(json3, null, 2) + "\n");
|
|
3840
5051
|
done.push(`${existed ? "updated" : "added"} \`buoy\` in ${rel(file, cwd)}`);
|
|
3841
5052
|
}
|
|
3842
5053
|
var GUIDE_HEADING = "# Debugging with Buoy";
|
|
@@ -3845,6 +5056,13 @@ var DEBUGGING_GUIDE = `${GUIDE_HEADING}
|
|
|
3845
5056
|
This app's runtime is inspectable while it runs: the Buoy MCP tools read live
|
|
3846
5057
|
state straight from the device. Route by symptom before reading source:
|
|
3847
5058
|
|
|
5059
|
+
- \`get_triage\` \u2014 START HERE. One call: device, recent console errors and
|
|
5060
|
+
crashes, recent network requests, storage keys, and what's on screen. It
|
|
5061
|
+
usually names the problem, and always names the tool to drill into next.
|
|
5062
|
+
- \`run_flow\` \u2014 reproduce a bug or verify a fix in ONE call: a scripted
|
|
5063
|
+
tap/type/wait/assert sequence that returns the final screen plus the network
|
|
5064
|
+
and console output it produced. Use it instead of alternating
|
|
5065
|
+
\`describe_screen\` and \`tap_element\` a dozen times.
|
|
3848
5066
|
- \`get_events\` \u2014 the universal activity timeline (network, state changes,
|
|
3849
5067
|
storage writes, routes, renders). Check it BEFORE driving the UI to
|
|
3850
5068
|
reproduce a bug \u2014 the failure is usually already recorded.
|
|
@@ -3852,19 +5070,46 @@ state straight from the device. Route by symptom before reading source:
|
|
|
3852
5070
|
request + response bodies instead of guessing from code. Boot-time requests
|
|
3853
5071
|
are captured too.
|
|
3854
5072
|
- \`get_console\` \u2014 crashes and errors, including FATAL uncaught JS errors
|
|
3855
|
-
(tagged \`[FATAL]
|
|
5073
|
+
(tagged \`[FATAL]\`, with the component that crashed). Readable even after the
|
|
5074
|
+
app dies, so a redboxed app still tells you why.
|
|
3856
5075
|
- \`get_storage\` \u2014 data wrong or missing after an app restart \u2192 read the
|
|
3857
5076
|
persisted values FIRST.
|
|
5077
|
+
- \`reload_app\` \u2014 recover a crashed app (the other tools stop answering until
|
|
5078
|
+
you do) or pick up a change Fast Refresh missed.
|
|
3858
5079
|
- \`get_snapshot\` \u2014 full current state of any one tool when the compact views
|
|
3859
5080
|
aren't enough.
|
|
3860
5081
|
|
|
3861
|
-
Runtime facts beat guesses
|
|
5082
|
+
Runtime facts beat guesses \u2014 and after you edit, prove the fix on the device:
|
|
5083
|
+
reload, then re-drive EVERY screen the symptom could show up on and assert the
|
|
5084
|
+
corrected value. Fixes usually fail by being incomplete, not by being wrong.
|
|
5085
|
+
|
|
5086
|
+
## Don't report a fix you haven't watched work
|
|
5087
|
+
|
|
5088
|
+
Saying "fixed" is a claim about how the app behaves, so check it the same way
|
|
5089
|
+
you'd check anything else about the app \u2014 by looking at it. Re-run the exact
|
|
5090
|
+
interaction that was broken and report what the numbers did:
|
|
5091
|
+
|
|
5092
|
+
- \`measure_renders\` with the same \`steps\` and \`compareToPrevious: true\` for a
|
|
5093
|
+
performance change \u2014 it prints the before/after delta and flags a change that
|
|
5094
|
+
made things worse.
|
|
5095
|
+
- \`run_flow\` re-driving the broken screen for a behaviour change.
|
|
5096
|
+
|
|
5097
|
+
Two things this catches that reading cannot: a fix that is right but incomplete
|
|
5098
|
+
(the value was wrong in three places and you corrected one), and a fix that
|
|
5099
|
+
moved the cost instead of removing it \u2014 the usual failure mode for re-render
|
|
5100
|
+
work, where a page gets faster to type in and slower to tap.
|
|
5101
|
+
|
|
5102
|
+
If the app changed since anything was last checked, Buoy will say so in a tool
|
|
5103
|
+
result. Whether that's worth acting on is your call \u2014 a doc edit isn't worth a
|
|
5104
|
+
device check, a state-management change is. Set \`BUOY_VERIFY\` in the MCP config
|
|
5105
|
+
to \`always\` (repeat until checked) or \`never\` (silent) to change how often it
|
|
5106
|
+
mentions it.
|
|
3862
5107
|
`;
|
|
3863
5108
|
function appendDebuggingGuide(file, cwd, done) {
|
|
3864
5109
|
let existing = "";
|
|
3865
|
-
if (
|
|
5110
|
+
if (import_node_fs4.default.existsSync(file)) {
|
|
3866
5111
|
try {
|
|
3867
|
-
existing =
|
|
5112
|
+
existing = import_node_fs4.default.readFileSync(file, "utf8");
|
|
3868
5113
|
} catch {
|
|
3869
5114
|
done.push(`\u26A0 could not read ${rel(file, cwd)} \u2014 skipped the debugging guide`);
|
|
3870
5115
|
return;
|
|
@@ -3876,40 +5121,40 @@ function appendDebuggingGuide(file, cwd, done) {
|
|
|
3876
5121
|
}
|
|
3877
5122
|
const separator = existing === "" ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
|
|
3878
5123
|
try {
|
|
3879
|
-
|
|
5124
|
+
import_node_fs4.default.writeFileSync(file, existing + separator + DEBUGGING_GUIDE);
|
|
3880
5125
|
done.push(`${existing ? "appended" : "created"} "${GUIDE_HEADING}" block in ${rel(file, cwd)}`);
|
|
3881
5126
|
} catch {
|
|
3882
5127
|
done.push(`\u26A0 could not write ${rel(file, cwd)} \u2014 skipped the debugging guide`);
|
|
3883
5128
|
}
|
|
3884
5129
|
}
|
|
3885
5130
|
function installSkills(skillSrcDir, cwd, done) {
|
|
3886
|
-
if (!
|
|
5131
|
+
if (!import_node_fs4.default.existsSync(skillSrcDir)) {
|
|
3887
5132
|
done.push("\u26A0 no bundled skills found \u2014 skipped");
|
|
3888
5133
|
return;
|
|
3889
5134
|
}
|
|
3890
|
-
const skills =
|
|
5135
|
+
const skills = import_node_fs4.default.readdirSync(skillSrcDir, { withFileTypes: true }).filter((e) => e.isDirectory() && import_node_fs4.default.existsSync(import_node_path4.default.join(skillSrcDir, e.name, "SKILL.md")));
|
|
3891
5136
|
if (skills.length === 0) {
|
|
3892
5137
|
done.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");
|
|
3893
5138
|
return;
|
|
3894
5139
|
}
|
|
3895
5140
|
for (const skill of skills) {
|
|
3896
|
-
const from =
|
|
3897
|
-
const to =
|
|
5141
|
+
const from = import_node_path4.default.join(skillSrcDir, skill.name);
|
|
5142
|
+
const to = import_node_path4.default.join(cwd, ".claude", "skills", skill.name);
|
|
3898
5143
|
copyDir(from, to);
|
|
3899
|
-
done.push(`installed the ${skill.name} skill \u2192 ${rel(
|
|
5144
|
+
done.push(`installed the ${skill.name} skill \u2192 ${rel(import_node_path4.default.join(to, "SKILL.md"), cwd)}`);
|
|
3900
5145
|
}
|
|
3901
5146
|
}
|
|
3902
5147
|
function copyDir(from, to) {
|
|
3903
|
-
|
|
3904
|
-
for (const entry of
|
|
3905
|
-
const s =
|
|
3906
|
-
const d =
|
|
5148
|
+
import_node_fs4.default.mkdirSync(to, { recursive: true });
|
|
5149
|
+
for (const entry of import_node_fs4.default.readdirSync(from, { withFileTypes: true })) {
|
|
5150
|
+
const s = import_node_path4.default.join(from, entry.name);
|
|
5151
|
+
const d = import_node_path4.default.join(to, entry.name);
|
|
3907
5152
|
if (entry.isDirectory()) copyDir(s, d);
|
|
3908
|
-
else
|
|
5153
|
+
else import_node_fs4.default.copyFileSync(s, d);
|
|
3909
5154
|
}
|
|
3910
5155
|
}
|
|
3911
5156
|
function rel(file, cwd) {
|
|
3912
|
-
const r =
|
|
5157
|
+
const r = import_node_path4.default.relative(cwd, file);
|
|
3913
5158
|
return r && !r.startsWith("..") ? r : file;
|
|
3914
5159
|
}
|
|
3915
5160
|
|