@buoy-gg/mcp 7.0.21 → 7.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-JQ5GZ4LG.mjs → chunk-SGRL6UKT.mjs} +1391 -110
- package/dist/cli.js +1391 -110
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +167 -11
- package/dist/index.d.ts +167 -11
- package/dist/index.js +1391 -110
- package/dist/index.mjs +1 -1
- package/package.json +5 -3
|
@@ -3,7 +3,12 @@ import { DEFAULT_BROKER_PORT } from "@buoy-gg/sync-broker";
|
|
|
3
3
|
var BROKER_PORT = DEFAULT_BROKER_PORT;
|
|
4
4
|
var BROKER_URL = `http://localhost:${BROKER_PORT}`;
|
|
5
5
|
var DEFAULT_ACTION_TIMEOUT_MS = 15e3;
|
|
6
|
+
var UNRESPONSIVE_ACTION_TIMEOUT_MS = 2500;
|
|
7
|
+
var UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS = 1200;
|
|
8
|
+
var RECOVERY_PROBE_MS = 2e4;
|
|
9
|
+
var UNRESPONSIVE_AFTER_MS = 3e4;
|
|
6
10
|
var DEFAULT_SNAPSHOT_TIMEOUT_MS = 5e3;
|
|
11
|
+
var DEVICE_RETENTION_MS = 15 * 6e4;
|
|
7
12
|
var DASHBOARD_NAME = "Dashboard";
|
|
8
13
|
var ALL_DEVICES = "All";
|
|
9
14
|
|
|
@@ -34,6 +39,16 @@ var SyncClient = class {
|
|
|
34
39
|
this.pendingActions = /* @__PURE__ */ new Map();
|
|
35
40
|
/** Callbacks waiting for the next snapshot of `${deviceId}::${toolId}`. */
|
|
36
41
|
this.snapshotWaiters = /* @__PURE__ */ new Map();
|
|
42
|
+
/** When each cached snapshot arrived, keyed by snapKey (staleness reporting). */
|
|
43
|
+
this.snapshotAt = /* @__PURE__ */ new Map();
|
|
44
|
+
/** Liveness per device — see {@link noteTimeout}. */
|
|
45
|
+
this.health = /* @__PURE__ */ new Map();
|
|
46
|
+
/** Dev-server origin per device — see {@link noteDevServerOrigin}. */
|
|
47
|
+
this.devServerOrigins = /* @__PURE__ */ new Map();
|
|
48
|
+
/** Devices whose origin probe already ran (a production bundle has none). */
|
|
49
|
+
this.originProbed = /* @__PURE__ */ new Set();
|
|
50
|
+
/** Last time each device appeared in the broker's device list. */
|
|
51
|
+
this.lastSeen = /* @__PURE__ */ new Map();
|
|
37
52
|
this.port = opts.port ?? BROKER_PORT;
|
|
38
53
|
this.url = opts.url ?? (opts.port ? `http://localhost:${opts.port}` : BROKER_URL);
|
|
39
54
|
this.actionTimeoutMs = opts.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS;
|
|
@@ -93,13 +108,19 @@ var SyncClient = class {
|
|
|
93
108
|
});
|
|
94
109
|
socket.on("devtool-capabilities", (msg) => {
|
|
95
110
|
this.capabilities.set(msg.persistentDeviceId, msg);
|
|
111
|
+
void this.learnDevServerOrigin(msg.persistentDeviceId);
|
|
96
112
|
});
|
|
97
113
|
socket.on("all-devices-update", (list) => {
|
|
98
|
-
if (Array.isArray(list))
|
|
114
|
+
if (!Array.isArray(list)) return;
|
|
115
|
+
this.devices = list;
|
|
116
|
+
const now = Date.now();
|
|
117
|
+
for (const d of list) if (d.deviceId) this.lastSeen.set(d.deviceId, now);
|
|
118
|
+
this.pruneStaleDevices();
|
|
99
119
|
});
|
|
100
120
|
socket.on("devtool-sync", (msg) => {
|
|
101
121
|
const key = snapKey(msg.persistentDeviceId, msg.toolId);
|
|
102
122
|
this.snapshots.set(key, msg.payload);
|
|
123
|
+
this.snapshotAt.set(key, Date.now());
|
|
103
124
|
const waiters = this.snapshotWaiters.get(key);
|
|
104
125
|
if (waiters && waiters.length) {
|
|
105
126
|
this.snapshotWaiters.set(key, []);
|
|
@@ -115,6 +136,37 @@ var SyncClient = class {
|
|
|
115
136
|
});
|
|
116
137
|
});
|
|
117
138
|
}
|
|
139
|
+
/**
|
|
140
|
+
* Drop everything remembered about devices that have been gone a while.
|
|
141
|
+
*
|
|
142
|
+
* Deliberately NOT on disconnect: a crashed app often drops off the broker,
|
|
143
|
+
* and its cached console snapshot is the crash evidence — throwing that away
|
|
144
|
+
* the instant it disconnects would delete the answer. But device ids change
|
|
145
|
+
* with every simulator erase and fresh dev client, and each one can hold
|
|
146
|
+
* multi-MB snapshots, so a long-lived server has to forget eventually.
|
|
147
|
+
*/
|
|
148
|
+
pruneStaleDevices() {
|
|
149
|
+
const cutoff = Date.now() - DEVICE_RETENTION_MS;
|
|
150
|
+
for (const [deviceId, seen] of this.lastSeen) {
|
|
151
|
+
if (seen > cutoff) continue;
|
|
152
|
+
if (this.devices.some((d) => d.deviceId === deviceId)) continue;
|
|
153
|
+
this.lastSeen.delete(deviceId);
|
|
154
|
+
this.capabilities.delete(deviceId);
|
|
155
|
+
this.health.delete(deviceId);
|
|
156
|
+
this.devServerOrigins.delete(deviceId);
|
|
157
|
+
this.originProbed.delete(deviceId);
|
|
158
|
+
const prefix = `${deviceId}::`;
|
|
159
|
+
for (const key of [...this.snapshots.keys()]) {
|
|
160
|
+
if (key.startsWith(prefix)) {
|
|
161
|
+
this.snapshots.delete(key);
|
|
162
|
+
this.snapshotAt.delete(key);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const key of [...this.watching.keys()]) {
|
|
166
|
+
if (key.startsWith(prefix)) this.watching.delete(key);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
118
170
|
/** Disconnect and tear down a spawned broker, if any. */
|
|
119
171
|
async stop() {
|
|
120
172
|
for (const [, p] of this.pendingActions) {
|
|
@@ -122,6 +174,8 @@ var SyncClient = class {
|
|
|
122
174
|
p.reject(new Error("SyncClient stopped"));
|
|
123
175
|
}
|
|
124
176
|
this.pendingActions.clear();
|
|
177
|
+
for (const [, waiters] of this.snapshotWaiters) for (const w of waiters) w(void 0);
|
|
178
|
+
this.snapshotWaiters.clear();
|
|
125
179
|
this.socket?.close();
|
|
126
180
|
this.socket = null;
|
|
127
181
|
if (this.broker) {
|
|
@@ -142,6 +196,7 @@ var SyncClient = class {
|
|
|
142
196
|
platform: d.platform,
|
|
143
197
|
isConnected: d.isConnected !== false,
|
|
144
198
|
isPro: d.isPro === true,
|
|
199
|
+
tier: d.tier ?? (d.isPro === true ? "pro" : "anonymous"),
|
|
145
200
|
tools: caps?.tools ?? []
|
|
146
201
|
};
|
|
147
202
|
});
|
|
@@ -165,11 +220,19 @@ var SyncClient = class {
|
|
|
165
220
|
resolveDevice(deviceId) {
|
|
166
221
|
if (deviceId) return deviceId;
|
|
167
222
|
const connected = this.connectedDevices();
|
|
168
|
-
if (connected.length === 1) return connected[0].deviceId;
|
|
169
223
|
if (connected.length === 0) {
|
|
170
224
|
throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.");
|
|
171
225
|
}
|
|
172
|
-
|
|
226
|
+
if (connected.length === 1) return connected[0].deviceId;
|
|
227
|
+
const usable = connected.filter((d) => d.tools.length > 0);
|
|
228
|
+
if (usable.length === 1) return usable[0].deviceId;
|
|
229
|
+
if (usable.length === 0) {
|
|
230
|
+
const names = connected.map((d) => d.deviceName).join(", ");
|
|
231
|
+
throw new Error(
|
|
232
|
+
`Connected devices (${names}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
const list = usable.map((d) => `${d.deviceName} (${d.deviceId})`).join(", ");
|
|
173
236
|
throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${list}`);
|
|
174
237
|
}
|
|
175
238
|
/**
|
|
@@ -183,17 +246,153 @@ var SyncClient = class {
|
|
|
183
246
|
* is blocked.
|
|
184
247
|
*/
|
|
185
248
|
requireProDevice(deviceId) {
|
|
186
|
-
const
|
|
249
|
+
const tierNote = (dev2) => {
|
|
250
|
+
if (!dev2) return "";
|
|
251
|
+
return dev2.tier === "anonymous" ? ` The connected app "${dev2.deviceName}" has no license key at all.` : ` The connected app "${dev2.deviceName}" is on the ${dev2.tier} tier.`;
|
|
252
|
+
};
|
|
253
|
+
const proMsg = (dev2) => `Buoy Pro is required to use the MCP.${tierNote(
|
|
254
|
+
dev2
|
|
255
|
+
)} Upgrade to Buoy Pro in the app to enable MCP access (run \`list_devices\` to check status).`;
|
|
187
256
|
if (deviceId === ALL_DEVICES) {
|
|
188
257
|
if (!this.connectedDevices().some((d) => d.isPro)) throw new Error(proMsg());
|
|
189
258
|
return ALL_DEVICES;
|
|
190
259
|
}
|
|
191
260
|
const target = this.resolveDevice(deviceId);
|
|
192
261
|
const dev = this.connectedDevices().find((d) => d.deviceId === target);
|
|
193
|
-
if (!dev?.isPro) throw new Error(proMsg(dev
|
|
262
|
+
if (!dev?.isPro) throw new Error(proMsg(dev));
|
|
194
263
|
return target;
|
|
195
264
|
}
|
|
196
265
|
// ----------------------------------------------------------------
|
|
266
|
+
// Device liveness
|
|
267
|
+
// ----------------------------------------------------------------
|
|
268
|
+
healthOf(deviceId) {
|
|
269
|
+
let h = this.health.get(deviceId);
|
|
270
|
+
if (!h) {
|
|
271
|
+
h = { consecutiveTimeouts: 0, lastOkAt: 0, lastFullBudgetAt: 0 };
|
|
272
|
+
this.health.set(deviceId, h);
|
|
273
|
+
}
|
|
274
|
+
return h;
|
|
275
|
+
}
|
|
276
|
+
/** The device answered — it's alive. */
|
|
277
|
+
noteOk(deviceId) {
|
|
278
|
+
const h = this.healthOf(deviceId);
|
|
279
|
+
h.consecutiveTimeouts = 0;
|
|
280
|
+
h.lastOkAt = Date.now();
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* The device didn't answer. A crashed app never answers again, so after the
|
|
284
|
+
* first miss we stop paying the full timeout on every subsequent call.
|
|
285
|
+
*/
|
|
286
|
+
noteTimeout(deviceId) {
|
|
287
|
+
this.healthOf(deviceId).consecutiveTimeouts += 1;
|
|
288
|
+
}
|
|
289
|
+
/** True once a device has missed a call and hasn't answered since. */
|
|
290
|
+
isUnresponsive(deviceId) {
|
|
291
|
+
return this.healthOf(deviceId).consecutiveTimeouts > 0;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Full timeout normally; a short one for a device already not answering.
|
|
295
|
+
*
|
|
296
|
+
* With one escape hatch: every RECOVERY_PROBE_MS a flagged device gets the
|
|
297
|
+
* full budget again. Without it the flag is self-sustaining — a device whose
|
|
298
|
+
* work legitimately takes longer than the short budget (a big snapshot, a
|
|
299
|
+
* slow simulator) can never answer, so it can never clear the flag, and every
|
|
300
|
+
* later reply is a confident "most likely CRASHED" about a healthy app.
|
|
301
|
+
*/
|
|
302
|
+
timeoutFor(deviceId) {
|
|
303
|
+
if (!this.isUnresponsive(deviceId)) return this.actionTimeoutMs;
|
|
304
|
+
const h = this.healthOf(deviceId);
|
|
305
|
+
if (Date.now() - h.lastFullBudgetAt > RECOVERY_PROBE_MS) {
|
|
306
|
+
h.lastFullBudgetAt = Date.now();
|
|
307
|
+
return this.actionTimeoutMs;
|
|
308
|
+
}
|
|
309
|
+
return UNRESPONSIVE_ACTION_TIMEOUT_MS;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Plain-language diagnosis for a device that isn't answering, including the
|
|
313
|
+
* app's last words if the console tool got a crash flush out in time.
|
|
314
|
+
*
|
|
315
|
+
* A silent timeout is the worst possible answer here: the app is on a redbox,
|
|
316
|
+
* the reason is already captured, and without this the caller reads "timed
|
|
317
|
+
* out" and keeps retrying the same dead device.
|
|
318
|
+
*/
|
|
319
|
+
unresponsiveNote(deviceId) {
|
|
320
|
+
const h = this.healthOf(deviceId);
|
|
321
|
+
const since = h.lastOkAt ? Math.round((Date.now() - h.lastOkAt) / 1e3) : null;
|
|
322
|
+
const crashed = h.consecutiveTimeouts >= 2 || h.lastOkAt === 0 || Date.now() - h.lastOkAt > UNRESPONSIVE_AFTER_MS;
|
|
323
|
+
const lines = [
|
|
324
|
+
`The app on "${deviceId}" is not responding (${h.consecutiveTimeouts} call${h.consecutiveTimeouts === 1 ? "" : "s"} unanswered${since != null ? `, last answered ${since}s ago` : ""}).`,
|
|
325
|
+
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."
|
|
326
|
+
];
|
|
327
|
+
const fatal = this.lastFatalFor(deviceId);
|
|
328
|
+
if (fatal) lines.push(`Last captured error: ${fatal}`);
|
|
329
|
+
lines.push(
|
|
330
|
+
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."
|
|
331
|
+
);
|
|
332
|
+
return lines.join(" ");
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* The newest error line the console tool synced for this device, if any.
|
|
336
|
+
* Reads the cached console snapshot rather than the device (which, by the
|
|
337
|
+
* time this matters, is not answering).
|
|
338
|
+
*/
|
|
339
|
+
lastFatalFor(deviceId) {
|
|
340
|
+
const snap = this.snapshots.get(snapKey(deviceId, "console"));
|
|
341
|
+
const entries = snap?.entries;
|
|
342
|
+
if (!Array.isArray(entries)) return null;
|
|
343
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
344
|
+
const e = entries[i];
|
|
345
|
+
if (e?.fatal || e?.level === "error") {
|
|
346
|
+
const msg = (e.message ?? "").split("\n")[0];
|
|
347
|
+
if (msg) return msg.length > 300 ? `${msg.slice(0, 300)}\u2026` : msg;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
/** Age of the cached snapshot for a tool, in ms (null = never received). */
|
|
353
|
+
snapshotAgeMs(toolId, deviceId) {
|
|
354
|
+
const at = this.snapshotAt.get(snapKey(deviceId, toolId));
|
|
355
|
+
return at ? Date.now() - at : null;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Remember where a device's bundle came from, reported by core's `app`
|
|
359
|
+
* adapter while the app is healthy. It is the only way to reload an app that
|
|
360
|
+
* has crashed: the in-app reload needs the React tree that the crash
|
|
361
|
+
* destroyed, but the dev server's reload is handled natively.
|
|
362
|
+
*/
|
|
363
|
+
noteDevServerOrigin(deviceId, origin) {
|
|
364
|
+
if (typeof origin === "string" && /^https?:\/\//.test(origin)) {
|
|
365
|
+
this.devServerOrigins.set(deviceId, origin);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Ask a freshly-announced device where its bundle came from, once.
|
|
370
|
+
*
|
|
371
|
+
* Deliberately eager: this is the piece of information that can ONLY be
|
|
372
|
+
* collected while the app is healthy, and is only ever needed after it has
|
|
373
|
+
* stopped answering. One cheap round-trip per device buys the ability to
|
|
374
|
+
* recover a crashed app instead of telling the caller to go do it by hand.
|
|
375
|
+
*/
|
|
376
|
+
async learnDevServerOrigin(deviceId) {
|
|
377
|
+
if (this.devServerOrigins.has(deviceId) || this.originProbed.has(deviceId)) return;
|
|
378
|
+
this.originProbed.add(deviceId);
|
|
379
|
+
const hasApp = this.capabilities.get(deviceId)?.tools?.some((t) => t.toolId === "app");
|
|
380
|
+
if (!hasApp) return;
|
|
381
|
+
try {
|
|
382
|
+
const { payload } = await this.getSnapshot("app", deviceId, { timeoutMs: 4e3, silent: true });
|
|
383
|
+
this.noteDevServerOrigin(deviceId, payload?.devServerOrigin);
|
|
384
|
+
} catch {
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/** The dev-server origin last reported by this device, if any. */
|
|
388
|
+
devServerOrigin(deviceId) {
|
|
389
|
+
const known = this.devServerOrigins.get(deviceId);
|
|
390
|
+
if (known) return known;
|
|
391
|
+
const snap = this.snapshots.get(snapKey(deviceId, "app"));
|
|
392
|
+
if (typeof snap?.devServerOrigin === "string") return snap.devServerOrigin;
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
// ----------------------------------------------------------------
|
|
197
396
|
// Watch + snapshots
|
|
198
397
|
// ----------------------------------------------------------------
|
|
199
398
|
/**
|
|
@@ -264,13 +463,36 @@ var SyncClient = class {
|
|
|
264
463
|
const target = this.resolveDevice(deviceId);
|
|
265
464
|
const key = snapKey(target, toolId);
|
|
266
465
|
this.ensureWatching(toolId, target);
|
|
267
|
-
|
|
466
|
+
let budget = opts.timeoutMs ?? DEFAULT_SNAPSHOT_TIMEOUT_MS;
|
|
467
|
+
if (opts.timeoutMs === void 0 && this.isUnresponsive(target)) {
|
|
468
|
+
const h = this.healthOf(target);
|
|
469
|
+
if (Date.now() - h.lastFullBudgetAt > RECOVERY_PROBE_MS) {
|
|
470
|
+
h.lastFullBudgetAt = Date.now();
|
|
471
|
+
} else {
|
|
472
|
+
budget = UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
const next = this.waitForSnapshot(key, budget);
|
|
268
476
|
this.socket?.emit("request-devtool-state", { toolId, targetDeviceId: target });
|
|
269
477
|
const payload = await next;
|
|
270
|
-
if (payload !== void 0)
|
|
478
|
+
if (payload !== void 0) {
|
|
479
|
+
if (!opts.silent) this.noteOk(target);
|
|
480
|
+
return { deviceId: target, payload };
|
|
481
|
+
}
|
|
482
|
+
if (!opts.silent) this.noteTimeout(target);
|
|
271
483
|
const cached = this.snapshots.get(key);
|
|
272
|
-
if (cached !== void 0)
|
|
273
|
-
|
|
484
|
+
if (cached !== void 0) {
|
|
485
|
+
return { deviceId: target, payload: cached, stale: this.staleNote(toolId, target) };
|
|
486
|
+
}
|
|
487
|
+
throw new Error(
|
|
488
|
+
`Timed out waiting for "${toolId}" state from ${target} (is the tool active?). ${this.unresponsiveNote(target)}`
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
/** Header line for data served from cache because the device went quiet. */
|
|
492
|
+
staleNote(toolId, deviceId) {
|
|
493
|
+
const age = this.snapshotAgeMs(toolId, deviceId);
|
|
494
|
+
const ageText = age == null ? "an earlier sync" : `${Math.round(age / 1e3)}s ago`;
|
|
495
|
+
return `\u26A0\uFE0F Served from the last sync (${ageText}) \u2014 ${this.unresponsiveNote(deviceId)}`;
|
|
274
496
|
}
|
|
275
497
|
waitForSnapshot(key, timeoutMs) {
|
|
276
498
|
return new Promise((resolve) => {
|
|
@@ -299,11 +521,16 @@ var SyncClient = class {
|
|
|
299
521
|
const target = deviceId === ALL_DEVICES ? ALL_DEVICES : this.resolveDevice(deviceId);
|
|
300
522
|
if (!this.socket) throw new Error("SyncClient is not connected");
|
|
301
523
|
const requestId = randomUUID();
|
|
302
|
-
const timeoutMs = opts.timeoutMs ?? this.
|
|
524
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutFor(target);
|
|
303
525
|
const result = await new Promise((resolve, reject) => {
|
|
304
526
|
const timer = setTimeout(() => {
|
|
305
527
|
this.pendingActions.delete(requestId);
|
|
306
|
-
|
|
528
|
+
if (target !== ALL_DEVICES && !opts.silent) this.noteTimeout(target);
|
|
529
|
+
reject(
|
|
530
|
+
new Error(
|
|
531
|
+
`Action "${toolId}.${action}" got no answer in ${timeoutMs}ms. ` + (target === ALL_DEVICES ? "No device responded." : this.unresponsiveNote(target))
|
|
532
|
+
)
|
|
533
|
+
);
|
|
307
534
|
}, timeoutMs);
|
|
308
535
|
this.pendingActions.set(requestId, { resolve, reject, timer });
|
|
309
536
|
this.socket.emit("devtool-action", {
|
|
@@ -314,6 +541,7 @@ var SyncClient = class {
|
|
|
314
541
|
params: params ?? {}
|
|
315
542
|
});
|
|
316
543
|
});
|
|
544
|
+
if (target !== ALL_DEVICES && !opts.silent) this.noteOk(target);
|
|
317
545
|
if (!result.ok) {
|
|
318
546
|
throw new Error(result.error || `Action "${toolId}.${action}" failed on device`);
|
|
319
547
|
}
|
|
@@ -344,7 +572,7 @@ async function waitForBroker(url, attempts = 20) {
|
|
|
344
572
|
var delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
345
573
|
|
|
346
574
|
// src/version.ts
|
|
347
|
-
var VERSION = "7.0.
|
|
575
|
+
var VERSION = "7.0.23" ? "7.0.23" : "0.0.0-dev";
|
|
348
576
|
var PACKAGE_NAME = "@buoy-gg/mcp";
|
|
349
577
|
|
|
350
578
|
// src/update/checkForUpdate.ts
|
|
@@ -439,11 +667,13 @@ function registerGenericTools(server, sync) {
|
|
|
439
667
|
...updateNotice ? { updateAvailable: updateNotice } : {}
|
|
440
668
|
});
|
|
441
669
|
}
|
|
442
|
-
const
|
|
670
|
+
const connected = devices.filter((d) => d.isConnected);
|
|
671
|
+
const anyPro = connected.some((d) => d.isPro);
|
|
672
|
+
const anySignedIn = connected.some((d) => d.tier !== "anonymous");
|
|
443
673
|
return json({
|
|
444
674
|
devices,
|
|
445
675
|
...anyPro ? {} : {
|
|
446
|
-
hint: "The Buoy MCP is a Pro feature \u2014 no connected device has an active Buoy Pro license, so data/action tools are blocked. Upgrade to Buoy Pro in the app to enable them."
|
|
676
|
+
hint: anySignedIn ? "The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app to enable them." : "The Buoy MCP is a Pro feature \u2014 no connected device has an active Buoy Pro license, so data/action tools are blocked. Upgrade to Buoy Pro in the app to enable them."
|
|
447
677
|
},
|
|
448
678
|
...updateNotice ? { updateAvailable: updateNotice } : {}
|
|
449
679
|
});
|
|
@@ -516,6 +746,14 @@ function errMsg(e) {
|
|
|
516
746
|
|
|
517
747
|
// src/tools/packs/perfRanking.ts
|
|
518
748
|
var clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
|
|
749
|
+
var WARMUP_CASE_NAME = "__batch_warmup__";
|
|
750
|
+
var THERMAL_MARK = {
|
|
751
|
+
nominal: "\u{1F7E2} nominal",
|
|
752
|
+
fair: "\u{1F7E1} fair",
|
|
753
|
+
serious: "\u{1F7E0} serious",
|
|
754
|
+
critical: "\u{1F534} critical",
|
|
755
|
+
unknown: "\u2014"
|
|
756
|
+
};
|
|
519
757
|
var FALLBACK = {
|
|
520
758
|
perCaseDurationMs: 5e3,
|
|
521
759
|
settleMs: 600,
|
|
@@ -575,6 +813,7 @@ function buildAutomationConfig(input, base = {}) {
|
|
|
575
813
|
runsPerCase,
|
|
576
814
|
coolDownMs,
|
|
577
815
|
discardWarmupRuns,
|
|
816
|
+
discardWarmupCase: input.discardWarmupCase ?? base.discardWarmupCase ?? true,
|
|
578
817
|
shuffleCases,
|
|
579
818
|
reloadBetweenCases: input.reloadBetweenCases ?? base.reloadBetweenCases ?? false,
|
|
580
819
|
captureRenders: input.captureRenders ?? base.captureRenders ?? true
|
|
@@ -619,7 +858,9 @@ function computeFlags(r) {
|
|
|
619
858
|
function rankBatchFromIndex(index, batchId, casesOrder, failures = []) {
|
|
620
859
|
const entries = index.filter((e) => e.batchId === batchId);
|
|
621
860
|
const failureByIndex = new Map(failures.map((f) => [f.index, f.reason]));
|
|
622
|
-
const indexes =
|
|
861
|
+
const indexes = Array.from(new Set(entries.map((e) => e.batchIndex ?? 0))).sort(
|
|
862
|
+
(a, b) => a - b
|
|
863
|
+
);
|
|
623
864
|
const medianForCase = (batchIndex) => {
|
|
624
865
|
const runs = entries.filter((e) => (e.batchIndex ?? 0) === batchIndex);
|
|
625
866
|
if (runs.length === 0) return void 0;
|
|
@@ -629,7 +870,7 @@ function rankBatchFromIndex(index, batchId, casesOrder, failures = []) {
|
|
|
629
870
|
const rows = indexes.map((batchIndex) => {
|
|
630
871
|
const median = medianForCase(batchIndex);
|
|
631
872
|
const runs = entries.filter((e) => (e.batchIndex ?? 0) === batchIndex).length;
|
|
632
|
-
const caseName = casesOrder?.[batchIndex]?.name ??
|
|
873
|
+
const caseName = median?.name ?? casesOrder?.[batchIndex]?.name ?? `case ${batchIndex + 1}`;
|
|
633
874
|
const failureReason = failureByIndex.get(batchIndex) ?? median?.batchFailureReason;
|
|
634
875
|
const failed = Boolean(failureReason) || !median;
|
|
635
876
|
const base = {
|
|
@@ -648,11 +889,13 @@ function rankBatchFromIndex(index, batchId, casesOrder, failures = []) {
|
|
|
648
889
|
deviceMaxRefreshRate: num(median?.deviceMaxRefreshRate),
|
|
649
890
|
deltaUiFps: null,
|
|
650
891
|
deltaJsFps: null,
|
|
892
|
+
...median?.thermalState ? { thermalState: median.thermalState } : {},
|
|
651
893
|
renderCommits: num(median?.renderCommits),
|
|
894
|
+
renderWasted: median?.renderWasted,
|
|
652
895
|
topRenderers: median?.topRenderers ?? []
|
|
653
896
|
};
|
|
654
897
|
return { ...base, flags: failed ? [] : computeFlags(base) };
|
|
655
|
-
});
|
|
898
|
+
}).filter((r) => r.caseName !== WARMUP_CASE_NAME).map((r, i) => ({ ...r, batchIndex: i }));
|
|
656
899
|
const baseline = rows[0];
|
|
657
900
|
if (baseline) {
|
|
658
901
|
for (const r of rows) {
|
|
@@ -706,18 +949,33 @@ function formatRankingMarkdown(ranking) {
|
|
|
706
949
|
`**No single winner \u2014 weigh the trade-offs.** UI-thread health matters more than raw averages: a cheap run that drops UI frames is worse than a pricier one that holds them.`
|
|
707
950
|
);
|
|
708
951
|
lines.push("");
|
|
709
|
-
|
|
710
|
-
|
|
952
|
+
const anyThermal = ranking.rows.some((r) => r.thermalState);
|
|
953
|
+
const thermalHead = anyThermal ? " Thermal |" : "";
|
|
954
|
+
const thermalRule = anyThermal ? "-------|" : "";
|
|
955
|
+
lines.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${thermalHead} Flags |`);
|
|
956
|
+
lines.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${thermalRule}-------|`);
|
|
711
957
|
for (const r of ranking.rows) {
|
|
958
|
+
const thermalCell = anyThermal ? ` ${THERMAL_MARK[r.thermalState ?? "unknown"] ?? "\u2014"} |` : "";
|
|
712
959
|
if (r.failed) {
|
|
713
|
-
lines.push(
|
|
960
|
+
lines.push(
|
|
961
|
+
`| ${r.batchIndex} | ${r.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${thermalCell} \u274C FAILED (${r.failureReason}) |`
|
|
962
|
+
);
|
|
714
963
|
continue;
|
|
715
964
|
}
|
|
716
965
|
const flagCell = r.flags.length ? `\u26A0\uFE0F ${r.flags.join("; ")}` : "\u2713 clean";
|
|
717
966
|
lines.push(
|
|
718
967
|
`| ${r.batchIndex} | ${r.caseName} | ${f(r.uiFps)}${delta(r.deltaUiFps)} | ${f(r.jsFps)}${delta(
|
|
719
968
|
r.deltaJsFps
|
|
720
|
-
)} | ${f(r.cpu)} | ${f(r.memMb)} | ${f(r.jsJank, 0)} | ${f(r.uiJank, 0)}
|
|
969
|
+
)} | ${f(r.cpu)} | ${f(r.memMb)} | ${f(r.jsJank, 0)} | ${f(r.uiJank, 0)} |${thermalCell} ${flagCell} |`
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
const throttled = ranking.rows.filter(
|
|
973
|
+
(r) => r.thermalState === "serious" || r.thermalState === "critical"
|
|
974
|
+
);
|
|
975
|
+
if (throttled.length) {
|
|
976
|
+
lines.push("");
|
|
977
|
+
lines.push(
|
|
978
|
+
`**\u{1F525} Thermally throttled: ${throttled.map((r) => r.caseName).join(", ")}.** A throttled device runs SLOWER at a LOWER cpu%, so these cases can look like the cheapest in the batch while actually delivering fewer frames \u2014 check their UI FPS and jank, and re-run them on a cool device before drawing any conclusion.`
|
|
721
979
|
);
|
|
722
980
|
}
|
|
723
981
|
lines.push("");
|
|
@@ -739,13 +997,18 @@ function formatRankingMarkdown(ranking) {
|
|
|
739
997
|
);
|
|
740
998
|
}
|
|
741
999
|
const renderLines = ranking.rows.filter((r) => !r.failed && (r.renderCommits != null || r.topRenderers.length > 0)).map((r) => {
|
|
742
|
-
const top = r.topRenderers.map(
|
|
1000
|
+
const top = r.topRenderers.map(
|
|
1001
|
+
(t) => `${t.name} \xD7${t.renders} (${t.totalMs}ms${t.cause ? `, ${t.cause}` : ""})`
|
|
1002
|
+
).join(", ");
|
|
743
1003
|
const commits = r.renderCommits != null ? `${r.renderCommits} commits` : "";
|
|
744
|
-
|
|
1004
|
+
const wasted = r.renderWasted != null ? `${r.renderWasted} wasted` : "";
|
|
1005
|
+
return `- **${r.caseName}** \u2014 ${[commits, wasted, top].filter(Boolean).join(": ")}`;
|
|
745
1006
|
});
|
|
746
1007
|
if (renderLines.length) {
|
|
747
1008
|
lines.push("");
|
|
748
|
-
lines.push(
|
|
1009
|
+
lines.push(
|
|
1010
|
+
"**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."
|
|
1011
|
+
);
|
|
749
1012
|
lines.push(...renderLines);
|
|
750
1013
|
}
|
|
751
1014
|
lines.push("");
|
|
@@ -768,7 +1031,20 @@ function compareReportStats(a, b) {
|
|
|
768
1031
|
cpuUsage: ch(a.stats.cpuUsage, b.stats.cpuUsage),
|
|
769
1032
|
memoryUsage: ch(a.stats.memoryUsage, b.stats.memoryUsage),
|
|
770
1033
|
jsJankFrames: { a: a.stats.jsJankFrames, b: b.stats.jsJankFrames, delta: b.stats.jsJankFrames - a.stats.jsJankFrames },
|
|
771
|
-
uiJankFrames: { a: a.stats.uiJankFrames, b: b.stats.uiJankFrames, delta: b.stats.uiJankFrames - a.stats.uiJankFrames }
|
|
1034
|
+
uiJankFrames: { a: a.stats.uiJankFrames, b: b.stats.uiJankFrames, delta: b.stats.uiJankFrames - a.stats.uiJankFrames },
|
|
1035
|
+
...compareRenders(a.renders, b.renders)
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
function compareRenders(a, b) {
|
|
1039
|
+
if (!a && !b) return null;
|
|
1040
|
+
const n = (v) => v ?? 0;
|
|
1041
|
+
return {
|
|
1042
|
+
renders: {
|
|
1043
|
+
total: { a: n(a?.totalRenders), b: n(b?.totalRenders), delta: n(b?.totalRenders) - n(a?.totalRenders) },
|
|
1044
|
+
commits: { a: n(a?.totalCommits), b: n(b?.totalCommits), delta: n(b?.totalCommits) - n(a?.totalCommits) },
|
|
1045
|
+
wasted: { a: n(a?.wastedRenders), b: n(b?.wastedRenders), delta: n(b?.wastedRenders) - n(a?.wastedRenders) },
|
|
1046
|
+
causes: { a: a?.causes ?? {}, b: b?.causes ?? {} }
|
|
1047
|
+
}
|
|
772
1048
|
};
|
|
773
1049
|
}
|
|
774
1050
|
function round(n, d) {
|
|
@@ -1024,7 +1300,7 @@ ${JSON.stringify(summary, null, 2)}
|
|
|
1024
1300
|
async ({ deviceId, maxWaitMs }) => {
|
|
1025
1301
|
const log = (m) => process.stderr.write(`[buoy-mcp] ${m}
|
|
1026
1302
|
`);
|
|
1027
|
-
const
|
|
1303
|
+
const cap3 = maxWaitMs ?? 6e5;
|
|
1028
1304
|
try {
|
|
1029
1305
|
const target = sync.requireProDevice(deviceId);
|
|
1030
1306
|
const start = Date.now();
|
|
@@ -1032,7 +1308,7 @@ ${JSON.stringify(summary, null, 2)}
|
|
|
1032
1308
|
let idleStreak = 0;
|
|
1033
1309
|
let lastCount = -1;
|
|
1034
1310
|
let resolved = null;
|
|
1035
|
-
while (Date.now() - start <
|
|
1311
|
+
while (Date.now() - start < cap3) {
|
|
1036
1312
|
let snap2;
|
|
1037
1313
|
try {
|
|
1038
1314
|
snap2 = await readPerfSnapshot(sync, target);
|
|
@@ -1117,7 +1393,7 @@ ${JSON.stringify(ranking, null, 2)}
|
|
|
1117
1393
|
server.registerTool(
|
|
1118
1394
|
"compare_reports",
|
|
1119
1395
|
{
|
|
1120
|
-
description: "Compare two saved benchmark runs head-to-head
|
|
1396
|
+
description: "Compare two saved benchmark runs head-to-head: avg + p95 for FPS/CPU/memory, jank, AND render counts \u2014 total, commits, and wasted (parent cascades + identity-only prop churn) \u2014 each with deltas. Use this to prove a memoization or re-render fix actually landed: the wasted-render delta is the number that says so.",
|
|
1121
1397
|
inputSchema: {
|
|
1122
1398
|
reportIdA: z2.string().describe("First (baseline) report id."),
|
|
1123
1399
|
reportIdB: z2.string().describe("Second report id to compare against the baseline."),
|
|
@@ -1135,8 +1411,8 @@ ${JSON.stringify(ranking, null, 2)}
|
|
|
1135
1411
|
if (!b) return fail2(`Report "${reportIdB}" not found.`);
|
|
1136
1412
|
return json2(
|
|
1137
1413
|
compareReportStats(
|
|
1138
|
-
{ name: a.metadata.name, stats: a.stats },
|
|
1139
|
-
{ name: b.metadata.name, stats: b.stats }
|
|
1414
|
+
{ name: a.metadata.name, stats: a.stats, renders: a.renders },
|
|
1415
|
+
{ name: b.metadata.name, stats: b.stats, renders: b.renders }
|
|
1140
1416
|
)
|
|
1141
1417
|
);
|
|
1142
1418
|
} catch (e) {
|
|
@@ -1662,13 +1938,13 @@ function registerStorageTools(server, sync) {
|
|
|
1662
1938
|
const target = sync.requireProDevice(args.deviceId);
|
|
1663
1939
|
const pattern = args.pattern?.toLowerCase();
|
|
1664
1940
|
const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 100;
|
|
1665
|
-
const
|
|
1941
|
+
const matches2 = (k) => !pattern || k.toLowerCase().includes(pattern);
|
|
1666
1942
|
const sections = [];
|
|
1667
1943
|
const allKeys = await sync.callAction(STORAGE_TOOL_ID, "async.getAllKeys", {}, target);
|
|
1668
1944
|
if (!Array.isArray(allKeys)) {
|
|
1669
1945
|
return fail8("No storage result from the device. The storage tool may be inactive.");
|
|
1670
1946
|
}
|
|
1671
|
-
const asyncKeys = allKeys.filter(
|
|
1947
|
+
const asyncKeys = allKeys.filter(matches2).slice(0, limit);
|
|
1672
1948
|
if (asyncKeys.length > 0) {
|
|
1673
1949
|
let lines;
|
|
1674
1950
|
if (args.includeValues) {
|
|
@@ -1683,7 +1959,7 @@ ${lines.join("\n")}`);
|
|
|
1683
1959
|
}
|
|
1684
1960
|
const mmkv = await sync.callAction(STORAGE_TOOL_ID, "mmkv.snapshot", {}, target).catch(() => null);
|
|
1685
1961
|
for (const inst of mmkv ?? []) {
|
|
1686
|
-
const entries = inst.entries.filter((e) =>
|
|
1962
|
+
const entries = inst.entries.filter((e) => matches2(e.key)).slice(0, limit);
|
|
1687
1963
|
if (entries.length === 0) continue;
|
|
1688
1964
|
const lines = entries.map(
|
|
1689
1965
|
(e) => args.includeValues ? `- \`${e.key}\` (${e.valueType}) = ${truncate(e.value)}` : `- \`${e.key}\``
|
|
@@ -1693,7 +1969,7 @@ ${lines.join("\n")}`);
|
|
|
1693
1969
|
${lines.join("\n")}`);
|
|
1694
1970
|
}
|
|
1695
1971
|
const secure = await sync.callAction(STORAGE_TOOL_ID, "secure.keys", {}, target).catch(() => null);
|
|
1696
|
-
const secureKeys = (secure ?? []).filter((d) =>
|
|
1972
|
+
const secureKeys = (secure ?? []).filter((d) => matches2(d.key)).slice(0, limit);
|
|
1697
1973
|
if (secureKeys.length > 0) {
|
|
1698
1974
|
const lines = await Promise.all(
|
|
1699
1975
|
secureKeys.map(async (d) => {
|
|
@@ -1861,7 +2137,10 @@ function registerConsoleTools(server, sync) {
|
|
|
1861
2137
|
async (args) => {
|
|
1862
2138
|
try {
|
|
1863
2139
|
const target = sync.requireProDevice(args.deviceId);
|
|
1864
|
-
const { payload } = await sync.getSnapshot(CONSOLE_TOOL_ID, target);
|
|
2140
|
+
const { payload, stale } = await sync.getSnapshot(CONSOLE_TOOL_ID, target);
|
|
2141
|
+
const staleHeader = stale ? `${stale}
|
|
2142
|
+
|
|
2143
|
+
` : "";
|
|
1865
2144
|
const p = Array.isArray(payload) ? { entries: payload } : payload ?? {};
|
|
1866
2145
|
const all = Array.isArray(p.entries) ? p.entries : [];
|
|
1867
2146
|
const minSev = args.level ? SEVERITY[args.level] : 0;
|
|
@@ -1873,12 +2152,12 @@ function registerConsoleTools(server, sync) {
|
|
|
1873
2152
|
const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 50;
|
|
1874
2153
|
const shown = sorted.slice(-limit);
|
|
1875
2154
|
if (shown.length === 0) {
|
|
1876
|
-
return text9(
|
|
2155
|
+
return text9(`${staleHeader}No console entries${args.level ? ` at level \u2265 ${args.level}` : ""}${pattern ? ` matching "${args.pattern}"` : ""} (${all.length} total captured).`);
|
|
1877
2156
|
}
|
|
1878
2157
|
const lines = shown.map((e) => `${hhmmss(e.timestamp)} [${TAG[e.level] ?? e.level}] ${e.message}`);
|
|
1879
2158
|
const levelNote = args.level ? `, level \u2265 ${args.level}` : "";
|
|
1880
2159
|
const header = `**Console \u2014 ${all.length} entries (showing ${shown.length}${levelNote}):**`;
|
|
1881
|
-
return text9(`${header}
|
|
2160
|
+
return text9(`${staleHeader}${header}
|
|
1882
2161
|
|
|
1883
2162
|
\`\`\`
|
|
1884
2163
|
${lines.join("\n")}
|
|
@@ -2068,7 +2347,7 @@ function registerScreenshotTools(server, sync) {
|
|
|
2068
2347
|
|
|
2069
2348
|
// src/server.ts
|
|
2070
2349
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2071
|
-
import { z as
|
|
2350
|
+
import { z as z22 } from "zod";
|
|
2072
2351
|
|
|
2073
2352
|
// src/tools/packs/network.ts
|
|
2074
2353
|
import { z as z12 } from "zod";
|
|
@@ -2567,13 +2846,19 @@ function kb(bytes) {
|
|
|
2567
2846
|
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
|
2568
2847
|
}
|
|
2569
2848
|
function formatOutcome(outcome) {
|
|
2570
|
-
const lines = Object.entries(outcome.results).map(([sid,
|
|
2571
|
-
const skips =
|
|
2849
|
+
const lines = Object.entries(outcome.results).map(([sid, r2]) => {
|
|
2850
|
+
const skips = r2.skipped.slice(0, 3).map((s) => `
|
|
2572
2851
|
\xB7 ${s.id}: ${s.reason}`).join("");
|
|
2573
|
-
const warns =
|
|
2852
|
+
const warns = r2.warnings.slice(0, 3).map((w) => `
|
|
2574
2853
|
\u26A0 ${w}`).join("");
|
|
2575
|
-
return ` ${
|
|
2854
|
+
return ` ${r2.ok ? "\u2713" : "\u2715"} ${sid} \u2014 applied ${r2.applied}${r2.skipped.length ? `, skipped ${r2.skipped.length}` : ""}${skips}${warns}`;
|
|
2576
2855
|
});
|
|
2856
|
+
const r = outcome.route;
|
|
2857
|
+
if (r) {
|
|
2858
|
+
lines.push(
|
|
2859
|
+
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}`
|
|
2860
|
+
);
|
|
2861
|
+
}
|
|
2577
2862
|
return `Restored "${outcome.snapshotName}" (${outcome.mode}${outcome.willReload ? ", app reloading" : ""}):
|
|
2578
2863
|
${lines.join("\n")}`;
|
|
2579
2864
|
}
|
|
@@ -2581,7 +2866,7 @@ function registerTimeMachineTools(server, sync) {
|
|
|
2581
2866
|
server.registerTool(
|
|
2582
2867
|
"get_time_machine",
|
|
2583
2868
|
{
|
|
2584
|
-
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.",
|
|
2869
|
+
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.",
|
|
2585
2870
|
inputSchema: {
|
|
2586
2871
|
deviceId: z13.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
2587
2872
|
}
|
|
@@ -2594,13 +2879,19 @@ function registerTimeMachineTools(server, sync) {
|
|
|
2594
2879
|
const snapshots = p.snapshots ?? [];
|
|
2595
2880
|
const providers = p.providers ?? [];
|
|
2596
2881
|
const providerLines = providers.map((pr) => {
|
|
2597
|
-
const
|
|
2598
|
-
return `- ${pr.label} (${pr.id}): ${
|
|
2882
|
+
const cap3 = pr.canCapture ? pr.canRestore ? "capture+restore" : "capture only" : "unavailable";
|
|
2883
|
+
return `- ${pr.label} (${pr.id}): ${cap3}${pr.detail ? ` \u2014 ${pr.detail}` : ""}`;
|
|
2599
2884
|
});
|
|
2885
|
+
if (p.route) {
|
|
2886
|
+
providerLines.push(
|
|
2887
|
+
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"
|
|
2888
|
+
);
|
|
2889
|
+
}
|
|
2600
2890
|
const snapLines = snapshots.map((s) => {
|
|
2601
2891
|
const warnings = Object.values(s.sources).reduce((n, src) => n + src.warnings.length, 0);
|
|
2602
2892
|
const desc = s.baseline ? "baseline \u2014 restore wipes to fresh install (always reloads)" : `${kb(s.sizeBytes)} \xB7 ${Object.keys(s.sources).join(", ")}`;
|
|
2603
|
-
|
|
2893
|
+
const route = s.route ? ` \xB7 route ${s.route.href}` : "";
|
|
2894
|
+
return `- \`${s.id}\` **${s.name}** \u2014 ${new Date(s.createdAt).toISOString()} \xB7 ${desc}${route}${warnings ? ` \xB7 \u26A0 ${warnings}` : ""}`;
|
|
2604
2895
|
});
|
|
2605
2896
|
const parts = [
|
|
2606
2897
|
`**Time Machine \u2014 ${snapshots.length} snapshot(s):**`,
|
|
@@ -2619,13 +2910,14 @@ ${formatOutcome(p.lastOutcome)}`);
|
|
|
2619
2910
|
server.registerTool(
|
|
2620
2911
|
"time_machine_action",
|
|
2621
2912
|
{
|
|
2622
|
-
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.",
|
|
2913
|
+
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.",
|
|
2623
2914
|
inputSchema: {
|
|
2624
2915
|
action: z13.enum(["capture", "capture_baseline", "preview", "restore", "delete", "rename"]).describe("What to do."),
|
|
2625
2916
|
id: z13.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),
|
|
2626
2917
|
name: z13.string().optional().describe("Snapshot name (for capture and rename)."),
|
|
2627
2918
|
mode: z13.enum(["live", "reload"]).optional().describe("Restore mode. Default 'live'."),
|
|
2628
2919
|
excludeKeys: z13.array(z13.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").'),
|
|
2920
|
+
restoreRoute: z13.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."),
|
|
2629
2921
|
sourceIds: z13.array(z13.string()).optional().describe("Capture/restore only these source ids (default all)."),
|
|
2630
2922
|
deviceId: z13.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
2631
2923
|
}
|
|
@@ -2674,7 +2966,8 @@ ${lines.join("\n")}`);
|
|
|
2674
2966
|
const outcome = await call("restore", {
|
|
2675
2967
|
id: args.id,
|
|
2676
2968
|
mode: args.mode ?? "live",
|
|
2677
|
-
excludeKeys: args.excludeKeys
|
|
2969
|
+
excludeKeys: args.excludeKeys,
|
|
2970
|
+
restoreRoute: args.restoreRoute
|
|
2678
2971
|
});
|
|
2679
2972
|
return text11(formatOutcome(outcome));
|
|
2680
2973
|
}
|
|
@@ -2718,11 +3011,14 @@ function formatElement(e) {
|
|
|
2718
3011
|
if (e.nativeTag != null) line += ` #${e.nativeTag}`;
|
|
2719
3012
|
return line;
|
|
2720
3013
|
}
|
|
3014
|
+
var tapCount = 0;
|
|
3015
|
+
var FLOW_TIP_EVERY = 3;
|
|
3016
|
+
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.";
|
|
2721
3017
|
function registerInteractTools(server, sync) {
|
|
2722
3018
|
server.registerTool(
|
|
2723
3019
|
"describe_screen",
|
|
2724
3020
|
{
|
|
2725
|
-
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.",
|
|
3021
|
+
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.",
|
|
2726
3022
|
inputSchema: {
|
|
2727
3023
|
interactiveOnly: z14.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),
|
|
2728
3024
|
deviceId: z14.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
@@ -2751,7 +3047,7 @@ ${elements.map(formatElement).join("\n")}`);
|
|
|
2751
3047
|
server.registerTool(
|
|
2752
3048
|
"tap_element",
|
|
2753
3049
|
{
|
|
2754
|
-
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.",
|
|
3050
|
+
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.",
|
|
2755
3051
|
inputSchema: {
|
|
2756
3052
|
nativeTag: z14.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),
|
|
2757
3053
|
testID: z14.string().optional().describe("Exact testID of the element."),
|
|
@@ -2783,13 +3079,15 @@ ${elements.map(formatElement).join("\n")}`);
|
|
|
2783
3079
|
},
|
|
2784
3080
|
target
|
|
2785
3081
|
);
|
|
3082
|
+
tapCount += 1;
|
|
3083
|
+
const flowTip = tapCount >= FLOW_TIP_EVERY && tapCount % FLOW_TIP_EVERY === 0 ? FLOW_TIP : "";
|
|
2786
3084
|
if (res?.tapped && res.matched) {
|
|
2787
3085
|
const m = res.matched;
|
|
2788
3086
|
const label = m.text ?? m.label ?? m.name;
|
|
2789
3087
|
const id = m.testID ? ` [testID=${m.testID}]` : m.nativeTag != null ? ` #${m.nativeTag}` : "";
|
|
2790
3088
|
const scrolledNote = res.scrolled ? " (scrolled into view)" : "";
|
|
2791
3089
|
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}`;
|
|
2792
|
-
return text12(`${verb}${scrolledNote}
|
|
3090
|
+
return text12(`${verb}${scrolledNote}.${flowTip}`);
|
|
2793
3091
|
}
|
|
2794
3092
|
let msg = res?.reason ?? "Tap failed.";
|
|
2795
3093
|
if (res?.candidates?.length) {
|
|
@@ -2877,7 +3175,7 @@ function registerJsThreadTools(server, sync) {
|
|
|
2877
3175
|
server.registerTool(
|
|
2878
3176
|
"get_js_thread_top",
|
|
2879
3177
|
{
|
|
2880
|
-
description:
|
|
3178
|
+
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.',
|
|
2881
3179
|
inputSchema: {
|
|
2882
3180
|
deviceId: z15.string().optional().describe("Target device id (auto-selected if one is connected)."),
|
|
2883
3181
|
durationMs: z15.number().optional().describe("How long to sample before reading the table. Default 3000, max 30000."),
|
|
@@ -3457,6 +3755,62 @@ ${JSON.stringify(slim)}
|
|
|
3457
3755
|
|
|
3458
3756
|
// src/tools/packs/reload.ts
|
|
3459
3757
|
import { z as z18 } from "zod";
|
|
3758
|
+
|
|
3759
|
+
// src/capture/devServerReload.ts
|
|
3760
|
+
import { WebSocket } from "ws";
|
|
3761
|
+
var CONNECT_TIMEOUT_MS = 3e3;
|
|
3762
|
+
function messageSocketUrl(origin) {
|
|
3763
|
+
return `${origin.replace(/^http/, "ws").replace(/\/+$/, "")}/message`;
|
|
3764
|
+
}
|
|
3765
|
+
function reloadViaDevServer(origin) {
|
|
3766
|
+
return new Promise((resolve) => {
|
|
3767
|
+
let settled = false;
|
|
3768
|
+
const done = (result) => {
|
|
3769
|
+
if (settled) return;
|
|
3770
|
+
settled = true;
|
|
3771
|
+
resolve(result);
|
|
3772
|
+
};
|
|
3773
|
+
let socket;
|
|
3774
|
+
try {
|
|
3775
|
+
socket = new WebSocket(messageSocketUrl(origin));
|
|
3776
|
+
} catch (e) {
|
|
3777
|
+
done({ ok: false, error: e.message });
|
|
3778
|
+
return;
|
|
3779
|
+
}
|
|
3780
|
+
const timer = setTimeout(() => {
|
|
3781
|
+
try {
|
|
3782
|
+
socket.close();
|
|
3783
|
+
} catch {
|
|
3784
|
+
}
|
|
3785
|
+
done({ ok: false, error: `dev server at ${origin} did not accept a connection` });
|
|
3786
|
+
}, CONNECT_TIMEOUT_MS);
|
|
3787
|
+
let sent = false;
|
|
3788
|
+
socket.on("open", () => {
|
|
3789
|
+
try {
|
|
3790
|
+
socket.send(JSON.stringify({ version: 2, method: "reload" }));
|
|
3791
|
+
sent = true;
|
|
3792
|
+
clearTimeout(timer);
|
|
3793
|
+
setTimeout(() => {
|
|
3794
|
+
try {
|
|
3795
|
+
socket.close();
|
|
3796
|
+
} catch {
|
|
3797
|
+
}
|
|
3798
|
+
done({ ok: true });
|
|
3799
|
+
}, 250);
|
|
3800
|
+
} catch (e) {
|
|
3801
|
+
clearTimeout(timer);
|
|
3802
|
+
done({ ok: false, error: e.message });
|
|
3803
|
+
}
|
|
3804
|
+
});
|
|
3805
|
+
socket.on("error", (e) => {
|
|
3806
|
+
clearTimeout(timer);
|
|
3807
|
+
if (sent) return;
|
|
3808
|
+
done({ ok: false, error: e.message });
|
|
3809
|
+
});
|
|
3810
|
+
});
|
|
3811
|
+
}
|
|
3812
|
+
|
|
3813
|
+
// src/tools/packs/reload.ts
|
|
3460
3814
|
var APP_TOOL_ID = "app";
|
|
3461
3815
|
var RELOAD_ACTION = "reloadApp";
|
|
3462
3816
|
var DEFAULT_WAIT_MS = 3e4;
|
|
@@ -3469,7 +3823,11 @@ var errMsg18 = (e) => e instanceof Error ? e.message : String(e);
|
|
|
3469
3823
|
var delay3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3470
3824
|
async function ping(sync, deviceId, timeoutMs) {
|
|
3471
3825
|
try {
|
|
3472
|
-
const pong = await sync.callAction(APP_TOOL_ID, "ping", {}, deviceId, {
|
|
3826
|
+
const pong = await sync.callAction(APP_TOOL_ID, "ping", {}, deviceId, {
|
|
3827
|
+
timeoutMs,
|
|
3828
|
+
silent: true
|
|
3829
|
+
});
|
|
3830
|
+
sync.noteDevServerOrigin(deviceId, pong?.devServerOrigin);
|
|
3473
3831
|
return typeof pong?.startedAt === "number" ? pong.startedAt : null;
|
|
3474
3832
|
} catch {
|
|
3475
3833
|
return null;
|
|
@@ -3498,7 +3856,7 @@ function registerReloadTools(server, sync) {
|
|
|
3498
3856
|
server.registerTool(
|
|
3499
3857
|
"reload_app",
|
|
3500
3858
|
{
|
|
3501
|
-
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,
|
|
3859
|
+
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.",
|
|
3502
3860
|
inputSchema: {
|
|
3503
3861
|
strategy: z18.enum(["auto", "dev-settings", "expo-updates"]).optional().describe(
|
|
3504
3862
|
"Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."
|
|
@@ -3513,13 +3871,27 @@ function registerReloadTools(server, sync) {
|
|
|
3513
3871
|
const target = sync.requireProDevice(args.deviceId);
|
|
3514
3872
|
assertReloadSupported(sync, target);
|
|
3515
3873
|
const previousRealm = args.wait === false ? null : await ping(sync, target, PROBE_TIMEOUT_MS);
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3874
|
+
let ack = null;
|
|
3875
|
+
let recovered = false;
|
|
3876
|
+
try {
|
|
3877
|
+
ack = await sync.callAction(
|
|
3878
|
+
APP_TOOL_ID,
|
|
3879
|
+
RELOAD_ACTION,
|
|
3880
|
+
{ strategy: args.strategy ?? "auto" },
|
|
3881
|
+
target
|
|
3882
|
+
);
|
|
3883
|
+
} catch (inAppError) {
|
|
3884
|
+
const origin = sync.devServerOrigin(target);
|
|
3885
|
+
if (!origin) throw inAppError;
|
|
3886
|
+
const res = await reloadViaDevServer(origin);
|
|
3887
|
+
if (!res.ok) {
|
|
3888
|
+
throw new Error(
|
|
3889
|
+
`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.`
|
|
3890
|
+
);
|
|
3891
|
+
}
|
|
3892
|
+
recovered = true;
|
|
3893
|
+
}
|
|
3894
|
+
const via = recovered ? ` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)` : ack?.strategy ? ` via ${ack.strategy}` : "";
|
|
3523
3895
|
if (args.wait === false) {
|
|
3524
3896
|
return text16(`Reload requested${via}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`);
|
|
3525
3897
|
}
|
|
@@ -3539,12 +3911,836 @@ function registerReloadTools(server, sync) {
|
|
|
3539
3911
|
);
|
|
3540
3912
|
}
|
|
3541
3913
|
|
|
3914
|
+
// src/tools/packs/triage.ts
|
|
3915
|
+
import { z as z19 } from "zod";
|
|
3916
|
+
var text17 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
3917
|
+
var fail19 = (message) => ({
|
|
3918
|
+
isError: true,
|
|
3919
|
+
content: [{ type: "text", text: message }]
|
|
3920
|
+
});
|
|
3921
|
+
var errMsg19 = (e) => e instanceof Error ? e.message : String(e);
|
|
3922
|
+
var PROBE_TIMEOUT_MS2 = 5e3;
|
|
3923
|
+
var MAX_STORAGE_KEYS = 20;
|
|
3924
|
+
var MAX_STORAGE_VALUE = 400;
|
|
3925
|
+
var STORAGE_VALUE_BUDGET = 1600;
|
|
3926
|
+
var MAX_LINE = 160;
|
|
3927
|
+
var cap = (s, n = MAX_LINE) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
3928
|
+
function hhmmss2(ts) {
|
|
3929
|
+
if (!ts) return "--:--:--";
|
|
3930
|
+
const d = new Date(ts);
|
|
3931
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
3932
|
+
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
3933
|
+
}
|
|
3934
|
+
async function otherBackends(sync, target, opts) {
|
|
3935
|
+
const notes = [];
|
|
3936
|
+
try {
|
|
3937
|
+
const mmkv = await sync.callAction("storage", "mmkv.snapshot", {}, target, opts);
|
|
3938
|
+
for (const inst of mmkv ?? []) {
|
|
3939
|
+
const n = inst.entries?.length ?? 0;
|
|
3940
|
+
if (n > 0) notes.push(`MMKV "${inst.id}": ${n} key${n === 1 ? "" : "s"}`);
|
|
3941
|
+
}
|
|
3942
|
+
} catch {
|
|
3943
|
+
}
|
|
3944
|
+
try {
|
|
3945
|
+
const secure = await sync.callAction("storage", "secure.keys", {}, target, opts);
|
|
3946
|
+
if (secure?.length) notes.push(`SecureStore: ${secure.length} key${secure.length === 1 ? "" : "s"}`);
|
|
3947
|
+
} catch {
|
|
3948
|
+
}
|
|
3949
|
+
return notes.length ? `
|
|
3950
|
+
${notes.join(" \xB7 ")} \u2014 read with get_storage` : "";
|
|
3951
|
+
}
|
|
3952
|
+
async function section(title, run) {
|
|
3953
|
+
try {
|
|
3954
|
+
const body = await run();
|
|
3955
|
+
return body ? `${title}
|
|
3956
|
+
${body}` : null;
|
|
3957
|
+
} catch (e) {
|
|
3958
|
+
const msg = errMsg19(e);
|
|
3959
|
+
if (/not responding|timed out|got no answer/i.test(msg)) {
|
|
3960
|
+
return `${title}
|
|
3961
|
+
(no answer \u2014 see the note above)`;
|
|
3962
|
+
}
|
|
3963
|
+
return `${title}
|
|
3964
|
+
(unavailable: ${cap(msg, 120)})`;
|
|
3965
|
+
}
|
|
3966
|
+
}
|
|
3967
|
+
function registerTriageTools(server, sync) {
|
|
3968
|
+
server.registerTool(
|
|
3969
|
+
"get_triage",
|
|
3970
|
+
{
|
|
3971
|
+
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.",
|
|
3972
|
+
inputSchema: {
|
|
3973
|
+
deviceId: z19.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
3974
|
+
}
|
|
3975
|
+
},
|
|
3976
|
+
async (args) => {
|
|
3977
|
+
try {
|
|
3978
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
3979
|
+
const device = sync.connectedDevices().find((d) => d.deviceId === target);
|
|
3980
|
+
const toolIds = new Set((device?.tools ?? []).map((t) => t.toolId));
|
|
3981
|
+
const head = `**${device?.deviceName ?? target}** (${device?.platform ?? "?"}, id \`${target}\`) \u2014 tools: ${[...toolIds].join(", ") || "none"}`;
|
|
3982
|
+
const opts = { timeoutMs: PROBE_TIMEOUT_MS2 };
|
|
3983
|
+
const [consoleSec, netSec, storeSec, screenSec] = await Promise.all([
|
|
3984
|
+
section("**Console \u2014 recent errors/warnings:**", async () => {
|
|
3985
|
+
if (!toolIds.has("console")) return null;
|
|
3986
|
+
const { payload } = await sync.getSnapshot("console", target, opts);
|
|
3987
|
+
const p = payload;
|
|
3988
|
+
const entries = Array.isArray(p) ? p : p?.entries ?? [];
|
|
3989
|
+
const bad = entries.filter(
|
|
3990
|
+
(e) => e.level === "error" || e.level === "warning"
|
|
3991
|
+
);
|
|
3992
|
+
const shown = bad.slice(-8);
|
|
3993
|
+
if (shown.length === 0) {
|
|
3994
|
+
return `(none \u2014 ${entries.length} entries captured)`;
|
|
3995
|
+
}
|
|
3996
|
+
return shown.map(
|
|
3997
|
+
(e) => `${hhmmss2(e.timestamp)} [${e.level === "error" ? "ERR" : "warn"}] ${cap(
|
|
3998
|
+
(e.message ?? "").split("\n").map((l) => l.trim()).filter(Boolean).slice(0, 3).join(" \u23CE "),
|
|
3999
|
+
220
|
|
4000
|
+
)}`
|
|
4001
|
+
).join("\n");
|
|
4002
|
+
}),
|
|
4003
|
+
section("**Network \u2014 recent requests:**", async () => {
|
|
4004
|
+
if (!toolIds.has("network")) return null;
|
|
4005
|
+
const { payload } = await sync.getSnapshot("network", target, opts);
|
|
4006
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4007
|
+
if (events.length === 0) return "(no requests captured yet)";
|
|
4008
|
+
const shown = events.slice(-8);
|
|
4009
|
+
return shown.map((e) => {
|
|
4010
|
+
const mark = e.error || (e.status ?? 0) >= 400 ? "\u274C" : "\u2705";
|
|
4011
|
+
const where = e.path ?? e.url ?? "?";
|
|
4012
|
+
const status = e.error ?? e.status ?? "pending";
|
|
4013
|
+
return `${mark} ${e.method ?? "GET"} ${cap(String(where), 80)} \u2192 ${status}${e.duration ? ` (${Math.round(e.duration)}ms)` : ""}`;
|
|
4014
|
+
}).join("\n");
|
|
4015
|
+
}),
|
|
4016
|
+
section("**Storage \u2014 persisted values:**", async () => {
|
|
4017
|
+
if (!toolIds.has("storage")) return null;
|
|
4018
|
+
const keys = await sync.callAction(
|
|
4019
|
+
"storage",
|
|
4020
|
+
"async.getAllKeys",
|
|
4021
|
+
{},
|
|
4022
|
+
target,
|
|
4023
|
+
opts
|
|
4024
|
+
);
|
|
4025
|
+
if (!Array.isArray(keys) || keys.length === 0) {
|
|
4026
|
+
return "(no app keys)";
|
|
4027
|
+
}
|
|
4028
|
+
const head2 = keys.slice(0, MAX_STORAGE_KEYS);
|
|
4029
|
+
let pairs = [];
|
|
4030
|
+
try {
|
|
4031
|
+
pairs = await sync.callAction(
|
|
4032
|
+
"storage",
|
|
4033
|
+
"async.multiGet",
|
|
4034
|
+
{ keys: head2 },
|
|
4035
|
+
target,
|
|
4036
|
+
opts
|
|
4037
|
+
) ?? [];
|
|
4038
|
+
} catch {
|
|
4039
|
+
return `${head2.map((k) => `\`${k}\``).join(", ")}
|
|
4040
|
+
_Values: get_storage includeValues:true_`;
|
|
4041
|
+
}
|
|
4042
|
+
const byKey = new Map(pairs);
|
|
4043
|
+
let budget = STORAGE_VALUE_BUDGET;
|
|
4044
|
+
const lines = head2.map((k) => {
|
|
4045
|
+
const v = byKey.get(k);
|
|
4046
|
+
if (v == null) return `- \`${k}\` = (null)`;
|
|
4047
|
+
if (v.length > MAX_STORAGE_VALUE) {
|
|
4048
|
+
return `- \`${k}\` = (${(v.length / 1024).toFixed(1)} KB \u2014 read with get_storage)`;
|
|
4049
|
+
}
|
|
4050
|
+
if (budget <= 0) return `- \`${k}\` = (not shown \u2014 triage budget spent; read with get_storage)`;
|
|
4051
|
+
budget -= v.length;
|
|
4052
|
+
return `- \`${k}\` = ${v}`;
|
|
4053
|
+
});
|
|
4054
|
+
const more = keys.length - head2.length;
|
|
4055
|
+
const others = await otherBackends(sync, target, opts);
|
|
4056
|
+
return `${lines.join("\n")}${more > 0 ? `
|
|
4057
|
+
\u2026+${more} more keys` : ""}${others}`;
|
|
4058
|
+
}),
|
|
4059
|
+
section("**Screen \u2014 what's visible now:**", async () => {
|
|
4060
|
+
if (!toolIds.has("highlight-updates")) return null;
|
|
4061
|
+
const res = await sync.callAction(
|
|
4062
|
+
"highlight-updates",
|
|
4063
|
+
"describeScreen",
|
|
4064
|
+
{},
|
|
4065
|
+
target,
|
|
4066
|
+
opts
|
|
4067
|
+
);
|
|
4068
|
+
const els = (res?.elements ?? []).filter((e) => e.interactive);
|
|
4069
|
+
if (els.length === 0) return "(nothing interactive on screen)";
|
|
4070
|
+
return els.slice(0, 20).map(
|
|
4071
|
+
(e) => `\u2022 ${e.name}${e.text || e.label ? ` "${cap(e.text ?? e.label ?? "", 60)}"` : ""}${e.testID ? ` [testID=${e.testID}]` : ""}`
|
|
4072
|
+
).join("\n");
|
|
4073
|
+
})
|
|
4074
|
+
]);
|
|
4075
|
+
const crashed = sync.isUnresponsive(target);
|
|
4076
|
+
const banner = crashed ? `
|
|
4077
|
+
|
|
4078
|
+
\u{1F6D1} ${sync.unresponsiveNote(target)}` : "";
|
|
4079
|
+
const body = [consoleSec, netSec, storeSec, screenSec].filter(Boolean).join("\n\n");
|
|
4080
|
+
return text17(
|
|
4081
|
+
`${head}${banner}
|
|
4082
|
+
|
|
4083
|
+
${body}
|
|
4084
|
+
|
|
4085
|
+
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`
|
|
4086
|
+
);
|
|
4087
|
+
} catch (e) {
|
|
4088
|
+
return fail19(errMsg19(e));
|
|
4089
|
+
}
|
|
4090
|
+
}
|
|
4091
|
+
);
|
|
4092
|
+
}
|
|
4093
|
+
|
|
4094
|
+
// src/tools/packs/flow.ts
|
|
4095
|
+
import { z as z20 } from "zod";
|
|
4096
|
+
var UI_TOOL_ID = "highlight-updates";
|
|
4097
|
+
var APP_TOOL_ID2 = "app";
|
|
4098
|
+
var text18 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
4099
|
+
var fail20 = (message) => ({
|
|
4100
|
+
isError: true,
|
|
4101
|
+
content: [{ type: "text", text: message }]
|
|
4102
|
+
});
|
|
4103
|
+
var errMsg20 = (e) => e instanceof Error ? e.message : String(e);
|
|
4104
|
+
var delay4 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4105
|
+
var POLL_MS = 250;
|
|
4106
|
+
var DEFAULT_WAIT_MS2 = 5e3;
|
|
4107
|
+
var ASSERT_SETTLE_MS = 2e3;
|
|
4108
|
+
var TEARDOWN_GRACE_MS2 = 1200;
|
|
4109
|
+
var REALM_PROBE_MS = 1500;
|
|
4110
|
+
var MAX_FLOW_MS = 12e4;
|
|
4111
|
+
function matches(e, needle) {
|
|
4112
|
+
if (e.testID && e.testID === needle) return true;
|
|
4113
|
+
const n = needle.toLowerCase();
|
|
4114
|
+
return [e.testID, e.text, e.label, e.name].filter(Boolean).some((v) => String(v).toLowerCase().includes(n));
|
|
4115
|
+
}
|
|
4116
|
+
function formatElement2(e) {
|
|
4117
|
+
const display = e.text ?? e.label;
|
|
4118
|
+
return `${e.interactive ? "\u2022 " : " "}${e.name}${display ? ` "${display}"` : ""}${e.testID ? ` [testID=${e.testID}]` : ""}`;
|
|
4119
|
+
}
|
|
4120
|
+
var stepSchema = z20.object({
|
|
4121
|
+
tap: z20.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),
|
|
4122
|
+
longPress: z20.boolean().optional().describe("Make `tap` a long-press instead."),
|
|
4123
|
+
type: z20.string().optional().describe("Text to type (needs `into`)."),
|
|
4124
|
+
into: z20.string().optional().describe("Target text input for `type`: testID or fuzzy text."),
|
|
4125
|
+
set: z20.union([z20.number(), z20.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),
|
|
4126
|
+
reload: z20.boolean().optional().describe("Reload the JS bundle before this step's action."),
|
|
4127
|
+
waitMs: z20.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000)."),
|
|
4128
|
+
waitFor: z20.string().optional().describe("Wait until an element matching this appears (default 5s)."),
|
|
4129
|
+
waitGone: z20.string().optional().describe("Wait until no element matches this (default 5s)."),
|
|
4130
|
+
expect: z20.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),
|
|
4131
|
+
expectGone: z20.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),
|
|
4132
|
+
timeoutMs: z20.number().min(0).max(6e4).optional().describe("Budget for this step's waitFor/waitGone/expect, max 60000. Default 5000 (2000 for expect).")
|
|
4133
|
+
}).describe("One flow step. Order within a step: reload \u2192 tap/type/set \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect.");
|
|
4134
|
+
function registerFlowTools(server, sync) {
|
|
4135
|
+
server.registerTool(
|
|
4136
|
+
"run_flow",
|
|
4137
|
+
{
|
|
4138
|
+
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.",
|
|
4139
|
+
inputSchema: {
|
|
4140
|
+
steps: z20.array(stepSchema).min(1).describe("Steps to run, in order."),
|
|
4141
|
+
include: z20.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."),
|
|
4142
|
+
continueOnFailure: z20.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),
|
|
4143
|
+
deviceId: z20.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4144
|
+
}
|
|
4145
|
+
},
|
|
4146
|
+
async (args) => {
|
|
4147
|
+
const started = Date.now();
|
|
4148
|
+
try {
|
|
4149
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4150
|
+
const include = args.include ?? "all";
|
|
4151
|
+
const describe = async () => {
|
|
4152
|
+
const res = await sync.callAction(UI_TOOL_ID, "describeScreen", {}, target);
|
|
4153
|
+
return res?.elements ?? [];
|
|
4154
|
+
};
|
|
4155
|
+
const realmId = async () => {
|
|
4156
|
+
try {
|
|
4157
|
+
const pong = await sync.callAction(APP_TOOL_ID2, "ping", {}, target, {
|
|
4158
|
+
timeoutMs: REALM_PROBE_MS,
|
|
4159
|
+
silent: true
|
|
4160
|
+
// probes across a reload are expected to fail
|
|
4161
|
+
});
|
|
4162
|
+
return typeof pong?.startedAt === "number" ? pong.startedAt : null;
|
|
4163
|
+
} catch {
|
|
4164
|
+
return null;
|
|
4165
|
+
}
|
|
4166
|
+
};
|
|
4167
|
+
const untilNewRealm = async (previous, budgetMs) => {
|
|
4168
|
+
const t0 = Date.now();
|
|
4169
|
+
while (Date.now() - t0 < budgetMs) {
|
|
4170
|
+
const realm = await realmId();
|
|
4171
|
+
if (realm !== null && realm !== previous) return Date.now() - t0;
|
|
4172
|
+
await delay4(POLL_MS);
|
|
4173
|
+
}
|
|
4174
|
+
return null;
|
|
4175
|
+
};
|
|
4176
|
+
const beforeConsole = /* @__PURE__ */ new Set();
|
|
4177
|
+
const beforeNetwork = /* @__PURE__ */ new Set();
|
|
4178
|
+
const toolIds = new Set(
|
|
4179
|
+
(sync.connectedDevices().find((d) => d.deviceId === target)?.tools ?? []).map((t) => t.toolId)
|
|
4180
|
+
);
|
|
4181
|
+
if (include === "all") {
|
|
4182
|
+
if (toolIds.has("console")) {
|
|
4183
|
+
const { payload } = await sync.getSnapshot("console", target).catch(() => ({ payload: null }));
|
|
4184
|
+
const entries = payload?.entries ?? [];
|
|
4185
|
+
for (const e of entries) beforeConsole.add(e.id);
|
|
4186
|
+
}
|
|
4187
|
+
if (toolIds.has("network")) {
|
|
4188
|
+
const { payload } = await sync.getSnapshot("network", target).catch(() => ({ payload: null }));
|
|
4189
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4190
|
+
for (const e of events) beforeNetwork.add(e.id);
|
|
4191
|
+
}
|
|
4192
|
+
}
|
|
4193
|
+
const until = async (predicate, budgetMs) => {
|
|
4194
|
+
const t0 = Date.now();
|
|
4195
|
+
for (; ; ) {
|
|
4196
|
+
if (Date.now() - t0 >= budgetMs || Date.now() - started > MAX_FLOW_MS) {
|
|
4197
|
+
return { ok: false, ms: Date.now() - t0 };
|
|
4198
|
+
}
|
|
4199
|
+
let els = [];
|
|
4200
|
+
try {
|
|
4201
|
+
els = await describe();
|
|
4202
|
+
} catch {
|
|
4203
|
+
}
|
|
4204
|
+
if (predicate(els)) return { ok: true, ms: Date.now() - t0 };
|
|
4205
|
+
await delay4(POLL_MS);
|
|
4206
|
+
}
|
|
4207
|
+
};
|
|
4208
|
+
const lines = [];
|
|
4209
|
+
let failedAt = null;
|
|
4210
|
+
let okCount = 0;
|
|
4211
|
+
for (let i = 0; i < args.steps.length; i++) {
|
|
4212
|
+
const step = args.steps[i];
|
|
4213
|
+
const label = `${i + 1}`;
|
|
4214
|
+
const budget = step.timeoutMs ?? DEFAULT_WAIT_MS2;
|
|
4215
|
+
if (Date.now() - started > MAX_FLOW_MS) {
|
|
4216
|
+
lines.push(`${label} \u2717 flow exceeded ${MAX_FLOW_MS / 1e3}s \u2014 stopped here`);
|
|
4217
|
+
failedAt = i;
|
|
4218
|
+
break;
|
|
4219
|
+
}
|
|
4220
|
+
const stepErrors = [];
|
|
4221
|
+
const done = [];
|
|
4222
|
+
const actionable = step.reload || step.tap || step.type !== void 0 || step.waitMs || step.waitFor || step.waitGone || step.expect || step.expectGone;
|
|
4223
|
+
if (!actionable) {
|
|
4224
|
+
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)" : ""}`);
|
|
4225
|
+
failedAt = failedAt ?? i;
|
|
4226
|
+
if (!args.continueOnFailure) break;
|
|
4227
|
+
continue;
|
|
4228
|
+
}
|
|
4229
|
+
try {
|
|
4230
|
+
if (step.reload) {
|
|
4231
|
+
const previousRealm = await realmId();
|
|
4232
|
+
await sync.callAction(APP_TOOL_ID2, "reloadApp", { strategy: "auto" }, target);
|
|
4233
|
+
await delay4(TEARDOWN_GRACE_MS2);
|
|
4234
|
+
const back = await untilNewRealm(previousRealm, Math.max(budget, 2e4));
|
|
4235
|
+
if (back == null) {
|
|
4236
|
+
stepErrors.push("app did not come back after reload");
|
|
4237
|
+
} else {
|
|
4238
|
+
done.push(`reloaded (${back}ms)`);
|
|
4239
|
+
await until((els) => els.length > 0, 1e4);
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
if (step.type !== void 0) {
|
|
4243
|
+
const targetSel = step.into ?? step.tap;
|
|
4244
|
+
if (!targetSel) {
|
|
4245
|
+
stepErrors.push("`type` needs `into` (which input to type into)");
|
|
4246
|
+
} else {
|
|
4247
|
+
const res = await sync.callAction(
|
|
4248
|
+
UI_TOOL_ID,
|
|
4249
|
+
"tapElement",
|
|
4250
|
+
{ ...selector(targetSel), text: step.type },
|
|
4251
|
+
target
|
|
4252
|
+
);
|
|
4253
|
+
if (!res?.tapped) {
|
|
4254
|
+
stepErrors.push(res?.reason ?? `could not type into "${targetSel}"`);
|
|
4255
|
+
} else if (res.matched?.via && res.matched.via !== "onChangeText") {
|
|
4256
|
+
stepErrors.push(
|
|
4257
|
+
`"${targetSel}" is not a text input \u2014 it ran ${res.matched.via} instead, and the text was not entered`
|
|
4258
|
+
);
|
|
4259
|
+
} else {
|
|
4260
|
+
done.push(`typed ${JSON.stringify(step.type)} into "${targetSel}"`);
|
|
4261
|
+
}
|
|
4262
|
+
}
|
|
4263
|
+
} else if (step.tap) {
|
|
4264
|
+
const params = { ...selector(step.tap) };
|
|
4265
|
+
if (step.longPress) params.longPress = true;
|
|
4266
|
+
if (step.set !== void 0) params.value = step.set;
|
|
4267
|
+
const res = await sync.callAction(UI_TOOL_ID, "tapElement", params, target);
|
|
4268
|
+
if (!res?.tapped) {
|
|
4269
|
+
stepErrors.push(res?.reason ?? `no element matched "${step.tap}"`);
|
|
4270
|
+
} else {
|
|
4271
|
+
const m = res.matched;
|
|
4272
|
+
const what = m?.text ?? m?.label ?? m?.name ?? step.tap;
|
|
4273
|
+
if (step.set !== void 0 && m?.via && m.via !== "onValueChange") {
|
|
4274
|
+
stepErrors.push(
|
|
4275
|
+
`"${what}" is not a toggle/slider \u2014 it ran ${m.via} instead, so it was not set to ${JSON.stringify(step.set)}`
|
|
4276
|
+
);
|
|
4277
|
+
} else {
|
|
4278
|
+
done.push(
|
|
4279
|
+
step.set !== void 0 ? `set "${what}" \u2192 ${JSON.stringify(m?.value ?? step.set)}` : `${step.longPress ? "long-pressed" : "tapped"} "${what}"`
|
|
4280
|
+
);
|
|
4281
|
+
}
|
|
4282
|
+
}
|
|
4283
|
+
}
|
|
4284
|
+
if (!stepErrors.length && step.waitMs) {
|
|
4285
|
+
await delay4(step.waitMs);
|
|
4286
|
+
done.push(`waited ${step.waitMs}ms`);
|
|
4287
|
+
}
|
|
4288
|
+
if (!stepErrors.length && step.waitFor) {
|
|
4289
|
+
const r = await until((els) => els.some((e) => matches(e, step.waitFor)), budget);
|
|
4290
|
+
if (r.ok) done.push(`"${step.waitFor}" appeared (${r.ms}ms)`);
|
|
4291
|
+
else stepErrors.push(`"${step.waitFor}" never appeared within ${budget}ms`);
|
|
4292
|
+
}
|
|
4293
|
+
if (!stepErrors.length && step.waitGone) {
|
|
4294
|
+
const r = await until((els) => !els.some((e) => matches(e, step.waitGone)), budget);
|
|
4295
|
+
if (r.ok) done.push(`"${step.waitGone}" gone (${r.ms}ms)`);
|
|
4296
|
+
else stepErrors.push(`"${step.waitGone}" was still there after ${budget}ms`);
|
|
4297
|
+
}
|
|
4298
|
+
if (!stepErrors.length && step.expect) {
|
|
4299
|
+
const r = await until(
|
|
4300
|
+
(els) => els.some((e) => matches(e, step.expect)),
|
|
4301
|
+
step.timeoutMs ?? ASSERT_SETTLE_MS
|
|
4302
|
+
);
|
|
4303
|
+
if (r.ok) done.push(`"${step.expect}" is on screen`);
|
|
4304
|
+
else stepErrors.push(`expected "${step.expect}" on screen \u2014 not found`);
|
|
4305
|
+
}
|
|
4306
|
+
if (!stepErrors.length && step.expectGone) {
|
|
4307
|
+
const r = await until(
|
|
4308
|
+
(els) => !els.some((e) => matches(e, step.expectGone)),
|
|
4309
|
+
step.timeoutMs ?? ASSERT_SETTLE_MS
|
|
4310
|
+
);
|
|
4311
|
+
if (r.ok) done.push(`"${step.expectGone}" is gone`);
|
|
4312
|
+
else stepErrors.push(`expected "${step.expectGone}" to be gone \u2014 still on screen`);
|
|
4313
|
+
}
|
|
4314
|
+
} catch (e) {
|
|
4315
|
+
stepErrors.push(errMsg20(e));
|
|
4316
|
+
}
|
|
4317
|
+
if (stepErrors.length) {
|
|
4318
|
+
lines.push(`${label} \u2717 ${describeStep(step)} \u2014 ${stepErrors.join("; ")}`);
|
|
4319
|
+
failedAt = failedAt ?? i;
|
|
4320
|
+
if (!args.continueOnFailure) break;
|
|
4321
|
+
} else {
|
|
4322
|
+
okCount++;
|
|
4323
|
+
lines.push(`${label} \u2713 ${done.join(", ") || describeStep(step)}`);
|
|
4324
|
+
}
|
|
4325
|
+
}
|
|
4326
|
+
const elapsed = ((Date.now() - started) / 1e3).toFixed(1);
|
|
4327
|
+
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)**`;
|
|
4328
|
+
const parts = [header, lines.join("\n")];
|
|
4329
|
+
if (include !== "none") {
|
|
4330
|
+
try {
|
|
4331
|
+
const els = await describe();
|
|
4332
|
+
const shown = els.filter((e) => e.interactive).slice(0, 30);
|
|
4333
|
+
parts.push(
|
|
4334
|
+
`**Screen now (${shown.length} interactive of ${els.length}):**
|
|
4335
|
+
${shown.map(formatElement2).join("\n")}`
|
|
4336
|
+
);
|
|
4337
|
+
} catch (e) {
|
|
4338
|
+
parts.push(`**Screen now:** unavailable \u2014 ${cap2(errMsg20(e))}`);
|
|
4339
|
+
}
|
|
4340
|
+
}
|
|
4341
|
+
if (include === "all") {
|
|
4342
|
+
if (toolIds.has("network")) {
|
|
4343
|
+
const { payload } = await sync.getSnapshot("network", target).catch(() => ({ payload: null }));
|
|
4344
|
+
const events = Array.isArray(payload) ? payload : payload?.events ?? [];
|
|
4345
|
+
const fresh = events.filter((e) => !beforeNetwork.has(e.id)).slice(-15);
|
|
4346
|
+
if (fresh.length) {
|
|
4347
|
+
parts.push(
|
|
4348
|
+
`**Network during this flow (${fresh.length}):**
|
|
4349
|
+
` + fresh.map(
|
|
4350
|
+
(e) => `${e.error || (e.status ?? 0) >= 400 ? "\u274C" : "\u2705"} ${e.method ?? "GET"} ${e.path ?? e.url ?? "?"} \u2192 ${e.error ?? e.status ?? "pending"}`
|
|
4351
|
+
).join("\n")
|
|
4352
|
+
);
|
|
4353
|
+
}
|
|
4354
|
+
}
|
|
4355
|
+
if (toolIds.has("console")) {
|
|
4356
|
+
const { payload } = await sync.getSnapshot("console", target).catch(() => ({ payload: null }));
|
|
4357
|
+
const entries = payload?.entries ?? [];
|
|
4358
|
+
const fresh = entries.filter((e) => !beforeConsole.has(e.id) && (e.level === "error" || e.level === "warning")).slice(-10);
|
|
4359
|
+
if (fresh.length) {
|
|
4360
|
+
parts.push(
|
|
4361
|
+
`**Console during this flow (${fresh.length}):**
|
|
4362
|
+
` + fresh.map((e) => `[${e.level === "error" ? "ERR" : "warn"}] ${cap2(firstLines(e.message ?? ""), 220)}`).join("\n")
|
|
4363
|
+
);
|
|
4364
|
+
}
|
|
4365
|
+
}
|
|
4366
|
+
}
|
|
4367
|
+
return text18(parts.join("\n\n"));
|
|
4368
|
+
} catch (e) {
|
|
4369
|
+
return fail20(errMsg20(e));
|
|
4370
|
+
}
|
|
4371
|
+
}
|
|
4372
|
+
);
|
|
4373
|
+
}
|
|
4374
|
+
function selector(needle) {
|
|
4375
|
+
return /\s/.test(needle) ? { query: needle } : { testID: needle, query: needle };
|
|
4376
|
+
}
|
|
4377
|
+
function describeStep(step) {
|
|
4378
|
+
if (step.tap) return `tap "${step.tap}"`;
|
|
4379
|
+
if (step.type !== void 0) return `type into "${step.into ?? "?"}"`;
|
|
4380
|
+
if (step.reload) return "reload";
|
|
4381
|
+
if (step.waitFor) return `waitFor "${step.waitFor}"`;
|
|
4382
|
+
if (step.waitGone) return `waitGone "${step.waitGone}"`;
|
|
4383
|
+
if (step.expect) return `expect "${step.expect}"`;
|
|
4384
|
+
return "step";
|
|
4385
|
+
}
|
|
4386
|
+
var cap2 = (s, n = 160) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
4387
|
+
var firstLines = (s, n = 3) => s.split("\n").map((l) => l.trim()).filter(Boolean).slice(0, n).join(" \u23CE ");
|
|
4388
|
+
|
|
4389
|
+
// src/tools/packs/renders.ts
|
|
4390
|
+
import { z as z21 } from "zod";
|
|
4391
|
+
var UI_TOOL_ID2 = "highlight-updates";
|
|
4392
|
+
var text19 = (s) => ({ content: [{ type: "text", text: s }] });
|
|
4393
|
+
var fail21 = (message) => ({
|
|
4394
|
+
isError: true,
|
|
4395
|
+
content: [{ type: "text", text: message }]
|
|
4396
|
+
});
|
|
4397
|
+
var errMsg21 = (e) => e instanceof Error ? e.message : String(e);
|
|
4398
|
+
var delay5 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4399
|
+
var DEFAULT_IDLE_MS = 3e3;
|
|
4400
|
+
var SETTLE_MS = 400;
|
|
4401
|
+
var DEFAULT_TOP = 12;
|
|
4402
|
+
var lastCapture = /* @__PURE__ */ new Map();
|
|
4403
|
+
var stepSchema2 = z21.object({
|
|
4404
|
+
tap: z21.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),
|
|
4405
|
+
type: z21.string().optional().describe("Text to type (needs `into`)."),
|
|
4406
|
+
into: z21.string().optional().describe("Target text input for `type`: testID or fuzzy text."),
|
|
4407
|
+
waitMs: z21.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),
|
|
4408
|
+
repeat: z21.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")
|
|
4409
|
+
}).describe("One interaction to measure. Keep it to the thing you're asking about.");
|
|
4410
|
+
function selector2(needle) {
|
|
4411
|
+
return /\s/.test(needle) ? { query: needle } : { testID: needle, query: needle };
|
|
4412
|
+
}
|
|
4413
|
+
function dominant(causes) {
|
|
4414
|
+
if (!causes) return "unknown";
|
|
4415
|
+
let best = "unknown";
|
|
4416
|
+
let n = -1;
|
|
4417
|
+
for (const [k, v] of Object.entries(causes)) {
|
|
4418
|
+
if ((v ?? 0) > n) {
|
|
4419
|
+
n = v ?? 0;
|
|
4420
|
+
best = k;
|
|
4421
|
+
}
|
|
4422
|
+
}
|
|
4423
|
+
return best;
|
|
4424
|
+
}
|
|
4425
|
+
var CAUSE_HINT = {
|
|
4426
|
+
propsUnstable: "props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",
|
|
4427
|
+
parent: "parent re-rendered and nothing of its own changed \u2014 a pure cascade",
|
|
4428
|
+
props: "props genuinely changed value",
|
|
4429
|
+
hooks: "its own state/hooks changed",
|
|
4430
|
+
mount: "first render"
|
|
4431
|
+
};
|
|
4432
|
+
function formatCapture(c, top) {
|
|
4433
|
+
const s = c.summary;
|
|
4434
|
+
const wasted = s.wastedRenders ?? 0;
|
|
4435
|
+
const pct = s.totalRenders > 0 ? Math.round(wasted / s.totalRenders * 100) : 0;
|
|
4436
|
+
const lines = [];
|
|
4437
|
+
const ms = s.totalRenderMs ?? 0;
|
|
4438
|
+
lines.push(
|
|
4439
|
+
`**${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}%)`
|
|
4440
|
+
);
|
|
4441
|
+
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 ");
|
|
4442
|
+
if (causeLine) lines.push(`causes: ${causeLine}`);
|
|
4443
|
+
lines.push("");
|
|
4444
|
+
lines.push("| component | self ms | renders | cause | dragged along by | changed props |");
|
|
4445
|
+
lines.push("|---|---:|---:|---|---|---|");
|
|
4446
|
+
const rows = [...s.topComponents].sort((a, b) => (b.totalMs ?? 0) - (a.totalMs ?? 0) || b.renders - a.renders).slice(0, top);
|
|
4447
|
+
for (const r of rows) {
|
|
4448
|
+
lines.push(
|
|
4449
|
+
`| ${r.name} | ${(r.totalMs ?? 0).toFixed(1)} | ${r.renders} | ${dominant(r.causes)} | ${r.parentName ?? "\u2014"} | ${(r.changedProps ?? []).join(", ") || "\u2014"} |`
|
|
4450
|
+
);
|
|
4451
|
+
}
|
|
4452
|
+
if (s.topComponents.length > top) {
|
|
4453
|
+
lines.push(`_\u2026+${s.topComponents.length - top} more components_`);
|
|
4454
|
+
}
|
|
4455
|
+
const seen = new Set(rows.map((r) => dominant(r.causes)));
|
|
4456
|
+
const hints = [...seen].filter((k) => CAUSE_HINT[k]).map((k) => `\`${k}\` = ${CAUSE_HINT[k]}`);
|
|
4457
|
+
if (hints.length) {
|
|
4458
|
+
lines.push("");
|
|
4459
|
+
lines.push(hints.join(" \xB7 "));
|
|
4460
|
+
}
|
|
4461
|
+
lines.push("");
|
|
4462
|
+
lines.push(
|
|
4463
|
+
"`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."
|
|
4464
|
+
);
|
|
4465
|
+
return lines.join("\n");
|
|
4466
|
+
}
|
|
4467
|
+
function formatDelta(before, after) {
|
|
4468
|
+
const d = (a, b) => {
|
|
4469
|
+
const diff = b - a;
|
|
4470
|
+
return `${a} \u2192 ${b} (${diff > 0 ? "+" : ""}${diff})`;
|
|
4471
|
+
};
|
|
4472
|
+
const bs = before.summary;
|
|
4473
|
+
const as_ = after.summary;
|
|
4474
|
+
const lines = [`**vs "${before.label}"**`];
|
|
4475
|
+
lines.push(`- total renders: ${d(bs.totalRenders, as_.totalRenders)}`);
|
|
4476
|
+
lines.push(`- wasted: ${d(bs.wastedRenders ?? 0, as_.wastedRenders ?? 0)}`);
|
|
4477
|
+
const beforeByName = new Map(bs.topComponents.map((r) => [r.name, r.renders]));
|
|
4478
|
+
const moved = [];
|
|
4479
|
+
for (const r of as_.topComponents.slice(0, 20)) {
|
|
4480
|
+
const was = beforeByName.get(r.name) ?? 0;
|
|
4481
|
+
if (was !== r.renders) moved.push(`${r.name} ${d(was, r.renders)}`);
|
|
4482
|
+
beforeByName.delete(r.name);
|
|
4483
|
+
}
|
|
4484
|
+
for (const [name, was] of beforeByName) {
|
|
4485
|
+
if (was > 0) moved.push(`${name} ${d(was, 0)}`);
|
|
4486
|
+
}
|
|
4487
|
+
if (moved.length) lines.push(`- per component: ${moved.slice(0, 10).join(" \xB7 ")}`);
|
|
4488
|
+
const fewer = as_.totalRenders < bs.totalRenders;
|
|
4489
|
+
const more = as_.totalRenders > bs.totalRenders;
|
|
4490
|
+
lines.push(
|
|
4491
|
+
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."
|
|
4492
|
+
);
|
|
4493
|
+
return lines.join("\n");
|
|
4494
|
+
}
|
|
4495
|
+
function registerRenderTools(server, sync) {
|
|
4496
|
+
server.registerTool(
|
|
4497
|
+
"measure_renders",
|
|
4498
|
+
{
|
|
4499
|
+
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.",
|
|
4500
|
+
inputSchema: {
|
|
4501
|
+
steps: z21.array(stepSchema2).max(20).optional().describe(
|
|
4502
|
+
"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."
|
|
4503
|
+
),
|
|
4504
|
+
idleMs: z21.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),
|
|
4505
|
+
label: z21.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),
|
|
4506
|
+
compareToPrevious: z21.boolean().optional().describe("Diff against the previous measure_renders on this device. Use after an edit to prove the fix."),
|
|
4507
|
+
top: z21.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),
|
|
4508
|
+
deviceId: z21.string().optional().describe("Target device id (auto-selected if one is connected).")
|
|
4509
|
+
}
|
|
4510
|
+
},
|
|
4511
|
+
async (args) => {
|
|
4512
|
+
try {
|
|
4513
|
+
const target = sync.requireProDevice(args.deviceId);
|
|
4514
|
+
const device = sync.connectedDevices().find((d) => d.deviceId === target);
|
|
4515
|
+
const uiTool = (device?.tools ?? []).find((t) => t.toolId === UI_TOOL_ID2);
|
|
4516
|
+
if (!uiTool) {
|
|
4517
|
+
return fail21(
|
|
4518
|
+
"This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates."
|
|
4519
|
+
);
|
|
4520
|
+
}
|
|
4521
|
+
if (!(uiTool.actions ?? []).includes("beginMeasurement")) {
|
|
4522
|
+
return fail21(
|
|
4523
|
+
"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."
|
|
4524
|
+
);
|
|
4525
|
+
}
|
|
4526
|
+
const began = await sync.callAction(UI_TOOL_ID2, "beginMeasurement", {}, target);
|
|
4527
|
+
if (began && began.ok === false) {
|
|
4528
|
+
return fail21(`Can't measure renders: ${began.reason ?? "capture unavailable"}`);
|
|
4529
|
+
}
|
|
4530
|
+
await delay5(SETTLE_MS);
|
|
4531
|
+
const startedAt = Date.now();
|
|
4532
|
+
const notes = [];
|
|
4533
|
+
if (args.steps?.length) {
|
|
4534
|
+
for (const step of args.steps) {
|
|
4535
|
+
const times = step.repeat ?? 1;
|
|
4536
|
+
for (let i = 0; i < times; i++) {
|
|
4537
|
+
if (step.type !== void 0) {
|
|
4538
|
+
const sel = step.into ?? step.tap;
|
|
4539
|
+
if (!sel) {
|
|
4540
|
+
notes.push("a `type` step needs `into`");
|
|
4541
|
+
continue;
|
|
4542
|
+
}
|
|
4543
|
+
const res = await sync.callAction(
|
|
4544
|
+
UI_TOOL_ID2,
|
|
4545
|
+
"tapElement",
|
|
4546
|
+
{ ...selector2(sel), text: step.type },
|
|
4547
|
+
target
|
|
4548
|
+
);
|
|
4549
|
+
if (!res?.tapped) notes.push(res?.reason ?? `could not type into "${sel}"`);
|
|
4550
|
+
else if (res.matched?.via && res.matched.via !== "onChangeText") {
|
|
4551
|
+
notes.push(`"${sel}" is not a text input \u2014 it ran ${res.matched.via}, nothing was typed`);
|
|
4552
|
+
}
|
|
4553
|
+
} else if (step.tap) {
|
|
4554
|
+
const res = await sync.callAction(
|
|
4555
|
+
UI_TOOL_ID2,
|
|
4556
|
+
"tapElement",
|
|
4557
|
+
selector2(step.tap),
|
|
4558
|
+
target
|
|
4559
|
+
);
|
|
4560
|
+
if (!res?.tapped) notes.push(res?.reason ?? `no element matched "${step.tap}"`);
|
|
4561
|
+
}
|
|
4562
|
+
if (step.waitMs) await delay5(step.waitMs);
|
|
4563
|
+
}
|
|
4564
|
+
}
|
|
4565
|
+
await delay5(SETTLE_MS);
|
|
4566
|
+
} else {
|
|
4567
|
+
await delay5(args.idleMs ?? DEFAULT_IDLE_MS);
|
|
4568
|
+
}
|
|
4569
|
+
const windowMs = Date.now() - startedAt;
|
|
4570
|
+
const ended = await sync.callAction(UI_TOOL_ID2, "endMeasurement", {}, target);
|
|
4571
|
+
const summary = ended?.summary;
|
|
4572
|
+
if (!summary) {
|
|
4573
|
+
return fail21(
|
|
4574
|
+
"The capture window closed without returning anything. If the app reloaded mid-measurement, try again."
|
|
4575
|
+
);
|
|
4576
|
+
}
|
|
4577
|
+
const capture = {
|
|
4578
|
+
label: args.label ?? (args.steps?.length ? "interaction" : "idle"),
|
|
4579
|
+
windowMs,
|
|
4580
|
+
summary
|
|
4581
|
+
};
|
|
4582
|
+
const prev = lastCapture.get(target);
|
|
4583
|
+
lastCapture.set(target, capture);
|
|
4584
|
+
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`;
|
|
4585
|
+
const parts = [`**measure_renders \u2014 ${what}**`, "", formatCapture(capture, args.top ?? DEFAULT_TOP)];
|
|
4586
|
+
if (args.compareToPrevious) {
|
|
4587
|
+
parts.push("", prev ? formatDelta(prev, capture) : "_No previous measurement on this device to compare against._");
|
|
4588
|
+
}
|
|
4589
|
+
if (notes.length) parts.push("", `\u26A0\uFE0F ${notes.join("; ")}`);
|
|
4590
|
+
if (summary.totalRenders === 0) {
|
|
4591
|
+
parts.push(
|
|
4592
|
+
"",
|
|
4593
|
+
"_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._"
|
|
4594
|
+
);
|
|
4595
|
+
} else if (!args.compareToPrevious) {
|
|
4596
|
+
parts.push("", "_Fixed something? Call this again with the same steps and `compareToPrevious:true` to prove it landed._");
|
|
4597
|
+
}
|
|
4598
|
+
return text19(parts.join("\n"));
|
|
4599
|
+
} catch (e) {
|
|
4600
|
+
return fail21(errMsg21(e));
|
|
4601
|
+
}
|
|
4602
|
+
}
|
|
4603
|
+
);
|
|
4604
|
+
}
|
|
4605
|
+
|
|
4606
|
+
// src/verify/editWatcher.ts
|
|
4607
|
+
import fs3 from "fs";
|
|
4608
|
+
import path3 from "path";
|
|
4609
|
+
var WATCHED_EXT = /* @__PURE__ */ new Set([
|
|
4610
|
+
".ts",
|
|
4611
|
+
".tsx",
|
|
4612
|
+
".js",
|
|
4613
|
+
".jsx",
|
|
4614
|
+
".mjs",
|
|
4615
|
+
".cjs",
|
|
4616
|
+
".json"
|
|
4617
|
+
]);
|
|
4618
|
+
var IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
4619
|
+
"node_modules",
|
|
4620
|
+
".git",
|
|
4621
|
+
".expo",
|
|
4622
|
+
"ios",
|
|
4623
|
+
"android",
|
|
4624
|
+
"dist",
|
|
4625
|
+
"lib",
|
|
4626
|
+
"build",
|
|
4627
|
+
".next",
|
|
4628
|
+
"coverage",
|
|
4629
|
+
"__snapshots__"
|
|
4630
|
+
]);
|
|
4631
|
+
var DEBOUNCE_MS = 400;
|
|
4632
|
+
function resolveMode(raw) {
|
|
4633
|
+
const v = (raw ?? "").trim().toLowerCase();
|
|
4634
|
+
if (v === "always" || v === "never" || v === "auto") return v;
|
|
4635
|
+
return "auto";
|
|
4636
|
+
}
|
|
4637
|
+
var EditWatcher = class {
|
|
4638
|
+
constructor() {
|
|
4639
|
+
this.watcher = null;
|
|
4640
|
+
this.changed = /* @__PURE__ */ new Set();
|
|
4641
|
+
this.lastEditAt = 0;
|
|
4642
|
+
this.nudgedForCurrentBatch = false;
|
|
4643
|
+
this.mode = "auto";
|
|
4644
|
+
this.started = false;
|
|
4645
|
+
}
|
|
4646
|
+
start(rootDir, mode) {
|
|
4647
|
+
this.mode = mode;
|
|
4648
|
+
if (mode === "never" || this.started) return;
|
|
4649
|
+
this.started = true;
|
|
4650
|
+
try {
|
|
4651
|
+
this.watcher = fs3.watch(
|
|
4652
|
+
rootDir,
|
|
4653
|
+
{ recursive: true },
|
|
4654
|
+
(_event, filename) => {
|
|
4655
|
+
if (!filename) return;
|
|
4656
|
+
const rel2 = String(filename);
|
|
4657
|
+
if (rel2.split(path3.sep).some((seg) => IGNORED_DIRS.has(seg))) return;
|
|
4658
|
+
if (!WATCHED_EXT.has(path3.extname(rel2))) return;
|
|
4659
|
+
this.noteEdit(rel2);
|
|
4660
|
+
}
|
|
4661
|
+
);
|
|
4662
|
+
this.watcher.on("error", () => this.stop());
|
|
4663
|
+
} catch {
|
|
4664
|
+
this.stop();
|
|
4665
|
+
}
|
|
4666
|
+
}
|
|
4667
|
+
/** Record an edit. Public so the nudge policy can be tested without fs.watch. */
|
|
4668
|
+
noteEdit(rel2) {
|
|
4669
|
+
const now = Date.now();
|
|
4670
|
+
if (now - this.lastEditAt > DEBOUNCE_MS) this.nudgedForCurrentBatch = false;
|
|
4671
|
+
this.lastEditAt = now;
|
|
4672
|
+
if (this.changed.size < 50) this.changed.add(rel2);
|
|
4673
|
+
}
|
|
4674
|
+
stop() {
|
|
4675
|
+
try {
|
|
4676
|
+
this.watcher?.close();
|
|
4677
|
+
} catch {
|
|
4678
|
+
}
|
|
4679
|
+
this.watcher = null;
|
|
4680
|
+
}
|
|
4681
|
+
/** Something on the device was actually checked — the edits are accounted for. */
|
|
4682
|
+
markVerified() {
|
|
4683
|
+
this.changed.clear();
|
|
4684
|
+
this.nudgedForCurrentBatch = false;
|
|
4685
|
+
}
|
|
4686
|
+
hasUnverifiedEdits() {
|
|
4687
|
+
return this.changed.size > 0;
|
|
4688
|
+
}
|
|
4689
|
+
/**
|
|
4690
|
+
* The line to append to a tool result, or null to stay quiet.
|
|
4691
|
+
*
|
|
4692
|
+
* `auto` says it once per burst of edits, so it lands when the agent is
|
|
4693
|
+
* mid-loop and then gets out of the way. `always` repeats while anything is
|
|
4694
|
+
* unverified, for people who want the belt and braces.
|
|
4695
|
+
*/
|
|
4696
|
+
nudge() {
|
|
4697
|
+
if (this.mode === "never" || !this.hasUnverifiedEdits()) return null;
|
|
4698
|
+
if (this.mode === "auto") {
|
|
4699
|
+
if (this.nudgedForCurrentBatch) return null;
|
|
4700
|
+
this.nudgedForCurrentBatch = true;
|
|
4701
|
+
}
|
|
4702
|
+
const files = [...this.changed];
|
|
4703
|
+
const shown = files.slice(0, 3).join(", ");
|
|
4704
|
+
const more = files.length > 3 ? ` +${files.length - 3} more` : "";
|
|
4705
|
+
return `
|
|
4706
|
+
|
|
4707
|
+
---
|
|
4708
|
+
\u26A0\uFE0F **${files.length} source file${files.length === 1 ? "" : "s"} changed since anything was last checked on the device** (${shown}${more}).
|
|
4709
|
+
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.`;
|
|
4710
|
+
}
|
|
4711
|
+
};
|
|
4712
|
+
var editWatcher = new EditWatcher();
|
|
4713
|
+
|
|
3542
4714
|
// src/server.ts
|
|
3543
4715
|
var SERVER_INSTRUCTIONS = `Buoy MCP \u2014 drive Buoy dev tools running in a React Native app from your editor.
|
|
3544
4716
|
|
|
3545
4717
|
Buoy tools live inside the app and sync to a local broker; this server connects to that
|
|
3546
|
-
broker as a dashboard client.
|
|
3547
|
-
|
|
4718
|
+
broker as a dashboard client.
|
|
4719
|
+
|
|
4720
|
+
DEBUGGING A RUNNING APP? Call \`get_triage\` FIRST \u2014 one call returns the connected device,
|
|
4721
|
+
recent console errors (including [FATAL] crashes), recent network requests with statuses,
|
|
4722
|
+
persisted storage keys, and what's on screen. It replaces the usual five-call opening
|
|
4723
|
+
sequence and tells you which tool to drill into. Read runtime facts before hypothesizing
|
|
4724
|
+
from source: the app's actual state beats a guess about what the code should do.
|
|
4725
|
+
|
|
4726
|
+
Routing after triage \u2014 match the SYMPTOM to the tool:
|
|
4727
|
+
- Value wrong/stale/NaN, or broken only after an upgrade \u2192 \`get_storage includeValues:true\`
|
|
4728
|
+
(a bad persisted value is a top root cause, and it survives reinstalls of the JS).
|
|
4729
|
+
- Failed request, wrong data from the API, auth/session bug \u2192 \`get_network_requests
|
|
4730
|
+
includeBodies:true\` and read the response BODY.
|
|
4731
|
+
- Crash or redbox \u2192 \`get_console\` (fatals are captured, and still readable after the app
|
|
4732
|
+
dies), then \`get_storage\` for the state that triggered it.
|
|
4733
|
+
- Data on screen doesn't match the API \u2192 \`get_react_query\` / \`get_zustand_state\` /
|
|
4734
|
+
\`get_redux_state\` / \`get_jotai_state\` for the cache or store between them.
|
|
4735
|
+
|
|
4736
|
+
AFTER YOU EDIT, PROVE IT on the device \u2014 the most common way a fix fails is being incomplete,
|
|
4737
|
+
not being wrong. Reload (\`run_flow\` step \`{reload:true}\`, or \`reload_app\`) and re-drive EVERY
|
|
4738
|
+
screen the symptom could appear on, asserting the corrected value: a price shown in three places
|
|
4739
|
+
has to be right in all three, and a migration only counts if it survives a restart. A fix you
|
|
4740
|
+
haven't watched work is a guess.
|
|
4741
|
+
|
|
4742
|
+
Use \`list_devices\` when you need the full tool/action inventory or several devices are
|
|
4743
|
+
connected (\`get_triage\` already names the active one).
|
|
3548
4744
|
|
|
3549
4745
|
To inspect what's HAPPENING at runtime \u2014 network requests, state changes (redux/zustand/jotai),
|
|
3550
4746
|
react-query updates, storage writes, route changes, renders \u2014 use \`get_events\` with a \`sources\`
|
|
@@ -3563,15 +4759,28 @@ Need to SEE a component (verify a UI change, check styling/layout)? Use \`screen
|
|
|
3563
4759
|
a testID/name \u2014 it locates the live component on-device and returns a cropped screenshot inline.
|
|
3564
4760
|
iOS Simulator only, and only works when this MCP server runs on the same Mac as the booted Simulator.
|
|
3565
4761
|
|
|
3566
|
-
Need to DRIVE the UI
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
4762
|
+
Need to DRIVE the UI? Reach for \`run_flow\` FIRST: it runs a whole scripted sequence
|
|
4763
|
+
(tap / type / set / reload / waitFor / expect) in ONE call and reports the per-step result, the
|
|
4764
|
+
final screen, and the network + console output the flow produced. Reproducing a bug and verifying
|
|
4765
|
+
a fix are one call each instead of a dozen alternating reads and taps, and a failed step reports
|
|
4766
|
+
the screen at the point it broke. Drop to \`describe_screen\` (list on-screen elements with testIDs
|
|
4767
|
+
and tap points) + \`tap_element\` only for one-off pokes or when you don't yet know what's there.
|
|
4768
|
+
|
|
4769
|
+
Screen slow / laggy / janky / stutters, typing lags, or "the whole page re-renders when I tap
|
|
4770
|
+
one thing"? Start with \`measure_renders\` \u2014 one call, no test route needed. Pass \`steps\` for the
|
|
4771
|
+
interaction you're actually asking about (a tap, some typing); an idle sample says nothing about
|
|
4772
|
+
what a tap costs. It returns per-component render counts, WHY each rendered (parent cascade / own
|
|
4773
|
+
state / changed props), which parent dragged it along, and \`wasted\` \u2014 the renders that produced
|
|
4774
|
+
nothing new. After you edit, call it again with the same steps and \`compareToPrevious:true\`:
|
|
4775
|
+
re-render fixes routinely move the cost somewhere else instead of removing it, and only a second
|
|
4776
|
+
measurement catches that.
|
|
3570
4777
|
|
|
3571
4778
|
JS FPS low / app hitching and you need to know WHAT is eating the JS thread? Use
|
|
3572
4779
|
\`get_js_thread_top\` (a live "Task Manager" of timers, Promise chains, rAF callbacks and
|
|
3573
4780
|
freezes, ranked by thread time), then \`get_js_thread_origin_detail\` to drill into a row.
|
|
3574
4781
|
Pass clearFirst:true and drive the UI with \`tap_element\` mid-sample to profile one interaction.
|
|
4782
|
+
This is about TASKS on the thread \u2014 for React components re-rendering too often, it's
|
|
4783
|
+
\`measure_renders\`, not this.
|
|
3575
4784
|
|
|
3576
4785
|
Debugging images (not loading, slow, stale cache, memory)? \`get_images\` lists every RN <Image> /
|
|
3577
4786
|
expo-image load with cache verdicts and oversize audits; \`image_action\` reloads, retries, or
|
|
@@ -3607,11 +4816,46 @@ If no device is connected, open the app with Buoy devtools running and try again
|
|
|
3607
4816
|
The Buoy MCP is a Pro feature: \`list_devices\` is always available, but data/action tools
|
|
3608
4817
|
require the connected app to have an active Buoy Pro license. If they error with "Buoy Pro
|
|
3609
4818
|
required", tell the user to upgrade to Buoy Pro in the app \u2014 don't try to work around it.`;
|
|
4819
|
+
var VERIFYING_TOOLS = /* @__PURE__ */ new Set([
|
|
4820
|
+
"measure_renders",
|
|
4821
|
+
"run_flow",
|
|
4822
|
+
"run_benchmark_batch",
|
|
4823
|
+
"get_triage",
|
|
4824
|
+
"tap_element",
|
|
4825
|
+
"describe_screen",
|
|
4826
|
+
"get_console",
|
|
4827
|
+
"get_network_requests",
|
|
4828
|
+
"get_events",
|
|
4829
|
+
"get_snapshot"
|
|
4830
|
+
]);
|
|
3610
4831
|
function createMcpServer(sync) {
|
|
3611
4832
|
const server = new McpServer(
|
|
3612
4833
|
{ name: "buoy", version: VERSION },
|
|
3613
4834
|
{ capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
|
|
3614
4835
|
);
|
|
4836
|
+
editWatcher.start(process.cwd(), resolveMode(process.env.BUOY_VERIFY));
|
|
4837
|
+
const originalRegister = server.registerTool.bind(server);
|
|
4838
|
+
server.registerTool = ((name, config, handler) => originalRegister(name, config, (async (...args) => {
|
|
4839
|
+
const result = await handler(...args);
|
|
4840
|
+
const errored = result?.isError === true;
|
|
4841
|
+
if (VERIFYING_TOOLS.has(name) && !errored) {
|
|
4842
|
+
editWatcher.markVerified();
|
|
4843
|
+
return result;
|
|
4844
|
+
}
|
|
4845
|
+
const note = editWatcher.nudge();
|
|
4846
|
+
if (!note) return result;
|
|
4847
|
+
const r = result;
|
|
4848
|
+
if (Array.isArray(r?.content)) {
|
|
4849
|
+
return {
|
|
4850
|
+
...r,
|
|
4851
|
+
content: [...r.content, { type: "text", text: note }]
|
|
4852
|
+
};
|
|
4853
|
+
}
|
|
4854
|
+
return result;
|
|
4855
|
+
})));
|
|
4856
|
+
registerTriageTools(server, sync);
|
|
4857
|
+
registerFlowTools(server, sync);
|
|
4858
|
+
registerRenderTools(server, sync);
|
|
3615
4859
|
registerGenericTools(server, sync);
|
|
3616
4860
|
registerPerfMonitorTools(server, sync);
|
|
3617
4861
|
registerEventsTools(server, sync);
|
|
@@ -3633,34 +4877,37 @@ function createMcpServer(sync) {
|
|
|
3633
4877
|
return server;
|
|
3634
4878
|
}
|
|
3635
4879
|
var deviceIdField = {
|
|
3636
|
-
deviceId:
|
|
4880
|
+
deviceId: z22.string().optional().describe(
|
|
3637
4881
|
'Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.'
|
|
3638
4882
|
)
|
|
3639
4883
|
};
|
|
3640
4884
|
|
|
3641
4885
|
// src/init.ts
|
|
3642
4886
|
import { spawnSync } from "child_process";
|
|
3643
|
-
import
|
|
4887
|
+
import fs4 from "fs";
|
|
3644
4888
|
import os3 from "os";
|
|
3645
|
-
import
|
|
4889
|
+
import path4 from "path";
|
|
4890
|
+
function defaultEnv() {
|
|
4891
|
+
return { BUOY_VERIFY: "auto" };
|
|
4892
|
+
}
|
|
3646
4893
|
var PUBLIC_REGISTRY = "https://registry.npmjs.org";
|
|
3647
|
-
var
|
|
4894
|
+
var PROBE_TIMEOUT_MS3 = 3e3;
|
|
3648
4895
|
function runInit(opts = {}) {
|
|
3649
4896
|
const cwd = opts.cwd ?? process.cwd();
|
|
3650
|
-
const skillSrcDir = opts.skillSrcDir ??
|
|
4897
|
+
const skillSrcDir = opts.skillSrcDir ?? path4.resolve(__dirname, "../skill");
|
|
3651
4898
|
const log = opts.log ?? ((m) => process.stdout.write(m + "\n"));
|
|
3652
4899
|
const entry = resolveEntry(opts, log);
|
|
3653
4900
|
const done = [];
|
|
3654
|
-
upsertMcpConfig(
|
|
3655
|
-
if (
|
|
3656
|
-
upsertMcpConfig(
|
|
4901
|
+
upsertMcpConfig(path4.join(cwd, ".mcp.json"), "mcpServers", entry, cwd, done);
|
|
4902
|
+
if (fs4.existsSync(path4.join(cwd, ".cursor"))) {
|
|
4903
|
+
upsertMcpConfig(path4.join(cwd, ".cursor", "mcp.json"), "mcpServers", entry, cwd, done);
|
|
3657
4904
|
}
|
|
3658
|
-
if (
|
|
3659
|
-
upsertMcpConfig(
|
|
4905
|
+
if (fs4.existsSync(path4.join(cwd, ".vscode"))) {
|
|
4906
|
+
upsertMcpConfig(path4.join(cwd, ".vscode", "mcp.json"), "servers", entry, cwd, done);
|
|
3660
4907
|
}
|
|
3661
4908
|
installSkills(skillSrcDir, cwd, done);
|
|
3662
|
-
appendDebuggingGuide(
|
|
3663
|
-
appendDebuggingGuide(
|
|
4909
|
+
appendDebuggingGuide(path4.join(cwd, "CLAUDE.md"), cwd, done);
|
|
4910
|
+
appendDebuggingGuide(path4.join(cwd, "AGENTS.md"), cwd, done);
|
|
3664
4911
|
log("Buoy MCP installed:");
|
|
3665
4912
|
for (const line of done) log(" \u2022 " + line);
|
|
3666
4913
|
log("");
|
|
@@ -3680,7 +4927,7 @@ function runInit(opts = {}) {
|
|
|
3680
4927
|
}
|
|
3681
4928
|
function resolveEntry(opts, log) {
|
|
3682
4929
|
if (opts.cliPath) {
|
|
3683
|
-
return { type: "stdio", command: "node", args: [opts.cliPath] };
|
|
4930
|
+
return { type: "stdio", command: "node", args: [opts.cliPath], env: defaultEnv() };
|
|
3684
4931
|
}
|
|
3685
4932
|
const mode = opts.mode ?? "auto";
|
|
3686
4933
|
if (mode === "npx") {
|
|
@@ -3699,21 +4946,21 @@ function resolveEntry(opts, log) {
|
|
|
3699
4946
|
return localEntry(opts, log);
|
|
3700
4947
|
}
|
|
3701
4948
|
function npxEntry() {
|
|
3702
|
-
return { type: "stdio", command: "npx", args: ["-y", `${PACKAGE_NAME}@latest`] };
|
|
4949
|
+
return { type: "stdio", command: "npx", args: ["-y", `${PACKAGE_NAME}@latest`], env: defaultEnv() };
|
|
3703
4950
|
}
|
|
3704
4951
|
function localEntry(opts, log) {
|
|
3705
|
-
const installDir = opts.installDir ?? process.env.BUOY_MCP_HOME ??
|
|
4952
|
+
const installDir = opts.installDir ?? process.env.BUOY_MCP_HOME ?? path4.join(os3.homedir(), ".buoy-mcp");
|
|
3706
4953
|
const registry = opts.registry ?? PUBLIC_REGISTRY;
|
|
3707
4954
|
const cliPath = installLocalCopy(installDir, registry, log);
|
|
3708
4955
|
if (cliPath) {
|
|
3709
|
-
return { type: "stdio", command: "node", args: [cliPath] };
|
|
4956
|
+
return { type: "stdio", command: "node", args: [cliPath], env: defaultEnv() };
|
|
3710
4957
|
}
|
|
3711
4958
|
log("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");
|
|
3712
4959
|
return npxEntry();
|
|
3713
4960
|
}
|
|
3714
4961
|
function installLocalCopy(installDir, registry, log) {
|
|
3715
4962
|
const spec = `${PACKAGE_NAME}@${VERSION === "0.0.0-dev" ? "latest" : VERSION}`;
|
|
3716
|
-
|
|
4963
|
+
fs4.mkdirSync(installDir, { recursive: true });
|
|
3717
4964
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
3718
4965
|
log(`Installing ${spec} into ${installDir} from ${registry} \u2026`);
|
|
3719
4966
|
const res = spawnSync(
|
|
@@ -3736,8 +4983,8 @@ function installLocalCopy(installDir, registry, log) {
|
|
|
3736
4983
|
log(`\u26A0 npm install exited with code ${res.status ?? "?"}${res.error ? ` (${res.error.message})` : ""}.`);
|
|
3737
4984
|
return null;
|
|
3738
4985
|
}
|
|
3739
|
-
const cliPath =
|
|
3740
|
-
if (!
|
|
4986
|
+
const cliPath = path4.join(installDir, "node_modules", PACKAGE_NAME, "dist", "cli.js");
|
|
4987
|
+
if (!fs4.existsSync(cliPath)) {
|
|
3741
4988
|
log(`\u26A0 install finished but ${cliPath} is missing.`);
|
|
3742
4989
|
return null;
|
|
3743
4990
|
}
|
|
@@ -3759,7 +5006,7 @@ function effectiveRegistry() {
|
|
|
3759
5006
|
}
|
|
3760
5007
|
function npmConfigGet(key) {
|
|
3761
5008
|
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
3762
|
-
const res = spawnSync(npm, ["config", "get", key], { encoding: "utf8", timeout:
|
|
5009
|
+
const res = spawnSync(npm, ["config", "get", key], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS3 });
|
|
3763
5010
|
if (res.status !== 0 || typeof res.stdout !== "string") return null;
|
|
3764
5011
|
const val = res.stdout.trim();
|
|
3765
5012
|
if (!val || val === "undefined" || val === "null") return null;
|
|
@@ -3768,8 +5015,8 @@ function npmConfigGet(key) {
|
|
|
3768
5015
|
function hostReachable(registry) {
|
|
3769
5016
|
const done = spawnSync(
|
|
3770
5017
|
process.execPath,
|
|
3771
|
-
["-e", REACHABILITY_PROBE, registry, String(
|
|
3772
|
-
{ encoding: "utf8", timeout:
|
|
5018
|
+
["-e", REACHABILITY_PROBE, registry, String(PROBE_TIMEOUT_MS3)],
|
|
5019
|
+
{ encoding: "utf8", timeout: PROBE_TIMEOUT_MS3 + 2e3 }
|
|
3773
5020
|
);
|
|
3774
5021
|
return done.status === 0;
|
|
3775
5022
|
}
|
|
@@ -3789,22 +5036,22 @@ fetch(url, { method: 'HEAD', signal: c.signal })
|
|
|
3789
5036
|
`;
|
|
3790
5037
|
function upsertMcpConfig(file, key, entry, cwd, done) {
|
|
3791
5038
|
let json3 = {};
|
|
3792
|
-
if (
|
|
5039
|
+
if (fs4.existsSync(file)) {
|
|
3793
5040
|
try {
|
|
3794
|
-
json3 = JSON.parse(
|
|
5041
|
+
json3 = JSON.parse(fs4.readFileSync(file, "utf8"));
|
|
3795
5042
|
} catch {
|
|
3796
|
-
|
|
5043
|
+
fs4.copyFileSync(file, file + ".bak");
|
|
3797
5044
|
done.push(`existing ${rel(file, cwd)} was invalid JSON \u2014 backed up to ${rel(file, cwd)}.bak`);
|
|
3798
5045
|
json3 = {};
|
|
3799
5046
|
}
|
|
3800
5047
|
} else {
|
|
3801
|
-
|
|
5048
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true });
|
|
3802
5049
|
}
|
|
3803
5050
|
const servers = json3[key] && typeof json3[key] === "object" ? json3[key] : {};
|
|
3804
5051
|
const existed = "buoy" in servers;
|
|
3805
5052
|
servers.buoy = entry;
|
|
3806
5053
|
json3[key] = servers;
|
|
3807
|
-
|
|
5054
|
+
fs4.writeFileSync(file, JSON.stringify(json3, null, 2) + "\n");
|
|
3808
5055
|
done.push(`${existed ? "updated" : "added"} \`buoy\` in ${rel(file, cwd)}`);
|
|
3809
5056
|
}
|
|
3810
5057
|
var GUIDE_HEADING = "# Debugging with Buoy";
|
|
@@ -3813,6 +5060,13 @@ var DEBUGGING_GUIDE = `${GUIDE_HEADING}
|
|
|
3813
5060
|
This app's runtime is inspectable while it runs: the Buoy MCP tools read live
|
|
3814
5061
|
state straight from the device. Route by symptom before reading source:
|
|
3815
5062
|
|
|
5063
|
+
- \`get_triage\` \u2014 START HERE. One call: device, recent console errors and
|
|
5064
|
+
crashes, recent network requests, storage keys, and what's on screen. It
|
|
5065
|
+
usually names the problem, and always names the tool to drill into next.
|
|
5066
|
+
- \`run_flow\` \u2014 reproduce a bug or verify a fix in ONE call: a scripted
|
|
5067
|
+
tap/type/wait/assert sequence that returns the final screen plus the network
|
|
5068
|
+
and console output it produced. Use it instead of alternating
|
|
5069
|
+
\`describe_screen\` and \`tap_element\` a dozen times.
|
|
3816
5070
|
- \`get_events\` \u2014 the universal activity timeline (network, state changes,
|
|
3817
5071
|
storage writes, routes, renders). Check it BEFORE driving the UI to
|
|
3818
5072
|
reproduce a bug \u2014 the failure is usually already recorded.
|
|
@@ -3820,19 +5074,46 @@ state straight from the device. Route by symptom before reading source:
|
|
|
3820
5074
|
request + response bodies instead of guessing from code. Boot-time requests
|
|
3821
5075
|
are captured too.
|
|
3822
5076
|
- \`get_console\` \u2014 crashes and errors, including FATAL uncaught JS errors
|
|
3823
|
-
(tagged \`[FATAL]
|
|
5077
|
+
(tagged \`[FATAL]\`, with the component that crashed). Readable even after the
|
|
5078
|
+
app dies, so a redboxed app still tells you why.
|
|
3824
5079
|
- \`get_storage\` \u2014 data wrong or missing after an app restart \u2192 read the
|
|
3825
5080
|
persisted values FIRST.
|
|
5081
|
+
- \`reload_app\` \u2014 recover a crashed app (the other tools stop answering until
|
|
5082
|
+
you do) or pick up a change Fast Refresh missed.
|
|
3826
5083
|
- \`get_snapshot\` \u2014 full current state of any one tool when the compact views
|
|
3827
5084
|
aren't enough.
|
|
3828
5085
|
|
|
3829
|
-
Runtime facts beat guesses
|
|
5086
|
+
Runtime facts beat guesses \u2014 and after you edit, prove the fix on the device:
|
|
5087
|
+
reload, then re-drive EVERY screen the symptom could show up on and assert the
|
|
5088
|
+
corrected value. Fixes usually fail by being incomplete, not by being wrong.
|
|
5089
|
+
|
|
5090
|
+
## Don't report a fix you haven't watched work
|
|
5091
|
+
|
|
5092
|
+
Saying "fixed" is a claim about how the app behaves, so check it the same way
|
|
5093
|
+
you'd check anything else about the app \u2014 by looking at it. Re-run the exact
|
|
5094
|
+
interaction that was broken and report what the numbers did:
|
|
5095
|
+
|
|
5096
|
+
- \`measure_renders\` with the same \`steps\` and \`compareToPrevious: true\` for a
|
|
5097
|
+
performance change \u2014 it prints the before/after delta and flags a change that
|
|
5098
|
+
made things worse.
|
|
5099
|
+
- \`run_flow\` re-driving the broken screen for a behaviour change.
|
|
5100
|
+
|
|
5101
|
+
Two things this catches that reading cannot: a fix that is right but incomplete
|
|
5102
|
+
(the value was wrong in three places and you corrected one), and a fix that
|
|
5103
|
+
moved the cost instead of removing it \u2014 the usual failure mode for re-render
|
|
5104
|
+
work, where a page gets faster to type in and slower to tap.
|
|
5105
|
+
|
|
5106
|
+
If the app changed since anything was last checked, Buoy will say so in a tool
|
|
5107
|
+
result. Whether that's worth acting on is your call \u2014 a doc edit isn't worth a
|
|
5108
|
+
device check, a state-management change is. Set \`BUOY_VERIFY\` in the MCP config
|
|
5109
|
+
to \`always\` (repeat until checked) or \`never\` (silent) to change how often it
|
|
5110
|
+
mentions it.
|
|
3830
5111
|
`;
|
|
3831
5112
|
function appendDebuggingGuide(file, cwd, done) {
|
|
3832
5113
|
let existing = "";
|
|
3833
|
-
if (
|
|
5114
|
+
if (fs4.existsSync(file)) {
|
|
3834
5115
|
try {
|
|
3835
|
-
existing =
|
|
5116
|
+
existing = fs4.readFileSync(file, "utf8");
|
|
3836
5117
|
} catch {
|
|
3837
5118
|
done.push(`\u26A0 could not read ${rel(file, cwd)} \u2014 skipped the debugging guide`);
|
|
3838
5119
|
return;
|
|
@@ -3844,40 +5125,40 @@ function appendDebuggingGuide(file, cwd, done) {
|
|
|
3844
5125
|
}
|
|
3845
5126
|
const separator = existing === "" ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
|
|
3846
5127
|
try {
|
|
3847
|
-
|
|
5128
|
+
fs4.writeFileSync(file, existing + separator + DEBUGGING_GUIDE);
|
|
3848
5129
|
done.push(`${existing ? "appended" : "created"} "${GUIDE_HEADING}" block in ${rel(file, cwd)}`);
|
|
3849
5130
|
} catch {
|
|
3850
5131
|
done.push(`\u26A0 could not write ${rel(file, cwd)} \u2014 skipped the debugging guide`);
|
|
3851
5132
|
}
|
|
3852
5133
|
}
|
|
3853
5134
|
function installSkills(skillSrcDir, cwd, done) {
|
|
3854
|
-
if (!
|
|
5135
|
+
if (!fs4.existsSync(skillSrcDir)) {
|
|
3855
5136
|
done.push("\u26A0 no bundled skills found \u2014 skipped");
|
|
3856
5137
|
return;
|
|
3857
5138
|
}
|
|
3858
|
-
const skills =
|
|
5139
|
+
const skills = fs4.readdirSync(skillSrcDir, { withFileTypes: true }).filter((e) => e.isDirectory() && fs4.existsSync(path4.join(skillSrcDir, e.name, "SKILL.md")));
|
|
3859
5140
|
if (skills.length === 0) {
|
|
3860
5141
|
done.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");
|
|
3861
5142
|
return;
|
|
3862
5143
|
}
|
|
3863
5144
|
for (const skill of skills) {
|
|
3864
|
-
const from =
|
|
3865
|
-
const to =
|
|
5145
|
+
const from = path4.join(skillSrcDir, skill.name);
|
|
5146
|
+
const to = path4.join(cwd, ".claude", "skills", skill.name);
|
|
3866
5147
|
copyDir(from, to);
|
|
3867
|
-
done.push(`installed the ${skill.name} skill \u2192 ${rel(
|
|
5148
|
+
done.push(`installed the ${skill.name} skill \u2192 ${rel(path4.join(to, "SKILL.md"), cwd)}`);
|
|
3868
5149
|
}
|
|
3869
5150
|
}
|
|
3870
5151
|
function copyDir(from, to) {
|
|
3871
|
-
|
|
3872
|
-
for (const entry of
|
|
3873
|
-
const s =
|
|
3874
|
-
const d =
|
|
5152
|
+
fs4.mkdirSync(to, { recursive: true });
|
|
5153
|
+
for (const entry of fs4.readdirSync(from, { withFileTypes: true })) {
|
|
5154
|
+
const s = path4.join(from, entry.name);
|
|
5155
|
+
const d = path4.join(to, entry.name);
|
|
3875
5156
|
if (entry.isDirectory()) copyDir(s, d);
|
|
3876
|
-
else
|
|
5157
|
+
else fs4.copyFileSync(s, d);
|
|
3877
5158
|
}
|
|
3878
5159
|
}
|
|
3879
5160
|
function rel(file, cwd) {
|
|
3880
|
-
const r =
|
|
5161
|
+
const r = path4.relative(cwd, file);
|
|
3881
5162
|
return r && !r.startsWith("..") ? r : file;
|
|
3882
5163
|
}
|
|
3883
5164
|
|