From bc7c89bbc958a730880557a7408ffdddf0bb863a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Tue, 24 Nov 2026 18:58:57 +0100 Subject: [PATCH] feat(performance): mark Android display frames on FPS charts --- apps/claude/skills/mobile-dev/SKILL.md | 4 +- docs/performance.md | 6 +- docs/telemetry.md | 5 + package-lock.json | 4 +- package.json | 2 +- packages/core/src/recording-tools.ts | 23 +++- packages/core/test/recording-tools.test.ts | 13 +- packages/shared/src/frame-statistics.ts | 33 ++++- packages/shared/src/version.ts | 2 +- packages/skills/mobile-dev/SKILL.md | 5 +- .../ui/src/components/fps-frame-markers.tsx | 117 ++++++++++++++++++ .../ui/src/components/performance-view.tsx | 23 +++- .../performance/DisplayFpsTrack.tsx | 7 +- .../performance/PerformanceAreaChart.tsx | 31 ++++- packages/ui/src/components/recording-card.tsx | 41 +++--- .../ui/src/components/recording-hitches.tsx | 77 ------------ packages/ui/src/fps-frame-overlay.ts | 67 ++++++++++ packages/ui/src/recording-controller.ts | 4 +- packages/ui/src/recording-series.ts | 28 ----- packages/ui/src/style.css | 6 +- packages/ui/test/performance-view.test.ts | 31 ++++- packages/ui/test/recording-series.test.ts | 42 +++++-- .../codex/android-frame-markers-dark.png | Bin 0 -> 21909 bytes .../codex/android-frame-markers-light.png | Bin 0 -> 21541 bytes tooling/hosts/visual.spec.ts | 36 +++++- website/src/content/docs/docs/performance.mdx | 4 +- 26 files changed, 437 insertions(+), 174 deletions(-) create mode 100644 packages/ui/src/components/fps-frame-markers.tsx delete mode 100644 packages/ui/src/components/recording-hitches.tsx create mode 100644 packages/ui/src/fps-frame-overlay.ts create mode 100644 tooling/hosts/screenshots/codex/android-frame-markers-dark.png create mode 100644 tooling/hosts/screenshots/codex/android-frame-markers-light.png diff --git a/apps/claude/skills/mobile-dev/SKILL.md b/apps/claude/skills/mobile-dev/SKILL.md index 2eb62fd7..17a87ae4 100644 --- a/apps/claude/skills/mobile-dev/SKILL.md +++ b/apps/claude/skills/mobile-dev/SKILL.md @@ -140,7 +140,9 @@ CPU, memory, and FPS, but not per-thread detail, and their Ask buttons cannot se chat, so the user asks you instead: read the samples with `mobile_read_performance_recording` (and frame pages with `mobile_read_performance_frames` for Android jank) before answering. FPS is -device-wide and cannot attribute a slowdown to one app. For a physical iPhone, +device-wide and cannot attribute a slowdown to one app. When the card includes +Android frame detail, select a diamond on the FPS graph to inspect a late, +dropped or janky display frame and its SurfaceFlinger reasons. For a physical iPhone, use `summary.hitchStats` for the count and time lost to visible hitches in the selected range. A null result means hitch data is unavailable for that range. Use `mobile_list_performance_recordings` to find earlier runs and diff --git a/docs/performance.md b/docs/performance.md index a0ae8b3c..3da25d69 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -81,7 +81,11 @@ The Memory track shows the main process's current usage, sampled average, maximu The green **Display FPS** track shares the CPU and memory timeline, cursor, zoom and 150-second history. It records independently of the selected app, with current, average, maximum and minimum FPS. It includes other apps and system UI; a quiet or locked screen can report zero. This measures display updates rather than the panel's refresh rate, and does not identify which app caused a drop. Missing measurements remain gaps. -Android 12+ uses only Perfetto FrameTimeline's presented actual display frames, excluding dropped frames and individual app/layer frames. A bundled external native consumer reads a bounded 4 MiB trace buffer once per second over ADB without creating a trace file, attaching a debugger, requiring root or installing an app SDK. Readback adds roughly three seconds of delay. SurfaceFlinger can report a frame later; the chart updates that frame's original interval. Devices without FrameTimeline and Android versions below 12 report an explicit limitation. +On Android 12+, the FPS counter counts presented display frames from Perfetto FrameTimeline. A bundled external native consumer reads a bounded 4 MiB trace buffer once per second over ADB without creating a trace file, attaching a debugger, requiring root or installing an app SDK. Readback adds roughly three seconds of delay. SurfaceFlinger can report a frame later; the chart updates that frame's original interval. Devices without FrameTimeline and Android versions below 12 report an explicit limitation. + +Diamonds on the live and saved **Display FPS** graphs mark frames SurfaceFlinger reported as late, dropped or janky. A frame with multiple reasons gets one diamond. Select it to see its time, presentation status and reported reasons. For a dropped frame the time is the end of the frame event. The **Inspect** menu also lists FPS samples with their flagged-frame counts and distinguishes a captured interval with zero flags from one without FrameTimeline data. An idle interval adds no markers by itself. These events cover the whole display, including system UI. + +In chat hosts that can only show a recording preview, the diamonds appear when the frame data fits the tool result. Open the full recording in Mobile Dev to inspect larger runs. Android FPS intervals also retain `frameTimeline`: its `clock` is `boottime`, `intervalEndNs` identifies the device interval endpoint, and `frames` contains diff --git a/docs/telemetry.md b/docs/telemetry.md index 4b6d0878..21f5072d 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -905,6 +905,11 @@ The server measures Instruments startup and finalization with Hitch events, app identity, and trace contents stay local. Existing `ui.recording.derive` timing includes matching hitches to recorded FPS intervals and summarizing the selected range. +Since 0.1.195, `ui.performance.frame_markers` measures the time in milliseconds +to derive Android markers when the live FPS history changes. It uses the existing +bounded UI timing windows. Saved Android marker processing is included in +`ui.recording.derive`. Frame times, tokens and jank reasons stay local. + ## Resource-saving operations Since 0.1.179, `resource_saving.apply` counts successful and failed applications of diff --git a/package-lock.json b/package-lock.json index e6fd4387..3d6fbbb2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mobile-dev", - "version": "0.1.194", + "version": "0.1.195", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mobile-dev", - "version": "0.1.194", + "version": "0.1.195", "workspaces": [ "packages/shared", "packages/core", diff --git a/package.json b/package.json index 53d70f92..4d232396 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mobile-dev", - "version": "0.1.194", + "version": "0.1.195", "private": true, "workspaces": [ "packages/shared", diff --git a/packages/core/src/recording-tools.ts b/packages/core/src/recording-tools.ts index 9561bf06..4e00f3a1 100644 --- a/packages/core/src/recording-tools.ts +++ b/packages/core/src/recording-tools.ts @@ -156,13 +156,28 @@ export function registerRecordingTools(server: McpServer, recordings: Performanc const result = { content: [{ type: "text" as const, text: describeRecording(recording, summary, range) }], structuredContent }; const preview = recordingPreview(recording); const response = withinResultBytes(result, { preview }); - if (response === result || recording.iosHitches === undefined) return response; - const withHitches = { ...preview, iosHitches: recording.iosHitches }; - return withinResultBytes(response, { preview: withHitches }); + if (response === result) return response; + if (recording.iosHitches) { + const withHitches = { ...preview, iosHitches: recording.iosHitches }; + return withinResultBytes(response, { preview: withHitches }); + } + if (recording.target.platform === "android") { + let frameCount = 0; + let captured = false; + for (const sample of recording.fps.samples) { + if (sample.frameTimeline === undefined) continue; + captured = true; + frameCount += sample.frameTimeline.frames.length; + // Even a frame with one-digit values takes over 60 JSON bytes. + if (frameCount * 60 > RESULT_BYTES) return response; + } + if (captured) return withinResultBytes(response, { preview: { ...preview, fps: recording.fps } }); + } + return response; }); registerAppTool(server, "mobile_render_performance_recording", { title: "Show an interactive performance chart in chat", - description: "Show a saved CPU/memory/FPS recording as an inline interactive chart with shared drag selection, thread breakdown and Ask. Completed physical iOS recordings overlay hitch markers on Display FPS, with per-sample hitch counts and range totals. Android frame data adds jank rate, classification coverage, dropped frames and frame-interval P50/P95/P99, updating with the selected range. Call this when reporting scrolling FPS/jank or comparing implementations so the user sees the chart alongside the analysis. The full timeline stays visible; automatic change highlights do not select or limit a range. Omit range unless the user requested a selection. Pass recording.id from mobile_record_performance or mobile_list_performance_recordings. Active runs update until finished. Data tools return measurements without rendering a chart. Returns the recording ID and summary numbers; the chart reads the samples itself, so use mobile_read_performance_recording for sample-level detail.", + description: "Show a saved CPU/memory/FPS recording as an inline interactive chart with shared drag selection, thread breakdown and Ask. Completed physical iOS recordings overlay hitch markers on Display FPS, with per-sample hitch counts and range totals. Android FrameTimeline marks late, dropped and janky device-wide display frames. Range statistics include jank rate, classification coverage, dropped frames and frame-interval P50/P95/P99. Call this when reporting scrolling FPS/jank or comparing implementations so the user sees the chart alongside the analysis. The full timeline stays visible; automatic change highlights do not select or limit a range. Omit range unless the user requested a selection. Pass recording.id from mobile_record_performance or mobile_list_performance_recordings. Active runs update until finished. Data tools return measurements without rendering a chart. Returns the recording ID and summary numbers; the chart reads the samples itself, so use mobile_read_performance_recording for sample-level detail.", inputSchema, outputSchema: referenceOutputSchema, annotations: read, _meta: { ui: { resourceUri: RECORDING_URI, visibility } }, }, showRecording); const comparisonTitle = comparisonTitleSchema.default("Performance comparison"); diff --git a/packages/core/test/recording-tools.test.ts b/packages/core/test/recording-tools.test.ts index c5769920..a65429cc 100644 --- a/packages/core/test/recording-tools.test.ts +++ b/packages/core/test/recording-tools.test.ts @@ -95,11 +95,11 @@ test("recording tools distinguish data, inline rendering, workspace opening and assert.equal(result.structuredContent?.title, recording.title); const text = result.content.map(item => item.type === "text" ? item.text : "").join(""); assert.match(text, new RegExp(`recordingId ${recording.id}`)); - // A preview for cards that cannot read the recording: every sample, no thread or frame detail. + // Small Android recordings carry exact frame timings for preview-only hosts. const preview = result.structuredContent?.preview as typeof recording | undefined; assert.equal(preview?.samples.length, recording.samples.length); assert.ok(preview?.samples.every(sample => sample.threads.length === 0)); - assert.ok(preview?.fps.samples.every(sample => sample.frameTimeline === undefined)); + assert.deepEqual(preview?.fps, recording.fps); assert.ok(JSON.stringify(result).length < 45_000, `${name} fits a host's tool result cap`); } assert.deepEqual(result.structuredContent?.range, { start: 12, end: 18 }); @@ -204,6 +204,11 @@ test("results that show recordings fit a host's result limit, leaving out previe const directory = await mkdtemp(join(tmpdir(), "mobile-dev-recording-tools-")); const store = new RecordingStore(directory); const longest = longestRecordingFixture(); + const frames = Array.from({ length: 900 }, (_, index) => { + const time = String(index + 1); + return { token: time, startTimeNs: time, endTimeNs: time, presentType: 2, jankType: 2 }; + }); + longest.fps.samples[0].frameTimeline = { clock: "boottime", intervalEndNs: "1000000000", frames }; const second = { ...longestRecordingFixture(), id: "44b7030b-a74e-466f-aeb0-bcd3ae8af972" }; const short = { ...recordingFixture(), id: "27cfecab-d99c-4533-90dd-e14a7cb0087b" }; const shortSecond = { ...recordingFixture(), id: "5d1f3c0e-8a4b-4e2a-9c61-0f7e2b9d4a13" }; @@ -219,7 +224,9 @@ test("results that show recordings fit a host's result limit, leaving out previe const bytes = (result: unknown) => Buffer.byteLength(JSON.stringify(result)); // The longest recording still carries its preview, for cards that cannot read it. const shown = await client.callTool({ name: "mobile_render_performance_recording", arguments: { recordingId: longest.id } }); - assert.ok(shown.structuredContent?.preview); + const preview = shown.structuredContent?.preview as typeof longest; + assert.equal(preview.fps.samples.length, longest.fps.samples.length); + assert.equal(preview.fps.samples[0].frameTimeline, undefined); assert.ok(bytes(shown) <= RESULT_BYTES, `${bytes(shown)} bytes`); const compared = await client.callTool({ name: "mobile_compare_performance_recordings", arguments: { recordingIds: [longest.id, second.id] } }); assert.equal(compared.structuredContent?.previews, undefined); diff --git a/packages/shared/src/frame-statistics.ts b/packages/shared/src/frame-statistics.ts index 553e16e0..28192242 100644 --- a/packages/shared/src/frame-statistics.ts +++ b/packages/shared/src/frame-statistics.ts @@ -31,10 +31,32 @@ export const nullableDisplayFrameStatsSchema = displayFrameStatsSchema.nullable( export type DisplayFrameStats = z.infer; const JANK_NONE = 1; -// UNKNOWN (256), unspecified (0), and future bits do not identify a classified frame. -const JANK_REASONS = 2 | 4 | 8 | 16 | 32 | 64 | 128 | 512 | 1024; +const JANK_UNKNOWN = 256; +const jankReasons: [number, string][] = [ + [2, "SurfaceFlinger scheduling"], [4, "Prediction error"], [8, "Display HAL"], + [16, "SurfaceFlinger CPU deadline missed"], [32, "SurfaceFlinger GPU deadline missed"], + [64, "App deadline missed"], [128, "Buffer stuffing"], + [512, "SurfaceFlinger stuffing"], [1024, "Dropped frame"], +]; +const JANK_REASONS = jankReasons.reduce((mask, [bit]) => mask | bit, 0); const CLASSIFIED_JANK_BITS = JANK_NONE | JANK_REASONS; +export function classifyDisplayJank(bits: number | undefined) { + if (bits === undefined || bits === 0 || (bits & ~CLASSIFIED_JANK_BITS) !== 0) return "unknown"; + return (bits & JANK_REASONS) === 0 ? "none" : "janky"; +} + +export function describeDisplayJank(bits = 0) { + const labels = []; + for (const [bit, label] of jankReasons) { + if ((bits & bit) !== 0) labels.push(label); + } + if ((bits & JANK_UNKNOWN) !== 0) labels.push("Unknown reason"); + if ((bits & ~(CLASSIFIED_JANK_BITS | JANK_UNKNOWN)) !== 0) labels.push("Unrecognized jank flags"); + if (labels.length > 0) return labels.join(", "); + return bits === JANK_NONE ? "No classified jank" : "Jank classification unavailable"; +} + function percentile(sorted: number[], fraction: number) { const rank = Math.ceil(sorted.length * fraction); return sorted[rank - 1]; @@ -88,11 +110,10 @@ export function summarizeDisplayFrames(samples: DisplayFpsSample[], duration: nu continue; } stats.presentedFrameCount++; - const jank = frame.jankType; - const classified = jank !== undefined && jank !== 0 && (jank & ~CLASSIFIED_JANK_BITS) === 0; - if (classified) { + const jank = classifyDisplayJank(frame.jankType); + if (jank !== "unknown") { stats.classifiedPresentedFrameCount++; - if ((jank & JANK_REASONS) !== 0) stats.jankyPresentedFrameCount++; + if (jank === "janky") stats.jankyPresentedFrameCount++; } else stats.unclassifiedPresentedFrameCount++; const presentation = BigInt(frame.endTimeNs); if (previousPresentation !== undefined && presentation > previousPresentation) { diff --git a/packages/shared/src/version.ts b/packages/shared/src/version.ts index b64d61e4..03540483 100644 --- a/packages/shared/src/version.ts +++ b/packages/shared/src/version.ts @@ -1 +1 @@ -export const PLUGIN_VERSION = "0.1.194"; +export const PLUGIN_VERSION = "0.1.195"; diff --git a/packages/skills/mobile-dev/SKILL.md b/packages/skills/mobile-dev/SKILL.md index 30b10d7f..c85bdefe 100644 --- a/packages/skills/mobile-dev/SKILL.md +++ b/packages/skills/mobile-dev/SKILL.md @@ -214,7 +214,10 @@ the same interaction and duration. Use `summary.frameStats` from frames and pacing percentiles alongside FPS. Show each run with `mobile_render_performance_recording` when reporting FPS/jank, including when the analysis uses the frame-read tool. The existing chart card includes Android jank -statistics and updates them for the selected range. Do not infer jank from average +statistics and updates them for the selected range. The live and saved FPS charts +mark each late, dropped or janky display frame once. Select a diamond for its +timestamp and SurfaceFlinger reasons, or inspect a sample for its flagged-frame +count. These events cover the whole device. Do not infer jank from average FPS or count unknown classifications as smooth frames. If `frameStats` is null, report that per-frame statistics were not captured. diff --git a/packages/ui/src/components/fps-frame-markers.tsx b/packages/ui/src/components/fps-frame-markers.tsx new file mode 100644 index 00000000..5b57af1f --- /dev/null +++ b/packages/ui/src/components/fps-frame-markers.tsx @@ -0,0 +1,117 @@ +import { memo, useState } from "react"; +import { DefaultZIndexes, usePlotArea, useXAxisScale, useYAxisScale, ZIndexLayer } from "recharts"; +import type { IosHitch } from "@mobile-dev/shared/ios-hitches.ts"; +import { describeDisplayJank } from "@mobile-dev/shared/frame-statistics.ts"; +import type { AndroidFrameMarker, FpsFrameOverlay } from "../fps-frame-overlay.ts"; + +export type FpsInspection = { kind: "marker" | "sample"; index: number }; + +function markerId(event: IosHitch | AndroidFrameMarker, index: number) { + return "frame" in event ? event.frame.token + "/" + event.frame.endTimeNs : index; +} + +// Late readback replaces an interval; eviction shifts every subsequent index. +export function useFpsInspection(overlay: FpsFrameOverlay | undefined, live = false) { + const [picked, setPicked] = useState<{ kind: FpsInspection["kind"]; id: number | string }>(); + const inspection: FpsInspection = { kind: overlay?.markers.length ? "marker" : "sample", index: 0 }; + if (overlay && live) { + inspection.index = inspection.kind === "marker" ? overlay.markers.length - 1 : Math.max(0, overlay.samples.length - 1); + } + if (picked && overlay) { + const index = picked.kind === "sample" ? overlay.samples.findIndex(sample => sample.end === picked.id) + : overlay.markers.findIndex((marker, index) => markerId(marker.event, index) === picked.id); + if (index >= 0) { + inspection.kind = picked.kind; + inspection.index = index; + } + } + function inspect(next: FpsInspection) { + if (!overlay) return; + const id = next.kind === "sample" ? overlay.samples[next.index].end : markerId(overlay.markers[next.index].event, next.index); + setPicked({ kind: next.kind, id }); + } + return { inspection, inspect }; +} + +function frameTiming(event: IosHitch | AndroidFrameMarker) { + if ("frame" in event) { + const { frame, label } = event; + const reasons = describeDisplayJank(frame.jankType); + const presentation = frame.presentType === 1 ? "on-time presentation" : "early presentation"; + const status = label === "Janky" ? `Janky display frame (${presentation})` : `${label} display frame`; + return `${event.time.toFixed(3)} s · ${status} · ${reasons}`; + } + const hz = Math.round(1000 / event.refreshIntervalMs); + const fraction = event.lateMs / event.refreshIntervalMs; + const intervals = Math.round(fraction * 100) / 100; + const unit = intervals === 1 ? "refresh interval" : "refresh intervals"; + return `${event.time.toFixed(3)} s · ${hz} Hz · ${event.lateMs.toFixed(2)} ms late · ${intervals} ${unit}`; +} + +export const FrameMarkers = memo(function FrameMarkers({ overlay, selected, onPick }: { overlay: FpsFrameOverlay; selected?: number; onPick?: (index: number) => void }) { + const x = useXAxisScale(); + const y = useYAxisScale(); + const plot = usePlotArea(); + if (x === undefined || y === undefined || plot === undefined) return null; + const diamond = (index: number, active: boolean) => { + const { event, sample } = overlay.markers[index]; + if (sample === undefined) return null; + const cx = x(event.time); + const cy = y(sample.fps); + if (cx === undefined || cy === undefined || cx < plot.x || cx > plot.x + plot.width || cy < plot.y || cy > plot.y + plot.height) return null; + const radius = active ? 6 : 4; + const maxLabelX = plot.x + plot.width - 25 - cx; + const rightBound = Math.min(0, maxLabelX); + const labelX = Math.max(plot.x + 25 - cx, rightBound); + return onPick(index))}> + {active && {event.time.toFixed(3)} s} + + + {frameTiming(event)} + ; + }; + return + {overlay.markers.map((_, index) => index === selected ? null : diamond(index, false))} + {selected !== undefined && overlay.markers[selected] && diamond(selected, true)} + ; +}); + +const InspectionOptions = memo(function InspectionOptions({ overlay }: { overlay: FpsFrameOverlay }) { + return <> + {overlay.markers.length > 0 && + {overlay.markers.map(({ event }, i) => )} + } + {overlay.samples.length > 0 && + {overlay.samples.map((sample, i) => )} + } + ; +}); + +export function FpsInspector({ overlay, inspection, onInspect }: { + overlay: FpsFrameOverlay; inspection: FpsInspection; onInspect: (next: FpsInspection) => void; +}) { + const marker = inspection.kind === "marker" ? overlay.markers[inspection.index] : undefined; + const sample = inspection.kind === "sample" ? overlay.samples[inspection.index] : marker?.sample; + const android = overlay.platform === "android"; + let detail = android ? "No flagged display frames in the captured interval." : "No visible hitches in the captured interval."; + if (marker) { + const fps = sample ? `${sample.fps.toFixed(1)} FPS in this sample` : "No FPS sample at this time"; + detail = `${frameTiming(marker.event)} · ${fps}`; + } else if (sample) { + const count = sample.markerCount; + const singular = android ? "flagged display frame" : "visible hitch"; + const plural = android ? "flagged display frames" : "visible hitches"; + const unit = count === 1 ? singular : plural; + const unavailable = android ? "FrameTimeline unavailable for this sample" : "Hitch count unavailable for the full sample"; + const timing = count === null ? unavailable : `${count} ${unit}`; + detail = `${sample.fps.toFixed(1)} FPS · ${timing}`; + } + return
+ {(marker || sample) && } +

{detail}

+
; +} diff --git a/packages/ui/src/components/performance-view.tsx b/packages/ui/src/components/performance-view.tsx index 6527f325..f9cdc687 100644 --- a/packages/ui/src/components/performance-view.tsx +++ b/packages/ui/src/components/performance-view.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; import { ActivityIcon, RefreshCwIcon, SlidersHorizontalIcon, SquareIcon } from "lucide-react"; import type { PerformancePanel } from "../performance-panel.ts"; import { SIDEBAR_WIDTH, TIMELINE_HEIGHT } from "../performance/constants"; @@ -8,6 +8,9 @@ import { TimelineChartWidth } from "../performance/TimelineChartWidth"; import { CpuTrack } from "./performance/CpuTrack"; import { MemoryTrack } from "./performance/MemoryTrack"; import { DisplayFpsTrack } from "./performance/DisplayFpsTrack"; +import { createAndroidFrameOverlay } from "../fps-frame-overlay.ts"; +import { recordUiTiming } from "../telemetry.ts"; +import { FrameMarkers, FpsInspector, useFpsInspection } from "./fps-frame-markers"; import { TimelineRuler } from "./performance/TimelineRuler"; import { Button } from "./ui/button"; import { NativeSelect, NativeSelectOption } from "./ui/native-select"; @@ -17,6 +20,15 @@ import { Alert, AlertDescription } from "./ui/alert"; export function PerformanceView({ panel }: { panel: PerformancePanel }) { const state = useSyncExternalStore(panel.subscribe, panel.getSnapshot); + const overlay = useMemo(() => { + if (state.platform !== "android" || state.fpsSamples.length === 0) return; + const started = performance.now(); + const frames = createAndroidFrameOverlay(state.fpsSamples); + const elapsed = performance.now() - started; + recordUiTiming("ui.performance.frame_markers", elapsed, "android"); + return frames; + }, [state.platform, state.fpsSamples]); + const { inspection, inspect } = useFpsInspection(overlay, true); const container = useRef(null); const [scrollElement, setScrollElement] = useState(null); const { zoom, following, contentWidth, chartWidth, hasMoreToRight, reset, change, handleScroll } = useTimelineViewport(state.samples, scrollElement, state.fpsSamples); @@ -73,7 +85,10 @@ export function PerformanceView({ panel }: { panel: PerformancePanel }) {
panel.retryFps()} /> + platform={state.platform} zoomState={zoom} onZoomChange={change} onZoomOut={reset} onRetry={() => panel.retryFps()}> + {overlay && inspect({ kind: "marker", index })} />} + panel.setThreadOrder(order)} phase={state.phase} error={state.error || null} scrollElement={scrollElement} @@ -88,5 +103,9 @@ export function PerformanceView({ panel }: { panel: PerformancePanel }) { bottom: scrollElement ? scrollElement.offsetHeight - scrollElement.clientHeight : 0, background: "linear-gradient(to right, transparent, var(--background))" }} />} + {overlay &&
+
Device-wide FPSFlagged display frame
+ +
} ; } diff --git a/packages/ui/src/components/performance/DisplayFpsTrack.tsx b/packages/ui/src/components/performance/DisplayFpsTrack.tsx index 1040ba94..644444ba 100644 --- a/packages/ui/src/components/performance/DisplayFpsTrack.tsx +++ b/packages/ui/src/components/performance/DisplayFpsTrack.tsx @@ -1,4 +1,4 @@ -import { useMemo } from "react"; +import { useMemo, type ReactNode } from "react"; import { GaugeIcon } from "lucide-react"; import type { CpuPhase } from "@mobile-dev/shared/cpu.ts"; import type { DisplayFpsSample } from "@mobile-dev/shared/display-fps.ts"; @@ -11,12 +11,13 @@ import { createFpsSeries } from "./fpsSeries"; const colors = { stroke: "#22c55e", fillStart: "#22c55e", fillEnd: "#166534" }; type Props = { + children?: ReactNode; samples: DisplayFpsSample[]; phase: CpuPhase; error: string; supported: boolean; platform: "ios" | "android"; zoomState: ZoomState; onZoomChange: (state: ZoomState) => void; onZoomOut: () => void; onRetry: () => void; }; function format(value: number | null) { return value === null ? "—" : value.toFixed(1); } -export function DisplayFpsTrack({ samples, phase, error, supported, platform, zoomState, onZoomChange, onZoomOut, onRetry }: Props) { +export function DisplayFpsTrack({ samples, phase, error, supported, platform, zoomState, onZoomChange, onZoomOut, onRetry, children }: Props) { const series = useMemo(() => createFpsSeries(samples), [samples]); const current = format(phase === "failed" ? null : series.current); const average = format(series.average); @@ -39,7 +40,7 @@ export function DisplayFpsTrack({ samples, phase, error, supported, platform, zo } metrics={metrics} title={title} />
+ chartColors={colors} gradientId="displayFpsGradient" tooltipPostfix="FPS" curveType="linear">{children} {showMessage &&
{message}{phase === "failed" && }
} diff --git a/packages/ui/src/components/performance/PerformanceAreaChart.tsx b/packages/ui/src/components/performance/PerformanceAreaChart.tsx index b296eac4..82fa6bf7 100644 --- a/packages/ui/src/components/performance/PerformanceAreaChart.tsx +++ b/packages/ui/src/components/performance/PerformanceAreaChart.tsx @@ -1,4 +1,4 @@ -import React, { memo, useCallback, useContext, useMemo, type ComponentProps } from "react"; +import React, { memo, useCallback, useContext, useMemo, useRef, type ComponentProps } from "react"; import { AreaChart, Area, @@ -26,6 +26,7 @@ import { ChartToolTip } from "./ChartToolTip"; import { Button } from "../ui/button"; type PerformanceAreaChartProps = { + children?: React.ReactNode; data: CpuPoint[]; zoomState: ZoomState; onZoomChange: (state: ZoomState) => void; @@ -48,6 +49,7 @@ const defaultChartColors = { }; export const PerformanceAreaChart = memo(function PerformanceAreaChart({ + children, data, zoomState, onZoomChange, @@ -59,6 +61,7 @@ export const PerformanceAreaChart = memo(function PerformanceAreaChart({ curveType = "step", }: PerformanceAreaChartProps) { const chartWidth = useContext(TimelineChartWidth); + const markerPress = useRef<{ x: number; time: number } | undefined>(undefined); const { refAreaLeft, refAreaRight, left, right, viewDuration } = zoomState; const yDomain = useMemo(() => { const domain = getAxisYDomain(data, left, right, 10); @@ -73,6 +76,10 @@ export const PerformanceAreaChart = memo(function PerformanceAreaChart({ const tooltipPosition = useMemo(() => ({ y: trackHeight / 2 }), [trackHeight]); const zoom = useCallback(() => { + if (markerPress.current) { + markerPress.current = undefined; + return; + } const { refAreaLeft, refAreaRight } = zoomState; if ( @@ -105,16 +112,29 @@ export const PerformanceAreaChart = memo(function PerformanceAreaChart({ }, [zoomState, onZoomChange]); const onMouseDown = useCallback( - (e: MouseHandlerDataParam) => { - if (typeof e.activeLabel === "number") { - onZoomChange({ ...zoomState, refAreaLeft: e.activeLabel }); + (e: MouseHandlerDataParam, event: React.MouseEvent) => { + markerPress.current = undefined; + const marker = event.target instanceof Element ? event.target.closest("[data-frame-time]") : null; + if (marker) { + markerPress.current = { x: event.clientX, time: Number(marker.dataset.frameTime) }; + return; } + if (typeof e.activeLabel === "number") onZoomChange({ ...zoomState, refAreaLeft: e.activeLabel }); }, [zoomState, onZoomChange] ); const onMouseMove = useCallback( - (e: MouseHandlerDataParam) => { + (e: MouseHandlerDataParam, event: React.MouseEvent) => { + const press = markerPress.current; + if (press) { + if (event.buttons !== 1 || typeof e.activeLabel !== "number") return; + const distance = Math.abs(event.clientX - press.x); + if (distance <= 3) return; + markerPress.current = undefined; + onZoomChange({ ...zoomState, refAreaLeft: press.time, refAreaRight: e.activeLabel }); + return; + } if ( zoomState.refAreaLeft !== undefined && typeof e.activeLabel === "number" @@ -213,6 +233,7 @@ export const PerformanceAreaChart = memo(function PerformanceAreaChart({ shape={renderSelectionReferenceArea} /> ) : null} + {children}
); diff --git a/packages/ui/src/components/recording-card.tsx b/packages/ui/src/components/recording-card.tsx index 40bf71c2..91b05d90 100644 --- a/packages/ui/src/components/recording-card.tsx +++ b/packages/ui/src/components/recording-card.tsx @@ -6,12 +6,13 @@ import type { RecordingController } from "../recording-controller.ts"; import type { RecordingRange } from "@mobile-dev/shared/recordings.ts"; import { summarizeRecording } from "@mobile-dev/shared/recordings.ts"; import { recordUiTiming } from "../telemetry.ts"; -import { createRecordingCpuSeries, createRecordingFpsSeries, createRecordingHitchOverlay, findRecordingChangeRanges } from "../recording-series.ts"; -import type { RecordingHitchOverlay, RecordingPoint } from "../recording-series.ts"; +import type { FpsFrameOverlay } from "../fps-frame-overlay.ts"; +import { createIosFrameOverlay, createAndroidFrameOverlay } from "../fps-frame-overlay.ts"; +import { createRecordingCpuSeries, createRecordingFpsSeries, findRecordingChangeRanges } from "../recording-series.ts"; +import type { RecordingPoint } from "../recording-series.ts"; import { Button } from "./ui/button"; import { InfoPopover as RecordingInfo } from "./card-parts"; -import { FpsInspector, HitchMarkers } from "./recording-hitches"; -import type { FpsInspection } from "./recording-hitches"; +import { FpsInspector, FrameMarkers, useFpsInspection } from "./fps-frame-markers"; import { RecordingChartShape, recordingChartPoints } from "./recording-chart-shape"; import { useMediaQuery } from "./use-media-query"; @@ -43,14 +44,13 @@ function RecordingOverview({ duration, range, changes, onClear }: { duration: nu function RecordingChart({ label, info, metricLabel, metric, data, duration, range, changes, color, unit, overlay, onDrag, onSelect }: { label: string; info: string; metricLabel: string; metric: string; data: RecordingPoint[]; duration: number; range?: RecordingRange; changes: RecordingRange[]; color: string; unit: string; - overlay?: RecordingHitchOverlay; onDrag: (range?: RecordingRange) => void; onSelect: (range?: RecordingRange) => void; + overlay?: FpsFrameOverlay; onDrag: (range?: RecordingRange) => void; onSelect: (range?: RecordingRange) => void; }) { const root = useRef(null); const anchor = useRef(undefined); const press = useRef<{ x: number; marker?: string }>(undefined); - const [picked, setPicked] = useState(); - const inspection: FpsInspection = picked ?? { kind: overlay?.hitches.length ? "hitch" : "sample", index: 0 }; - const inspectedSample = inspection.kind === "hitch" ? overlay?.hitches[inspection.index]?.sample : overlay?.samples[inspection.index]; + const { inspection, inspect } = useFpsInspection(overlay); + const inspectedSample = inspection.kind === "marker" ? overlay?.markers[inspection.index]?.sample : overlay?.samples[inspection.index]; const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)"); const [reveal, setReveal] = useState<"pending" | "finished" | "settled">(reducedMotion ? "settled" : "pending"); const revealStartedAt = useRef(undefined); @@ -106,26 +106,26 @@ function RecordingChart({ label, info, metricLabel, metric, data, duration, rang if (overlay === undefined || press.current === undefined) return false; if (Math.abs(event.clientX - press.current.x) > 3) return false; if (press.current.marker !== undefined) { - setPicked({ kind: "hitch", index: Number(press.current.marker) }); + inspect({ kind: "marker", index: Number(press.current.marker) }); return true; } const time = timeAt(event); const index = overlay.samples.findIndex(sample => sample.start <= time && time < sample.end); if (index < 0) return false; - setPicked({ kind: "sample", index }); + inspect({ kind: "sample", index }); return true; } return

{label}

{info}{metricLabel} {metric}
- {overlay && overlay.samples.length > 0 &&
Device-wide FPSVisible hitch
} + {overlay && overlay.samples.length > 0 &&
Device-wide FPS{overlay.platform === "android" ? "Flagged display frame" : "Visible hitch"}
} {(overlay === undefined || overlay.samples.length > 0) &&
{ if (event.button !== 0) return; setReveal("settled"); revealStartedAt.current = undefined; anchor.current = timeAt(event); if (overlay && event.target instanceof Element) { - const marker = event.target.closest("[data-hitch-index]"); - press.current = { x: event.clientX, marker: marker?.dataset.hitchIndex }; + const marker = event.target.closest("[data-frame-index]"); + press.current = { x: event.clientX, marker: marker?.dataset.frameIndex }; } event.currentTarget.setPointerCapture(event.pointerId); }} onPointerMove={event => { if (anchor.current !== undefined) onDrag(selection(event)); }} onPointerUp={event => { @@ -147,11 +147,11 @@ function RecordingChart({ label, info, metricLabel, metric, data, duration, rang {changes.map(change => )} {range && } - {overlay && } + {overlay && }
} - {overlay && } + {overlay && }
; } @@ -177,7 +177,9 @@ export function RecordingCard({ controller, detailed = false }: { controller: Re const total = summarizeRecording(recording); const cpu = createRecordingCpuSeries(recording); const fps = createRecordingFpsSeries(recording); - const overlay = createRecordingHitchOverlay(recording.iosHitches, fps); + const overlay = recording.target.platform === "android" + ? createAndroidFrameOverlay(recording.fps.samples, { start: 0, end: recording.durationSeconds }) + : createIosFrameOverlay(recording.iosHitches, fps); const memory: RecordingPoint[] = []; for (const sample of recording.samples) { memory.push({ time: sample.time, value: sample.memoryBytes === null ? null : sample.memoryBytes / MIB }); @@ -208,6 +210,9 @@ export function RecordingCard({ controller, detailed = false }: { controller: Re const selectedFrameStats = selected.frameStats; const hasDisplayData = hasFps || frameStats !== null; const displayScope = frameStats === null ? "Display FPS measures the whole device, including activity outside this app." : "Display FPS and frame statistics measure the whole device, including activity outside this app."; + let fpsInfo = displayScope; + if (derived.overlay?.platform === "android") fpsInfo += " Diamonds mark late, dropped or janky display frames. Select one to inspect its FrameTimeline classification."; + if (derived.overlay?.platform === "ios") fpsInfo += " Select a diamond to inspect a late frame containing this app’s content, or click a sample to see its hitch count. Drag to select a range."; const hasFrames = frameStats !== null && frameStats.frameCount > 0; const hitches = recording.iosHitches; const hitchStats = selected.hitchStats; @@ -222,12 +227,12 @@ export function RecordingCard({ controller, detailed = false }: { controller: Re {hasReadings === false &&

No performance readings recorded yet.

} {hasCpu && } {hasMemory && } - {(hasFps || derived.overlay) && } + {(hasFps || derived.overlay) && } {hitches?.status === "finished" && hitches.end < recording.durationSeconds &&

Frame timing captured through {seconds(hitches.end)}.

} {hitches?.status === "unavailable" &&

{hitches.error}

} {hasDisplayData &&

{displayScope}

} {recording.status === "finishing" &&

Finishing the recording…

} - {state.preview === "only" &&

{hitches ? "Thread detail requires the full recording." : "This app shows CPU, memory and FPS without thread or frame detail."}{state.canOpen && " Open the recording in Mobile Dev for all of it."}

} + {state.preview === "only" &&

{(derived.overlay || hitches) ? "Thread detail requires the full recording." : "This app shows CPU, memory and FPS without thread or frame detail."}{state.canOpen && " Open the recording in Mobile Dev for all of it."}

}