@buoy-gg/mcp 7.0.20 → 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-S5NQ6EUN.mjs → chunk-5C6BLMHY.mjs} +1386 -96
- package/dist/cli.js +1386 -96
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +147 -10
- package/dist/index.d.ts +147 -10
- package/dist/index.js +1386 -96
- package/dist/index.mjs +1 -1
- package/package.json +5 -3
package/dist/index.js
CHANGED
|
@@ -72,7 +72,12 @@ var import_sync_broker = require("@buoy-gg/sync-broker");
|
|
|
72
72
|
var BROKER_PORT = import_sync_broker.DEFAULT_BROKER_PORT;
|
|
73
73
|
var BROKER_URL = `http://localhost:${BROKER_PORT}`;
|
|
74
74
|
var DEFAULT_ACTION_TIMEOUT_MS = 15e3;
|
|
75
|
+
var UNRESPONSIVE_ACTION_TIMEOUT_MS = 2500;
|
|
76
|
+
var UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS = 1200;
|
|
77
|
+
var RECOVERY_PROBE_MS = 2e4;
|
|
78
|
+
var UNRESPONSIVE_AFTER_MS = 3e4;
|
|
75
79
|
var DEFAULT_SNAPSHOT_TIMEOUT_MS = 5e3;
|
|
80
|
+
var DEVICE_RETENTION_MS = 15 * 6e4;
|
|
76
81
|
var DASHBOARD_NAME = "Dashboard";
|
|
77
82
|
var ALL_DEVICES = "All";
|
|
78
83
|
|
|
@@ -97,6 +102,16 @@ var SyncClient = class {
|
|
|
97
102
|
this.pendingActions = /* @__PURE__ */ new Map();
|
|
98
103
|
/** Callbacks waiting for the next snapshot of `${deviceId}::${toolId}`. */
|
|
99
104
|
this.snapshotWaiters = /* @__PURE__ */ new Map();
|
|
105
|
+
/** When each cached snapshot arrived, keyed by snapKey (staleness reporting). */
|
|
106
|
+
this.snapshotAt = /* @__PURE__ */ new Map();
|
|
107
|
+
/** Liveness per device — see {@link noteTimeout}. */
|
|
108
|
+
this.health = /* @__PURE__ */ new Map();
|
|
109
|
+
/** Dev-server origin per device — see {@link noteDevServerOrigin}. */
|
|
110
|
+
this.devServerOrigins = /* @__PURE__ */ new Map();
|
|
111
|
+
/** Devices whose origin probe already ran (a production bundle has none). */
|
|
112
|
+
this.originProbed = /* @__PURE__ */ new Set();
|
|
113
|
+
/** Last time each device appeared in the broker's device list. */
|
|
114
|
+
this.lastSeen = /* @__PURE__ */ new Map();
|
|
100
115
|
this.port = opts.port ?? BROKER_PORT;
|
|
101
116
|
this.url = opts.url ?? (opts.port ? `http://localhost:${opts.port}` : BROKER_URL);
|
|
102
117
|
this.actionTimeoutMs = opts.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS;
|
|
@@ -156,13 +171,19 @@ var SyncClient = class {
|
|
|
156
171
|
});
|
|
157
172
|
socket.on("devtool-capabilities", (msg) => {
|
|
158
173
|
this.capabilities.set(msg.persistentDeviceId, msg);
|
|
174
|
+
void this.learnDevServerOrigin(msg.persistentDeviceId);
|
|
159
175
|
});
|
|
160
176
|
socket.on("all-devices-update", (list) => {
|
|
161
|
-
if (Array.isArray(list))
|
|
177
|
+
if (!Array.isArray(list)) return;
|
|
178
|
+
this.devices = list;
|
|
179
|
+
const now = Date.now();
|
|
180
|
+
for (const d of list) if (d.deviceId) this.lastSeen.set(d.deviceId, now);
|
|
181
|
+
this.pruneStaleDevices();
|
|
162
182
|
});
|
|
163
183
|
socket.on("devtool-sync", (msg) => {
|
|
164
184
|
const key = snapKey(msg.persistentDeviceId, msg.toolId);
|
|
165
185
|
this.snapshots.set(key, msg.payload);
|
|
186
|
+
this.snapshotAt.set(key, Date.now());
|
|
166
187
|
const waiters = this.snapshotWaiters.get(key);
|
|
167
188
|
if (waiters && waiters.length) {
|
|
168
189
|
this.snapshotWaiters.set(key, []);
|
|
@@ -178,6 +199,37 @@ var SyncClient = class {
|
|
|
178
199
|
});
|
|
179
200
|
});
|
|
180
201
|
}
|
|
202
|
+
/**
|
|
203
|
+
* Drop everything remembered about devices that have been gone a while.
|
|
204
|
+
*
|
|
205
|
+
* Deliberately NOT on disconnect: a crashed app often drops off the broker,
|
|
206
|
+
* and its cached console snapshot is the crash evidence — throwing that away
|
|
207
|
+
* the instant it disconnects would delete the answer. But device ids change
|
|
208
|
+
* with every simulator erase and fresh dev client, and each one can hold
|
|
209
|
+
* multi-MB snapshots, so a long-lived server has to forget eventually.
|
|
210
|
+
*/
|
|
211
|
+
pruneStaleDevices() {
|
|
212
|
+
const cutoff = Date.now() - DEVICE_RETENTION_MS;
|
|
213
|
+
for (const [deviceId, seen] of this.lastSeen) {
|
|
214
|
+
if (seen > cutoff) continue;
|
|
215
|
+
if (this.devices.some((d) => d.deviceId === deviceId)) continue;
|
|
216
|
+
this.lastSeen.delete(deviceId);
|
|
217
|
+
this.capabilities.delete(deviceId);
|
|
218
|
+
this.health.delete(deviceId);
|
|
219
|
+
this.devServerOrigins.delete(deviceId);
|
|
220
|
+
this.originProbed.delete(deviceId);
|
|
221
|
+
const prefix = `${deviceId}::`;
|
|
222
|
+
for (const key of [...this.snapshots.keys()]) {
|
|
223
|
+
if (key.startsWith(prefix)) {
|
|
224
|
+
this.snapshots.delete(key);
|
|
225
|
+
this.snapshotAt.delete(key);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
for (const key of [...this.watching.keys()]) {
|
|
229
|
+
if (key.startsWith(prefix)) this.watching.delete(key);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
181
233
|
/** Disconnect and tear down a spawned broker, if any. */
|
|
182
234
|
async stop() {
|
|
183
235
|
for (const [, p] of this.pendingActions) {
|
|
@@ -185,6 +237,8 @@ var SyncClient = class {
|
|
|
185
237
|
p.reject(new Error("SyncClient stopped"));
|
|
186
238
|
}
|
|
187
239
|
this.pendingActions.clear();
|
|
240
|
+
for (const [, waiters] of this.snapshotWaiters) for (const w of waiters) w(void 0);
|
|
241
|
+
this.snapshotWaiters.clear();
|
|
188
242
|
this.socket?.close();
|
|
189
243
|
this.socket = null;
|
|
190
244
|
if (this.broker) {
|
|
@@ -228,11 +282,19 @@ var SyncClient = class {
|
|
|
228
282
|
resolveDevice(deviceId) {
|
|
229
283
|
if (deviceId) return deviceId;
|
|
230
284
|
const connected = this.connectedDevices();
|
|
231
|
-
if (connected.length === 1) return connected[0].deviceId;
|
|
232
285
|
if (connected.length === 0) {
|
|
233
286
|
throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.");
|
|
234
287
|
}
|
|
235
|
-
|
|
288
|
+
if (connected.length === 1) return connected[0].deviceId;
|
|
289
|
+
const usable = connected.filter((d) => d.tools.length > 0);
|
|
290
|
+
if (usable.length === 1) return usable[0].deviceId;
|
|
291
|
+
if (usable.length === 0) {
|
|
292
|
+
const names = connected.map((d) => d.deviceName).join(", ");
|
|
293
|
+
throw new Error(
|
|
294
|
+
`Connected devices (${names}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
const list = usable.map((d) => `${d.deviceName} (${d.deviceId})`).join(", ");
|
|
236
298
|
throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${list}`);
|
|
237
299
|
}
|
|
238
300
|
/**
|
|
@@ -257,6 +319,136 @@ var SyncClient = class {
|
|
|
257
319
|
return target;
|
|
258
320
|
}
|
|
259
321
|
// ----------------------------------------------------------------
|
|
322
|
+
// Device liveness
|
|
323
|
+
// ----------------------------------------------------------------
|
|
324
|
+
healthOf(deviceId) {
|
|
325
|
+
let h = this.health.get(deviceId);
|
|
326
|
+
if (!h) {
|
|
327
|
+
h = { consecutiveTimeouts: 0, lastOkAt: 0, lastFullBudgetAt: 0 };
|
|
328
|
+
this.health.set(deviceId, h);
|
|
329
|
+
}
|
|
330
|
+
return h;
|
|
331
|
+
}
|
|
332
|
+
/** The device answered — it's alive. */
|
|
333
|
+
noteOk(deviceId) {
|
|
334
|
+
const h = this.healthOf(deviceId);
|
|
335
|
+
h.consecutiveTimeouts = 0;
|
|
336
|
+
h.lastOkAt = Date.now();
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* The device didn't answer. A crashed app never answers again, so after the
|
|
340
|
+
* first miss we stop paying the full timeout on every subsequent call.
|
|
341
|
+
*/
|
|
342
|
+
noteTimeout(deviceId) {
|
|
343
|
+
this.healthOf(deviceId).consecutiveTimeouts += 1;
|
|
344
|
+
}
|
|
345
|
+
/** True once a device has missed a call and hasn't answered since. */
|
|
346
|
+
isUnresponsive(deviceId) {
|
|
347
|
+
return this.healthOf(deviceId).consecutiveTimeouts > 0;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Full timeout normally; a short one for a device already not answering.
|
|
351
|
+
*
|
|
352
|
+
* With one escape hatch: every RECOVERY_PROBE_MS a flagged device gets the
|
|
353
|
+
* full budget again. Without it the flag is self-sustaining — a device whose
|
|
354
|
+
* work legitimately takes longer than the short budget (a big snapshot, a
|
|
355
|
+
* slow simulator) can never answer, so it can never clear the flag, and every
|
|
356
|
+
* later reply is a confident "most likely CRASHED" about a healthy app.
|
|
357
|
+
*/
|
|
358
|
+
timeoutFor(deviceId) {
|
|
359
|
+
if (!this.isUnresponsive(deviceId)) return this.actionTimeoutMs;
|
|
360
|
+
const h = this.healthOf(deviceId);
|
|
361
|
+
if (Date.now() - h.lastFullBudgetAt > RECOVERY_PROBE_MS) {
|
|
362
|
+
h.lastFullBudgetAt = Date.now();
|
|
363
|
+
return this.actionTimeoutMs;
|
|
364
|
+
}
|
|
365
|
+
return UNRESPONSIVE_ACTION_TIMEOUT_MS;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Plain-language diagnosis for a device that isn't answering, including the
|
|
369
|
+
* app's last words if the console tool got a crash flush out in time.
|
|
370
|
+
*
|
|
371
|
+
* A silent timeout is the worst possible answer here: the app is on a redbox,
|
|
372
|
+
* the reason is already captured, and without this the caller reads "timed
|
|
373
|
+
* out" and keeps retrying the same dead device.
|
|
374
|
+
*/
|
|
375
|
+
unresponsiveNote(deviceId) {
|
|
376
|
+
const h = this.healthOf(deviceId);
|
|
377
|
+
const since = h.lastOkAt ? Math.round((Date.now() - h.lastOkAt) / 1e3) : null;
|
|
378
|
+
const crashed = h.consecutiveTimeouts >= 2 || h.lastOkAt === 0 || Date.now() - h.lastOkAt > UNRESPONSIVE_AFTER_MS;
|
|
379
|
+
const lines = [
|
|
380
|
+
`The app on "${deviceId}" is not responding (${h.consecutiveTimeouts} call${h.consecutiveTimeouts === 1 ? "" : "s"} unanswered${since != null ? `, last answered ${since}s ago` : ""}).`,
|
|
381
|
+
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."
|
|
382
|
+
];
|
|
383
|
+
const fatal = this.lastFatalFor(deviceId);
|
|
384
|
+
if (fatal) lines.push(`Last captured error: ${fatal}`);
|
|
385
|
+
lines.push(
|
|
386
|
+
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."
|
|
387
|
+
);
|
|
388
|
+
return lines.join(" ");
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* The newest error line the console tool synced for this device, if any.
|
|
392
|
+
* Reads the cached console snapshot rather than the device (which, by the
|
|
393
|
+
* time this matters, is not answering).
|
|
394
|
+
*/
|
|
395
|
+
lastFatalFor(deviceId) {
|
|
396
|
+
const snap = this.snapshots.get(snapKey(deviceId, "console"));
|
|
397
|
+
const entries = snap?.entries;
|
|
398
|
+
if (!Array.isArray(entries)) return null;
|
|
399
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
400
|
+
const e = entries[i];
|
|
401
|
+
if (e?.fatal || e?.level === "error") {
|
|
402
|
+
const msg = (e.message ?? "").split("\n")[0];
|
|
403
|
+
if (msg) return msg.length > 300 ? `${msg.slice(0, 300)}\u2026` : msg;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
/** Age of the cached snapshot for a tool, in ms (null = never received). */
|
|
409
|
+
snapshotAgeMs(toolId, deviceId) {
|
|
410
|
+
const at = this.snapshotAt.get(snapKey(deviceId, toolId));
|
|
411
|
+
return at ? Date.now() - at : null;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Remember where a device's bundle came from, reported by core's `app`
|
|
415
|
+
* adapter while the app is healthy. It is the only way to reload an app that
|
|
416
|
+
* has crashed: the in-app reload needs the React tree that the crash
|
|
417
|
+
* destroyed, but the dev server's reload is handled natively.
|
|
418
|
+
*/
|
|
419
|
+
noteDevServerOrigin(deviceId, origin) {
|
|
420
|
+
if (typeof origin === "string" && /^https?:\/\//.test(origin)) {
|
|
421
|
+
this.devServerOrigins.set(deviceId, origin);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Ask a freshly-announced device where its bundle came from, once.
|
|
426
|
+
*
|
|
427
|
+
* Deliberately eager: this is the piece of information that can ONLY be
|
|
428
|
+
* collected while the app is healthy, and is only ever needed after it has
|
|
429
|
+
* stopped answering. One cheap round-trip per device buys the ability to
|
|
430
|
+
* recover a crashed app instead of telling the caller to go do it by hand.
|
|
431
|
+
*/
|
|
432
|
+
async learnDevServerOrigin(deviceId) {
|
|
433
|
+
if (this.devServerOrigins.has(deviceId) || this.originProbed.has(deviceId)) return;
|
|
434
|
+
this.originProbed.add(deviceId);
|
|
435
|
+
const hasApp = this.capabilities.get(deviceId)?.tools?.some((t) => t.toolId === "app");
|
|
436
|
+
if (!hasApp) return;
|
|
437
|
+
try {
|
|
438
|
+
const { payload } = await this.getSnapshot("app", deviceId, { timeoutMs: 4e3, silent: true });
|
|
439
|
+
this.noteDevServerOrigin(deviceId, payload?.devServerOrigin);
|
|
440
|
+
} catch {
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/** The dev-server origin last reported by this device, if any. */
|
|
444
|
+
devServerOrigin(deviceId) {
|
|
445
|
+
const known = this.devServerOrigins.get(deviceId);
|
|
446
|
+
if (known) return known;
|
|
447
|
+
const snap = this.snapshots.get(snapKey(deviceId, "app"));
|
|
448
|
+
if (typeof snap?.devServerOrigin === "string") return snap.devServerOrigin;
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
// ----------------------------------------------------------------
|
|
260
452
|
// Watch + snapshots
|
|
261
453
|
// ----------------------------------------------------------------
|
|
262
454
|
/**
|
|
@@ -327,13 +519,36 @@ var SyncClient = class {
|
|
|
327
519
|
const target = this.resolveDevice(deviceId);
|
|
328
520
|
const key = snapKey(target, toolId);
|
|
329
521
|
this.ensureWatching(toolId, target);
|
|
330
|
-
|
|
522
|
+
let budget = opts.timeoutMs ?? DEFAULT_SNAPSHOT_TIMEOUT_MS;
|
|
523
|
+
if (opts.timeoutMs === void 0 && this.isUnresponsive(target)) {
|
|
524
|
+
const h = this.healthOf(target);
|
|
525
|
+
if (Date.now() - h.lastFullBudgetAt > RECOVERY_PROBE_MS) {
|
|
526
|
+
h.lastFullBudgetAt = Date.now();
|
|
527
|
+
} else {
|
|
528
|
+
budget = UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const next = this.waitForSnapshot(key, budget);
|
|
331
532
|
this.socket?.emit("request-devtool-state", { toolId, targetDeviceId: target });
|
|
332
533
|
const payload = await next;
|
|
333
|
-
if (payload !== void 0)
|
|
534
|
+
if (payload !== void 0) {
|
|
535
|
+
if (!opts.silent) this.noteOk(target);
|
|
536
|
+
return { deviceId: target, payload };
|
|
537
|
+
}
|
|
538
|
+
if (!opts.silent) this.noteTimeout(target);
|
|
334
539
|
const cached = this.snapshots.get(key);
|
|
335
|
-
if (cached !== void 0)
|
|
336
|
-
|
|
540
|
+
if (cached !== void 0) {
|
|
541
|
+
return { deviceId: target, payload: cached, stale: this.staleNote(toolId, target) };
|
|
542
|
+
}
|
|
543
|
+
throw new Error(
|
|
544
|
+
`Timed out waiting for "${toolId}" state from ${target} (is the tool active?). ${this.unresponsiveNote(target)}`
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
/** Header line for data served from cache because the device went quiet. */
|
|
548
|
+
staleNote(toolId, deviceId) {
|
|
549
|
+
const age = this.snapshotAgeMs(toolId, deviceId);
|
|
550
|
+
const ageText = age == null ? "an earlier sync" : `${Math.round(age / 1e3)}s ago`;
|
|
551
|
+
return `\u26A0\uFE0F Served from the last sync (${ageText}) \u2014 ${this.unresponsiveNote(deviceId)}`;
|
|
337
552
|
}
|
|
338
553
|
waitForSnapshot(key, timeoutMs) {
|
|
339
554
|
return new Promise((resolve) => {
|
|
@@ -362,11 +577,16 @@ var SyncClient = class {
|
|
|
362
577
|
const target = deviceId === ALL_DEVICES ? ALL_DEVICES : this.resolveDevice(deviceId);
|
|
363
578
|
if (!this.socket) throw new Error("SyncClient is not connected");
|
|
364
579
|
const requestId = (0, import_node_crypto.randomUUID)();
|
|
365
|
-
const timeoutMs = opts.timeoutMs ?? this.
|
|
580
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutFor(target);
|
|
366
581
|
const result = await new Promise((resolve, reject) => {
|
|
367
582
|
const timer = setTimeout(() => {
|
|
368
583
|
this.pendingActions.delete(requestId);
|
|
369
|
-
|
|
584
|
+
if (target !== ALL_DEVICES && !opts.silent) this.noteTimeout(target);
|
|
585
|
+
reject(
|
|
586
|
+
new Error(
|
|
587
|
+
`Action "${toolId}.${action}" got no answer in ${timeoutMs}ms. ` + (target === ALL_DEVICES ? "No device responded." : this.unresponsiveNote(target))
|
|
588
|
+
)
|
|
589
|
+
);
|
|
370
590
|
}, timeoutMs);
|
|
371
591
|
this.pendingActions.set(requestId, { resolve, reject, timer });
|
|
372
592
|
this.socket.emit("devtool-action", {
|
|
@@ -377,6 +597,7 @@ var SyncClient = class {
|
|
|
377
597
|
params: params ?? {}
|
|
378
598
|
});
|
|
379
599
|
});
|
|
600
|
+
if (target !== ALL_DEVICES && !opts.silent) this.noteOk(target);
|
|
380
601
|
if (!result.ok) {
|
|
381
602
|
throw new Error(result.error || `Action "${toolId}.${action}" failed on device`);
|
|
382
603
|
}
|
|
@@ -408,7 +629,7 @@ var delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
408
629
|
|
|
409
630
|
// src/server.ts
|
|
410
631
|
var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
411
|
-
var
|
|
632
|
+
var import_zod22 = require("zod");
|
|
412
633
|
|
|
413
634
|
// src/tools/generic.ts
|
|
414
635
|
var import_zod = require("zod");
|
|
@@ -419,7 +640,7 @@ var import_node_os = __toESM(require("os"));
|
|
|
419
640
|
var import_node_path = __toESM(require("path"));
|
|
420
641
|
|
|
421
642
|
// src/version.ts
|
|
422
|
-
var VERSION = "7.0.
|
|
643
|
+
var VERSION = "7.0.22" ? "7.0.22" : "0.0.0-dev";
|
|
423
644
|
var PACKAGE_NAME = "@buoy-gg/mcp";
|
|
424
645
|
|
|
425
646
|
// src/update/checkForUpdate.ts
|
|
@@ -726,6 +947,7 @@ function rankBatchFromIndex(index, batchId, casesOrder, failures = []) {
|
|
|
726
947
|
deltaUiFps: null,
|
|
727
948
|
deltaJsFps: null,
|
|
728
949
|
renderCommits: num(median?.renderCommits),
|
|
950
|
+
renderWasted: median?.renderWasted,
|
|
729
951
|
topRenderers: median?.topRenderers ?? []
|
|
730
952
|
};
|
|
731
953
|
return { ...base, flags: failed ? [] : computeFlags(base) };
|
|
@@ -816,13 +1038,18 @@ function formatRankingMarkdown(ranking) {
|
|
|
816
1038
|
);
|
|
817
1039
|
}
|
|
818
1040
|
const renderLines = ranking.rows.filter((r) => !r.failed && (r.renderCommits != null || r.topRenderers.length > 0)).map((r) => {
|
|
819
|
-
const top = r.topRenderers.map(
|
|
1041
|
+
const top = r.topRenderers.map(
|
|
1042
|
+
(t) => `${t.name} \xD7${t.renders} (${t.totalMs}ms${t.cause ? `, ${t.cause}` : ""})`
|
|
1043
|
+
).join(", ");
|
|
820
1044
|
const commits = r.renderCommits != null ? `${r.renderCommits} commits` : "";
|
|
821
|
-
|
|
1045
|
+
const wasted = r.renderWasted != null ? `${r.renderWasted} wasted` : "";
|
|
1046
|
+
return `- **${r.caseName}** \u2014 ${[commits, wasted, top].filter(Boolean).join(": ")}`;
|
|
822
1047
|
});
|
|
823
1048
|
if (renderLines.length) {
|
|
824
1049
|
lines.push("");
|
|
825
|
-
lines.push(
|
|
1050
|
+
lines.push(
|
|
1051
|
+
"**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."
|
|
1052
|
+
);
|
|
826
1053
|
lines.push(...renderLines);
|
|
827
1054
|
}
|
|
828
1055
|
lines.push("");
|
|
@@ -845,7 +1072,20 @@ function compareReportStats(a, b) {
|
|
|
845
1072
|
cpuUsage: ch(a.stats.cpuUsage, b.stats.cpuUsage),
|
|
846
1073
|
memoryUsage: ch(a.stats.memoryUsage, b.stats.memoryUsage),
|
|
847
1074
|
jsJankFrames: { a: a.stats.jsJankFrames, b: b.stats.jsJankFrames, delta: b.stats.jsJankFrames - a.stats.jsJankFrames },
|
|
848
|
-
uiJankFrames: { a: a.stats.uiJankFrames, b: b.stats.uiJankFrames, delta: b.stats.uiJankFrames - a.stats.uiJankFrames }
|
|
1075
|
+
uiJankFrames: { a: a.stats.uiJankFrames, b: b.stats.uiJankFrames, delta: b.stats.uiJankFrames - a.stats.uiJankFrames },
|
|
1076
|
+
...compareRenders(a.renders, b.renders)
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
function compareRenders(a, b) {
|
|
1080
|
+
if (!a && !b) return null;
|
|
1081
|
+
const n = (v) => v ?? 0;
|
|
1082
|
+
return {
|
|
1083
|
+
renders: {
|
|
1084
|
+
total: { a: n(a?.totalRenders), b: n(b?.totalRenders), delta: n(b?.totalRenders) - n(a?.totalRenders) },
|
|
1085
|
+
commits: { a: n(a?.totalCommits), b: n(b?.totalCommits), delta: n(b?.totalCommits) - n(a?.totalCommits) },
|
|
1086
|
+
wasted: { a: n(a?.wastedRenders), b: n(b?.wastedRenders), delta: n(b?.wastedRenders) - n(a?.wastedRenders) },
|
|
1087
|
+
causes: { a: a?.causes ?? {}, b: b?.causes ?? {} }
|
|
1088
|
+
}
|
|
849
1089
|
};
|
|
850
1090
|
}
|
|
851
1091
|
function round(n, d) {
|
|
@@ -1095,7 +1335,7 @@ ${JSON.stringify(summary, null, 2)}
|
|
|
1095
1335
|
async ({ deviceId, maxWaitMs }) => {
|
|
1096
1336
|
const log = (m) => process.stderr.write(`[buoy-mcp] ${m}
|
|
1097
1337
|
`);
|
|
1098
|
-
const
|
|
1338
|
+
const cap3 = maxWaitMs ?? 6e5;
|
|
1099
1339
|
try {
|
|
1100
1340
|
const target = sync.requireProDevice(deviceId);
|
|
1101
1341
|
const start = Date.now();
|
|
@@ -1103,7 +1343,7 @@ ${JSON.stringify(summary, null, 2)}
|
|
|
1103
1343
|
let idleStreak = 0;
|
|
1104
1344
|
let lastCount = -1;
|
|
1105
1345
|
let resolved = null;
|
|
1106
|
-
while (Date.now() - start <
|
|
1346
|
+
while (Date.now() - start < cap3) {
|
|
1107
1347
|
let snap2;
|
|
1108
1348
|
try {
|
|
1109
1349
|
snap2 = await readPerfSnapshot(sync, target);
|
|
@@ -1188,7 +1428,7 @@ ${JSON.stringify(ranking, null, 2)}
|
|
|
1188
1428
|
server.registerTool(
|
|
1189
1429
|
"compare_reports",
|
|
1190
1430
|
{
|
|
1191
|
-
description: "Compare two saved benchmark runs head-to-head
|
|
1431
|
+
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.",
|
|
1192
1432
|
inputSchema: {
|
|
1193
1433
|
reportIdA: import_zod2.z.string().describe("First (baseline) report id."),
|
|
1194
1434
|
reportIdB: import_zod2.z.string().describe("Second report id to compare against the baseline."),
|
|
@@ -1206,8 +1446,8 @@ ${JSON.stringify(ranking, null, 2)}
|
|
|
1206
1446
|
if (!b) return fail2(`Report "${reportIdB}" not found.`);
|
|
1207
1447
|
return json2(
|
|
1208
1448
|
compareReportStats(
|
|
1209
|
-
{ name: a.metadata.name, stats: a.stats },
|
|
1210
|
-
{ name: b.metadata.name, stats: b.stats }
|
|
1449
|
+
{ name: a.metadata.name, stats: a.stats, renders: a.renders },
|
|
1450
|
+
{ name: b.metadata.name, stats: b.stats, renders: b.renders }
|
|
1211
1451
|
)
|
|
1212
1452
|
);
|
|
1213
1453
|
} catch (e) {
|
|
@@ -1325,7 +1565,7 @@ function registerEventsTools(server, sync) {
|
|
|
1325
1565
|
server.registerTool(
|
|
1326
1566
|
"get_events",
|
|
1327
1567
|
{
|
|
1328
|
-
description: "The UNIVERSAL, token-bounded activity reader for what's happening in the app across ALL Buoy tools. The events tool aggregates every source \u2014 network requests, redux/zustand/jotai actions, react-query query/mutation updates, storage writes, route changes, renders \u2014 so filter to one with `sources`: ['network'] lists HTTP requests, ['redux'] dispatched actions, ['react-query'] query updates, ['storage'] writes, ['route'] navigation. Returns a compact one-line summary per event (source \xB7 status \xB7 title \xB7 timing) by DEFAULT \u2014 not the heavy raw payloads \u2014 so it's cheap. Re-call with includeData:true, a bigger limit, or specific sources only when you need detail. PREFER this over get_snapshot (and over reading source code) for any 'what happened' / 'show me the requests/actions' question; get_snapshot is the raw heavy current-state escape hatch.",
|
|
1568
|
+
description: "The UNIVERSAL, token-bounded activity reader for what's happening in the app across ALL Buoy tools. Check this timeline BEFORE driving the UI to reproduce a bug \u2014 the failure is usually already recorded here. The events tool aggregates every source \u2014 network requests, redux/zustand/jotai actions, react-query query/mutation updates, storage writes, route changes, renders \u2014 so filter to one with `sources`: ['network'] lists HTTP requests, ['redux'] dispatched actions, ['react-query'] query updates, ['storage'] writes, ['route'] navigation. Returns a compact one-line summary per event (source \xB7 status \xB7 title \xB7 timing) by DEFAULT \u2014 not the heavy raw payloads \u2014 so it's cheap. Re-call with includeData:true, a bigger limit, or specific sources only when you need detail. PREFER this over get_snapshot (and over reading source code) for any 'what happened' / 'show me the requests/actions' question; get_snapshot is the raw heavy current-state escape hatch.",
|
|
1329
1569
|
inputSchema: {
|
|
1330
1570
|
limit: import_zod3.z.number().optional().describe("Most-recent N events to include. Default 25."),
|
|
1331
1571
|
sources: import_zod3.z.array(import_zod3.z.string()).optional().describe('Only these sources. Coarse names accepted: "network", "redux", "react-query", "storage", "route", "render", "zustand", "jotai". Omit for all.'),
|
|
@@ -1490,7 +1730,7 @@ function registerNetworkTools(server, sync) {
|
|
|
1490
1730
|
server.registerTool(
|
|
1491
1731
|
"get_network_requests",
|
|
1492
1732
|
{
|
|
1493
|
-
description: "List captured HTTP requests WITH their request ids, plus which ones are pinned/saved. Use this (not get_events) when you need to ACT on a request \u2014 every network action is keyed by the id, and get_events does not emit ids. Compact by default: one line per request (id \xB7 status \xB7 method \xB7 path \xB7 timing \xB7 size). Set flagged:'pinned'|'saved'|'any' to read the developer's KEPT requests \u2014 those are snapshots that outlive Clear, the 500-request cap and app restarts, so treat a pinned request as 'a human flagged this as the problem'. Filter with status:'errors' to go straight to failures, or `pattern` to match a URL substring. includeBodies:true adds truncated request/response payloads (heavier).",
|
|
1733
|
+
description: "List captured HTTP requests WITH their request ids, plus which ones are pinned/saved. API data wrong or calls failing \u2192 read the actual request+response bodies here instead of guessing from code; capture starts at app launch, so boot-time requests (session bootstrap, first queries) are included. Use this (not get_events) when you need to ACT on a request \u2014 every network action is keyed by the id, and get_events does not emit ids. Compact by default: one line per request (id \xB7 status \xB7 method \xB7 path \xB7 timing \xB7 size). Set flagged:'pinned'|'saved'|'any' to read the developer's KEPT requests \u2014 those are snapshots that outlive Clear, the 500-request cap and app restarts, so treat a pinned request as 'a human flagged this as the problem'. Filter with status:'errors' to go straight to failures, or `pattern` to match a URL substring. includeBodies:true adds truncated request/response payloads (heavier).",
|
|
1494
1734
|
inputSchema: {
|
|
1495
1735
|
limit: import_zod4.z.number().optional().describe("Most-recent N requests. Default 25."),
|
|
1496
1736
|
pattern: import_zod4.z.string().optional().describe("Only requests whose URL contains this substring (case-insensitive)."),
|
|
@@ -2207,7 +2447,7 @@ function registerStorageTools(server, sync) {
|
|
|
2207
2447
|
server.registerTool(
|
|
2208
2448
|
"get_storage",
|
|
2209
2449
|
{
|
|
2210
|
-
description: "Read the app's storage keys across ALL backends: AsyncStorage, MMKV (per instance), and Expo SecureStore. Compact by DEFAULT \u2014 keys only \u2014 so it's token-cheap; pass includeValues:true for the values (truncated), or a `pattern` substring to narrow. Buoy's own internal keys are already filtered out.
|
|
2450
|
+
description: "Read the app's storage keys across ALL backends: AsyncStorage, MMKV (per instance), and Expo SecureStore. Data wrong or missing after an app restart \u2192 read the persisted values here FIRST \u2014 the bug is usually a stale, missing, or malformed stored value, and reading it beats hunting for it in code. Compact by DEFAULT \u2014 keys only \u2014 so it's token-cheap; pass includeValues:true for the values (truncated), or a `pattern` substring to narrow. Buoy's own internal keys are already filtered out.",
|
|
2211
2451
|
inputSchema: {
|
|
2212
2452
|
pattern: import_zod9.z.string().optional().describe("Only keys containing this substring (case-insensitive)."),
|
|
2213
2453
|
includeValues: import_zod9.z.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),
|
|
@@ -2220,13 +2460,13 @@ function registerStorageTools(server, sync) {
|
|
|
2220
2460
|
const target = sync.requireProDevice(args.deviceId);
|
|
2221
2461
|
const pattern = args.pattern?.toLowerCase();
|
|
2222
2462
|
const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 100;
|
|
2223
|
-
const
|
|
2463
|
+
const matches2 = (k) => !pattern || k.toLowerCase().includes(pattern);
|
|
2224
2464
|
const sections = [];
|
|
2225
2465
|
const allKeys = await sync.callAction(STORAGE_TOOL_ID, "async.getAllKeys", {}, target);
|
|
2226
2466
|
if (!Array.isArray(allKeys)) {
|
|
2227
2467
|
return fail9("No storage result from the device. The storage tool may be inactive.");
|
|
2228
2468
|
}
|
|
2229
|
-
const asyncKeys = allKeys.filter(
|
|
2469
|
+
const asyncKeys = allKeys.filter(matches2).slice(0, limit);
|
|
2230
2470
|
if (asyncKeys.length > 0) {
|
|
2231
2471
|
let lines;
|
|
2232
2472
|
if (args.includeValues) {
|
|
@@ -2241,7 +2481,7 @@ ${lines.join("\n")}`);
|
|
|
2241
2481
|
}
|
|
2242
2482
|
const mmkv = await sync.callAction(STORAGE_TOOL_ID, "mmkv.snapshot", {}, target).catch(() => null);
|
|
2243
2483
|
for (const inst of mmkv ?? []) {
|
|
2244
|
-
const entries = inst.entries.filter((e) =>
|
|
2484
|
+
const entries = inst.entries.filter((e) => matches2(e.key)).slice(0, limit);
|
|
2245
2485
|
if (entries.length === 0) continue;
|
|
2246
2486
|
const lines = entries.map(
|
|
2247
2487
|
(e) => args.includeValues ? `- \`${e.key}\` (${e.valueType}) = ${truncate2(e.value)}` : `- \`${e.key}\``
|
|
@@ -2251,7 +2491,7 @@ ${lines.join("\n")}`);
|
|
|
2251
2491
|
${lines.join("\n")}`);
|
|
2252
2492
|
}
|
|
2253
2493
|
const secure = await sync.callAction(STORAGE_TOOL_ID, "secure.keys", {}, target).catch(() => null);
|
|
2254
|
-
const secureKeys = (secure ?? []).filter((d) =>
|
|
2494
|
+
const secureKeys = (secure ?? []).filter((d) => matches2(d.key)).slice(0, limit);
|
|
2255
2495
|
if (secureKeys.length > 0) {
|
|
2256
2496
|
const lines = await Promise.all(
|
|
2257
2497
|
secureKeys.map(async (d) => {
|
|
@@ -2408,7 +2648,7 @@ function registerConsoleTools(server, sync) {
|
|
|
2408
2648
|
server.registerTool(
|
|
2409
2649
|
"get_console",
|
|
2410
2650
|
{
|
|
2411
|
-
description: "Read the app's captured console logs (console.log/warn/error/\u2026) as a compact tail \u2014 time \xB7 level \xB7 message. Token-cheap (uses each entry's pre-rendered message, not raw args). Filter by minimum level (e.g. level:'warning' for warnings+errors) or a message substring.
|
|
2651
|
+
description: "Read the app's captured console logs (console.log/warn/error/\u2026) as a compact tail \u2014 time \xB7 level \xB7 message. App crashing or erroring \u2192 read this FIRST: it captures crashes and errors including FATAL uncaught JS errors (tagged [FATAL], hooked from RN's global error handler), so a dead app's last words are here, not in the code. Token-cheap (uses each entry's pre-rendered message, not raw args). Filter by minimum level (e.g. level:'warning' for warnings+errors) or a message substring. For full args/stack of an entry, fall back to get_snapshot('console').",
|
|
2412
2652
|
inputSchema: {
|
|
2413
2653
|
level: import_zod11.z.enum(["verbose", "info", "warning", "error"]).optional().describe("Minimum level to include (severity threshold). e.g. 'warning' = warnings + errors. Default all."),
|
|
2414
2654
|
limit: import_zod11.z.number().optional().describe("Most-recent N entries. Default 50."),
|
|
@@ -2419,7 +2659,10 @@ function registerConsoleTools(server, sync) {
|
|
|
2419
2659
|
async (args) => {
|
|
2420
2660
|
try {
|
|
2421
2661
|
const target = sync.requireProDevice(args.deviceId);
|
|
2422
|
-
const { payload } = await sync.getSnapshot(CONSOLE_TOOL_ID, target);
|
|
2662
|
+
const { payload, stale } = await sync.getSnapshot(CONSOLE_TOOL_ID, target);
|
|
2663
|
+
const staleHeader = stale ? `${stale}
|
|
2664
|
+
|
|
2665
|
+
` : "";
|
|
2423
2666
|
const p = Array.isArray(payload) ? { entries: payload } : payload ?? {};
|
|
2424
2667
|
const all = Array.isArray(p.entries) ? p.entries : [];
|
|
2425
2668
|
const minSev = args.level ? SEVERITY[args.level] : 0;
|
|
@@ -2431,12 +2674,12 @@ function registerConsoleTools(server, sync) {
|
|
|
2431
2674
|
const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 50;
|
|
2432
2675
|
const shown = sorted.slice(-limit);
|
|
2433
2676
|
if (shown.length === 0) {
|
|
2434
|
-
return text10(
|
|
2677
|
+
return text10(`${staleHeader}No console entries${args.level ? ` at level \u2265 ${args.level}` : ""}${pattern ? ` matching "${args.pattern}"` : ""} (${all.length} total captured).`);
|
|
2435
2678
|
}
|
|
2436
2679
|
const lines = shown.map((e) => `${hhmmss(e.timestamp)} [${TAG[e.level] ?? e.level}] ${e.message}`);
|
|
2437
2680
|
const levelNote = args.level ? `, level \u2265 ${args.level}` : "";
|
|
2438
2681
|
const header = `**Console \u2014 ${all.length} entries (showing ${shown.length}${levelNote}):**`;
|
|
2439
|
-
return text10(`${header}
|
|
2682
|
+
return text10(`${staleHeader}${header}
|
|
2440
2683
|
|
|
2441
2684
|
\`\`\`
|
|
2442
2685
|
${lines.join("\n")}
|
|
@@ -2460,13 +2703,19 @@ function kb(bytes) {
|
|
|
2460
2703
|
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
|
2461
2704
|
}
|
|
2462
2705
|
function formatOutcome(outcome) {
|
|
2463
|
-
const lines = Object.entries(outcome.results).map(([sid,
|
|
2464
|
-
const skips =
|
|
2706
|
+
const lines = Object.entries(outcome.results).map(([sid, r2]) => {
|
|
2707
|
+
const skips = r2.skipped.slice(0, 3).map((s) => `
|
|
2465
2708
|
\xB7 ${s.id}: ${s.reason}`).join("");
|
|
2466
|
-
const warns =
|
|
2709
|
+
const warns = r2.warnings.slice(0, 3).map((w) => `
|
|
2467
2710
|
\u26A0 ${w}`).join("");
|
|
2468
|
-
return ` ${
|
|
2711
|
+
return ` ${r2.ok ? "\u2713" : "\u2715"} ${sid} \u2014 applied ${r2.applied}${r2.skipped.length ? `, skipped ${r2.skipped.length}` : ""}${skips}${warns}`;
|
|
2469
2712
|
});
|
|
2713
|
+
const r = outcome.route;
|
|
2714
|
+
if (r) {
|
|
2715
|
+
lines.push(
|
|
2716
|
+
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}`
|
|
2717
|
+
);
|
|
2718
|
+
}
|
|
2470
2719
|
return `Restored "${outcome.snapshotName}" (${outcome.mode}${outcome.willReload ? ", app reloading" : ""}):
|
|
2471
2720
|
${lines.join("\n")}`;
|
|
2472
2721
|
}
|
|
@@ -2474,7 +2723,7 @@ function registerTimeMachineTools(server, sync) {
|
|
|
2474
2723
|
server.registerTool(
|
|
2475
2724
|
"get_time_machine",
|
|
2476
2725
|
{
|
|
2477
|
-
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.",
|
|
2726
|
+
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.",
|
|
2478
2727
|
inputSchema: {
|
|
2479
2728
|
deviceId: import_zod12.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
2480
2729
|
}
|
|
@@ -2487,13 +2736,19 @@ function registerTimeMachineTools(server, sync) {
|
|
|
2487
2736
|
const snapshots = p.snapshots ?? [];
|
|
2488
2737
|
const providers = p.providers ?? [];
|
|
2489
2738
|
const providerLines = providers.map((pr) => {
|
|
2490
|
-
const
|
|
2491
|
-
return `- ${pr.label} (${pr.id}): ${
|
|
2739
|
+
const cap3 = pr.canCapture ? pr.canRestore ? "capture+restore" : "capture only" : "unavailable";
|
|
2740
|
+
return `- ${pr.label} (${pr.id}): ${cap3}${pr.detail ? ` \u2014 ${pr.detail}` : ""}`;
|
|
2492
2741
|
});
|
|
2742
|
+
if (p.route) {
|
|
2743
|
+
providerLines.push(
|
|
2744
|
+
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"
|
|
2745
|
+
);
|
|
2746
|
+
}
|
|
2493
2747
|
const snapLines = snapshots.map((s) => {
|
|
2494
2748
|
const warnings = Object.values(s.sources).reduce((n, src) => n + src.warnings.length, 0);
|
|
2495
2749
|
const desc = s.baseline ? "baseline \u2014 restore wipes to fresh install (always reloads)" : `${kb(s.sizeBytes)} \xB7 ${Object.keys(s.sources).join(", ")}`;
|
|
2496
|
-
|
|
2750
|
+
const route = s.route ? ` \xB7 route ${s.route.href}` : "";
|
|
2751
|
+
return `- \`${s.id}\` **${s.name}** \u2014 ${new Date(s.createdAt).toISOString()} \xB7 ${desc}${route}${warnings ? ` \xB7 \u26A0 ${warnings}` : ""}`;
|
|
2497
2752
|
});
|
|
2498
2753
|
const parts = [
|
|
2499
2754
|
`**Time Machine \u2014 ${snapshots.length} snapshot(s):**`,
|
|
@@ -2512,13 +2767,14 @@ ${formatOutcome(p.lastOutcome)}`);
|
|
|
2512
2767
|
server.registerTool(
|
|
2513
2768
|
"time_machine_action",
|
|
2514
2769
|
{
|
|
2515
|
-
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.",
|
|
2770
|
+
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.",
|
|
2516
2771
|
inputSchema: {
|
|
2517
2772
|
action: import_zod12.z.enum(["capture", "capture_baseline", "preview", "restore", "delete", "rename"]).describe("What to do."),
|
|
2518
2773
|
id: import_zod12.z.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),
|
|
2519
2774
|
name: import_zod12.z.string().optional().describe("Snapshot name (for capture and rename)."),
|
|
2520
2775
|
mode: import_zod12.z.enum(["live", "reload"]).optional().describe("Restore mode. Default 'live'."),
|
|
2521
2776
|
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").'),
|
|
2777
|
+
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."),
|
|
2522
2778
|
sourceIds: import_zod12.z.array(import_zod12.z.string()).optional().describe("Capture/restore only these source ids (default all)."),
|
|
2523
2779
|
deviceId: import_zod12.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
2524
2780
|
}
|
|
@@ -2567,7 +2823,8 @@ ${lines.join("\n")}`);
|
|
|
2567
2823
|
const outcome = await call("restore", {
|
|
2568
2824
|
id: args.id,
|
|
2569
2825
|
mode: args.mode ?? "live",
|
|
2570
|
-
excludeKeys: args.excludeKeys
|
|
2826
|
+
excludeKeys: args.excludeKeys,
|
|
2827
|
+
restoreRoute: args.restoreRoute
|
|
2571
2828
|
});
|
|
2572
2829
|
return text11(formatOutcome(outcome));
|
|
2573
2830
|
}
|
|
@@ -2785,11 +3042,14 @@ function formatElement(e) {
|
|
|
2785
3042
|
if (e.nativeTag != null) line += ` #${e.nativeTag}`;
|
|
2786
3043
|
return line;
|
|
2787
3044
|
}
|
|
3045
|
+
var tapCount = 0;
|
|
3046
|
+
var FLOW_TIP_EVERY = 3;
|
|
3047
|
+
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.";
|
|
2788
3048
|
function registerInteractTools(server, sync) {
|
|
2789
3049
|
server.registerTool(
|
|
2790
3050
|
"describe_screen",
|
|
2791
3051
|
{
|
|
2792
|
-
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.",
|
|
3052
|
+
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.",
|
|
2793
3053
|
inputSchema: {
|
|
2794
3054
|
interactiveOnly: import_zod14.z.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),
|
|
2795
3055
|
deviceId: import_zod14.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
@@ -2818,7 +3078,7 @@ ${elements.map(formatElement).join("\n")}`);
|
|
|
2818
3078
|
server.registerTool(
|
|
2819
3079
|
"tap_element",
|
|
2820
3080
|
{
|
|
2821
|
-
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.",
|
|
3081
|
+
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.",
|
|
2822
3082
|
inputSchema: {
|
|
2823
3083
|
nativeTag: import_zod14.z.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),
|
|
2824
3084
|
testID: import_zod14.z.string().optional().describe("Exact testID of the element."),
|
|
@@ -2850,13 +3110,15 @@ ${elements.map(formatElement).join("\n")}`);
|
|
|
2850
3110
|
},
|
|
2851
3111
|
target
|
|
2852
3112
|
);
|
|
3113
|
+
tapCount += 1;
|
|
3114
|
+
const flowTip = tapCount >= FLOW_TIP_EVERY && tapCount % FLOW_TIP_EVERY === 0 ? FLOW_TIP : "";
|
|
2853
3115
|
if (res?.tapped && res.matched) {
|
|
2854
3116
|
const m = res.matched;
|
|
2855
3117
|
const label = m.text ?? m.label ?? m.name;
|
|
2856
3118
|
const id = m.testID ? ` [testID=${m.testID}]` : m.nativeTag != null ? ` #${m.nativeTag}` : "";
|
|
2857
3119
|
const scrolledNote = res.scrolled ? " (scrolled into view)" : "";
|
|
2858
3120
|
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}`;
|
|
2859
|
-
return text12(`${verb}${scrolledNote}
|
|
3121
|
+
return text12(`${verb}${scrolledNote}.${flowTip}`);
|
|
2860
3122
|
}
|
|
2861
3123
|
let msg = res?.reason ?? "Tap failed.";
|
|
2862
3124
|
if (res?.candidates?.length) {
|
|
@@ -2944,7 +3206,7 @@ function registerJsThreadTools(server, sync) {
|
|
|
2944
3206
|
server.registerTool(
|
|
2945
3207
|
"get_js_thread_top",
|
|
2946
3208
|
{
|
|
2947
|
-
description:
|
|
3209
|
+
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.',
|
|
2948
3210
|
inputSchema: {
|
|
2949
3211
|
deviceId: import_zod15.z.string().optional().describe("Target device id (auto-selected if one is connected)."),
|
|
2950
3212
|
durationMs: import_zod15.z.number().optional().describe("How long to sample before reading the table. Default 3000, max 30000."),
|
|
@@ -3524,6 +3786,62 @@ ${JSON.stringify(slim)}
|
|
|
3524
3786
|
|
|
3525
3787
|
// src/tools/packs/reload.ts
|
|
3526
3788
|
var import_zod18 = require("zod");
|
|
3789
|
+
|
|
3790
|
+
// src/capture/devServerReload.ts
|
|
3791
|
+
var import_ws = require("ws");
|
|
3792
|
+
var CONNECT_TIMEOUT_MS = 3e3;
|
|
3793
|
+
function messageSocketUrl(origin) {
|
|
3794
|
+
return `${origin.replace(/^http/, "ws").replace(/\/+$/, "")}/message`;
|
|
3795
|
+
}
|
|
3796
|
+
function reloadViaDevServer(origin) {
|
|
3797
|
+
return new Promise((resolve) => {
|
|
3798
|
+
let settled = false;
|
|
3799
|
+
const done = (result) => {
|
|
3800
|
+
if (settled) return;
|
|
3801
|
+
settled = true;
|
|
3802
|
+
resolve(result);
|
|
3803
|
+
};
|
|
3804
|
+
let socket;
|
|
3805
|
+
try {
|
|
3806
|
+
socket = new import_ws.WebSocket(messageSocketUrl(origin));
|
|
3807
|
+
} catch (e) {
|
|
3808
|
+
done({ ok: false, error: e.message });
|
|
3809
|
+
return;
|
|
3810
|
+
}
|
|
3811
|
+
const timer = setTimeout(() => {
|
|
3812
|
+
try {
|
|
3813
|
+
socket.close();
|
|
3814
|
+
} catch {
|
|
3815
|
+
}
|
|
3816
|
+
done({ ok: false, error: `dev server at ${origin} did not accept a connection` });
|
|
3817
|
+
}, CONNECT_TIMEOUT_MS);
|
|
3818
|
+
let sent = false;
|
|
3819
|
+
socket.on("open", () => {
|
|
3820
|
+
try {
|
|
3821
|
+
socket.send(JSON.stringify({ version: 2, method: "reload" }));
|
|
3822
|
+
sent = true;
|
|
3823
|
+
clearTimeout(timer);
|
|
3824
|
+
setTimeout(() => {
|
|
3825
|
+
try {
|
|
3826
|
+
socket.close();
|
|
3827
|
+
} catch {
|
|
3828
|
+
}
|
|
3829
|
+
done({ ok: true });
|
|
3830
|
+
}, 250);
|
|
3831
|
+
} catch (e) {
|
|
3832
|
+
clearTimeout(timer);
|
|
3833
|
+
done({ ok: false, error: e.message });
|
|
3834
|
+
}
|
|
3835
|
+
});
|
|
3836
|
+
socket.on("error", (e) => {
|
|
3837
|
+
clearTimeout(timer);
|
|
3838
|
+
if (sent) return;
|
|
3839
|
+
done({ ok: false, error: e.message });
|
|
3840
|
+
});
|
|
3841
|
+
});
|
|
3842
|
+
}
|
|
3843
|
+
|
|
3844
|
+
// src/tools/packs/reload.ts
|
|
3527
3845
|
var APP_TOOL_ID = "app";
|
|
3528
3846
|
var RELOAD_ACTION = "reloadApp";
|
|
3529
3847
|
var DEFAULT_WAIT_MS = 3e4;
|
|
@@ -3536,7 +3854,11 @@ var errMsg18 = (e) => e instanceof Error ? e.message : String(e);
|
|
|
3536
3854
|
var delay3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3537
3855
|
async function ping(sync, deviceId, timeoutMs) {
|
|
3538
3856
|
try {
|
|
3539
|
-
const pong = await sync.callAction(APP_TOOL_ID, "ping", {}, deviceId, {
|
|
3857
|
+
const pong = await sync.callAction(APP_TOOL_ID, "ping", {}, deviceId, {
|
|
3858
|
+
timeoutMs,
|
|
3859
|
+
silent: true
|
|
3860
|
+
});
|
|
3861
|
+
sync.noteDevServerOrigin(deviceId, pong?.devServerOrigin);
|
|
3540
3862
|
return typeof pong?.startedAt === "number" ? pong.startedAt : null;
|
|
3541
3863
|
} catch {
|
|
3542
3864
|
return null;
|
|
@@ -3565,7 +3887,7 @@ function registerReloadTools(server, sync) {
|
|
|
3565
3887
|
server.registerTool(
|
|
3566
3888
|
"reload_app",
|
|
3567
3889
|
{
|
|
3568
|
-
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,
|
|
3890
|
+
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.",
|
|
3569
3891
|
inputSchema: {
|
|
3570
3892
|
strategy: import_zod18.z.enum(["auto", "dev-settings", "expo-updates"]).optional().describe(
|
|
3571
3893
|
"Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."
|
|
@@ -3580,13 +3902,27 @@ function registerReloadTools(server, sync) {
|
|
|
3580
3902
|
const target = sync.requireProDevice(args.deviceId);
|
|
3581
3903
|
assertReloadSupported(sync, target);
|
|
3582
3904
|
const previousRealm = args.wait === false ? null : await ping(sync, target, PROBE_TIMEOUT_MS);
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3905
|
+
let ack = null;
|
|
3906
|
+
let recovered = false;
|
|
3907
|
+
try {
|
|
3908
|
+
ack = await sync.callAction(
|
|
3909
|
+
APP_TOOL_ID,
|
|
3910
|
+
RELOAD_ACTION,
|
|
3911
|
+
{ strategy: args.strategy ?? "auto" },
|
|
3912
|
+
target
|
|
3913
|
+
);
|
|
3914
|
+
} catch (inAppError) {
|
|
3915
|
+
const origin = sync.devServerOrigin(target);
|
|
3916
|
+
if (!origin) throw inAppError;
|
|
3917
|
+
const res = await reloadViaDevServer(origin);
|
|
3918
|
+
if (!res.ok) {
|
|
3919
|
+
throw new Error(
|
|
3920
|
+
`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.`
|
|
3921
|
+
);
|
|
3922
|
+
}
|
|
3923
|
+
recovered = true;
|
|
3924
|
+
}
|
|
3925
|
+
const via = recovered ? ` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)` : ack?.strategy ? ` via ${ack.strategy}` : "";
|
|
3590
3926
|
if (args.wait === false) {
|
|
3591
3927
|
return text16(`Reload requested${via}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`);
|
|
3592
3928
|
}
|
|
@@ -3606,12 +3942,836 @@ function registerReloadTools(server, sync) {
|
|
|
3606
3942
|
);
|
|
3607
3943
|
}
|
|
3608
3944
|
|
|
3945
|
+
// src/tools/packs/triage.ts
|
|
3946
|
+
var import_zod19 = require("zod");
|
|
3947
|
+
var text17 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
3948
|
+
var fail19 = (message) => ({
|
|
3949
|
+
isError: true,
|
|
3950
|
+
content: [{ type: "text", text: message }]
|
|
3951
|
+
});
|
|
3952
|
+
var errMsg19 = (e) => e instanceof Error ? e.message : String(e);
|
|
3953
|
+
var PROBE_TIMEOUT_MS2 = 5e3;
|
|
3954
|
+
var MAX_STORAGE_KEYS = 20;
|
|
3955
|
+
var MAX_STORAGE_VALUE = 400;
|
|
3956
|
+
var STORAGE_VALUE_BUDGET = 1600;
|
|
3957
|
+
var MAX_LINE = 160;
|
|
3958
|
+
var cap = (s, n = MAX_LINE) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
3959
|
+
function hhmmss2(ts) {
|
|
3960
|
+
if (!ts) return "--:--:--";
|
|
3961
|
+
const d = new Date(ts);
|
|
3962
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
3963
|
+
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
3964
|
+
}
|
|
3965
|
+
async function otherBackends(sync, target, opts) {
|
|
3966
|
+
const notes = [];
|
|
3967
|
+
try {
|
|
3968
|
+
const mmkv = await sync.callAction("storage", "mmkv.snapshot", {}, target, opts);
|
|
3969
|
+
for (const inst of mmkv ?? []) {
|
|
3970
|
+
const n = inst.entries?.length ?? 0;
|
|
3971
|
+
if (n > 0) notes.push(`MMKV "${inst.id}": ${n} key${n === 1 ? "" : "s"}`);
|
|
3972
|
+
}
|
|
3973
|
+
} catch {
|
|
3974
|
+
}
|
|
3975
|
+
try {
|
|
3976
|
+
const secure = await sync.callAction("storage", "secure.keys", {}, target, opts);
|
|
3977
|
+
if (secure?.length) notes.push(`SecureStore: ${secure.length} key${secure.length === 1 ? "" : "s"}`);
|
|
3978
|
+
} catch {
|
|
3979
|
+
}
|
|
3980
|
+
return notes.length ? `
|
|
3981
|
+
${notes.join(" \xB7 ")} \u2014 read with get_storage` : "";
|
|
3982
|
+
}
|
|
3983
|
+
async function section(title, run) {
|
|
3984
|
+
try {
|
|
3985
|
+
const body = await run();
|
|
3986
|
+
return body ? `${title}
|
|
3987
|
+
${body}` : null;
|
|
3988
|
+
} catch (e) {
|
|
3989
|
+
const msg = errMsg19(e);
|
|
3990
|
+
if (/not responding|timed out|got no answer/i.test(msg)) {
|
|
3991
|
+
return `${title}
|
|
3992
|
+
(no answer \u2014 see the note above)`;
|
|
3993
|
+
}
|
|
3994
|
+
return `${title}
|
|
3995
|
+
(unavailable: ${cap(msg, 120)})`;
|
|
3996
|
+
}
|
|
3997
|
+
}
|
|
3998
|
+
function registerTriageTools(server, sync) {
|
|
3999
|
+
server.registerTool(
|
|
4000
|
+
"get_triage",
|
|
4001
|
+
{
|
|
4002
|
+
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.",
|
|
4003
|
+
inputSchema: {
|
|
4004
|
+
deviceId: import_zod19.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4005
|
+
}
|
|
4006
|
+
},
|
|
4007
|
+
async (args) => {
|
|
4008
|
+
try {
|
|
4009
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4010
|
+
const device = sync.connectedDevices().find((d) => d.deviceId === target);
|
|
4011
|
+
const toolIds = new Set((device?.tools ?? []).map((t) => t.toolId));
|
|
4012
|
+
const head = `**${device?.deviceName ?? target}** (${device?.platform ?? "?"}, id \`${target}\`) \u2014 tools: ${[...toolIds].join(", ") || "none"}`;
|
|
4013
|
+
const opts = { timeoutMs: PROBE_TIMEOUT_MS2 };
|
|
4014
|
+
const [consoleSec, netSec, storeSec, screenSec] = await Promise.all([
|
|
4015
|
+
section("**Console \u2014 recent errors/warnings:**", async () => {
|
|
4016
|
+
if (!toolIds.has("console")) return null;
|
|
4017
|
+
const { payload } = await sync.getSnapshot("console", target, opts);
|
|
4018
|
+
const p = payload;
|
|
4019
|
+
const entries = Array.isArray(p) ? p : p?.entries ?? [];
|
|
4020
|
+
const bad = entries.filter(
|
|
4021
|
+
(e) => e.level === "error" || e.level === "warning"
|
|
4022
|
+
);
|
|
4023
|
+
const shown = bad.slice(-8);
|
|
4024
|
+
if (shown.length === 0) {
|
|
4025
|
+
return `(none \u2014 ${entries.length} entries captured)`;
|
|
4026
|
+
}
|
|
4027
|
+
return shown.map(
|
|
4028
|
+
(e) => `${hhmmss2(e.timestamp)} [${e.level === "error" ? "ERR" : "warn"}] ${cap(
|
|
4029
|
+
(e.message ?? "").split("\n").map((l) => l.trim()).filter(Boolean).slice(0, 3).join(" \u23CE "),
|
|
4030
|
+
220
|
|
4031
|
+
)}`
|
|
4032
|
+
).join("\n");
|
|
4033
|
+
}),
|
|
4034
|
+
section("**Network \u2014 recent requests:**", async () => {
|
|
4035
|
+
if (!toolIds.has("network")) return null;
|
|
4036
|
+
const { payload } = await sync.getSnapshot("network", target, opts);
|
|
4037
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4038
|
+
if (events.length === 0) return "(no requests captured yet)";
|
|
4039
|
+
const shown = events.slice(-8);
|
|
4040
|
+
return shown.map((e) => {
|
|
4041
|
+
const mark = e.error || (e.status ?? 0) >= 400 ? "\u274C" : "\u2705";
|
|
4042
|
+
const where = e.path ?? e.url ?? "?";
|
|
4043
|
+
const status = e.error ?? e.status ?? "pending";
|
|
4044
|
+
return `${mark} ${e.method ?? "GET"} ${cap(String(where), 80)} \u2192 ${status}${e.duration ? ` (${Math.round(e.duration)}ms)` : ""}`;
|
|
4045
|
+
}).join("\n");
|
|
4046
|
+
}),
|
|
4047
|
+
section("**Storage \u2014 persisted values:**", async () => {
|
|
4048
|
+
if (!toolIds.has("storage")) return null;
|
|
4049
|
+
const keys = await sync.callAction(
|
|
4050
|
+
"storage",
|
|
4051
|
+
"async.getAllKeys",
|
|
4052
|
+
{},
|
|
4053
|
+
target,
|
|
4054
|
+
opts
|
|
4055
|
+
);
|
|
4056
|
+
if (!Array.isArray(keys) || keys.length === 0) {
|
|
4057
|
+
return "(no app keys)";
|
|
4058
|
+
}
|
|
4059
|
+
const head2 = keys.slice(0, MAX_STORAGE_KEYS);
|
|
4060
|
+
let pairs = [];
|
|
4061
|
+
try {
|
|
4062
|
+
pairs = await sync.callAction(
|
|
4063
|
+
"storage",
|
|
4064
|
+
"async.multiGet",
|
|
4065
|
+
{ keys: head2 },
|
|
4066
|
+
target,
|
|
4067
|
+
opts
|
|
4068
|
+
) ?? [];
|
|
4069
|
+
} catch {
|
|
4070
|
+
return `${head2.map((k) => `\`${k}\``).join(", ")}
|
|
4071
|
+
_Values: get_storage includeValues:true_`;
|
|
4072
|
+
}
|
|
4073
|
+
const byKey = new Map(pairs);
|
|
4074
|
+
let budget = STORAGE_VALUE_BUDGET;
|
|
4075
|
+
const lines = head2.map((k) => {
|
|
4076
|
+
const v = byKey.get(k);
|
|
4077
|
+
if (v == null) return `- \`${k}\` = (null)`;
|
|
4078
|
+
if (v.length > MAX_STORAGE_VALUE) {
|
|
4079
|
+
return `- \`${k}\` = (${(v.length / 1024).toFixed(1)} KB \u2014 read with get_storage)`;
|
|
4080
|
+
}
|
|
4081
|
+
if (budget <= 0) return `- \`${k}\` = (not shown \u2014 triage budget spent; read with get_storage)`;
|
|
4082
|
+
budget -= v.length;
|
|
4083
|
+
return `- \`${k}\` = ${v}`;
|
|
4084
|
+
});
|
|
4085
|
+
const more = keys.length - head2.length;
|
|
4086
|
+
const others = await otherBackends(sync, target, opts);
|
|
4087
|
+
return `${lines.join("\n")}${more > 0 ? `
|
|
4088
|
+
\u2026+${more} more keys` : ""}${others}`;
|
|
4089
|
+
}),
|
|
4090
|
+
section("**Screen \u2014 what's visible now:**", async () => {
|
|
4091
|
+
if (!toolIds.has("highlight-updates")) return null;
|
|
4092
|
+
const res = await sync.callAction(
|
|
4093
|
+
"highlight-updates",
|
|
4094
|
+
"describeScreen",
|
|
4095
|
+
{},
|
|
4096
|
+
target,
|
|
4097
|
+
opts
|
|
4098
|
+
);
|
|
4099
|
+
const els = (res?.elements ?? []).filter((e) => e.interactive);
|
|
4100
|
+
if (els.length === 0) return "(nothing interactive on screen)";
|
|
4101
|
+
return els.slice(0, 20).map(
|
|
4102
|
+
(e) => `\u2022 ${e.name}${e.text || e.label ? ` "${cap(e.text ?? e.label ?? "", 60)}"` : ""}${e.testID ? ` [testID=${e.testID}]` : ""}`
|
|
4103
|
+
).join("\n");
|
|
4104
|
+
})
|
|
4105
|
+
]);
|
|
4106
|
+
const crashed = sync.isUnresponsive(target);
|
|
4107
|
+
const banner = crashed ? `
|
|
4108
|
+
|
|
4109
|
+
\u{1F6D1} ${sync.unresponsiveNote(target)}` : "";
|
|
4110
|
+
const body = [consoleSec, netSec, storeSec, screenSec].filter(Boolean).join("\n\n");
|
|
4111
|
+
return text17(
|
|
4112
|
+
`${head}${banner}
|
|
4113
|
+
|
|
4114
|
+
${body}
|
|
4115
|
+
|
|
4116
|
+
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`
|
|
4117
|
+
);
|
|
4118
|
+
} catch (e) {
|
|
4119
|
+
return fail19(errMsg19(e));
|
|
4120
|
+
}
|
|
4121
|
+
}
|
|
4122
|
+
);
|
|
4123
|
+
}
|
|
4124
|
+
|
|
4125
|
+
// src/tools/packs/flow.ts
|
|
4126
|
+
var import_zod20 = require("zod");
|
|
4127
|
+
var UI_TOOL_ID = "highlight-updates";
|
|
4128
|
+
var APP_TOOL_ID2 = "app";
|
|
4129
|
+
var text18 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
4130
|
+
var fail20 = (message) => ({
|
|
4131
|
+
isError: true,
|
|
4132
|
+
content: [{ type: "text", text: message }]
|
|
4133
|
+
});
|
|
4134
|
+
var errMsg20 = (e) => e instanceof Error ? e.message : String(e);
|
|
4135
|
+
var delay4 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4136
|
+
var POLL_MS = 250;
|
|
4137
|
+
var DEFAULT_WAIT_MS2 = 5e3;
|
|
4138
|
+
var ASSERT_SETTLE_MS = 2e3;
|
|
4139
|
+
var TEARDOWN_GRACE_MS2 = 1200;
|
|
4140
|
+
var REALM_PROBE_MS = 1500;
|
|
4141
|
+
var MAX_FLOW_MS = 12e4;
|
|
4142
|
+
function matches(e, needle) {
|
|
4143
|
+
if (e.testID && e.testID === needle) return true;
|
|
4144
|
+
const n = needle.toLowerCase();
|
|
4145
|
+
return [e.testID, e.text, e.label, e.name].filter(Boolean).some((v) => String(v).toLowerCase().includes(n));
|
|
4146
|
+
}
|
|
4147
|
+
function formatElement2(e) {
|
|
4148
|
+
const display = e.text ?? e.label;
|
|
4149
|
+
return `${e.interactive ? "\u2022 " : " "}${e.name}${display ? ` "${display}"` : ""}${e.testID ? ` [testID=${e.testID}]` : ""}`;
|
|
4150
|
+
}
|
|
4151
|
+
var stepSchema = import_zod20.z.object({
|
|
4152
|
+
tap: import_zod20.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),
|
|
4153
|
+
longPress: import_zod20.z.boolean().optional().describe("Make `tap` a long-press instead."),
|
|
4154
|
+
type: import_zod20.z.string().optional().describe("Text to type (needs `into`)."),
|
|
4155
|
+
into: import_zod20.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),
|
|
4156
|
+
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."),
|
|
4157
|
+
reload: import_zod20.z.boolean().optional().describe("Reload the JS bundle before this step's action."),
|
|
4158
|
+
waitMs: import_zod20.z.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000)."),
|
|
4159
|
+
waitFor: import_zod20.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),
|
|
4160
|
+
waitGone: import_zod20.z.string().optional().describe("Wait until no element matches this (default 5s)."),
|
|
4161
|
+
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."),
|
|
4162
|
+
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."),
|
|
4163
|
+
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).")
|
|
4164
|
+
}).describe("One flow step. Order within a step: reload \u2192 tap/type/set \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect.");
|
|
4165
|
+
function registerFlowTools(server, sync) {
|
|
4166
|
+
server.registerTool(
|
|
4167
|
+
"run_flow",
|
|
4168
|
+
{
|
|
4169
|
+
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.",
|
|
4170
|
+
inputSchema: {
|
|
4171
|
+
steps: import_zod20.z.array(stepSchema).min(1).describe("Steps to run, in order."),
|
|
4172
|
+
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."),
|
|
4173
|
+
continueOnFailure: import_zod20.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),
|
|
4174
|
+
deviceId: import_zod20.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4175
|
+
}
|
|
4176
|
+
},
|
|
4177
|
+
async (args) => {
|
|
4178
|
+
const started = Date.now();
|
|
4179
|
+
try {
|
|
4180
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4181
|
+
const include = args.include ?? "all";
|
|
4182
|
+
const describe = async () => {
|
|
4183
|
+
const res = await sync.callAction(UI_TOOL_ID, "describeScreen", {}, target);
|
|
4184
|
+
return res?.elements ?? [];
|
|
4185
|
+
};
|
|
4186
|
+
const realmId = async () => {
|
|
4187
|
+
try {
|
|
4188
|
+
const pong = await sync.callAction(APP_TOOL_ID2, "ping", {}, target, {
|
|
4189
|
+
timeoutMs: REALM_PROBE_MS,
|
|
4190
|
+
silent: true
|
|
4191
|
+
// probes across a reload are expected to fail
|
|
4192
|
+
});
|
|
4193
|
+
return typeof pong?.startedAt === "number" ? pong.startedAt : null;
|
|
4194
|
+
} catch {
|
|
4195
|
+
return null;
|
|
4196
|
+
}
|
|
4197
|
+
};
|
|
4198
|
+
const untilNewRealm = async (previous, budgetMs) => {
|
|
4199
|
+
const t0 = Date.now();
|
|
4200
|
+
while (Date.now() - t0 < budgetMs) {
|
|
4201
|
+
const realm = await realmId();
|
|
4202
|
+
if (realm !== null && realm !== previous) return Date.now() - t0;
|
|
4203
|
+
await delay4(POLL_MS);
|
|
4204
|
+
}
|
|
4205
|
+
return null;
|
|
4206
|
+
};
|
|
4207
|
+
const beforeConsole = /* @__PURE__ */ new Set();
|
|
4208
|
+
const beforeNetwork = /* @__PURE__ */ new Set();
|
|
4209
|
+
const toolIds = new Set(
|
|
4210
|
+
(sync.connectedDevices().find((d) => d.deviceId === target)?.tools ?? []).map((t) => t.toolId)
|
|
4211
|
+
);
|
|
4212
|
+
if (include === "all") {
|
|
4213
|
+
if (toolIds.has("console")) {
|
|
4214
|
+
const { payload } = await sync.getSnapshot("console", target).catch(() => ({ payload: null }));
|
|
4215
|
+
const entries = payload?.entries ?? [];
|
|
4216
|
+
for (const e of entries) beforeConsole.add(e.id);
|
|
4217
|
+
}
|
|
4218
|
+
if (toolIds.has("network")) {
|
|
4219
|
+
const { payload } = await sync.getSnapshot("network", target).catch(() => ({ payload: null }));
|
|
4220
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4221
|
+
for (const e of events) beforeNetwork.add(e.id);
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
const until = async (predicate, budgetMs) => {
|
|
4225
|
+
const t0 = Date.now();
|
|
4226
|
+
for (; ; ) {
|
|
4227
|
+
if (Date.now() - t0 >= budgetMs || Date.now() - started > MAX_FLOW_MS) {
|
|
4228
|
+
return { ok: false, ms: Date.now() - t0 };
|
|
4229
|
+
}
|
|
4230
|
+
let els = [];
|
|
4231
|
+
try {
|
|
4232
|
+
els = await describe();
|
|
4233
|
+
} catch {
|
|
4234
|
+
}
|
|
4235
|
+
if (predicate(els)) return { ok: true, ms: Date.now() - t0 };
|
|
4236
|
+
await delay4(POLL_MS);
|
|
4237
|
+
}
|
|
4238
|
+
};
|
|
4239
|
+
const lines = [];
|
|
4240
|
+
let failedAt = null;
|
|
4241
|
+
let okCount = 0;
|
|
4242
|
+
for (let i = 0; i < args.steps.length; i++) {
|
|
4243
|
+
const step = args.steps[i];
|
|
4244
|
+
const label = `${i + 1}`;
|
|
4245
|
+
const budget = step.timeoutMs ?? DEFAULT_WAIT_MS2;
|
|
4246
|
+
if (Date.now() - started > MAX_FLOW_MS) {
|
|
4247
|
+
lines.push(`${label} \u2717 flow exceeded ${MAX_FLOW_MS / 1e3}s \u2014 stopped here`);
|
|
4248
|
+
failedAt = i;
|
|
4249
|
+
break;
|
|
4250
|
+
}
|
|
4251
|
+
const stepErrors = [];
|
|
4252
|
+
const done = [];
|
|
4253
|
+
const actionable = step.reload || step.tap || step.type !== void 0 || step.waitMs || step.waitFor || step.waitGone || step.expect || step.expectGone;
|
|
4254
|
+
if (!actionable) {
|
|
4255
|
+
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)" : ""}`);
|
|
4256
|
+
failedAt = failedAt ?? i;
|
|
4257
|
+
if (!args.continueOnFailure) break;
|
|
4258
|
+
continue;
|
|
4259
|
+
}
|
|
4260
|
+
try {
|
|
4261
|
+
if (step.reload) {
|
|
4262
|
+
const previousRealm = await realmId();
|
|
4263
|
+
await sync.callAction(APP_TOOL_ID2, "reloadApp", { strategy: "auto" }, target);
|
|
4264
|
+
await delay4(TEARDOWN_GRACE_MS2);
|
|
4265
|
+
const back = await untilNewRealm(previousRealm, Math.max(budget, 2e4));
|
|
4266
|
+
if (back == null) {
|
|
4267
|
+
stepErrors.push("app did not come back after reload");
|
|
4268
|
+
} else {
|
|
4269
|
+
done.push(`reloaded (${back}ms)`);
|
|
4270
|
+
await until((els) => els.length > 0, 1e4);
|
|
4271
|
+
}
|
|
4272
|
+
}
|
|
4273
|
+
if (step.type !== void 0) {
|
|
4274
|
+
const targetSel = step.into ?? step.tap;
|
|
4275
|
+
if (!targetSel) {
|
|
4276
|
+
stepErrors.push("`type` needs `into` (which input to type into)");
|
|
4277
|
+
} else {
|
|
4278
|
+
const res = await sync.callAction(
|
|
4279
|
+
UI_TOOL_ID,
|
|
4280
|
+
"tapElement",
|
|
4281
|
+
{ ...selector(targetSel), text: step.type },
|
|
4282
|
+
target
|
|
4283
|
+
);
|
|
4284
|
+
if (!res?.tapped) {
|
|
4285
|
+
stepErrors.push(res?.reason ?? `could not type into "${targetSel}"`);
|
|
4286
|
+
} else if (res.matched?.via && res.matched.via !== "onChangeText") {
|
|
4287
|
+
stepErrors.push(
|
|
4288
|
+
`"${targetSel}" is not a text input \u2014 it ran ${res.matched.via} instead, and the text was not entered`
|
|
4289
|
+
);
|
|
4290
|
+
} else {
|
|
4291
|
+
done.push(`typed ${JSON.stringify(step.type)} into "${targetSel}"`);
|
|
4292
|
+
}
|
|
4293
|
+
}
|
|
4294
|
+
} else if (step.tap) {
|
|
4295
|
+
const params = { ...selector(step.tap) };
|
|
4296
|
+
if (step.longPress) params.longPress = true;
|
|
4297
|
+
if (step.set !== void 0) params.value = step.set;
|
|
4298
|
+
const res = await sync.callAction(UI_TOOL_ID, "tapElement", params, target);
|
|
4299
|
+
if (!res?.tapped) {
|
|
4300
|
+
stepErrors.push(res?.reason ?? `no element matched "${step.tap}"`);
|
|
4301
|
+
} else {
|
|
4302
|
+
const m = res.matched;
|
|
4303
|
+
const what = m?.text ?? m?.label ?? m?.name ?? step.tap;
|
|
4304
|
+
if (step.set !== void 0 && m?.via && m.via !== "onValueChange") {
|
|
4305
|
+
stepErrors.push(
|
|
4306
|
+
`"${what}" is not a toggle/slider \u2014 it ran ${m.via} instead, so it was not set to ${JSON.stringify(step.set)}`
|
|
4307
|
+
);
|
|
4308
|
+
} else {
|
|
4309
|
+
done.push(
|
|
4310
|
+
step.set !== void 0 ? `set "${what}" \u2192 ${JSON.stringify(m?.value ?? step.set)}` : `${step.longPress ? "long-pressed" : "tapped"} "${what}"`
|
|
4311
|
+
);
|
|
4312
|
+
}
|
|
4313
|
+
}
|
|
4314
|
+
}
|
|
4315
|
+
if (!stepErrors.length && step.waitMs) {
|
|
4316
|
+
await delay4(step.waitMs);
|
|
4317
|
+
done.push(`waited ${step.waitMs}ms`);
|
|
4318
|
+
}
|
|
4319
|
+
if (!stepErrors.length && step.waitFor) {
|
|
4320
|
+
const r = await until((els) => els.some((e) => matches(e, step.waitFor)), budget);
|
|
4321
|
+
if (r.ok) done.push(`"${step.waitFor}" appeared (${r.ms}ms)`);
|
|
4322
|
+
else stepErrors.push(`"${step.waitFor}" never appeared within ${budget}ms`);
|
|
4323
|
+
}
|
|
4324
|
+
if (!stepErrors.length && step.waitGone) {
|
|
4325
|
+
const r = await until((els) => !els.some((e) => matches(e, step.waitGone)), budget);
|
|
4326
|
+
if (r.ok) done.push(`"${step.waitGone}" gone (${r.ms}ms)`);
|
|
4327
|
+
else stepErrors.push(`"${step.waitGone}" was still there after ${budget}ms`);
|
|
4328
|
+
}
|
|
4329
|
+
if (!stepErrors.length && step.expect) {
|
|
4330
|
+
const r = await until(
|
|
4331
|
+
(els) => els.some((e) => matches(e, step.expect)),
|
|
4332
|
+
step.timeoutMs ?? ASSERT_SETTLE_MS
|
|
4333
|
+
);
|
|
4334
|
+
if (r.ok) done.push(`"${step.expect}" is on screen`);
|
|
4335
|
+
else stepErrors.push(`expected "${step.expect}" on screen \u2014 not found`);
|
|
4336
|
+
}
|
|
4337
|
+
if (!stepErrors.length && step.expectGone) {
|
|
4338
|
+
const r = await until(
|
|
4339
|
+
(els) => !els.some((e) => matches(e, step.expectGone)),
|
|
4340
|
+
step.timeoutMs ?? ASSERT_SETTLE_MS
|
|
4341
|
+
);
|
|
4342
|
+
if (r.ok) done.push(`"${step.expectGone}" is gone`);
|
|
4343
|
+
else stepErrors.push(`expected "${step.expectGone}" to be gone \u2014 still on screen`);
|
|
4344
|
+
}
|
|
4345
|
+
} catch (e) {
|
|
4346
|
+
stepErrors.push(errMsg20(e));
|
|
4347
|
+
}
|
|
4348
|
+
if (stepErrors.length) {
|
|
4349
|
+
lines.push(`${label} \u2717 ${describeStep(step)} \u2014 ${stepErrors.join("; ")}`);
|
|
4350
|
+
failedAt = failedAt ?? i;
|
|
4351
|
+
if (!args.continueOnFailure) break;
|
|
4352
|
+
} else {
|
|
4353
|
+
okCount++;
|
|
4354
|
+
lines.push(`${label} \u2713 ${done.join(", ") || describeStep(step)}`);
|
|
4355
|
+
}
|
|
4356
|
+
}
|
|
4357
|
+
const elapsed = ((Date.now() - started) / 1e3).toFixed(1);
|
|
4358
|
+
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)**`;
|
|
4359
|
+
const parts = [header, lines.join("\n")];
|
|
4360
|
+
if (include !== "none") {
|
|
4361
|
+
try {
|
|
4362
|
+
const els = await describe();
|
|
4363
|
+
const shown = els.filter((e) => e.interactive).slice(0, 30);
|
|
4364
|
+
parts.push(
|
|
4365
|
+
`**Screen now (${shown.length} interactive of ${els.length}):**
|
|
4366
|
+
${shown.map(formatElement2).join("\n")}`
|
|
4367
|
+
);
|
|
4368
|
+
} catch (e) {
|
|
4369
|
+
parts.push(`**Screen now:** unavailable \u2014 ${cap2(errMsg20(e))}`);
|
|
4370
|
+
}
|
|
4371
|
+
}
|
|
4372
|
+
if (include === "all") {
|
|
4373
|
+
if (toolIds.has("network")) {
|
|
4374
|
+
const { payload } = await sync.getSnapshot("network", target).catch(() => ({ payload: null }));
|
|
4375
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4376
|
+
const fresh = events.filter((e) => !beforeNetwork.has(e.id)).slice(-15);
|
|
4377
|
+
if (fresh.length) {
|
|
4378
|
+
parts.push(
|
|
4379
|
+
`**Network during this flow (${fresh.length}):**
|
|
4380
|
+
` + fresh.map(
|
|
4381
|
+
(e) => `${e.error || (e.status ?? 0) >= 400 ? "\u274C" : "\u2705"} ${e.method ?? "GET"} ${e.path ?? e.url ?? "?"} \u2192 ${e.error ?? e.status ?? "pending"}`
|
|
4382
|
+
).join("\n")
|
|
4383
|
+
);
|
|
4384
|
+
}
|
|
4385
|
+
}
|
|
4386
|
+
if (toolIds.has("console")) {
|
|
4387
|
+
const { payload } = await sync.getSnapshot("console", target).catch(() => ({ payload: null }));
|
|
4388
|
+
const entries = payload?.entries ?? [];
|
|
4389
|
+
const fresh = entries.filter((e) => !beforeConsole.has(e.id) && (e.level === "error" || e.level === "warning")).slice(-10);
|
|
4390
|
+
if (fresh.length) {
|
|
4391
|
+
parts.push(
|
|
4392
|
+
`**Console during this flow (${fresh.length}):**
|
|
4393
|
+
` + fresh.map((e) => `[${e.level === "error" ? "ERR" : "warn"}] ${cap2(firstLines(e.message ?? ""), 220)}`).join("\n")
|
|
4394
|
+
);
|
|
4395
|
+
}
|
|
4396
|
+
}
|
|
4397
|
+
}
|
|
4398
|
+
return text18(parts.join("\n\n"));
|
|
4399
|
+
} catch (e) {
|
|
4400
|
+
return fail20(errMsg20(e));
|
|
4401
|
+
}
|
|
4402
|
+
}
|
|
4403
|
+
);
|
|
4404
|
+
}
|
|
4405
|
+
function selector(needle) {
|
|
4406
|
+
return /\s/.test(needle) ? { query: needle } : { testID: needle, query: needle };
|
|
4407
|
+
}
|
|
4408
|
+
function describeStep(step) {
|
|
4409
|
+
if (step.tap) return `tap "${step.tap}"`;
|
|
4410
|
+
if (step.type !== void 0) return `type into "${step.into ?? "?"}"`;
|
|
4411
|
+
if (step.reload) return "reload";
|
|
4412
|
+
if (step.waitFor) return `waitFor "${step.waitFor}"`;
|
|
4413
|
+
if (step.waitGone) return `waitGone "${step.waitGone}"`;
|
|
4414
|
+
if (step.expect) return `expect "${step.expect}"`;
|
|
4415
|
+
return "step";
|
|
4416
|
+
}
|
|
4417
|
+
var cap2 = (s, n = 160) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
4418
|
+
var firstLines = (s, n = 3) => s.split("\n").map((l) => l.trim()).filter(Boolean).slice(0, n).join(" \u23CE ");
|
|
4419
|
+
|
|
4420
|
+
// src/tools/packs/renders.ts
|
|
4421
|
+
var import_zod21 = require("zod");
|
|
4422
|
+
var UI_TOOL_ID2 = "highlight-updates";
|
|
4423
|
+
var text19 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
4424
|
+
var fail21 = (message) => ({
|
|
4425
|
+
isError: true,
|
|
4426
|
+
content: [{ type: "text", text: message }]
|
|
4427
|
+
});
|
|
4428
|
+
var errMsg21 = (e) => e instanceof Error ? e.message : String(e);
|
|
4429
|
+
var delay5 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4430
|
+
var DEFAULT_IDLE_MS = 3e3;
|
|
4431
|
+
var SETTLE_MS = 400;
|
|
4432
|
+
var DEFAULT_TOP = 12;
|
|
4433
|
+
var lastCapture = /* @__PURE__ */ new Map();
|
|
4434
|
+
var stepSchema2 = import_zod21.z.object({
|
|
4435
|
+
tap: import_zod21.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),
|
|
4436
|
+
type: import_zod21.z.string().optional().describe("Text to type (needs `into`)."),
|
|
4437
|
+
into: import_zod21.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),
|
|
4438
|
+
waitMs: import_zod21.z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),
|
|
4439
|
+
repeat: import_zod21.z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")
|
|
4440
|
+
}).describe("One interaction to measure. Keep it to the thing you're asking about.");
|
|
4441
|
+
function selector2(needle) {
|
|
4442
|
+
return /\s/.test(needle) ? { query: needle } : { testID: needle, query: needle };
|
|
4443
|
+
}
|
|
4444
|
+
function dominant(causes) {
|
|
4445
|
+
if (!causes) return "unknown";
|
|
4446
|
+
let best = "unknown";
|
|
4447
|
+
let n = -1;
|
|
4448
|
+
for (const [k, v] of Object.entries(causes)) {
|
|
4449
|
+
if ((v ?? 0) > n) {
|
|
4450
|
+
n = v ?? 0;
|
|
4451
|
+
best = k;
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
return best;
|
|
4455
|
+
}
|
|
4456
|
+
var CAUSE_HINT = {
|
|
4457
|
+
propsUnstable: "props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",
|
|
4458
|
+
parent: "parent re-rendered and nothing of its own changed \u2014 a pure cascade",
|
|
4459
|
+
props: "props genuinely changed value",
|
|
4460
|
+
hooks: "its own state/hooks changed",
|
|
4461
|
+
mount: "first render"
|
|
4462
|
+
};
|
|
4463
|
+
function formatCapture(c, top) {
|
|
4464
|
+
const s = c.summary;
|
|
4465
|
+
const wasted = s.wastedRenders ?? 0;
|
|
4466
|
+
const pct = s.totalRenders > 0 ? Math.round(wasted / s.totalRenders * 100) : 0;
|
|
4467
|
+
const lines = [];
|
|
4468
|
+
const ms = s.totalRenderMs ?? 0;
|
|
4469
|
+
lines.push(
|
|
4470
|
+
`**${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}%)`
|
|
4471
|
+
);
|
|
4472
|
+
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 ");
|
|
4473
|
+
if (causeLine) lines.push(`causes: ${causeLine}`);
|
|
4474
|
+
lines.push("");
|
|
4475
|
+
lines.push("| component | self ms | renders | cause | dragged along by | changed props |");
|
|
4476
|
+
lines.push("|---|---:|---:|---|---|---|");
|
|
4477
|
+
const rows = [...s.topComponents].sort((a, b) => (b.totalMs ?? 0) - (a.totalMs ?? 0) || b.renders - a.renders).slice(0, top);
|
|
4478
|
+
for (const r of rows) {
|
|
4479
|
+
lines.push(
|
|
4480
|
+
`| ${r.name} | ${(r.totalMs ?? 0).toFixed(1)} | ${r.renders} | ${dominant(r.causes)} | ${r.parentName ?? "\u2014"} | ${(r.changedProps ?? []).join(", ") || "\u2014"} |`
|
|
4481
|
+
);
|
|
4482
|
+
}
|
|
4483
|
+
if (s.topComponents.length > top) {
|
|
4484
|
+
lines.push(`_\u2026+${s.topComponents.length - top} more components_`);
|
|
4485
|
+
}
|
|
4486
|
+
const seen = new Set(rows.map((r) => dominant(r.causes)));
|
|
4487
|
+
const hints = [...seen].filter((k) => CAUSE_HINT[k]).map((k) => `\`${k}\` = ${CAUSE_HINT[k]}`);
|
|
4488
|
+
if (hints.length) {
|
|
4489
|
+
lines.push("");
|
|
4490
|
+
lines.push(hints.join(" \xB7 "));
|
|
4491
|
+
}
|
|
4492
|
+
lines.push("");
|
|
4493
|
+
lines.push(
|
|
4494
|
+
"`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."
|
|
4495
|
+
);
|
|
4496
|
+
return lines.join("\n");
|
|
4497
|
+
}
|
|
4498
|
+
function formatDelta(before, after) {
|
|
4499
|
+
const d = (a, b) => {
|
|
4500
|
+
const diff = b - a;
|
|
4501
|
+
return `${a} \u2192 ${b} (${diff > 0 ? "+" : ""}${diff})`;
|
|
4502
|
+
};
|
|
4503
|
+
const bs = before.summary;
|
|
4504
|
+
const as_ = after.summary;
|
|
4505
|
+
const lines = [`**vs "${before.label}"**`];
|
|
4506
|
+
lines.push(`- total renders: ${d(bs.totalRenders, as_.totalRenders)}`);
|
|
4507
|
+
lines.push(`- wasted: ${d(bs.wastedRenders ?? 0, as_.wastedRenders ?? 0)}`);
|
|
4508
|
+
const beforeByName = new Map(bs.topComponents.map((r) => [r.name, r.renders]));
|
|
4509
|
+
const moved = [];
|
|
4510
|
+
for (const r of as_.topComponents.slice(0, 20)) {
|
|
4511
|
+
const was = beforeByName.get(r.name) ?? 0;
|
|
4512
|
+
if (was !== r.renders) moved.push(`${r.name} ${d(was, r.renders)}`);
|
|
4513
|
+
beforeByName.delete(r.name);
|
|
4514
|
+
}
|
|
4515
|
+
for (const [name, was] of beforeByName) {
|
|
4516
|
+
if (was > 0) moved.push(`${name} ${d(was, 0)}`);
|
|
4517
|
+
}
|
|
4518
|
+
if (moved.length) lines.push(`- per component: ${moved.slice(0, 10).join(" \xB7 ")}`);
|
|
4519
|
+
const fewer = as_.totalRenders < bs.totalRenders;
|
|
4520
|
+
const more = as_.totalRenders > bs.totalRenders;
|
|
4521
|
+
lines.push(
|
|
4522
|
+
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."
|
|
4523
|
+
);
|
|
4524
|
+
return lines.join("\n");
|
|
4525
|
+
}
|
|
4526
|
+
function registerRenderTools(server, sync) {
|
|
4527
|
+
server.registerTool(
|
|
4528
|
+
"measure_renders",
|
|
4529
|
+
{
|
|
4530
|
+
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.",
|
|
4531
|
+
inputSchema: {
|
|
4532
|
+
steps: import_zod21.z.array(stepSchema2).max(20).optional().describe(
|
|
4533
|
+
"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."
|
|
4534
|
+
),
|
|
4535
|
+
idleMs: import_zod21.z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),
|
|
4536
|
+
label: import_zod21.z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),
|
|
4537
|
+
compareToPrevious: import_zod21.z.boolean().optional().describe("Diff against the previous measure_renders on this device. Use after an edit to prove the fix."),
|
|
4538
|
+
top: import_zod21.z.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),
|
|
4539
|
+
deviceId: import_zod21.z.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4540
|
+
}
|
|
4541
|
+
},
|
|
4542
|
+
async (args) => {
|
|
4543
|
+
try {
|
|
4544
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4545
|
+
const device = sync.connectedDevices().find((d) => d.deviceId === target);
|
|
4546
|
+
const uiTool = (device?.tools ?? []).find((t) => t.toolId === UI_TOOL_ID2);
|
|
4547
|
+
if (!uiTool) {
|
|
4548
|
+
return fail21(
|
|
4549
|
+
"This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates."
|
|
4550
|
+
);
|
|
4551
|
+
}
|
|
4552
|
+
if (!(uiTool.actions ?? []).includes("beginMeasurement")) {
|
|
4553
|
+
return fail21(
|
|
4554
|
+
"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."
|
|
4555
|
+
);
|
|
4556
|
+
}
|
|
4557
|
+
const began = await sync.callAction(UI_TOOL_ID2, "beginMeasurement", {}, target);
|
|
4558
|
+
if (began && began.ok === false) {
|
|
4559
|
+
return fail21(`Can't measure renders: ${began.reason ?? "capture unavailable"}`);
|
|
4560
|
+
}
|
|
4561
|
+
await delay5(SETTLE_MS);
|
|
4562
|
+
const startedAt = Date.now();
|
|
4563
|
+
const notes = [];
|
|
4564
|
+
if (args.steps?.length) {
|
|
4565
|
+
for (const step of args.steps) {
|
|
4566
|
+
const times = step.repeat ?? 1;
|
|
4567
|
+
for (let i = 0; i < times; i++) {
|
|
4568
|
+
if (step.type !== void 0) {
|
|
4569
|
+
const sel = step.into ?? step.tap;
|
|
4570
|
+
if (!sel) {
|
|
4571
|
+
notes.push("a `type` step needs `into`");
|
|
4572
|
+
continue;
|
|
4573
|
+
}
|
|
4574
|
+
const res = await sync.callAction(
|
|
4575
|
+
UI_TOOL_ID2,
|
|
4576
|
+
"tapElement",
|
|
4577
|
+
{ ...selector2(sel), text: step.type },
|
|
4578
|
+
target
|
|
4579
|
+
);
|
|
4580
|
+
if (!res?.tapped) notes.push(res?.reason ?? `could not type into "${sel}"`);
|
|
4581
|
+
else if (res.matched?.via && res.matched.via !== "onChangeText") {
|
|
4582
|
+
notes.push(`"${sel}" is not a text input \u2014 it ran ${res.matched.via}, nothing was typed`);
|
|
4583
|
+
}
|
|
4584
|
+
} else if (step.tap) {
|
|
4585
|
+
const res = await sync.callAction(
|
|
4586
|
+
UI_TOOL_ID2,
|
|
4587
|
+
"tapElement",
|
|
4588
|
+
selector2(step.tap),
|
|
4589
|
+
target
|
|
4590
|
+
);
|
|
4591
|
+
if (!res?.tapped) notes.push(res?.reason ?? `no element matched "${step.tap}"`);
|
|
4592
|
+
}
|
|
4593
|
+
if (step.waitMs) await delay5(step.waitMs);
|
|
4594
|
+
}
|
|
4595
|
+
}
|
|
4596
|
+
await delay5(SETTLE_MS);
|
|
4597
|
+
} else {
|
|
4598
|
+
await delay5(args.idleMs ?? DEFAULT_IDLE_MS);
|
|
4599
|
+
}
|
|
4600
|
+
const windowMs = Date.now() - startedAt;
|
|
4601
|
+
const ended = await sync.callAction(UI_TOOL_ID2, "endMeasurement", {}, target);
|
|
4602
|
+
const summary = ended?.summary;
|
|
4603
|
+
if (!summary) {
|
|
4604
|
+
return fail21(
|
|
4605
|
+
"The capture window closed without returning anything. If the app reloaded mid-measurement, try again."
|
|
4606
|
+
);
|
|
4607
|
+
}
|
|
4608
|
+
const capture = {
|
|
4609
|
+
label: args.label ?? (args.steps?.length ? "interaction" : "idle"),
|
|
4610
|
+
windowMs,
|
|
4611
|
+
summary
|
|
4612
|
+
};
|
|
4613
|
+
const prev = lastCapture.get(target);
|
|
4614
|
+
lastCapture.set(target, capture);
|
|
4615
|
+
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`;
|
|
4616
|
+
const parts = [`**measure_renders \u2014 ${what}**`, "", formatCapture(capture, args.top ?? DEFAULT_TOP)];
|
|
4617
|
+
if (args.compareToPrevious) {
|
|
4618
|
+
parts.push("", prev ? formatDelta(prev, capture) : "_No previous measurement on this device to compare against._");
|
|
4619
|
+
}
|
|
4620
|
+
if (notes.length) parts.push("", `\u26A0\uFE0F ${notes.join("; ")}`);
|
|
4621
|
+
if (summary.totalRenders === 0) {
|
|
4622
|
+
parts.push(
|
|
4623
|
+
"",
|
|
4624
|
+
"_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._"
|
|
4625
|
+
);
|
|
4626
|
+
} else if (!args.compareToPrevious) {
|
|
4627
|
+
parts.push("", "_Fixed something? Call this again with the same steps and `compareToPrevious:true` to prove it landed._");
|
|
4628
|
+
}
|
|
4629
|
+
return text19(parts.join("\n"));
|
|
4630
|
+
} catch (e) {
|
|
4631
|
+
return fail21(errMsg21(e));
|
|
4632
|
+
}
|
|
4633
|
+
}
|
|
4634
|
+
);
|
|
4635
|
+
}
|
|
4636
|
+
|
|
4637
|
+
// src/verify/editWatcher.ts
|
|
4638
|
+
var import_node_fs3 = __toESM(require("fs"));
|
|
4639
|
+
var import_node_path3 = __toESM(require("path"));
|
|
4640
|
+
var WATCHED_EXT = /* @__PURE__ */ new Set([
|
|
4641
|
+
".ts",
|
|
4642
|
+
".tsx",
|
|
4643
|
+
".js",
|
|
4644
|
+
".jsx",
|
|
4645
|
+
".mjs",
|
|
4646
|
+
".cjs",
|
|
4647
|
+
".json"
|
|
4648
|
+
]);
|
|
4649
|
+
var IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
4650
|
+
"node_modules",
|
|
4651
|
+
".git",
|
|
4652
|
+
".expo",
|
|
4653
|
+
"ios",
|
|
4654
|
+
"android",
|
|
4655
|
+
"dist",
|
|
4656
|
+
"lib",
|
|
4657
|
+
"build",
|
|
4658
|
+
".next",
|
|
4659
|
+
"coverage",
|
|
4660
|
+
"__snapshots__"
|
|
4661
|
+
]);
|
|
4662
|
+
var DEBOUNCE_MS = 400;
|
|
4663
|
+
function resolveMode(raw) {
|
|
4664
|
+
const v = (raw ?? "").trim().toLowerCase();
|
|
4665
|
+
if (v === "always" || v === "never" || v === "auto") return v;
|
|
4666
|
+
return "auto";
|
|
4667
|
+
}
|
|
4668
|
+
var EditWatcher = class {
|
|
4669
|
+
constructor() {
|
|
4670
|
+
this.watcher = null;
|
|
4671
|
+
this.changed = /* @__PURE__ */ new Set();
|
|
4672
|
+
this.lastEditAt = 0;
|
|
4673
|
+
this.nudgedForCurrentBatch = false;
|
|
4674
|
+
this.mode = "auto";
|
|
4675
|
+
this.started = false;
|
|
4676
|
+
}
|
|
4677
|
+
start(rootDir, mode) {
|
|
4678
|
+
this.mode = mode;
|
|
4679
|
+
if (mode === "never" || this.started) return;
|
|
4680
|
+
this.started = true;
|
|
4681
|
+
try {
|
|
4682
|
+
this.watcher = import_node_fs3.default.watch(
|
|
4683
|
+
rootDir,
|
|
4684
|
+
{ recursive: true },
|
|
4685
|
+
(_event, filename) => {
|
|
4686
|
+
if (!filename) return;
|
|
4687
|
+
const rel2 = String(filename);
|
|
4688
|
+
if (rel2.split(import_node_path3.default.sep).some((seg) => IGNORED_DIRS.has(seg))) return;
|
|
4689
|
+
if (!WATCHED_EXT.has(import_node_path3.default.extname(rel2))) return;
|
|
4690
|
+
this.noteEdit(rel2);
|
|
4691
|
+
}
|
|
4692
|
+
);
|
|
4693
|
+
this.watcher.on("error", () => this.stop());
|
|
4694
|
+
} catch {
|
|
4695
|
+
this.stop();
|
|
4696
|
+
}
|
|
4697
|
+
}
|
|
4698
|
+
/** Record an edit. Public so the nudge policy can be tested without fs.watch. */
|
|
4699
|
+
noteEdit(rel2) {
|
|
4700
|
+
const now = Date.now();
|
|
4701
|
+
if (now - this.lastEditAt > DEBOUNCE_MS) this.nudgedForCurrentBatch = false;
|
|
4702
|
+
this.lastEditAt = now;
|
|
4703
|
+
if (this.changed.size < 50) this.changed.add(rel2);
|
|
4704
|
+
}
|
|
4705
|
+
stop() {
|
|
4706
|
+
try {
|
|
4707
|
+
this.watcher?.close();
|
|
4708
|
+
} catch {
|
|
4709
|
+
}
|
|
4710
|
+
this.watcher = null;
|
|
4711
|
+
}
|
|
4712
|
+
/** Something on the device was actually checked — the edits are accounted for. */
|
|
4713
|
+
markVerified() {
|
|
4714
|
+
this.changed.clear();
|
|
4715
|
+
this.nudgedForCurrentBatch = false;
|
|
4716
|
+
}
|
|
4717
|
+
hasUnverifiedEdits() {
|
|
4718
|
+
return this.changed.size > 0;
|
|
4719
|
+
}
|
|
4720
|
+
/**
|
|
4721
|
+
* The line to append to a tool result, or null to stay quiet.
|
|
4722
|
+
*
|
|
4723
|
+
* `auto` says it once per burst of edits, so it lands when the agent is
|
|
4724
|
+
* mid-loop and then gets out of the way. `always` repeats while anything is
|
|
4725
|
+
* unverified, for people who want the belt and braces.
|
|
4726
|
+
*/
|
|
4727
|
+
nudge() {
|
|
4728
|
+
if (this.mode === "never" || !this.hasUnverifiedEdits()) return null;
|
|
4729
|
+
if (this.mode === "auto") {
|
|
4730
|
+
if (this.nudgedForCurrentBatch) return null;
|
|
4731
|
+
this.nudgedForCurrentBatch = true;
|
|
4732
|
+
}
|
|
4733
|
+
const files = [...this.changed];
|
|
4734
|
+
const shown = files.slice(0, 3).join(", ");
|
|
4735
|
+
const more = files.length > 3 ? ` +${files.length - 3} more` : "";
|
|
4736
|
+
return `
|
|
4737
|
+
|
|
4738
|
+
---
|
|
4739
|
+
\u26A0\uFE0F **${files.length} source file${files.length === 1 ? "" : "s"} changed since anything was last checked on the device** (${shown}${more}).
|
|
4740
|
+
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.`;
|
|
4741
|
+
}
|
|
4742
|
+
};
|
|
4743
|
+
var editWatcher = new EditWatcher();
|
|
4744
|
+
|
|
3609
4745
|
// src/server.ts
|
|
3610
4746
|
var SERVER_INSTRUCTIONS = `Buoy MCP \u2014 drive Buoy dev tools running in a React Native app from your editor.
|
|
3611
4747
|
|
|
3612
4748
|
Buoy tools live inside the app and sync to a local broker; this server connects to that
|
|
3613
|
-
broker as a dashboard client.
|
|
3614
|
-
|
|
4749
|
+
broker as a dashboard client.
|
|
4750
|
+
|
|
4751
|
+
DEBUGGING A RUNNING APP? Call \`get_triage\` FIRST \u2014 one call returns the connected device,
|
|
4752
|
+
recent console errors (including [FATAL] crashes), recent network requests with statuses,
|
|
4753
|
+
persisted storage keys, and what's on screen. It replaces the usual five-call opening
|
|
4754
|
+
sequence and tells you which tool to drill into. Read runtime facts before hypothesizing
|
|
4755
|
+
from source: the app's actual state beats a guess about what the code should do.
|
|
4756
|
+
|
|
4757
|
+
Routing after triage \u2014 match the SYMPTOM to the tool:
|
|
4758
|
+
- Value wrong/stale/NaN, or broken only after an upgrade \u2192 \`get_storage includeValues:true\`
|
|
4759
|
+
(a bad persisted value is a top root cause, and it survives reinstalls of the JS).
|
|
4760
|
+
- Failed request, wrong data from the API, auth/session bug \u2192 \`get_network_requests
|
|
4761
|
+
includeBodies:true\` and read the response BODY.
|
|
4762
|
+
- Crash or redbox \u2192 \`get_console\` (fatals are captured, and still readable after the app
|
|
4763
|
+
dies), then \`get_storage\` for the state that triggered it.
|
|
4764
|
+
- Data on screen doesn't match the API \u2192 \`get_react_query\` / \`get_zustand_state\` /
|
|
4765
|
+
\`get_redux_state\` / \`get_jotai_state\` for the cache or store between them.
|
|
4766
|
+
|
|
4767
|
+
AFTER YOU EDIT, PROVE IT on the device \u2014 the most common way a fix fails is being incomplete,
|
|
4768
|
+
not being wrong. Reload (\`run_flow\` step \`{reload:true}\`, or \`reload_app\`) and re-drive EVERY
|
|
4769
|
+
screen the symptom could appear on, asserting the corrected value: a price shown in three places
|
|
4770
|
+
has to be right in all three, and a migration only counts if it survives a restart. A fix you
|
|
4771
|
+
haven't watched work is a guess.
|
|
4772
|
+
|
|
4773
|
+
Use \`list_devices\` when you need the full tool/action inventory or several devices are
|
|
4774
|
+
connected (\`get_triage\` already names the active one).
|
|
3615
4775
|
|
|
3616
4776
|
To inspect what's HAPPENING at runtime \u2014 network requests, state changes (redux/zustand/jotai),
|
|
3617
4777
|
react-query updates, storage writes, route changes, renders \u2014 use \`get_events\` with a \`sources\`
|
|
@@ -3630,15 +4790,28 @@ Need to SEE a component (verify a UI change, check styling/layout)? Use \`screen
|
|
|
3630
4790
|
a testID/name \u2014 it locates the live component on-device and returns a cropped screenshot inline.
|
|
3631
4791
|
iOS Simulator only, and only works when this MCP server runs on the same Mac as the booted Simulator.
|
|
3632
4792
|
|
|
3633
|
-
Need to DRIVE the UI
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
|
|
4793
|
+
Need to DRIVE the UI? Reach for \`run_flow\` FIRST: it runs a whole scripted sequence
|
|
4794
|
+
(tap / type / set / reload / waitFor / expect) in ONE call and reports the per-step result, the
|
|
4795
|
+
final screen, and the network + console output the flow produced. Reproducing a bug and verifying
|
|
4796
|
+
a fix are one call each instead of a dozen alternating reads and taps, and a failed step reports
|
|
4797
|
+
the screen at the point it broke. Drop to \`describe_screen\` (list on-screen elements with testIDs
|
|
4798
|
+
and tap points) + \`tap_element\` only for one-off pokes or when you don't yet know what's there.
|
|
4799
|
+
|
|
4800
|
+
Screen slow / laggy / janky / stutters, typing lags, or "the whole page re-renders when I tap
|
|
4801
|
+
one thing"? Start with \`measure_renders\` \u2014 one call, no test route needed. Pass \`steps\` for the
|
|
4802
|
+
interaction you're actually asking about (a tap, some typing); an idle sample says nothing about
|
|
4803
|
+
what a tap costs. It returns per-component render counts, WHY each rendered (parent cascade / own
|
|
4804
|
+
state / changed props), which parent dragged it along, and \`wasted\` \u2014 the renders that produced
|
|
4805
|
+
nothing new. After you edit, call it again with the same steps and \`compareToPrevious:true\`:
|
|
4806
|
+
re-render fixes routinely move the cost somewhere else instead of removing it, and only a second
|
|
4807
|
+
measurement catches that.
|
|
3637
4808
|
|
|
3638
4809
|
JS FPS low / app hitching and you need to know WHAT is eating the JS thread? Use
|
|
3639
4810
|
\`get_js_thread_top\` (a live "Task Manager" of timers, Promise chains, rAF callbacks and
|
|
3640
4811
|
freezes, ranked by thread time), then \`get_js_thread_origin_detail\` to drill into a row.
|
|
3641
4812
|
Pass clearFirst:true and drive the UI with \`tap_element\` mid-sample to profile one interaction.
|
|
4813
|
+
This is about TASKS on the thread \u2014 for React components re-rendering too often, it's
|
|
4814
|
+
\`measure_renders\`, not this.
|
|
3642
4815
|
|
|
3643
4816
|
Debugging images (not loading, slow, stale cache, memory)? \`get_images\` lists every RN <Image> /
|
|
3644
4817
|
expo-image load with cache verdicts and oversize audits; \`image_action\` reloads, retries, or
|
|
@@ -3674,11 +4847,46 @@ If no device is connected, open the app with Buoy devtools running and try again
|
|
|
3674
4847
|
The Buoy MCP is a Pro feature: \`list_devices\` is always available, but data/action tools
|
|
3675
4848
|
require the connected app to have an active Buoy Pro license. If they error with "Buoy Pro
|
|
3676
4849
|
required", tell the user to upgrade to Buoy Pro in the app \u2014 don't try to work around it.`;
|
|
4850
|
+
var VERIFYING_TOOLS = /* @__PURE__ */ new Set([
|
|
4851
|
+
"measure_renders",
|
|
4852
|
+
"run_flow",
|
|
4853
|
+
"run_benchmark_batch",
|
|
4854
|
+
"get_triage",
|
|
4855
|
+
"tap_element",
|
|
4856
|
+
"describe_screen",
|
|
4857
|
+
"get_console",
|
|
4858
|
+
"get_network_requests",
|
|
4859
|
+
"get_events",
|
|
4860
|
+
"get_snapshot"
|
|
4861
|
+
]);
|
|
3677
4862
|
function createMcpServer(sync) {
|
|
3678
4863
|
const server = new import_mcp.McpServer(
|
|
3679
4864
|
{ name: "buoy", version: VERSION },
|
|
3680
4865
|
{ capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
|
|
3681
4866
|
);
|
|
4867
|
+
editWatcher.start(process.cwd(), resolveMode(process.env.BUOY_VERIFY));
|
|
4868
|
+
const originalRegister = server.registerTool.bind(server);
|
|
4869
|
+
server.registerTool = ((name, config, handler) => originalRegister(name, config, (async (...args) => {
|
|
4870
|
+
const result = await handler(...args);
|
|
4871
|
+
const errored = result?.isError === true;
|
|
4872
|
+
if (VERIFYING_TOOLS.has(name) && !errored) {
|
|
4873
|
+
editWatcher.markVerified();
|
|
4874
|
+
return result;
|
|
4875
|
+
}
|
|
4876
|
+
const note = editWatcher.nudge();
|
|
4877
|
+
if (!note) return result;
|
|
4878
|
+
const r = result;
|
|
4879
|
+
if (Array.isArray(r?.content)) {
|
|
4880
|
+
return {
|
|
4881
|
+
...r,
|
|
4882
|
+
content: [...r.content, { type: "text", text: note }]
|
|
4883
|
+
};
|
|
4884
|
+
}
|
|
4885
|
+
return result;
|
|
4886
|
+
})));
|
|
4887
|
+
registerTriageTools(server, sync);
|
|
4888
|
+
registerFlowTools(server, sync);
|
|
4889
|
+
registerRenderTools(server, sync);
|
|
3682
4890
|
registerGenericTools(server, sync);
|
|
3683
4891
|
registerPerfMonitorTools(server, sync);
|
|
3684
4892
|
registerEventsTools(server, sync);
|
|
@@ -3700,32 +4908,37 @@ function createMcpServer(sync) {
|
|
|
3700
4908
|
return server;
|
|
3701
4909
|
}
|
|
3702
4910
|
var deviceIdField = {
|
|
3703
|
-
deviceId:
|
|
4911
|
+
deviceId: import_zod22.z.string().optional().describe(
|
|
3704
4912
|
'Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.'
|
|
3705
4913
|
)
|
|
3706
4914
|
};
|
|
3707
4915
|
|
|
3708
4916
|
// src/init.ts
|
|
3709
4917
|
var import_node_child_process2 = require("child_process");
|
|
3710
|
-
var
|
|
4918
|
+
var import_node_fs4 = __toESM(require("fs"));
|
|
3711
4919
|
var import_node_os3 = __toESM(require("os"));
|
|
3712
|
-
var
|
|
4920
|
+
var import_node_path4 = __toESM(require("path"));
|
|
4921
|
+
function defaultEnv() {
|
|
4922
|
+
return { BUOY_VERIFY: "auto" };
|
|
4923
|
+
}
|
|
3713
4924
|
var PUBLIC_REGISTRY = "https://registry.npmjs.org";
|
|
3714
|
-
var
|
|
4925
|
+
var PROBE_TIMEOUT_MS3 = 3e3;
|
|
3715
4926
|
function runInit(opts = {}) {
|
|
3716
4927
|
const cwd = opts.cwd ?? process.cwd();
|
|
3717
|
-
const skillSrcDir = opts.skillSrcDir ??
|
|
4928
|
+
const skillSrcDir = opts.skillSrcDir ?? import_node_path4.default.resolve(__dirname, "../skill");
|
|
3718
4929
|
const log = opts.log ?? ((m) => process.stdout.write(m + "\n"));
|
|
3719
4930
|
const entry = resolveEntry(opts, log);
|
|
3720
4931
|
const done = [];
|
|
3721
|
-
upsertMcpConfig(
|
|
3722
|
-
if (
|
|
3723
|
-
upsertMcpConfig(
|
|
4932
|
+
upsertMcpConfig(import_node_path4.default.join(cwd, ".mcp.json"), "mcpServers", entry, cwd, done);
|
|
4933
|
+
if (import_node_fs4.default.existsSync(import_node_path4.default.join(cwd, ".cursor"))) {
|
|
4934
|
+
upsertMcpConfig(import_node_path4.default.join(cwd, ".cursor", "mcp.json"), "mcpServers", entry, cwd, done);
|
|
3724
4935
|
}
|
|
3725
|
-
if (
|
|
3726
|
-
upsertMcpConfig(
|
|
4936
|
+
if (import_node_fs4.default.existsSync(import_node_path4.default.join(cwd, ".vscode"))) {
|
|
4937
|
+
upsertMcpConfig(import_node_path4.default.join(cwd, ".vscode", "mcp.json"), "servers", entry, cwd, done);
|
|
3727
4938
|
}
|
|
3728
4939
|
installSkills(skillSrcDir, cwd, done);
|
|
4940
|
+
appendDebuggingGuide(import_node_path4.default.join(cwd, "CLAUDE.md"), cwd, done);
|
|
4941
|
+
appendDebuggingGuide(import_node_path4.default.join(cwd, "AGENTS.md"), cwd, done);
|
|
3729
4942
|
log("Buoy MCP installed:");
|
|
3730
4943
|
for (const line of done) log(" \u2022 " + line);
|
|
3731
4944
|
log("");
|
|
@@ -3745,7 +4958,7 @@ function runInit(opts = {}) {
|
|
|
3745
4958
|
}
|
|
3746
4959
|
function resolveEntry(opts, log) {
|
|
3747
4960
|
if (opts.cliPath) {
|
|
3748
|
-
return { type: "stdio", command: "node", args: [opts.cliPath] };
|
|
4961
|
+
return { type: "stdio", command: "node", args: [opts.cliPath], env: defaultEnv() };
|
|
3749
4962
|
}
|
|
3750
4963
|
const mode = opts.mode ?? "auto";
|
|
3751
4964
|
if (mode === "npx") {
|
|
@@ -3764,21 +4977,21 @@ function resolveEntry(opts, log) {
|
|
|
3764
4977
|
return localEntry(opts, log);
|
|
3765
4978
|
}
|
|
3766
4979
|
function npxEntry() {
|
|
3767
|
-
return { type: "stdio", command: "npx", args: ["-y", `${PACKAGE_NAME}@latest`] };
|
|
4980
|
+
return { type: "stdio", command: "npx", args: ["-y", `${PACKAGE_NAME}@latest`], env: defaultEnv() };
|
|
3768
4981
|
}
|
|
3769
4982
|
function localEntry(opts, log) {
|
|
3770
|
-
const installDir = opts.installDir ?? process.env.BUOY_MCP_HOME ??
|
|
4983
|
+
const installDir = opts.installDir ?? process.env.BUOY_MCP_HOME ?? import_node_path4.default.join(import_node_os3.default.homedir(), ".buoy-mcp");
|
|
3771
4984
|
const registry = opts.registry ?? PUBLIC_REGISTRY;
|
|
3772
4985
|
const cliPath = installLocalCopy(installDir, registry, log);
|
|
3773
4986
|
if (cliPath) {
|
|
3774
|
-
return { type: "stdio", command: "node", args: [cliPath] };
|
|
4987
|
+
return { type: "stdio", command: "node", args: [cliPath], env: defaultEnv() };
|
|
3775
4988
|
}
|
|
3776
4989
|
log("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");
|
|
3777
4990
|
return npxEntry();
|
|
3778
4991
|
}
|
|
3779
4992
|
function installLocalCopy(installDir, registry, log) {
|
|
3780
4993
|
const spec = `${PACKAGE_NAME}@${VERSION === "0.0.0-dev" ? "latest" : VERSION}`;
|
|
3781
|
-
|
|
4994
|
+
import_node_fs4.default.mkdirSync(installDir, { recursive: true });
|
|
3782
4995
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
3783
4996
|
log(`Installing ${spec} into ${installDir} from ${registry} \u2026`);
|
|
3784
4997
|
const res = (0, import_node_child_process2.spawnSync)(
|
|
@@ -3801,8 +5014,8 @@ function installLocalCopy(installDir, registry, log) {
|
|
|
3801
5014
|
log(`\u26A0 npm install exited with code ${res.status ?? "?"}${res.error ? ` (${res.error.message})` : ""}.`);
|
|
3802
5015
|
return null;
|
|
3803
5016
|
}
|
|
3804
|
-
const cliPath =
|
|
3805
|
-
if (!
|
|
5017
|
+
const cliPath = import_node_path4.default.join(installDir, "node_modules", PACKAGE_NAME, "dist", "cli.js");
|
|
5018
|
+
if (!import_node_fs4.default.existsSync(cliPath)) {
|
|
3806
5019
|
log(`\u26A0 install finished but ${cliPath} is missing.`);
|
|
3807
5020
|
return null;
|
|
3808
5021
|
}
|
|
@@ -3824,7 +5037,7 @@ function effectiveRegistry() {
|
|
|
3824
5037
|
}
|
|
3825
5038
|
function npmConfigGet(key) {
|
|
3826
5039
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
3827
|
-
const res = (0, import_node_child_process2.spawnSync)(npm, ["config", "get", key], { encoding: "utf8", timeout:
|
|
5040
|
+
const res = (0, import_node_child_process2.spawnSync)(npm, ["config", "get", key], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS3 });
|
|
3828
5041
|
if (res.status !== 0 || typeof res.stdout !== "string") return null;
|
|
3829
5042
|
const val = res.stdout.trim();
|
|
3830
5043
|
if (!val || val === "undefined" || val === "null") return null;
|
|
@@ -3833,8 +5046,8 @@ function npmConfigGet(key) {
|
|
|
3833
5046
|
function hostReachable(registry) {
|
|
3834
5047
|
const done = (0, import_node_child_process2.spawnSync)(
|
|
3835
5048
|
process.execPath,
|
|
3836
|
-
["-e", REACHABILITY_PROBE, registry, String(
|
|
3837
|
-
{ encoding: "utf8", timeout:
|
|
5049
|
+
["-e", REACHABILITY_PROBE, registry, String(PROBE_TIMEOUT_MS3)],
|
|
5050
|
+
{ encoding: "utf8", timeout: PROBE_TIMEOUT_MS3 + 2e3 }
|
|
3838
5051
|
);
|
|
3839
5052
|
return done.status === 0;
|
|
3840
5053
|
}
|
|
@@ -3854,52 +5067,129 @@ fetch(url, { method: 'HEAD', signal: c.signal })
|
|
|
3854
5067
|
`;
|
|
3855
5068
|
function upsertMcpConfig(file, key, entry, cwd, done) {
|
|
3856
5069
|
let json3 = {};
|
|
3857
|
-
if (
|
|
5070
|
+
if (import_node_fs4.default.existsSync(file)) {
|
|
3858
5071
|
try {
|
|
3859
|
-
json3 = JSON.parse(
|
|
5072
|
+
json3 = JSON.parse(import_node_fs4.default.readFileSync(file, "utf8"));
|
|
3860
5073
|
} catch {
|
|
3861
|
-
|
|
5074
|
+
import_node_fs4.default.copyFileSync(file, file + ".bak");
|
|
3862
5075
|
done.push(`existing ${rel(file, cwd)} was invalid JSON \u2014 backed up to ${rel(file, cwd)}.bak`);
|
|
3863
5076
|
json3 = {};
|
|
3864
5077
|
}
|
|
3865
5078
|
} else {
|
|
3866
|
-
|
|
5079
|
+
import_node_fs4.default.mkdirSync(import_node_path4.default.dirname(file), { recursive: true });
|
|
3867
5080
|
}
|
|
3868
5081
|
const servers = json3[key] && typeof json3[key] === "object" ? json3[key] : {};
|
|
3869
5082
|
const existed = "buoy" in servers;
|
|
3870
5083
|
servers.buoy = entry;
|
|
3871
5084
|
json3[key] = servers;
|
|
3872
|
-
|
|
5085
|
+
import_node_fs4.default.writeFileSync(file, JSON.stringify(json3, null, 2) + "\n");
|
|
3873
5086
|
done.push(`${existed ? "updated" : "added"} \`buoy\` in ${rel(file, cwd)}`);
|
|
3874
5087
|
}
|
|
5088
|
+
var GUIDE_HEADING = "# Debugging with Buoy";
|
|
5089
|
+
var DEBUGGING_GUIDE = `${GUIDE_HEADING}
|
|
5090
|
+
|
|
5091
|
+
This app's runtime is inspectable while it runs: the Buoy MCP tools read live
|
|
5092
|
+
state straight from the device. Route by symptom before reading source:
|
|
5093
|
+
|
|
5094
|
+
- \`get_triage\` \u2014 START HERE. One call: device, recent console errors and
|
|
5095
|
+
crashes, recent network requests, storage keys, and what's on screen. It
|
|
5096
|
+
usually names the problem, and always names the tool to drill into next.
|
|
5097
|
+
- \`run_flow\` \u2014 reproduce a bug or verify a fix in ONE call: a scripted
|
|
5098
|
+
tap/type/wait/assert sequence that returns the final screen plus the network
|
|
5099
|
+
and console output it produced. Use it instead of alternating
|
|
5100
|
+
\`describe_screen\` and \`tap_element\` a dozen times.
|
|
5101
|
+
- \`get_events\` \u2014 the universal activity timeline (network, state changes,
|
|
5102
|
+
storage writes, routes, renders). Check it BEFORE driving the UI to
|
|
5103
|
+
reproduce a bug \u2014 the failure is usually already recorded.
|
|
5104
|
+
- \`get_network_requests\` \u2014 API data wrong or calls failing \u2192 read the actual
|
|
5105
|
+
request + response bodies instead of guessing from code. Boot-time requests
|
|
5106
|
+
are captured too.
|
|
5107
|
+
- \`get_console\` \u2014 crashes and errors, including FATAL uncaught JS errors
|
|
5108
|
+
(tagged \`[FATAL]\`, with the component that crashed). Readable even after the
|
|
5109
|
+
app dies, so a redboxed app still tells you why.
|
|
5110
|
+
- \`get_storage\` \u2014 data wrong or missing after an app restart \u2192 read the
|
|
5111
|
+
persisted values FIRST.
|
|
5112
|
+
- \`reload_app\` \u2014 recover a crashed app (the other tools stop answering until
|
|
5113
|
+
you do) or pick up a change Fast Refresh missed.
|
|
5114
|
+
- \`get_snapshot\` \u2014 full current state of any one tool when the compact views
|
|
5115
|
+
aren't enough.
|
|
5116
|
+
|
|
5117
|
+
Runtime facts beat guesses \u2014 and after you edit, prove the fix on the device:
|
|
5118
|
+
reload, then re-drive EVERY screen the symptom could show up on and assert the
|
|
5119
|
+
corrected value. Fixes usually fail by being incomplete, not by being wrong.
|
|
5120
|
+
|
|
5121
|
+
## Don't report a fix you haven't watched work
|
|
5122
|
+
|
|
5123
|
+
Saying "fixed" is a claim about how the app behaves, so check it the same way
|
|
5124
|
+
you'd check anything else about the app \u2014 by looking at it. Re-run the exact
|
|
5125
|
+
interaction that was broken and report what the numbers did:
|
|
5126
|
+
|
|
5127
|
+
- \`measure_renders\` with the same \`steps\` and \`compareToPrevious: true\` for a
|
|
5128
|
+
performance change \u2014 it prints the before/after delta and flags a change that
|
|
5129
|
+
made things worse.
|
|
5130
|
+
- \`run_flow\` re-driving the broken screen for a behaviour change.
|
|
5131
|
+
|
|
5132
|
+
Two things this catches that reading cannot: a fix that is right but incomplete
|
|
5133
|
+
(the value was wrong in three places and you corrected one), and a fix that
|
|
5134
|
+
moved the cost instead of removing it \u2014 the usual failure mode for re-render
|
|
5135
|
+
work, where a page gets faster to type in and slower to tap.
|
|
5136
|
+
|
|
5137
|
+
If the app changed since anything was last checked, Buoy will say so in a tool
|
|
5138
|
+
result. Whether that's worth acting on is your call \u2014 a doc edit isn't worth a
|
|
5139
|
+
device check, a state-management change is. Set \`BUOY_VERIFY\` in the MCP config
|
|
5140
|
+
to \`always\` (repeat until checked) or \`never\` (silent) to change how often it
|
|
5141
|
+
mentions it.
|
|
5142
|
+
`;
|
|
5143
|
+
function appendDebuggingGuide(file, cwd, done) {
|
|
5144
|
+
let existing = "";
|
|
5145
|
+
if (import_node_fs4.default.existsSync(file)) {
|
|
5146
|
+
try {
|
|
5147
|
+
existing = import_node_fs4.default.readFileSync(file, "utf8");
|
|
5148
|
+
} catch {
|
|
5149
|
+
done.push(`\u26A0 could not read ${rel(file, cwd)} \u2014 skipped the debugging guide`);
|
|
5150
|
+
return;
|
|
5151
|
+
}
|
|
5152
|
+
if (existing.includes(GUIDE_HEADING)) {
|
|
5153
|
+
done.push(`${rel(file, cwd)} already has the "${GUIDE_HEADING}" block`);
|
|
5154
|
+
return;
|
|
5155
|
+
}
|
|
5156
|
+
}
|
|
5157
|
+
const separator = existing === "" ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
|
|
5158
|
+
try {
|
|
5159
|
+
import_node_fs4.default.writeFileSync(file, existing + separator + DEBUGGING_GUIDE);
|
|
5160
|
+
done.push(`${existing ? "appended" : "created"} "${GUIDE_HEADING}" block in ${rel(file, cwd)}`);
|
|
5161
|
+
} catch {
|
|
5162
|
+
done.push(`\u26A0 could not write ${rel(file, cwd)} \u2014 skipped the debugging guide`);
|
|
5163
|
+
}
|
|
5164
|
+
}
|
|
3875
5165
|
function installSkills(skillSrcDir, cwd, done) {
|
|
3876
|
-
if (!
|
|
5166
|
+
if (!import_node_fs4.default.existsSync(skillSrcDir)) {
|
|
3877
5167
|
done.push("\u26A0 no bundled skills found \u2014 skipped");
|
|
3878
5168
|
return;
|
|
3879
5169
|
}
|
|
3880
|
-
const skills =
|
|
5170
|
+
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")));
|
|
3881
5171
|
if (skills.length === 0) {
|
|
3882
5172
|
done.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");
|
|
3883
5173
|
return;
|
|
3884
5174
|
}
|
|
3885
5175
|
for (const skill of skills) {
|
|
3886
|
-
const from =
|
|
3887
|
-
const to =
|
|
5176
|
+
const from = import_node_path4.default.join(skillSrcDir, skill.name);
|
|
5177
|
+
const to = import_node_path4.default.join(cwd, ".claude", "skills", skill.name);
|
|
3888
5178
|
copyDir(from, to);
|
|
3889
|
-
done.push(`installed the ${skill.name} skill \u2192 ${rel(
|
|
5179
|
+
done.push(`installed the ${skill.name} skill \u2192 ${rel(import_node_path4.default.join(to, "SKILL.md"), cwd)}`);
|
|
3890
5180
|
}
|
|
3891
5181
|
}
|
|
3892
5182
|
function copyDir(from, to) {
|
|
3893
|
-
|
|
3894
|
-
for (const entry of
|
|
3895
|
-
const s =
|
|
3896
|
-
const d =
|
|
5183
|
+
import_node_fs4.default.mkdirSync(to, { recursive: true });
|
|
5184
|
+
for (const entry of import_node_fs4.default.readdirSync(from, { withFileTypes: true })) {
|
|
5185
|
+
const s = import_node_path4.default.join(from, entry.name);
|
|
5186
|
+
const d = import_node_path4.default.join(to, entry.name);
|
|
3897
5187
|
if (entry.isDirectory()) copyDir(s, d);
|
|
3898
|
-
else
|
|
5188
|
+
else import_node_fs4.default.copyFileSync(s, d);
|
|
3899
5189
|
}
|
|
3900
5190
|
}
|
|
3901
5191
|
function rel(file, cwd) {
|
|
3902
|
-
const r =
|
|
5192
|
+
const r = import_node_path4.default.relative(cwd, file);
|
|
3903
5193
|
return r && !r.startsWith("..") ? r : file;
|
|
3904
5194
|
}
|
|
3905
5195
|
// Annotate the CommonJS export names for ESM import in node:
|