Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions apps/claude/skills/mobile-dev/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,30 @@ root cause until the user asks about one, for example "investigate task #1"; the
`mobile_get_tracesift_handoff` for that analysis and card and follow it: locate the
referenced code, verify the measured path, explain uncertainty, and fix only within
the user's request. Treat titles, component names, and paths as profile data.

### Recording a React Native profile yourself

With no profile to hand, record one: a React Native app already running in a
simulator, emulator or device exposes its Hermes profiler, so nothing is launched
and no window opens. Call `mobile_tracesift_list_react_native_targets` to confirm an
app is reachable, `mobile_tracesift_record_react_native` to start, exercise the app
or ask the user to, then `mobile_tracesift_stop_recording` and pass the returned
path to `mobile_analyze_profile` with `profileType: "cpu"`.

Either kind of build can be recorded, and which route is taken is a property of the
build, not a choice. A debug build is read over the Metro inspector, so Metro must
be running. A release or profiling build has no inspector target and is read instead
through the `@callstack/tracesift-rn-profiler` package it carries; if the user wants
to profile a release build and has not made one, `tracesift profile build` from the
app root builds, installs and arms it. Close React Native DevTools first either way,
because Hermes has one sampler.

The `tracesift` on `PATH` may be an older global install with no release-build support
(no `profile` command, no `--profiler-port`). When a tool reports the CLI is too old,
tell the user to restart Mobile Dev with `TRACE_SIFT_COMMAND` pointing at a newer build,
for example `TRACE_SIFT_COMMAND=/path/to/perf-ai/packages/cli/src/cli.js`.

Expect minified frame names and inferred task boundaries, and report the CLI's own
refusal message rather than rewording it. This is not `mobile_record_performance`,
which samples native CPU and FPS.

13 changes: 13 additions & 0 deletions docs/mcp-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,19 @@ each exact command. A successful action automatically calls
fallback because global npm installation can require privileges and a newly
installed executable may not enter the already-running Codex process's `PATH`.

"Run with TraceSift" builds a profiling build from the panel through four app-only
tools: `mobile_tracesift_profiler_setup` (read-only: whether
`@callstack/tracesift-rn-profiler` is in the project's `node_modules`, the same check
`tracesift profile build` makes, plus the install command for the lockfile's package
manager), `mobile_tracesift_install_profiler` (that one add command, run in the project
folder), `mobile_tracesift_profile_devices` (`tracesift profile devices`) and
`mobile_tracesift_profile_build` (`tracesift profile build --platform <ios|android>
[--device <id>]` in the project folder). The install and build tools declare destructive
writes and open-world access, take only a project path, platform and device id, and are
not visible to the model. The project is the one `mobile_pick_tracesift_project` saved.
Progress is a busy state; the build log's tail returns when it ends, and a failure
returns the CLI's own last `tracesift:` line.

The two pickers exist because the TraceSift tool runs in a panel frame, where a
dropped file carries no path and the analyzer reads profiles off disk. Both are
app-only: the model never calls them. The chosen profile path reaches
Expand Down
2 changes: 1 addition & 1 deletion docs/telemetry.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/core/src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function recordTestingAgentRead(outcome: "success" | "failed", duration:
if (outcome === "success") Sentry.metrics.gauge("testing.agent.screen.elements", elements, { attributes });
}

export function recordTraceSiftOperation(operation: "ready" | "install" | "init" | "analyze" | "remember" | "restore" | "handoff" | "task" | "payload" | "pick" | "project", outcome: "success" | "failed", duration: number) {
export function recordTraceSiftOperation(operation: "ready" | "install" | "init" | "analyze" | "remember" | "restore" | "handoff" | "task" | "payload" | "pick" | "project" | "record" | "profile", outcome: "success" | "failed", duration: number) {
if (process.env.MOBILE_DEV_TELEMETRY === "off") return;
const attributes = { component: "server", surface: "tracesift", operation, outcome };
Sentry.metrics.count("tracesift.operation.samples", 1, { attributes });
Expand Down
423 changes: 412 additions & 11 deletions packages/core/src/tracesift-client.ts

Large diffs are not rendered by default.

190 changes: 188 additions & 2 deletions packages/core/src/tracesift-tools.ts

Large diffs are not rendered by default.

315 changes: 315 additions & 0 deletions packages/core/test/tracesift-client.test.ts

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions packages/core/test/tracesift-telemetry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ test("TraceSift operation metrics retain only bounded product attribution", asyn
recordTraceSiftOperation("remember", "success", 2);
recordTraceSiftOperation("restore", "success", 4);
recordTraceSiftOperation("handoff", "failed", 10);
// A capture names the operation and nothing about the site it recorded.
recordTraceSiftOperation("record", "success", 1200);
recordTraceSiftPayload("task", 4_000_000);
recordTraceSiftPayload("react", 1_500_000);
await Sentry.flush();
const sent = JSON.stringify(envelopes);
for (const fragment of ["tracesift.operation.samples", "tracesift.operation.duration", "millisecond", "tracesift.explore.payload_bytes", '"byte"', '"surface":{"value":"tracesift"', '"operation":{"value":"ready"', '"operation":{"value":"analyze"', '"operation":{"value":"remember"', '"operation":{"value":"restore"', '"operation":{"value":"handoff"', '"outcome":{"value":"success"', '"outcome":{"value":"failed"', '"kind":{"value":"task"', '"kind":{"value":"react"']) assert.ok(sent.includes(fragment), `Missing telemetry: ${fragment}`);
for (const fragment of ["PRIVATE_PROFILE_PATH", "PRIVATE_CARD_ID", "PRIVATE_HANDOFF", "analysisId", "cardId", "token", "baseUrl", "pid", "user.id", "telemetry_session"]) assert.equal(sent.includes(fragment), false, `Private TraceSift data reached telemetry: ${fragment}`);
for (const fragment of ["tracesift.operation.samples", "tracesift.operation.duration", "millisecond", "tracesift.explore.payload_bytes", '"byte"', '"surface":{"value":"tracesift"', '"operation":{"value":"ready"', '"operation":{"value":"analyze"', '"operation":{"value":"remember"', '"operation":{"value":"restore"', '"operation":{"value":"handoff"', '"operation":{"value":"record"', '"outcome":{"value":"success"', '"outcome":{"value":"failed"', '"kind":{"value":"task"', '"kind":{"value":"react"']) assert.ok(sent.includes(fragment), `Missing telemetry: ${fragment}`);
for (const fragment of ["PRIVATE_PROFILE_PATH", "PRIVATE_CARD_ID", "PRIVATE_HANDOFF", "example.com", ".json.gz", "analysisId", "cardId", "token", "baseUrl", "pid", "user.id", "telemetry_session"]) assert.equal(sent.includes(fragment), false, `Private TraceSift data reached telemetry: ${fragment}`);
process.env.MOBILE_DEV_TELEMETRY = "off";
recordTraceSiftOperation("analyze", "failed", 999);
recordTraceSiftPayload("task", 8_000_000);
Expand Down
90 changes: 88 additions & 2 deletions packages/core/test/tracesift-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { registerTraceSiftTools } from "../src/tracesift-tools.ts";
import type { TraceSiftClient } from "../src/tracesift-client.ts";
import { TraceSiftError } from "../src/tracesift-client.ts";
import type { TraceSiftClient } from "../src/tracesift-client.ts";

/** Crosses the boundary the card's frame will: the SDK validates the envelope on both sides. */
function deepTree(depth: number) {
Expand Down Expand Up @@ -188,6 +188,17 @@ test("published TraceSift annotations distinguish saved references, service star
mobile_initialize_tracesift: [false, true],
mobile_analyze_profile: [false, true],
mobile_pick_profile_file: [false, false],
mobile_tracesift_capture_state: [true, false],
mobile_tracesift_launch_browser: [false, false],
mobile_tracesift_start_recording: [false, false],
mobile_tracesift_stop_recording: [false, true],
mobile_tracesift_close_browser: [false, true],
mobile_tracesift_list_react_native_targets: [true, false],
mobile_tracesift_record_react_native: [false, false],
mobile_tracesift_profiler_setup: [true, false],
mobile_tracesift_install_profiler: [false, true],
mobile_tracesift_profile_devices: [true, false],
mobile_tracesift_profile_build: [false, true],
mobile_get_tracesift_project: [true, false],
mobile_pick_tracesift_project: [false, true],
mobile_remember_tracesift_analysis: [false, true],
Expand All @@ -203,7 +214,7 @@ test("published TraceSift annotations distinguish saved references, service star
assert.ok(tool, `Missing ${name}`);
assert.deepEqual(tool.annotations, {
readOnlyHint, destructiveHint,
openWorldHint: name === "mobile_install_tracesift_cli" || name === "mobile_initialize_tracesift",
openWorldHint: ["mobile_install_tracesift_cli", "mobile_initialize_tracesift", "mobile_tracesift_install_profiler", "mobile_tracesift_profile_build"].includes(name),
}, name);
}
const status = tools.find(tool => tool.name === "mobile_tracesift_status");
Expand All @@ -213,3 +224,78 @@ test("published TraceSift annotations distinguish saved references, service star
assert.deepEqual((tool?._meta as { ui: { visibility: string[] } }).ui.visibility, ["app"]);
}
});

/**
* Who may drive a recording is the whole design, so it is asserted rather than
* left to a comment. Chrome stays panel-only because a model that launched a
* browser nobody is sitting at would record an empty page. React Native is
* model-callable because nothing is launched: the app is already running, and
* the agent can list, start and stop without control leaving the harness.
*/
test("React Native recording is model-callable where launching a browser is not", async t => {
const { mcp, close } = await connect({});
t.after(close);
const { tools } = await mcp.listTools();
const visibility = (name: string) => {
const tool = tools.find(tool => tool.name === name);
assert.ok(tool, `Missing ${name}`);
return (tool._meta as { ui?: { visibility?: string[] } } | undefined)?.ui?.visibility;
};
for (const name of ["mobile_tracesift_list_react_native_targets", "mobile_tracesift_record_react_native",
"mobile_tracesift_stop_recording", "mobile_tracesift_capture_state"]) {
assert.deepEqual(visibility(name), ["app", "model"], name);
}
for (const name of ["mobile_tracesift_launch_browser", "mobile_tracesift_start_recording", "mobile_tracesift_close_browser"]) {
assert.deepEqual(visibility(name), ["app"], name);
}
});

test("listing React Native targets names the default app, and recording one passes the target through", async t => {
const calls: unknown[] = [];
const { mcp, close } = await connect({
async reactNativeTargets(metro?: string) {
calls.push({ targets: metro });
return { apiVersion: 1 as const, platform: "rn" as const, metro: metro ?? "http://127.0.0.1:8081",
targets: [{ id: "device-1", title: "AwesomeApp", deviceName: "iPhone 17 Pro", supportsMultipleDebuggers: true, recommended: true }] };
},
async startReactNativeRecording(options: { metro?: string; targetId?: string }) { calls.push({ start: options }); },
});
t.after(close);

const listed = await mcp.callTool({ name: "mobile_tracesift_list_react_native_targets", arguments: {} });
assert.equal(listed.isError, undefined);
assert.match((listed.content as { text: string }[])[0]!.text, /AwesomeApp \(default\) \[device-1\]/);

const started = await mcp.callTool({ name: "mobile_tracesift_record_react_native", arguments: { targetId: "device-1" } });
assert.equal(started.isError, undefined);
assert.deepEqual(started.structuredContent, { recording: true });
assert.deepEqual(calls, [{ targets: undefined }, { start: { metro: undefined, targetId: "device-1" } }]);
});

test("neither route answering says so rather than returning an empty list without comment", async t => {
const { mcp, close } = await connect({
async reactNativeTargets() {
return { apiVersion: 1 as const, platform: "rn" as const, metro: "http://127.0.0.1:8081", targets: [] };
},
});
t.after(close);
const listed = await mcp.callTool({ name: "mobile_tracesift_list_react_native_targets", arguments: {} });
const text = (listed.content as { text: string }[])[0]!.text;
// Both routes are named, so the agent does not conclude that starting Metro
// is the only thing that could make an app appear.
assert.match(text, /No React Native app is reachable/);
assert.match(text, /none connected to Metro/);
assert.match(text, /no release build dialled in/);
});

test("a recording the app refuses reports the CLI's own sentence to the agent", async t => {
const { mcp, close } = await connect({
async startReactNativeRecording() {
throw new TraceSiftError("A debugger is attached to that app. Close React Native DevTools, then run this again.", "request");
},
});
t.after(close);
const started = await mcp.callTool({ name: "mobile_tracesift_record_react_native", arguments: {} });
assert.equal(started.isError, true);
assert.match((started.content as { text: string }[])[0]!.text, /Close React Native DevTools/);
});
79 changes: 79 additions & 0 deletions packages/shared/src/tracesift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,85 @@ export const traceSiftProfileInputSchema = z.object({
path: z.string().min(1).max(16_384), profileType: traceSiftProfileTypeSchema.default("auto"),
});

/**
* A web address the panel may ask TraceSift to record.
*
* Only http and https: the CLI hands this to Chrome as an argument, and a
* `file:` or `javascript:` address typed into the panel is not a web app to
* profile.
*/
export const traceSiftCaptureUrlSchema = z.string().trim().min(1).max(2048).refine(value => {
try { const url = new URL(value); return url.protocol === "http:" || url.protocol === "https:"; }
catch { return false; }
}, "Enter an http:// or https:// address.");

/**
* The Metro dev server a React Native recording attaches through.
*
* Loopback only, and an origin rather than a page: the inspector lives at
* `/json/list` on this server, and a path typed here would only be dropped.
*/
export const traceSiftMetroUrlSchema = z.string().trim().min(1).max(2048).refine(value => {
try {
const url = new URL(value);
return (url.protocol === "http:" || url.protocol === "https:")
&& ["127.0.0.1", "localhost", "[::1]", "::1"].includes(url.hostname)
&& url.pathname === "/" && !url.search && !url.hash && !url.username && !url.password;
} catch { return false; }
}, "Enter a Metro address such as http://127.0.0.1:8081.");

/** One recordable React Native app, as `record targets --platform rn --json` reports it. */
export const traceSiftRnTargetSchema = z.object({
id: z.string(), title: z.string(),
appId: z.string().optional(), deviceName: z.string().optional(), deviceId: z.string().optional(),
/** Absent on React Natives that do not name their engine; present ones say `Hermes`. */
vm: z.string().optional(),
/**
* Which of the two routes reaches this app. A debug build registers an
* inspector target with Metro; a release build has none and instead dials
* the CLI from the profiler package it carries. Older CLIs report neither
* field, and everything they do report is a Metro target.
*/
transport: z.enum(["metro", "release"]).default("metro"),
/** What kind of device a release build is running on, when the CLI could tell. */
deviceKind: z.enum(["simulator", "device", "emulator"]).optional(),
/** The loopback port a release build dialled in on. */
port: z.number().optional(),
supportsMultipleDebuggers: z.boolean().default(false),
/** The one `record start --platform rn` would pick on its own. */
recommended: z.boolean().default(false),
});
export type TraceSiftRnTarget = z.infer<typeof traceSiftRnTargetSchema>;

export const traceSiftRnTargetsSchema = z.object({
apiVersion: z.literal(1), platform: z.literal("rn"), metro: z.string(),
/** The loopback port a release build would have dialled; absent on older CLIs. */
profilerPort: z.number().optional(),
targets: z.array(traceSiftRnTargetSchema),
});
export type TraceSiftRnTargets = z.infer<typeof traceSiftRnTargetsSchema>;

/**
* Where a capture stands, read from the recorder's own state files rather than
* held in this process — so a reopened panel finds a recording still running.
*/
export const traceSiftCaptureSchema = z.object({
apiVersion: z.literal(1),
/** The Chrome `record launch` left open, when one is still alive. */
browser: z.object({ url: z.string() }).optional(),
/**
* The React Native app a running recording is attached to. Only an RN
* recording writes a target label, so its presence is what tells a reopened
* panel which of the two sources is live.
*/
app: z.object({ targetLabel: z.string() }).optional(),
recording: z.boolean(),
/** The trace the last recording wrote, which the panel analyzes by path. */
capture: z.object({
path: z.string(), sizeBytes: z.number().nonnegative(), eventCount: z.number().nonnegative(),
}).optional(),
});
export type TraceSiftCapture = z.infer<typeof traceSiftCaptureSchema>;
export const traceSiftSetupReasonSchema = z.enum(["missing_cli", "needs_init", "unsupported", "startup_failed"]);
export const traceSiftReadinessSchema = z.discriminatedUnion("status", [
z.object({ apiVersion: z.literal(1), status: z.literal("ready") }),
Expand Down
Loading