@swmansion/argent 0.32.1-next.15 → 0.32.1-next.16

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.
@@ -40996,7 +40996,7 @@ var require_get_intrinsic = __commonJS({
40996
40996
  var max = require_max();
40997
40997
  var min = require_min();
40998
40998
  var pow = require_pow();
40999
- var round2 = require_round();
40999
+ var round3 = require_round();
41000
41000
  var sign = require_sign();
41001
41001
  var $Function = Function;
41002
41002
  var getEvalledConstructor = function(expressionSyntax) {
@@ -41110,7 +41110,7 @@ var require_get_intrinsic = __commonJS({
41110
41110
  "%Math.max%": max,
41111
41111
  "%Math.min%": min,
41112
41112
  "%Math.pow%": pow,
41113
- "%Math.round%": round2,
41113
+ "%Math.round%": round3,
41114
41114
  "%Math.sign%": sign,
41115
41115
  "%Reflect.getPrototypeOf%": $ReflectGPO
41116
41116
  };
@@ -101252,7 +101252,7 @@ var _CI_VENDOR_COUNT_FOR_TEST = vendors_default.length;
101252
101252
  var SESSION_ID = (0, import_node_crypto3.randomUUID)();
101253
101253
  function readCliVersion() {
101254
101254
  if (true) {
101255
- return "0.32.1-next.15";
101255
+ return "0.32.1-next.16";
101256
101256
  }
101257
101257
  return "0.0.0";
101258
101258
  }
@@ -128801,9 +128801,9 @@ var VariantProposalStore = class {
128801
128801
  this.completed = true;
128802
128802
  if (!wasResubmit) this.consumed = false;
128803
128803
  this.lastOutcome = this.buildOutcome();
128804
- const round2 = this.round;
128805
- const toSettle = this.waitersList.filter((w) => !w.settled && w.round === round2);
128806
- this.waitersList = this.waitersList.filter((w) => w.round !== round2 || w.settled);
128804
+ const round3 = this.round;
128805
+ const toSettle = this.waitersList.filter((w) => !w.settled && w.round === round3);
128806
+ this.waitersList = this.waitersList.filter((w) => w.round !== round3 || w.settled);
128807
128807
  if (toSettle.length > 0) {
128808
128808
  this.consumed = true;
128809
128809
  for (const w of toSettle) {
@@ -128813,7 +128813,7 @@ var VariantProposalStore = class {
128813
128813
  } else if (this.cliSession) {
128814
128814
  this.consumed = true;
128815
128815
  } else if (!this.consumed) {
128816
- this.pendingOutcomes = this.pendingOutcomes.filter((o) => o.round !== round2);
128816
+ this.pendingOutcomes = this.pendingOutcomes.filter((o) => o.round !== round3);
128817
128817
  this.pendingOutcomes.push(this.lastOutcome);
128818
128818
  if (this.pendingOutcomes.length > MAX_PENDING_OUTCOMES) {
128819
128819
  this.pendingOutcomes.shift();
@@ -128842,7 +128842,7 @@ var VariantProposalStore = class {
128842
128842
  platform: this.device ? classifyDeviceForTelemetry(this.device) : void 0
128843
128843
  });
128844
128844
  }
128845
- return { ok: true, round: round2, resolved: this.submitted.length };
128845
+ return { ok: true, round: round3, resolved: this.submitted.length };
128846
128846
  }
128847
128847
  buildOutcome() {
128848
128848
  const selections = [];
@@ -142434,12 +142434,12 @@ function evaluateCondition(condition, expectedText, matches2, textMatch = "conta
142434
142434
  }
142435
142435
  function treeFingerprint(root, include) {
142436
142436
  const parts2 = [];
142437
- const round2 = (n) => Math.round(n * 1e3) / 1e3;
142437
+ const round3 = (n) => Math.round(n * 1e3) / 1e3;
142438
142438
  const walk = (node2) => {
142439
142439
  if (!include || include(node2)) {
142440
142440
  const f = node2.frame;
142441
142441
  parts2.push(
142442
- `${node2.role}|${round2(f.x)},${round2(f.y)},${round2(f.width)},${round2(f.height)}|${node2.label ?? ""}|${node2.value ?? ""}|${node2.identifier ?? ""}`
142442
+ `${node2.role}|${round3(f.x)},${round3(f.y)},${round3(f.width)},${round3(f.height)}|${node2.label ?? ""}|${node2.value ?? ""}|${node2.identifier ?? ""}`
142443
142443
  );
142444
142444
  }
142445
142445
  for (const child of node2.children) walk(child);
@@ -161276,12 +161276,12 @@ var capability29 = {
161276
161276
  macos: { app: true }
161277
161277
  };
161278
161278
  function treeSignature(root) {
161279
- const round2 = (n) => Math.round(n * 100) / 100;
161279
+ const round3 = (n) => Math.round(n * 100) / 100;
161280
161280
  const parts2 = [];
161281
161281
  const walk = (node2) => {
161282
161282
  const f = node2.frame;
161283
161283
  parts2.push(
161284
- `${node2.role}|${node2.label ?? ""}|${node2.value ?? ""}|${round2(f.x)},${round2(f.y)},${round2(f.width)},${round2(f.height)}`
161284
+ `${node2.role}|${node2.label ?? ""}|${node2.value ?? ""}|${round3(f.x)},${round3(f.y)},${round3(f.width)},${round3(f.height)}`
161285
161285
  );
161286
161286
  for (const child of node2.children) walk(child);
161287
161287
  };
@@ -161956,6 +161956,185 @@ async function readCommitTree(path63) {
161956
161956
  return JSON.parse(json2);
161957
161957
  }
161958
161958
 
161959
+ // ../tool-server/src/utils/react-profiler/pipeline/00-cpu-correlate.ts
161960
+ var ARGENT_PROFILER_PREFIX = "__argent_";
161961
+ var MIN_STALE_GAP_US = 1e6;
161962
+ function isArgentProfilerFunction(name) {
161963
+ return name.startsWith(ARGENT_PROFILER_PREFIX);
161964
+ }
161965
+ function dropStaleLeadingGap(profile) {
161966
+ const { timeDeltas } = profile;
161967
+ const first = timeDeltas.findIndex((delta, i) => i > 0 && delta > 0);
161968
+ if (first < 0) return;
161969
+ const gap = timeDeltas[first];
161970
+ if (gap < MIN_STALE_GAP_US || gap <= profile.endTime - profile.startTime - gap) return;
161971
+ timeDeltas[first] = 0;
161972
+ profile.startTime += gap;
161973
+ }
161974
+ function buildCpuSampleIndex(cpuProfile) {
161975
+ const { nodes, samples, timeDeltas, startTime, endTime } = cpuProfile;
161976
+ const nodeMap = /* @__PURE__ */ new Map();
161977
+ for (const node2 of nodes) {
161978
+ nodeMap.set(node2.id, node2);
161979
+ }
161980
+ const timestampsMs = new Float64Array(samples.length);
161981
+ const intervalStartsMs = new Float64Array(samples.length);
161982
+ let accumulatedUs = 0;
161983
+ for (let i = 0; i < samples.length; i++) {
161984
+ const raw = timeDeltas[i];
161985
+ const delta = Number.isFinite(raw) && (raw ?? 0) >= 0 ? raw : 0;
161986
+ intervalStartsMs[i] = accumulatedUs / 1e3;
161987
+ accumulatedUs += delta;
161988
+ timestampsMs[i] = accumulatedUs / 1e3;
161989
+ }
161990
+ return {
161991
+ childToParent: buildChildToParent(nodeMap),
161992
+ timestampsMs,
161993
+ intervalStartsMs,
161994
+ sampleNodeIds: samples,
161995
+ nodeMap,
161996
+ durationMs: (endTime - startTime) / 1e3
161997
+ };
161998
+ }
161999
+ var IDLE_FRAME_NAMES = /* @__PURE__ */ new Set(["(idle)", "(program)", "(root)", "[idle]", "[root]"]);
162000
+ function isIdleFrame(name) {
162001
+ return !name || IDLE_FRAME_NAMES.has(name);
162002
+ }
162003
+ function queryCpuWindow(index, startMs, endMs, topN2 = 5) {
162004
+ const { timestampsMs, intervalStartsMs, sampleNodeIds, nodeMap } = index;
162005
+ const n = timestampsMs.length;
162006
+ const sampleRangeMs = {
162007
+ start: n > 0 ? intervalStartsMs[0] : 0,
162008
+ end: n > 0 ? timestampsMs[n - 1] : 0
162009
+ };
162010
+ const empty2 = {
162011
+ hotspots: [],
162012
+ samplesInWindow: 0,
162013
+ coveredMs: 0,
162014
+ idleMs: 0,
162015
+ sampleRangeMs,
162016
+ medianIntervalMs: 0,
162017
+ maxIntervalMs: 0
162018
+ };
162019
+ if (n === 0) return empty2;
162020
+ let lo = 0;
162021
+ let hi = n;
162022
+ while (lo < hi) {
162023
+ const mid = lo + hi >>> 1;
162024
+ if (timestampsMs[mid] < startMs) lo = mid + 1;
162025
+ else hi = mid;
162026
+ }
162027
+ const selfMsByNode = /* @__PURE__ */ new Map();
162028
+ const intervals = [];
162029
+ let samplesInWindow = 0;
162030
+ let coveredMs = 0;
162031
+ let idleMs = 0;
162032
+ let maxIntervalMs = 0;
162033
+ for (let i = lo; i < n; i++) {
162034
+ const from2 = intervalStartsMs[i];
162035
+ if (from2 > endMs) break;
162036
+ const overlap = Math.min(endMs, timestampsMs[i]) - Math.max(startMs, from2);
162037
+ if (overlap <= 0) continue;
162038
+ samplesInWindow++;
162039
+ coveredMs += overlap;
162040
+ intervals.push(timestampsMs[i] - from2);
162041
+ if (timestampsMs[i] - from2 > maxIntervalMs) maxIntervalMs = timestampsMs[i] - from2;
162042
+ const nodeId = sampleNodeIds[i];
162043
+ const node2 = nodeMap.get(nodeId);
162044
+ if (isIdleFrame(node2?.callFrame.functionName)) {
162045
+ idleMs += overlap;
162046
+ continue;
162047
+ }
162048
+ selfMsByNode.set(nodeId, (selfMsByNode.get(nodeId) ?? 0) + overlap);
162049
+ }
162050
+ if (samplesInWindow === 0) return { ...empty2, sampleRangeMs };
162051
+ intervals.sort((a, b) => a - b);
162052
+ const medianIntervalMs = intervals[Math.floor(intervals.length / 2)] ?? 0;
162053
+ const childToParent = index.childToParent ?? buildChildToParent(nodeMap);
162054
+ const totalMsByNode = /* @__PURE__ */ new Map();
162055
+ for (const [nodeId, ms] of selfMsByNode) {
162056
+ totalMsByNode.set(nodeId, (totalMsByNode.get(nodeId) ?? 0) + ms);
162057
+ let current = nodeId;
162058
+ const seen = /* @__PURE__ */ new Set([current]);
162059
+ while (childToParent.has(current)) {
162060
+ const parent = childToParent.get(current);
162061
+ if (seen.has(parent)) break;
162062
+ seen.add(parent);
162063
+ totalMsByNode.set(parent, (totalMsByNode.get(parent) ?? 0) + ms);
162064
+ current = parent;
162065
+ }
162066
+ }
162067
+ const entries = [];
162068
+ for (const [nodeId, ms] of selfMsByNode) {
162069
+ const node2 = nodeMap.get(nodeId);
162070
+ if (!node2) continue;
162071
+ const name = node2.callFrame.functionName;
162072
+ if (isArgentProfilerFunction(name)) continue;
162073
+ entries.push({
162074
+ name,
162075
+ selfMs: Math.round(ms * 100) / 100,
162076
+ totalMs: Math.round((totalMsByNode.get(nodeId) ?? ms) * 100) / 100,
162077
+ url: node2.callFrame.url || void 0,
162078
+ lineNumber: node2.callFrame.lineNumber >= 0 ? node2.callFrame.lineNumber : void 0
162079
+ });
162080
+ }
162081
+ entries.sort((a, b) => b.selfMs - a.selfMs);
162082
+ return {
162083
+ hotspots: entries.slice(0, topN2),
162084
+ samplesInWindow,
162085
+ coveredMs,
162086
+ idleMs,
162087
+ sampleRangeMs,
162088
+ medianIntervalMs,
162089
+ maxIntervalMs
162090
+ };
162091
+ }
162092
+ function buildChildToParent(nodeMap) {
162093
+ const childToParent = /* @__PURE__ */ new Map();
162094
+ for (const node2 of nodeMap.values()) {
162095
+ for (const childId of node2.children ?? []) childToParent.set(childId, node2.id);
162096
+ }
162097
+ return childToParent;
162098
+ }
162099
+ function correlateCpuWithCommits(summaries, index, topNPerCommit = 5) {
162100
+ if (!index) return summaries;
162101
+ return summaries.map((summary) => {
162102
+ if (summary.isMargin) return summary;
162103
+ const startMs = summary.timestampMs;
162104
+ const endMs = summary.timestampMs + summary.totalRenderMs;
162105
+ const { hotspots } = queryCpuWindow(index, startMs, endMs, topNPerCommit);
162106
+ if (hotspots.length === 0) return summary;
162107
+ return { ...summary, cpuHotspots: hotspots };
162108
+ });
162109
+ }
162110
+ function serializeCpuSampleIndex(index) {
162111
+ return {
162112
+ version: 2,
162113
+ timestampsMs: Array.from(index.timestampsMs),
162114
+ intervalStartsMs: Array.from(index.intervalStartsMs),
162115
+ sampleNodeIds: index.sampleNodeIds,
162116
+ nodes: [...index.nodeMap.values()],
162117
+ durationMs: index.durationMs
162118
+ };
162119
+ }
162120
+ function deserializeCpuSampleIndex(raw) {
162121
+ if (raw?.version !== 2 || !Array.isArray(raw.timestampsMs) || !Array.isArray(raw.nodes)) {
162122
+ throw new Error("unsupported CPU sample index format");
162123
+ }
162124
+ const nodeMap = /* @__PURE__ */ new Map();
162125
+ for (const node2 of raw.nodes) {
162126
+ nodeMap.set(node2.id, node2);
162127
+ }
162128
+ return {
162129
+ timestampsMs: new Float64Array(raw.timestampsMs),
162130
+ intervalStartsMs: new Float64Array(raw.intervalStartsMs ?? []),
162131
+ sampleNodeIds: raw.sampleNodeIds,
162132
+ nodeMap,
162133
+ childToParent: buildChildToParent(nodeMap),
162134
+ durationMs: raw.durationMs
162135
+ };
162136
+ }
162137
+
161959
162138
  // ../tool-server/src/utils/react-profiler/last-run.ts
161960
162139
  function savedSessionInfo(paths) {
161961
162140
  return {
@@ -162005,6 +162184,424 @@ function lastRunText(saved, lost) {
162005
162184
  return null;
162006
162185
  }
162007
162186
 
162187
+ // ../tool-server/src/utils/react-profiler/pipeline/utils.ts
162188
+ function deriveReason(cd, hookTypes) {
162189
+ if (cd === null) return "unknown";
162190
+ if (cd.props !== null && cd.props.length > 0) return "props";
162191
+ if (cd.didHooksChange || cd.hooks !== null && cd.hooks.length > 0) {
162192
+ if (hookTypes && cd.hooks) {
162193
+ const isState = cd.hooks.some((idx) => {
162194
+ const ht = hookTypes[idx];
162195
+ return ht === "State" || ht === "Reducer" || ht === "useState" || ht === "useReducer";
162196
+ });
162197
+ if (isState) return "state";
162198
+ }
162199
+ return "hooks";
162200
+ }
162201
+ if (cd.context === true) return "context";
162202
+ if (cd.state === true) return "state";
162203
+ return "parent";
162204
+ }
162205
+ function emptyReasonHistogram() {
162206
+ return { parent: 0, props: 0, hooks: 0, context: 0, state: 0, force_update: 0, unknown: 0 };
162207
+ }
162208
+ function dominantReason(histogram) {
162209
+ let best = "unknown";
162210
+ let bestCount = -1;
162211
+ for (const [reason2, count2] of Object.entries(histogram)) {
162212
+ if (count2 > bestCount) {
162213
+ bestCount = count2;
162214
+ best = reason2;
162215
+ }
162216
+ }
162217
+ return best;
162218
+ }
162219
+
162220
+ // ../tool-server/src/utils/react-profiler/component-names.ts
162221
+ var WRAPPER_PATTERNS = [/^Forget\((.+)\)$/, /^Memo\((.+)\)$/, /^ForwardRef\((.+)\)$/];
162222
+ var MAX_WRAPPER_DEPTH = 4;
162223
+ function stripComponentWrappers(raw) {
162224
+ let name = raw;
162225
+ let hasForget = false;
162226
+ let hasMemo = false;
162227
+ let hasForwardRef = false;
162228
+ for (let i = 0; i < MAX_WRAPPER_DEPTH; i++) {
162229
+ const m = WRAPPER_PATTERNS.map((re2) => name.match(re2)).find(Boolean);
162230
+ if (!m) break;
162231
+ if (name.startsWith("Forget(")) hasForget = true;
162232
+ else if (name.startsWith("Memo(")) hasMemo = true;
162233
+ else if (name.startsWith("ForwardRef(")) hasForwardRef = true;
162234
+ name = m[1];
162235
+ }
162236
+ return { baseName: name, hasForget, hasMemo, hasForwardRef };
162237
+ }
162238
+ function annotateComponentName(raw) {
162239
+ const { baseName, hasForget, hasMemo, hasForwardRef } = stripComponentWrappers(raw);
162240
+ const parts2 = [];
162241
+ if (hasMemo) parts2.push("React.memo");
162242
+ if (hasForget) parts2.push("React Compiler");
162243
+ if (hasForwardRef) parts2.push("forwardRef");
162244
+ const tag3 = parts2.length > 0 ? ` [${parts2.join(" + ")}]` : "";
162245
+ return { displayName: baseName, tag: tag3, rawName: raw };
162246
+ }
162247
+ function resolveComponentName(query, recordedNames) {
162248
+ const names = [...new Set(recordedNames)];
162249
+ const sharingDisplayName = (raw) => {
162250
+ const display = annotateComponentName(raw).displayName;
162251
+ return names.filter((n) => n !== raw && annotateComponentName(n).displayName === display);
162252
+ };
162253
+ if (names.includes(query)) {
162254
+ return { kind: "exact", rawName: query, alsoMatching: sharingDisplayName(query) };
162255
+ }
162256
+ const candidates = names.filter((n) => annotateComponentName(n).displayName === query);
162257
+ if (candidates.length === 1) {
162258
+ return { kind: "display", rawName: candidates[0], query };
162259
+ }
162260
+ if (candidates.length > 1) {
162261
+ return { kind: "ambiguous", query, candidates };
162262
+ }
162263
+ return { kind: "missing", query, suggestions: suggestNames(query, names) };
162264
+ }
162265
+ function suggestNames(query, names, limit = 5) {
162266
+ const needle = query.toLowerCase();
162267
+ if (needle.length < 2) return [];
162268
+ return names.filter((n) => {
162269
+ const hay = `${n} ${annotateComponentName(n).displayName}`.toLowerCase();
162270
+ return hay.includes(needle) || needle.includes(annotateComponentName(n).displayName.toLowerCase());
162271
+ }).slice(0, limit);
162272
+ }
162273
+ function describeResolution(resolution) {
162274
+ if (resolution.kind === "display") {
162275
+ const { tag: tag3 } = annotateComponentName(resolution.rawName);
162276
+ const why = tag3 ? ` (${tag3.trim().slice(1, -1)})` : "";
162277
+ return `> Resolved \`${resolution.query}\` to the recorded component \`${resolution.rawName}\`${why}. Either name works here.`;
162278
+ }
162279
+ if (resolution.alsoMatching.length > 0) {
162280
+ const others = resolution.alsoMatching.map((n) => `\`${n}\``).join(", ");
162281
+ return `> Showing \`${resolution.rawName}\` only. ${others} also appear${resolution.alsoMatching.length === 1 ? "s" : ""} under this name once wrappers are stripped; they are separate fibers, so pass the exact name to target one.`;
162282
+ }
162283
+ return "";
162284
+ }
162285
+ function renderComponentNameMiss(resolution, context2 = {}) {
162286
+ if (resolution.kind === "ambiguous") {
162287
+ const list = resolution.candidates.map((c) => `- \`${c}\``).join("\n");
162288
+ return `_Component \`${resolution.query}\` is ambiguous: ${resolution.candidates.length} recorded components share this name once \`Memo(...)\` / \`ForwardRef(...)\` / \`Forget(...)\` wrappers are stripped. They are separate fibers and are not merged, because a combined total would not describe any real component. Re-run with one of these exact \`component_name\` values:_
162289
+
162290
+ ${list}`;
162291
+ }
162292
+ const recorded = context2.fiberRenders != null && context2.commits != null ? ` The session recorded ${context2.fiberRenders} fiber renders across ${context2.commits} commits.` : "";
162293
+ const suggestions = resolution.suggestions.length > 0 ? `
162294
+
162295
+ Closest recorded names \u2014 pass one verbatim as \`component_name\`:
162296
+ ` + resolution.suggestions.map((s) => `- \`${s}\``).join("\n") : "";
162297
+ return `_Component \`${resolution.query}\` not found in this profiling session \u2014 no exact match, and no component whose displayed name is \`${resolution.query}\` once \`Memo(...)\` / \`ForwardRef(...)\` / \`Forget(...)\` wrappers are stripped.${recorded}_${suggestions}
162298
+
162299
+ ` + (context2.nextStep ?? `To list every component in a commit instead, run \`profiler-commit-query mode=by_index commit_index=<n>\`.`);
162300
+ }
162301
+ function astLookupCandidates(raw) {
162302
+ const keys = [raw];
162303
+ const { baseName } = stripComponentWrappers(raw);
162304
+ if (baseName !== raw) keys.push(baseName);
162305
+ const withoutSuffix = baseName.replace(/\(.*\)$/, "");
162306
+ if (withoutSuffix !== baseName && /^[A-Za-z_$][\w$]*$/.test(withoutSuffix)) {
162307
+ keys.push(withoutSuffix);
162308
+ }
162309
+ return keys;
162310
+ }
162311
+
162312
+ // ../tool-server/src/utils/react-profiler/render-summary.ts
162313
+ var RENDER_SUMMARY_VERSION = 1;
162314
+ var MIN_FREQUENT_RERENDER_COMMITS = 10;
162315
+ var MIN_FREQUENT_SELF_MS_PER_S = 1;
162316
+ var MAX_FREQUENT_ROWS = 5;
162317
+ var MAX_TOP_PROPS = 3;
162318
+ var MAX_TOP_HOOKS = 3;
162319
+ var PEAK_WINDOW_MS = 1e3;
162320
+ function round2(n) {
162321
+ return Math.round(n * 100) / 100;
162322
+ }
162323
+ function topKeys(freq, n) {
162324
+ return [...freq.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([k]) => k);
162325
+ }
162326
+ function validDuration(ms) {
162327
+ return Number.isFinite(ms) && ms > 0 ? ms : 0;
162328
+ }
162329
+ function commitRenderMs(commit) {
162330
+ return Math.max(validDuration(commit.durationMs), validDuration(commit.selfMs ?? 0));
162331
+ }
162332
+ function peakWindowMs(commitTimings) {
162333
+ const sorted = commitTimings.filter((c) => Number.isFinite(c.timestamp)).sort((a, b) => a.timestamp - b.timestamp);
162334
+ let peak = 0;
162335
+ let inWindow = 0;
162336
+ let first = 0;
162337
+ for (const commit of sorted) {
162338
+ inWindow += commitRenderMs(commit);
162339
+ while (sorted[first].timestamp <= commit.timestamp - PEAK_WINDOW_MS) {
162340
+ inWindow -= commitRenderMs(sorted[first]);
162341
+ first++;
162342
+ }
162343
+ if (inWindow > peak) peak = inWindow;
162344
+ }
162345
+ return peak;
162346
+ }
162347
+ function summarizeRenders(commits, commitTimings, recordingMs) {
162348
+ const byName = /* @__PURE__ */ new Map();
162349
+ let fiberRenders = 0;
162350
+ let rerenders = 0;
162351
+ let mounts = 0;
162352
+ let untrackedRenders = 0;
162353
+ for (const c of commits) {
162354
+ if (!c.didRender) continue;
162355
+ fiberRenders++;
162356
+ let acc = byName.get(c.componentName);
162357
+ if (!acc) {
162358
+ acc = {
162359
+ rerenders: 0,
162360
+ rerenderSelfMs: 0,
162361
+ maxRerenderSelfMs: 0,
162362
+ untrackedRenders: 0,
162363
+ mounts: 0,
162364
+ mountSelfMs: 0,
162365
+ lastRerenderCommit: -1,
162366
+ rerenderCommits: 0,
162367
+ reasons: emptyReasonHistogram(),
162368
+ props: /* @__PURE__ */ new Map(),
162369
+ hooks: /* @__PURE__ */ new Map()
162370
+ };
162371
+ byName.set(c.componentName, acc);
162372
+ }
162373
+ const cd = c.changeDescription;
162374
+ if (cd === null) {
162375
+ untrackedRenders++;
162376
+ acc.untrackedRenders++;
162377
+ continue;
162378
+ }
162379
+ if (cd.isFirstMount === true) {
162380
+ mounts++;
162381
+ acc.mounts++;
162382
+ acc.mountSelfMs += c.selfDuration;
162383
+ continue;
162384
+ }
162385
+ rerenders++;
162386
+ acc.rerenders++;
162387
+ acc.rerenderSelfMs += c.selfDuration;
162388
+ if (c.selfDuration > acc.maxRerenderSelfMs) acc.maxRerenderSelfMs = c.selfDuration;
162389
+ if (c.commitIndex !== acc.lastRerenderCommit) {
162390
+ acc.rerenderCommits++;
162391
+ acc.lastRerenderCommit = c.commitIndex;
162392
+ }
162393
+ acc.reasons[deriveReason(cd, c.hookTypes ?? null)]++;
162394
+ for (const p of cd.props ?? []) acc.props.set(p, (acc.props.get(p) ?? 0) + 1);
162395
+ if (cd.hooks && c.hookTypes) {
162396
+ for (const idx of cd.hooks) {
162397
+ const hook = c.hookTypes[idx] ?? `hook[${idx}]`;
162398
+ acc.hooks.set(hook, (acc.hooks.get(hook) ?? 0) + 1);
162399
+ }
162400
+ }
162401
+ }
162402
+ const components = [];
162403
+ for (const [name, acc] of byName) {
162404
+ const reason2 = acc.rerenders > 0 ? dominantReason(acc.reasons) : null;
162405
+ const row = {
162406
+ name,
162407
+ rerenders: acc.rerenders,
162408
+ untrackedRenders: acc.untrackedRenders,
162409
+ rerenderCommits: acc.rerenderCommits,
162410
+ rerenderSelfMs: round2(acc.rerenderSelfMs),
162411
+ maxRerenderSelfMs: round2(acc.maxRerenderSelfMs),
162412
+ mounts: acc.mounts,
162413
+ mountSelfMs: round2(acc.mountSelfMs),
162414
+ reason: reason2
162415
+ };
162416
+ const topProps = topKeys(acc.props, MAX_TOP_PROPS);
162417
+ if (topProps.length > 0) row.topProps = topProps;
162418
+ const topHooks = topKeys(acc.hooks, MAX_TOP_HOOKS);
162419
+ if (topHooks.length > 0) row.topHooks = topHooks;
162420
+ components.push(row);
162421
+ }
162422
+ components.sort(
162423
+ (a, b) => b.rerenderSelfMs - a.rerenderSelfMs || b.rerenders - a.rerenders || b.mountSelfMs - a.mountSelfMs || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
162424
+ );
162425
+ let totalRenderMs = 0;
162426
+ let maxCommitMs = 0;
162427
+ for (const commit of commitTimings) {
162428
+ totalRenderMs += commitRenderMs(commit);
162429
+ const ms = validDuration(commit.durationMs);
162430
+ if (ms > maxCommitMs) maxCommitMs = ms;
162431
+ }
162432
+ return {
162433
+ version: RENDER_SUMMARY_VERSION,
162434
+ recordingMs: round2(recordingMs),
162435
+ totalCommits: commitTimings.length,
162436
+ totalRenderMs: round2(totalRenderMs),
162437
+ peakSecondRenderMs: round2(peakWindowMs(commitTimings)),
162438
+ // Rounded down: 15.996 ms did not reach the 16 ms floor.
162439
+ maxCommitMs: Math.floor(maxCommitMs * 100) / 100,
162440
+ fiberRenders,
162441
+ rerenders,
162442
+ mounts,
162443
+ untrackedRenders,
162444
+ components
162445
+ };
162446
+ }
162447
+ function isFiniteNumber(v) {
162448
+ return typeof v === "number" && Number.isFinite(v);
162449
+ }
162450
+ function parseRenderSummary(raw) {
162451
+ if (!raw || typeof raw !== "object") return null;
162452
+ const s = raw;
162453
+ if (s.version !== RENDER_SUMMARY_VERSION) return null;
162454
+ for (const key2 of [
162455
+ "recordingMs",
162456
+ "totalCommits",
162457
+ "totalRenderMs",
162458
+ "peakSecondRenderMs",
162459
+ "maxCommitMs",
162460
+ "fiberRenders",
162461
+ "rerenders",
162462
+ "mounts",
162463
+ "untrackedRenders"
162464
+ ]) {
162465
+ if (!isFiniteNumber(s[key2])) return null;
162466
+ }
162467
+ if (!Array.isArray(s.components)) return null;
162468
+ for (const c of s.components) {
162469
+ if (!c || typeof c !== "object") return null;
162470
+ const row = c;
162471
+ if (typeof row.name !== "string") return null;
162472
+ for (const key2 of [
162473
+ "rerenders",
162474
+ "untrackedRenders",
162475
+ "rerenderCommits",
162476
+ "rerenderSelfMs",
162477
+ "maxRerenderSelfMs",
162478
+ "mounts",
162479
+ "mountSelfMs"
162480
+ ]) {
162481
+ if (!isFiniteNumber(row[key2])) return null;
162482
+ }
162483
+ if (row.reason !== null && typeof row.reason !== "string") return null;
162484
+ for (const key2 of ["topProps", "topHooks"]) {
162485
+ if (row[key2] !== void 0 && !Array.isArray(row[key2])) return null;
162486
+ }
162487
+ }
162488
+ return raw;
162489
+ }
162490
+ function renderTimeShare(summary) {
162491
+ return summary.recordingMs > 0 ? summary.totalRenderMs / summary.recordingMs : 0;
162492
+ }
162493
+ function peakRenderShare(summary) {
162494
+ const windowMs = Math.min(PEAK_WINDOW_MS, summary.recordingMs);
162495
+ return windowMs > 0 ? Math.min(summary.peakSecondRenderMs / windowMs, 1) : 0;
162496
+ }
162497
+ var SLOW_COMMIT_MS = 16;
162498
+ function hasUnnamedSlowCommit(summary) {
162499
+ return summary.maxCommitMs >= SLOW_COMMIT_MS;
162500
+ }
162501
+ function formatShare(share) {
162502
+ const pct = share * 100;
162503
+ if (pct <= 0) return "0%";
162504
+ const rounded = Math.round(pct * 10) / 10;
162505
+ if (rounded >= 10) return `${Math.round(pct)}%`;
162506
+ if (rounded < 0.1) return "<0.1%";
162507
+ return `${rounded.toFixed(1)}%`;
162508
+ }
162509
+ function formatPeakCommit(ms) {
162510
+ return `${(Math.floor(ms * 10) / 10).toFixed(1)}ms`;
162511
+ }
162512
+ function formatMs(ms) {
162513
+ return ms >= 10 ? `${Math.round(ms).toLocaleString("en-US")} ms` : `${ms.toFixed(1)} ms`;
162514
+ }
162515
+ function formatCount(n) {
162516
+ return n.toLocaleString("en-US");
162517
+ }
162518
+ function formatRenderTime(summary) {
162519
+ const commits = summary.totalCommits === 1 ? "commit" : "commits";
162520
+ const peak = summary.totalCommits > 0 ? `, peak ${formatShare(peakRenderShare(summary))} in 1 s` : "";
162521
+ return `${formatMs(summary.totalRenderMs)} of ${(summary.recordingMs / 1e3).toFixed(1)} s (${formatShare(renderTimeShare(summary))})${peak}, ${formatCount(summary.totalCommits)} ${commits}`;
162522
+ }
162523
+ function renderSummaryNameMiss(resolution, summary) {
162524
+ return renderComponentNameMiss(resolution, {
162525
+ fiberRenders: summary.fiberRenders,
162526
+ commits: summary.totalCommits,
162527
+ nextStep: "Run `profiler-commit-query` mode=`render_counts` without `component_name` to list every component."
162528
+ });
162529
+ }
162530
+ function allRenderCount(row) {
162531
+ return row.rerenders + row.mounts + row.untrackedRenders;
162532
+ }
162533
+ function renderNameOutsideStoredCommits(query, summary, nextStep = "") {
162534
+ const resolution = resolveComponentName(
162535
+ query,
162536
+ summary.components.map((c) => c.name)
162537
+ );
162538
+ if (resolution.kind !== "exact" && resolution.kind !== "display") {
162539
+ return renderSummaryNameMiss(resolution, summary);
162540
+ }
162541
+ const row = summary.components.find((c) => c.name === resolution.rawName);
162542
+ const renders = allRenderCount(row);
162543
+ return `_\`${row.name}\` rendered ${formatCount(renders)} ${renders === 1 ? "time" : "times"} in this session, but never in a stored commit: only commits of 16ms or more and their neighbours are stored._
162544
+
162545
+ Run \`profiler-commit-query\` mode=\`render_counts\` component_name=\`${row.name}\` for its counts over all commits.${nextStep}`;
162546
+ }
162547
+ function describeStoredResolution(resolution, summary) {
162548
+ const separate = resolution.kind === "display" ? summary?.components.find(
162549
+ (c) => c.name !== resolution.rawName && annotateComponentName(c.name).displayName === resolution.query
162550
+ ) : void 0;
162551
+ if (resolution.kind !== "display" || !separate) return describeResolution(resolution);
162552
+ const renders = allRenderCount(separate);
162553
+ return `> Showing \`${resolution.rawName}\`, the only stored component named \`${resolution.query}\`. A separate \`${separate.name}\` rendered ${formatCount(renders)} ${renders === 1 ? "time" : "times"} outside the stored commits. Run \`profiler-commit-query\` mode=\`render_counts\` component_name=\`${separate.name}\` for its counts.`;
162554
+ }
162555
+ function storedOnlyNote(name, storedRenders, summary, renderCounts = "mode=`render_counts`") {
162556
+ const row = summary?.components.find((c) => c.name === name);
162557
+ if (!summary || !row) return "";
162558
+ const allRenders = allRenderCount(row);
162559
+ if (allRenders <= storedRenders) return "";
162560
+ return ` (stored commits only; ${formatCount(allRenders)} renders over all ${formatCount(summary.totalCommits)} commits, see ${renderCounts})`;
162561
+ }
162562
+ function formatRenderSummaryReason(c) {
162563
+ switch (c.reason) {
162564
+ case null:
162565
+ return c.mounts > 0 ? "mount only" : "no change data";
162566
+ case "props":
162567
+ return c.topProps && c.topProps.length > 0 ? `props: ${c.topProps.join(", ")}` : "props";
162568
+ case "hooks":
162569
+ case "state":
162570
+ return c.topHooks && c.topHooks.length > 0 ? `${c.reason}: ${c.topHooks.join(", ")}` : c.reason;
162571
+ case "context":
162572
+ return "context changed";
162573
+ case "parent":
162574
+ return "parent re-render";
162575
+ case "force_update":
162576
+ return "forceUpdate()";
162577
+ default:
162578
+ return c.reason;
162579
+ }
162580
+ }
162581
+ function frequentCandidates(summary) {
162582
+ const seconds = Math.max(summary.recordingMs / 1e3, 1e-3);
162583
+ const candidates = [];
162584
+ for (const component of summary.components) {
162585
+ if (component.rerenderCommits < MIN_FREQUENT_RERENDER_COMMITS) continue;
162586
+ const selfMsPerSecond = component.rerenderSelfMs / seconds;
162587
+ if (selfMsPerSecond < MIN_FREQUENT_SELF_MS_PER_S) continue;
162588
+ candidates.push({ component, perSecond: component.rerenders / seconds, selfMsPerSecond });
162589
+ }
162590
+ return candidates;
162591
+ }
162592
+ function selectFrequentRerenders(summary, classify, limit = MAX_FREQUENT_ROWS) {
162593
+ const rows = [];
162594
+ for (const candidate of frequentCandidates(summary)) {
162595
+ const origin = classify(candidate.component.name);
162596
+ if (origin.origin !== "library") rows.push({ ...candidate, origin });
162597
+ }
162598
+ rows.sort((a, b) => b.selfMsPerSecond - a.selfMsPerSecond);
162599
+ return rows.slice(0, limit);
162600
+ }
162601
+ function selectFrequentOutsideSource(summary, classify) {
162602
+ return frequentCandidates(summary).map((candidate) => candidate.component.name).filter((name) => classify(name).notInSource);
162603
+ }
162604
+
162008
162605
  // ../tool-server/src/tools/profiler/react/react-profiler-stop.ts
162009
162606
  function normalizeChangeDescription(raw) {
162010
162607
  if (!raw || typeof raw !== "object") return null;
@@ -162020,6 +162617,7 @@ function normalizeChangeDescription(raw) {
162020
162617
  function flattenProfilingData(merged, displayNameById, fiberMeta) {
162021
162618
  const commits = [];
162022
162619
  const unattributedByCommit = [];
162620
+ const commitTimings = [];
162023
162621
  let flatCommitIndex = 0;
162024
162622
  for (const root of merged.dataForRoots) {
162025
162623
  for (const c of root.commitData) {
@@ -162038,7 +162636,9 @@ function flattenProfilingData(merged, displayNameById, fiberMeta) {
162038
162636
  const commitDuration = typeof c.duration === "number" ? c.duration : 0;
162039
162637
  let droppedCount = 0;
162040
162638
  let droppedMs = 0;
162639
+ let selfMs = 0;
162041
162640
  for (const [fiberID, actualDuration] of actualMap) {
162641
+ if (actualDuration > 0) selfMs += selfMap.get(fiberID) ?? 0;
162042
162642
  const componentName = displayNameById[String(fiberID)] ?? null;
162043
162643
  if (!componentName) {
162044
162644
  droppedCount++;
@@ -162062,6 +162662,7 @@ function flattenProfilingData(merged, displayNameById, fiberMeta) {
162062
162662
  isCompilerOptimized: meta3?.isCompilerOptimized === true
162063
162663
  });
162064
162664
  }
162665
+ commitTimings.push({ timestamp: c.timestamp, durationMs: commitDuration, selfMs });
162065
162666
  if (droppedCount > 0) {
162066
162667
  unattributedByCommit.push([
162067
162668
  flatCommitIndex,
@@ -162072,7 +162673,7 @@ function flattenProfilingData(merged, displayNameById, fiberMeta) {
162072
162673
  flatCommitIndex++;
162073
162674
  }
162074
162675
  }
162075
- return { commits, totalCommits: flatCommitIndex, unattributedByCommit };
162676
+ return { commits, totalCommits: flatCommitIndex, unattributedByCommit, commitTimings };
162076
162677
  }
162077
162678
  var COLLECT_TIMEOUT_MS = 6e4;
162078
162679
  function stopInProgressError() {
@@ -162095,7 +162696,7 @@ function createReactProfilerStopTool(registry2) {
162095
162696
  description: `Stop CPU profiling and collect the cpuProfile + React commit tree.
162096
162697
  Stores the results for react-profiler-analyze or react-profiler-cpu-summary.
162097
162698
  Call react-profiler-start first, then exercise the app, then call this.
162098
- Returns { duration_ms, sample_count, fiber_renders_captured, total_react_commits, hot_commit_indices }.
162699
+ Returns { duration_ms, sample_count, fiber_renders_captured, total_react_commits, hot_commit_indices, react_render_ms, react_render_share_pct, react_render_peak_1s_pct }.
162099
162700
  If some fibers' display names could not be resolved (typically modals, tooltips or animations that unmounted before stop), it also returns { unattributed_ms, unattributed_fiber_count, unattributed_commit_count }: the work missing from the per-component breakdown. Per-commit durations stay correct.
162100
162701
  Fails if no active profiling session exists, another stop is running, the CDP connection was lost during recording, or another session took the run over.`,
162101
162702
  zodSchema: zodSchema46,
@@ -162217,6 +162818,7 @@ Fails if no active profiling session exists, another stop is running, the CDP co
162217
162818
  }
162218
162819
  );
162219
162820
  }
162821
+ dropStaleLeadingGap(profile);
162220
162822
  const stopReadStr = await cdp.send(
162221
162823
  "Runtime.evaluate",
162222
162824
  { expression: STOP_AND_READ_SCRIPT, returnByValue: true },
@@ -162265,18 +162867,24 @@ Fails if no active profiling session exists, another stop is running, the CDP co
162265
162867
  const {
162266
162868
  commits: allCommits,
162267
162869
  totalCommits,
162268
- unattributedByCommit
162870
+ unattributedByCommit,
162871
+ commitTimings
162269
162872
  } = flattenProfilingData(merged, stopRead.displayNameById, fiberMeta);
162873
+ const renderSummary = summarizeRenders(
162874
+ allCommits,
162875
+ commitTimings,
162876
+ (profile.endTime - profile.startTime) / 1e3
162877
+ );
162270
162878
  const commitHeat = /* @__PURE__ */ new Map();
162271
162879
  let anyCompilerOptimized = false;
162272
162880
  for (const c of allCommits) {
162881
+ if (c.isCompilerOptimized) anyCompilerOptimized = true;
162882
+ if (!c.didRender) continue;
162273
162883
  const prev = commitHeat.get(c.commitIndex) ?? 0;
162274
162884
  if (c.commitDuration > prev) commitHeat.set(c.commitIndex, c.commitDuration);
162275
- if (c.isCompilerOptimized) anyCompilerOptimized = true;
162276
162885
  }
162277
- const ABSOLUTE_FLOOR_MS = 16;
162278
162886
  const interestingKeys = [...commitHeat.keys()].filter(
162279
- (k) => (commitHeat.get(k) ?? 0) >= ABSOLUTE_FLOOR_MS
162887
+ (k) => (commitHeat.get(k) ?? 0) >= SLOW_COMMIT_MS
162280
162888
  );
162281
162889
  const hotSet = new Set(interestingKeys);
162282
162890
  const marginSet = /* @__PURE__ */ new Set();
@@ -162313,7 +162921,8 @@ Fails if no active profiling session exists, another stop is running, the CDP co
162313
162921
  port: api.port,
162314
162922
  appName: api.appName,
162315
162923
  deviceName: api.deviceName,
162316
- unattributedByCommit: unattributedByCommit.length > 0 ? unattributedByCommit : null
162924
+ unattributedByCommit: unattributedByCommit.length > 0 ? unattributedByCommit : null,
162925
+ renderSummary
162317
162926
  }
162318
162927
  }
162319
162928
  );
@@ -162345,9 +162954,15 @@ Fails if no active profiling session exists, another stop is running, the CDP co
162345
162954
  response["hot_commit_indices"] = api.hotCommitIndices ?? [];
162346
162955
  response["any_compiler_optimized"] = api.anyCompilerOptimized ?? false;
162347
162956
  response["fiber_renders_analyzed"] = filteredCommits.length;
162957
+ response["react_render_ms"] = renderSummary.totalRenderMs;
162958
+ response["react_render_share_pct"] = Math.round(renderTimeShare(renderSummary) * 1e3) / 10;
162959
+ response["react_render_peak_1s_pct"] = Math.round(peakRenderShare(renderSummary) * 1e3) / 10;
162348
162960
  const hotCount = api.hotCommitIndices?.length ?? 0;
162349
- if (hotCount === 0) {
162350
- response["selection_note"] = "All commits below 16ms \u2014 app appears smooth (all-clear)";
162961
+ const share = formatShare(renderTimeShare(renderSummary));
162962
+ if (hotCount === 0 && hasUnnamedSlowCommit(renderSummary)) {
162963
+ response["selection_note"] = `The slowest commit took ${formatPeakCommit(renderSummary.maxCommitMs)}, but none of its components could be named, so no commit was kept. React rendered for ${share} of the session`;
162964
+ } else if (hotCount === 0) {
162965
+ response["selection_note"] = `No commit reached 16ms. React rendered for ${share} of the session, peak ${formatShare(peakRenderShare(renderSummary))} in 1 s`;
162351
162966
  } else if (hotCount < totalCommits) {
162352
162967
  response["selection_note"] = `${hotCount} of ${totalCommits} commits at \u226516ms absolute floor`;
162353
162968
  }
@@ -162670,25 +163285,6 @@ async function detectSessionContext(input2) {
162670
163285
  };
162671
163286
  }
162672
163287
 
162673
- // ../tool-server/src/utils/react-profiler/pipeline/utils.ts
162674
- function deriveReason(cd, hookTypes) {
162675
- if (cd === null) return "unknown";
162676
- if (cd.props !== null && cd.props.length > 0) return "props";
162677
- if (cd.didHooksChange || cd.hooks !== null && cd.hooks.length > 0) {
162678
- if (hookTypes && cd.hooks) {
162679
- const isState = cd.hooks.some((idx) => {
162680
- const ht = hookTypes[idx];
162681
- return ht === "State" || ht === "Reducer" || ht === "useState" || ht === "useReducer";
162682
- });
162683
- if (isState) return "state";
162684
- }
162685
- return "hooks";
162686
- }
162687
- if (cd.context === true) return "context";
162688
- if (cd.state === true) return "state";
162689
- return "parent";
162690
- }
162691
-
162692
163288
  // ../tool-server/src/utils/react-profiler/pipeline/00-preprocess.ts
162693
163289
  function preprocess2(commits) {
162694
163290
  const commitMap = /* @__PURE__ */ new Map();
@@ -162768,10 +163364,10 @@ function buildHotCommitSummaries(commits, hotCommitIndices, unattributedByCommit
162768
163364
  const cd = e.changeDescription;
162769
163365
  return !(cd === null || cd.isFirstMount === true);
162770
163366
  });
163367
+ const rerenderNames = new Set(rerenderEntries.map((e) => e.componentName));
162771
163368
  const componentMap = /* @__PURE__ */ new Map();
162772
163369
  for (const e of entries) {
162773
- const cd = e.changeDescription;
162774
- const isFirstMount = cd === null || cd.isFirstMount === true;
163370
+ const isFirstMount = e.changeDescription?.isFirstMount === true;
162775
163371
  const existing = componentMap.get(e.componentName);
162776
163372
  if (existing) {
162777
163373
  existing.totalSelf += e.selfDuration ?? 0;
@@ -162791,9 +163387,10 @@ function buildHotCommitSummaries(commits, hotCommitIndices, unattributedByCommit
162791
163387
  const totalComponentCount = componentMap.size;
162792
163388
  const componentEntries = Array.from(componentMap.entries()).sort((a, b) => b[1].totalSelf - a[1].totalSelf).slice(0, MAX_COMPONENT_ENTRIES).map(([name, { totalSelf, totalActual, count: count2, firstEntry, isFirstMount }]) => {
162793
163389
  const cd = firstEntry.changeDescription;
162794
- const reason2 = !isFirstMount && cd ? deriveReason(cd, firstEntry.hookTypes) : void 0;
163390
+ const rerendered = rerenderNames.has(name);
163391
+ const reason2 = rerendered && cd ? deriveReason(cd, firstEntry.hookTypes) : void 0;
162795
163392
  let topChangedHookNames;
162796
- if (!isFirstMount && cd?.hooks && cd.hooks.length > 0 && firstEntry.hookTypes) {
163393
+ if (rerendered && cd?.hooks && cd.hooks.length > 0 && firstEntry.hookTypes) {
162797
163394
  const seen = /* @__PURE__ */ new Set();
162798
163395
  topChangedHookNames = [];
162799
163396
  for (const idx of cd.hooks.slice(0, 3)) {
@@ -162812,7 +163409,7 @@ function buildHotCommitSummaries(commits, hotCommitIndices, unattributedByCommit
162812
163409
  count: count2,
162813
163410
  ...isFirstMount && { isFirstMount: true },
162814
163411
  ...reason2 !== void 0 && { reason: reason2 },
162815
- ...!isFirstMount && cd?.props && cd.props.length > 0 && { topChangedProps: cd.props.slice(0, 3) },
163412
+ ...rerendered && cd?.props && cd.props.length > 0 && { topChangedProps: cd.props.slice(0, 3) },
162816
163413
  ...topChangedHookNames && { topChangedHookNames },
162817
163414
  ...firstEntry.isCompilerOptimized && { isCompilerOptimized: true }
162818
163415
  };
@@ -162881,185 +163478,7 @@ function buildHotCommitSummaries(commits, hotCommitIndices, unattributedByCommit
162881
163478
  return summaries.sort((a, b) => a.commitIndex - b.commitIndex);
162882
163479
  }
162883
163480
 
162884
- // ../tool-server/src/utils/react-profiler/pipeline/00-cpu-correlate.ts
162885
- var ARGENT_PROFILER_PREFIX = "__argent_";
162886
- function isArgentProfilerFunction(name) {
162887
- return name.startsWith(ARGENT_PROFILER_PREFIX);
162888
- }
162889
- function buildCpuSampleIndex(cpuProfile) {
162890
- const { nodes, samples, timeDeltas, startTime, endTime } = cpuProfile;
162891
- const nodeMap = /* @__PURE__ */ new Map();
162892
- for (const node2 of nodes) {
162893
- nodeMap.set(node2.id, node2);
162894
- }
162895
- const timestampsMs = new Float64Array(samples.length);
162896
- const intervalStartsMs = new Float64Array(samples.length);
162897
- let accumulatedUs = 0;
162898
- for (let i = 0; i < samples.length; i++) {
162899
- const raw = timeDeltas[i];
162900
- const delta = Number.isFinite(raw) && (raw ?? 0) >= 0 ? raw : 0;
162901
- intervalStartsMs[i] = accumulatedUs / 1e3;
162902
- accumulatedUs += delta;
162903
- timestampsMs[i] = accumulatedUs / 1e3;
162904
- }
162905
- return {
162906
- childToParent: buildChildToParent(nodeMap),
162907
- timestampsMs,
162908
- intervalStartsMs,
162909
- sampleNodeIds: samples,
162910
- nodeMap,
162911
- durationMs: (endTime - startTime) / 1e3
162912
- };
162913
- }
162914
- var IDLE_FRAME_NAMES = /* @__PURE__ */ new Set(["(idle)", "(program)", "(root)", "[idle]", "[root]"]);
162915
- function isIdleFrame(name) {
162916
- return !name || IDLE_FRAME_NAMES.has(name);
162917
- }
162918
- function queryCpuWindow(index, startMs, endMs, topN2 = 5) {
162919
- const { timestampsMs, intervalStartsMs, sampleNodeIds, nodeMap } = index;
162920
- const n = timestampsMs.length;
162921
- const sampleRangeMs = {
162922
- start: n > 0 ? intervalStartsMs[0] : 0,
162923
- end: n > 0 ? timestampsMs[n - 1] : 0
162924
- };
162925
- const empty2 = {
162926
- hotspots: [],
162927
- samplesInWindow: 0,
162928
- coveredMs: 0,
162929
- idleMs: 0,
162930
- sampleRangeMs,
162931
- medianIntervalMs: 0,
162932
- maxIntervalMs: 0
162933
- };
162934
- if (n === 0) return empty2;
162935
- let lo = 0;
162936
- let hi = n;
162937
- while (lo < hi) {
162938
- const mid = lo + hi >>> 1;
162939
- if (timestampsMs[mid] < startMs) lo = mid + 1;
162940
- else hi = mid;
162941
- }
162942
- const selfMsByNode = /* @__PURE__ */ new Map();
162943
- const intervals = [];
162944
- let samplesInWindow = 0;
162945
- let coveredMs = 0;
162946
- let idleMs = 0;
162947
- let maxIntervalMs = 0;
162948
- for (let i = lo; i < n; i++) {
162949
- const from2 = intervalStartsMs[i];
162950
- if (from2 > endMs) break;
162951
- const overlap = Math.min(endMs, timestampsMs[i]) - Math.max(startMs, from2);
162952
- if (overlap <= 0) continue;
162953
- samplesInWindow++;
162954
- coveredMs += overlap;
162955
- intervals.push(timestampsMs[i] - from2);
162956
- if (timestampsMs[i] - from2 > maxIntervalMs) maxIntervalMs = timestampsMs[i] - from2;
162957
- const nodeId = sampleNodeIds[i];
162958
- const node2 = nodeMap.get(nodeId);
162959
- if (isIdleFrame(node2?.callFrame.functionName)) {
162960
- idleMs += overlap;
162961
- continue;
162962
- }
162963
- selfMsByNode.set(nodeId, (selfMsByNode.get(nodeId) ?? 0) + overlap);
162964
- }
162965
- if (samplesInWindow === 0) return { ...empty2, sampleRangeMs };
162966
- intervals.sort((a, b) => a - b);
162967
- const medianIntervalMs = intervals[Math.floor(intervals.length / 2)] ?? 0;
162968
- const childToParent = index.childToParent ?? buildChildToParent(nodeMap);
162969
- const totalMsByNode = /* @__PURE__ */ new Map();
162970
- for (const [nodeId, ms] of selfMsByNode) {
162971
- totalMsByNode.set(nodeId, (totalMsByNode.get(nodeId) ?? 0) + ms);
162972
- let current = nodeId;
162973
- const seen = /* @__PURE__ */ new Set([current]);
162974
- while (childToParent.has(current)) {
162975
- const parent = childToParent.get(current);
162976
- if (seen.has(parent)) break;
162977
- seen.add(parent);
162978
- totalMsByNode.set(parent, (totalMsByNode.get(parent) ?? 0) + ms);
162979
- current = parent;
162980
- }
162981
- }
162982
- const entries = [];
162983
- for (const [nodeId, ms] of selfMsByNode) {
162984
- const node2 = nodeMap.get(nodeId);
162985
- if (!node2) continue;
162986
- const name = node2.callFrame.functionName;
162987
- if (isArgentProfilerFunction(name)) continue;
162988
- entries.push({
162989
- name,
162990
- selfMs: Math.round(ms * 100) / 100,
162991
- totalMs: Math.round((totalMsByNode.get(nodeId) ?? ms) * 100) / 100,
162992
- url: node2.callFrame.url || void 0,
162993
- lineNumber: node2.callFrame.lineNumber >= 0 ? node2.callFrame.lineNumber : void 0
162994
- });
162995
- }
162996
- entries.sort((a, b) => b.selfMs - a.selfMs);
162997
- return {
162998
- hotspots: entries.slice(0, topN2),
162999
- samplesInWindow,
163000
- coveredMs,
163001
- idleMs,
163002
- sampleRangeMs,
163003
- medianIntervalMs,
163004
- maxIntervalMs
163005
- };
163006
- }
163007
- function buildChildToParent(nodeMap) {
163008
- const childToParent = /* @__PURE__ */ new Map();
163009
- for (const node2 of nodeMap.values()) {
163010
- for (const childId of node2.children ?? []) childToParent.set(childId, node2.id);
163011
- }
163012
- return childToParent;
163013
- }
163014
- function correlateCpuWithCommits(summaries, index, topNPerCommit = 5) {
163015
- if (!index) return summaries;
163016
- return summaries.map((summary) => {
163017
- if (summary.isMargin) return summary;
163018
- const startMs = summary.timestampMs;
163019
- const endMs = summary.timestampMs + summary.totalRenderMs;
163020
- const { hotspots } = queryCpuWindow(index, startMs, endMs, topNPerCommit);
163021
- if (hotspots.length === 0) return summary;
163022
- return { ...summary, cpuHotspots: hotspots };
163023
- });
163024
- }
163025
- function serializeCpuSampleIndex(index) {
163026
- return {
163027
- version: 2,
163028
- timestampsMs: Array.from(index.timestampsMs),
163029
- intervalStartsMs: Array.from(index.intervalStartsMs),
163030
- sampleNodeIds: index.sampleNodeIds,
163031
- nodes: [...index.nodeMap.values()],
163032
- durationMs: index.durationMs
163033
- };
163034
- }
163035
- function deserializeCpuSampleIndex(raw) {
163036
- if (raw?.version !== 2 || !Array.isArray(raw.timestampsMs) || !Array.isArray(raw.nodes)) {
163037
- throw new Error("unsupported CPU sample index format");
163038
- }
163039
- const nodeMap = /* @__PURE__ */ new Map();
163040
- for (const node2 of raw.nodes) {
163041
- nodeMap.set(node2.id, node2);
163042
- }
163043
- return {
163044
- timestampsMs: new Float64Array(raw.timestampsMs),
163045
- intervalStartsMs: new Float64Array(raw.intervalStartsMs ?? []),
163046
- sampleNodeIds: raw.sampleNodeIds,
163047
- nodeMap,
163048
- childToParent: buildChildToParent(nodeMap),
163049
- durationMs: raw.durationMs
163050
- };
163051
- }
163052
-
163053
163481
  // ../tool-server/src/utils/react-profiler/pipeline/01-reduce.ts
163054
- var EMPTY_REASON_HISTOGRAM = () => ({
163055
- parent: 0,
163056
- props: 0,
163057
- hooks: 0,
163058
- context: 0,
163059
- state: 0,
163060
- force_update: 0,
163061
- unknown: 0
163062
- });
163063
163482
  function reduce(commitTree, sessionContext, recordingMs, sessionAnyCompilerOptimized) {
163064
163483
  const components = /* @__PURE__ */ new Map();
163065
163484
  const componentHadRerender = /* @__PURE__ */ new Set();
@@ -163096,7 +163515,7 @@ function reduce(commitTree, sessionContext, recordingMs, sessionAnyCompilerOptim
163096
163515
  sumSq: 0,
163097
163516
  min: Infinity,
163098
163517
  max: -Infinity,
163099
- reasonHistogram: EMPTY_REASON_HISTOGRAM(),
163518
+ reasonHistogram: emptyReasonHistogram(),
163100
163519
  propFreq: /* @__PURE__ */ new Map(),
163101
163520
  hookFreq: /* @__PURE__ */ new Map(),
163102
163521
  parentFreq: /* @__PURE__ */ new Map(),
@@ -163166,17 +163585,6 @@ function reduce(commitTree, sessionContext, recordingMs, sessionAnyCompilerOptim
163166
163585
  function topN(freq, n) {
163167
163586
  return Array.from(freq.entries()).sort((a, b) => b[1] - a[1]).slice(0, n).map(([k]) => k);
163168
163587
  }
163169
- function dominantReason(histogram) {
163170
- let best = "unknown";
163171
- let bestCount = -1;
163172
- for (const [reason2, count2] of Object.entries(histogram)) {
163173
- if (count2 > bestCount) {
163174
- bestCount = count2;
163175
- best = reason2;
163176
- }
163177
- }
163178
- return best;
163179
- }
163180
163588
  function topParent(parentFreq) {
163181
163589
  let best;
163182
163590
  let bestCount = -1;
@@ -163371,10 +163779,10 @@ async function runPipeline(input2, options) {
163371
163779
  componentFindings,
163372
163780
  sessionContext: tagOutput.sessionContext,
163373
163781
  recordingMs: tagOutput.recordingMs,
163374
- allClear: input2.sessionMeta.allClear ?? false,
163782
+ noHotCommits: input2.sessionMeta.noHotCommits ?? false,
163375
163783
  maxCommitMs: input2.sessionMeta.maxCommitMs,
163376
163784
  anyRuntimeCompilerDetected: tagOutput.anyRuntimeCompilerDetected,
163377
- // The all-clear path keeps no commits, so tagOutput.reactCommits is 0
163785
+ // With no hot commit no commits are kept, so tagOutput.reactCommits is 0
163378
163786
  reactCommits: input2.sessionMeta.totalReactCommits ?? tagOutput.reactCommits,
163379
163787
  fiberRenders: tagOutput.fiberRenders,
163380
163788
  totalFirstMounts: tagOutput.totalFirstMounts,
@@ -163382,98 +163790,6 @@ async function runPipeline(input2, options) {
163382
163790
  };
163383
163791
  }
163384
163792
 
163385
- // ../tool-server/src/utils/react-profiler/component-names.ts
163386
- var WRAPPER_PATTERNS = [/^Forget\((.+)\)$/, /^Memo\((.+)\)$/, /^ForwardRef\((.+)\)$/];
163387
- var MAX_WRAPPER_DEPTH = 4;
163388
- function stripComponentWrappers(raw) {
163389
- let name = raw;
163390
- let hasForget = false;
163391
- let hasMemo = false;
163392
- let hasForwardRef = false;
163393
- for (let i = 0; i < MAX_WRAPPER_DEPTH; i++) {
163394
- const m = WRAPPER_PATTERNS.map((re2) => name.match(re2)).find(Boolean);
163395
- if (!m) break;
163396
- if (name.startsWith("Forget(")) hasForget = true;
163397
- else if (name.startsWith("Memo(")) hasMemo = true;
163398
- else if (name.startsWith("ForwardRef(")) hasForwardRef = true;
163399
- name = m[1];
163400
- }
163401
- return { baseName: name, hasForget, hasMemo, hasForwardRef };
163402
- }
163403
- function annotateComponentName(raw) {
163404
- const { baseName, hasForget, hasMemo, hasForwardRef } = stripComponentWrappers(raw);
163405
- const parts2 = [];
163406
- if (hasMemo) parts2.push("React.memo");
163407
- if (hasForget) parts2.push("React Compiler");
163408
- if (hasForwardRef) parts2.push("forwardRef");
163409
- const tag3 = parts2.length > 0 ? ` [${parts2.join(" + ")}]` : "";
163410
- return { displayName: baseName, tag: tag3, rawName: raw };
163411
- }
163412
- function resolveComponentName(query, recordedNames) {
163413
- const names = [...new Set(recordedNames)];
163414
- const sharingDisplayName = (raw) => {
163415
- const display = annotateComponentName(raw).displayName;
163416
- return names.filter((n) => n !== raw && annotateComponentName(n).displayName === display);
163417
- };
163418
- if (names.includes(query)) {
163419
- return { kind: "exact", rawName: query, alsoMatching: sharingDisplayName(query) };
163420
- }
163421
- const candidates = names.filter((n) => annotateComponentName(n).displayName === query);
163422
- if (candidates.length === 1) {
163423
- return { kind: "display", rawName: candidates[0], query };
163424
- }
163425
- if (candidates.length > 1) {
163426
- return { kind: "ambiguous", query, candidates };
163427
- }
163428
- return { kind: "missing", query, suggestions: suggestNames(query, names) };
163429
- }
163430
- function suggestNames(query, names, limit = 5) {
163431
- const needle = query.toLowerCase();
163432
- if (needle.length < 2) return [];
163433
- return names.filter((n) => {
163434
- const hay = `${n} ${annotateComponentName(n).displayName}`.toLowerCase();
163435
- return hay.includes(needle) || needle.includes(annotateComponentName(n).displayName.toLowerCase());
163436
- }).slice(0, limit);
163437
- }
163438
- function describeResolution(resolution) {
163439
- if (resolution.kind === "display") {
163440
- const { tag: tag3 } = annotateComponentName(resolution.rawName);
163441
- const why = tag3 ? ` (${tag3.trim().slice(1, -1)})` : "";
163442
- return `> Resolved \`${resolution.query}\` to the recorded component \`${resolution.rawName}\`${why}. Either name works here.`;
163443
- }
163444
- if (resolution.alsoMatching.length > 0) {
163445
- const others = resolution.alsoMatching.map((n) => `\`${n}\``).join(", ");
163446
- return `> Showing \`${resolution.rawName}\` only. ${others} also appear${resolution.alsoMatching.length === 1 ? "s" : ""} under this name once wrappers are stripped; they are separate fibers, so pass the exact name to target one.`;
163447
- }
163448
- return "";
163449
- }
163450
- function renderComponentNameMiss(resolution, context2 = {}) {
163451
- if (resolution.kind === "ambiguous") {
163452
- const list = resolution.candidates.map((c) => `- \`${c}\``).join("\n");
163453
- return `_Component \`${resolution.query}\` is ambiguous: ${resolution.candidates.length} recorded components share this name once \`Memo(...)\` / \`ForwardRef(...)\` / \`Forget(...)\` wrappers are stripped. They are separate fibers and are not merged, because a combined total would not describe any real component. Re-run with one of these exact \`component_name\` values:_
163454
-
163455
- ${list}`;
163456
- }
163457
- const recorded = context2.fiberRenders != null && context2.commits != null ? ` The session recorded ${context2.fiberRenders} fiber renders across ${context2.commits} commits.` : "";
163458
- const suggestions = resolution.suggestions.length > 0 ? `
163459
-
163460
- Closest recorded names \u2014 pass one verbatim as \`component_name\`:
163461
- ` + resolution.suggestions.map((s) => `- \`${s}\``).join("\n") : "";
163462
- return `_Component \`${resolution.query}\` not found in this profiling session \u2014 no exact match, and no component whose displayed name is \`${resolution.query}\` once \`Memo(...)\` / \`ForwardRef(...)\` / \`Forget(...)\` wrappers are stripped.${recorded}_${suggestions}
163463
-
163464
- To list every component in a commit instead, run \`profiler-commit-query mode=by_index commit_index=<n>\`.`;
163465
- }
163466
- function astLookupCandidates(raw) {
163467
- const keys = [raw];
163468
- const { baseName } = stripComponentWrappers(raw);
163469
- if (baseName !== raw) keys.push(baseName);
163470
- const withoutSuffix = baseName.replace(/\(.*\)$/, "");
163471
- if (withoutSuffix !== baseName && /^[A-Za-z_$][\w$]*$/.test(withoutSuffix)) {
163472
- keys.push(withoutSuffix);
163473
- }
163474
- return keys;
163475
- }
163476
-
163477
163793
  // ../tool-server/src/utils/react-profiler/pipeline/06-resolve/ast-index.ts
163478
163794
  var import_fs3 = require("fs");
163479
163795
  var import_path4 = require("path");
@@ -163500,7 +163816,18 @@ function loadTreeSitter() {
163500
163816
  if (!_ParserClass || !_tsLanguage || !_tsxLanguage) return null;
163501
163817
  return { ParserClass: _ParserClass, ts: _tsLanguage, tsx: _tsxLanguage };
163502
163818
  }
163503
- var EXCLUDE_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "android", "ios", "dist", "build", ".expo"]);
163819
+ var EXCLUDE_DIRS = /* @__PURE__ */ new Set([
163820
+ "node_modules",
163821
+ ".git",
163822
+ "android",
163823
+ "ios",
163824
+ "dist",
163825
+ "build",
163826
+ ".expo",
163827
+ "__tests__",
163828
+ "__mocks__"
163829
+ ]);
163830
+ var TEST_FILE = /\.(test|spec)\.[jt]sx?$/;
163504
163831
  async function findSourceFiles(dir) {
163505
163832
  const result = [];
163506
163833
  async function walk(current) {
@@ -163517,7 +163844,7 @@ async function findSourceFiles(dir) {
163517
163844
  }
163518
163845
  } else if (entry.isFile()) {
163519
163846
  const name = entry.name;
163520
- if (name.endsWith(".ts") || name.endsWith(".tsx") || name.endsWith(".js") || name.endsWith(".jsx")) {
163847
+ if ((name.endsWith(".ts") || name.endsWith(".tsx") || name.endsWith(".js") || name.endsWith(".jsx")) && !TEST_FILE.test(name)) {
163521
163848
  result.push((0, import_path4.join)(current, name));
163522
163849
  }
163523
163850
  }
@@ -163588,6 +163915,8 @@ function pickPrimary(entries) {
163588
163915
  others: rest.map((e) => ({ file: e.file, line: e.line, col: e.col }))
163589
163916
  };
163590
163917
  }
163918
+ var DEFAULT_PARSE_BUFFER_CHARS = 32 * 1024 - 1;
163919
+ var MAX_JSX_FILE_CHARS = 512 * 1024;
163591
163920
  async function buildAstIndexWithDiagnostics(projectRoot) {
163592
163921
  const index = /* @__PURE__ */ new Map();
163593
163922
  const ts = loadTreeSitter();
@@ -163642,17 +163971,23 @@ async function buildAstIndexWithDiagnostics(projectRoot) {
163642
163971
  } catch {
163643
163972
  continue;
163644
163973
  }
163645
- const isTsxFile = file2.endsWith(".tsx") || file2.endsWith(".jsx");
163646
- const language = isTsxFile ? tsxLang : tsLang;
163974
+ const isJsxFile = file2.endsWith(".tsx") || file2.endsWith(".jsx");
163975
+ const language = isJsxFile || file2.endsWith(".js") ? tsxLang : tsLang;
163976
+ if (source.length > (isJsxFile ? MAX_JSX_FILE_CHARS : DEFAULT_PARSE_BUFFER_CHARS)) continue;
163647
163977
  let tree;
163648
163978
  try {
163649
163979
  const parser2 = new ParserClass();
163650
163980
  parser2.setLanguage(language);
163651
- tree = parser2.parse(source);
163981
+ tree = parser2.parse(source, void 0, { bufferSize: source.length + 1 });
163982
+ } catch {
163983
+ continue;
163984
+ }
163985
+ let memoizedNames;
163986
+ try {
163987
+ memoizedNames = collectMemoizedNames(tree.rootNode);
163652
163988
  } catch {
163653
163989
  continue;
163654
163990
  }
163655
- const memoizedNames = collectMemoizedNames(tree.rootNode);
163656
163991
  try {
163657
163992
  findComponents2(tree.rootNode);
163658
163993
  } catch {
@@ -163668,13 +164003,76 @@ async function buildAstIndexWithDiagnostics(projectRoot) {
163668
164003
  // ../tool-server/src/utils/react-profiler/pipeline/05-render.ts
163669
164004
  var import_fs4 = require("fs");
163670
164005
  var import_path5 = require("path");
164006
+
164007
+ // ../tool-server/src/utils/react-profiler/component-origin.ts
164008
+ var RN_CORE_NAMES = /* @__PURE__ */ new Set([
164009
+ "ActivityIndicator",
164010
+ "AppContainer",
164011
+ "Button",
164012
+ "DrawerLayoutAndroid",
164013
+ "Image",
164014
+ "ImageBackground",
164015
+ "InputAccessoryView",
164016
+ "InternalTextInput",
164017
+ "KeyboardAvoidingView",
164018
+ "Modal",
164019
+ "Pressable",
164020
+ "RefreshControl",
164021
+ "SafeAreaView",
164022
+ "ScrollView",
164023
+ "ScrollViewBase",
164024
+ "ScrollViewStickyHeader",
164025
+ "StatusBar",
164026
+ "Switch",
164027
+ "Text",
164028
+ "TextImpl",
164029
+ "TextInput",
164030
+ "TouchableHighlight",
164031
+ "TouchableNativeFeedback",
164032
+ "TouchableOpacity",
164033
+ "TouchableWithoutFeedback",
164034
+ "View",
164035
+ // React built-ins.
164036
+ "Fragment",
164037
+ "Profiler",
164038
+ "StrictMode",
164039
+ "Suspense"
164040
+ ]);
164041
+ var LIST_INTERNALS_PATTERN = /^(FlatList|SectionList|VirtualizedList\w*|VirtualizedSectionList\w*|CellRenderer\w*|FlashList\w*|AutoLayoutView|CellContainer|RecyclerListView\w*)$/;
164042
+ var PROVIDER_PATTERN = /(Provider|Context|\.Consumer)$/;
164043
+ var DEV_ONLY_PATTERN = /^(PressabilityDebugView|LogBox\w*|DebuggingOverlay\w*|ReactDevToolsOverlay|Inspector\w*|DebugContainer)$/;
164044
+ var UNRESOLVED_NAME = "Anonymous";
164045
+ function isRoleExcluded(baseName) {
164046
+ return baseName === UNRESOLVED_NAME || ANIMATED_PATTERN.test(baseName) || PROVIDER_PATTERN.test(baseName) || DEV_ONLY_PATTERN.test(baseName);
164047
+ }
164048
+ function isReactNativeName(baseName) {
164049
+ return RN_CORE_NAMES.has(baseName) || LIST_INTERNALS_PATTERN.test(baseName);
164050
+ }
164051
+ function createComponentOriginClassifier(index) {
164052
+ const usableIndex = index && index.size > 0 ? index : null;
164053
+ return (rawName) => {
164054
+ const { baseName, hasForget } = stripComponentWrappers(rawName);
164055
+ if (isRoleExcluded(baseName)) return { origin: "library" };
164056
+ const entry = usableIndex ? astLookupCandidates(rawName).map((k) => usableIndex.get(k)).find(Boolean) : void 0;
164057
+ const located = entry ? { file: entry.file, line: entry.line } : {};
164058
+ if (isReactNativeName(baseName)) {
164059
+ return hasForget ? { origin: "app", ...located } : { origin: "library" };
164060
+ }
164061
+ if (hasForget) return { origin: "app", ...located };
164062
+ if (!usableIndex) return { origin: "unknown" };
164063
+ return entry ? { origin: "app", ...located } : { origin: "library", notInSource: true };
164064
+ };
164065
+ }
164066
+
164067
+ // ../tool-server/src/utils/react-profiler/pipeline/05-render.ts
163671
164068
  var MAX_INLINE_COMMITS = 10;
164069
+ var MAX_OUTSIDE_SOURCE_NAMES = 5;
163672
164070
  var REPORT_FILENAME = "react-profiler-report.md";
163673
164071
  async function renderProfilingReport(input2) {
163674
164072
  const reportFile = (0, import_path5.join)(input2.debugDir, REPORT_FILENAME);
163675
- if (input2.allClear) {
164073
+ if (input2.noHotCommits) {
163676
164074
  const maxMs = input2.maxCommitMs ?? 0;
163677
- const report2 = renderAllClear(input2, maxMs);
164075
+ const report2 = renderNoHotCommits(input2, maxMs);
163678
164076
  const wroteFile2 = await writeReport(reportFile, report2);
163679
164077
  return {
163680
164078
  report: report2,
@@ -163686,7 +164084,7 @@ async function renderProfilingReport(input2) {
163686
164084
  const hotCommits = input2.hotCommitSummaries.filter((s) => !s.isMargin);
163687
164085
  const hotCommitsTotal = hotCommits.length;
163688
164086
  if (hotCommitsTotal === 0) {
163689
- const report2 = renderAllClear(input2, 0);
164087
+ const report2 = input2.renderSummary ? renderNoHotCommits(input2, input2.maxCommitMs ?? 0) : renderNoCommitData(input2);
163690
164088
  const wroteFile2 = await writeReport(reportFile, report2);
163691
164089
  return {
163692
164090
  report: report2,
@@ -163719,30 +164117,124 @@ async function renderProfilingReport(input2) {
163719
164117
  }
163720
164118
  return { report, reportFile: wroteFile ? reportFile : null, hotCommitsTotal, hotCommitsShown };
163721
164119
  }
163722
- function renderAllClear(input2, maxMs) {
164120
+ function renderTimeLine(input2, summary) {
164121
+ const label = input2.sessionContext.buildMode === "dev" ? " (dev build)" : "";
164122
+ return `**React render time${label}:** ${formatRenderTime(summary)}`;
164123
+ }
164124
+ function renderReportHeader(input2) {
163723
164125
  const durationS = (input2.recordingMs / 1e3).toFixed(1);
163724
164126
  const compilerLine = renderCompilerStatus(
163725
164127
  input2.sessionContext.reactCompilerEnabled,
163726
164128
  input2.anyRuntimeCompilerDetected
163727
164129
  );
163728
- const maxNote = maxMs > 0 ? ` (peak commit: ${maxMs.toFixed(1)}ms)` : "";
163729
164130
  const lines = [
163730
164131
  `# Profiling Analysis \u2014 ${durationS}s session`,
163731
- `${compilerLine} **Hot commits:** 0 of ${input2.reactCommits} total`,
163732
- ``,
163733
- `\u2705 **All clear** \u2014 all React commits were below 16ms${maxNote}.`,
163734
- `No performance issues detected in this session.`,
164132
+ `${compilerLine} **Hot commits:** 0 of ${input2.reactCommits} total`
164133
+ ];
164134
+ if (input2.renderSummary) lines.push(renderTimeLine(input2, input2.renderSummary));
164135
+ lines.push(``);
164136
+ return lines;
164137
+ }
164138
+ function renderNoCommitData(input2) {
164139
+ return [
164140
+ ...renderReportHeader(input2),
164141
+ `No React commit data could be read for this session, so no commit durations were measured. Re-profile to measure them.`
164142
+ ].join("\n");
164143
+ }
164144
+ function renderNoHotCommits(input2, maxMs) {
164145
+ const summary = input2.renderSummary ?? null;
164146
+ const lines = renderReportHeader(input2);
164147
+ if (summary?.totalCommits === 0 || input2.noReactCommits) {
164148
+ lines.push(
164149
+ `No React commits were recorded, so there is nothing to measure. Interact with the app while the profiler records.`
164150
+ );
164151
+ return lines.join("\n");
164152
+ }
164153
+ const maxNote = maxMs > 0 ? ` (peak commit: ${formatPeakCommit(maxMs)})` : "";
164154
+ lines.push(
164155
+ summary && hasUnnamedSlowCommit(summary) ? `\u26A0\uFE0F **Slow commit with no component names** \u2014 the slowest commit took ${formatPeakCommit(summary.maxCommitMs)}, but none of its components could be named, so it has no breakdown.` : `No commit reached 16ms${maxNote}.`
164156
+ );
164157
+ if (!summary) {
164158
+ lines.push(
164159
+ ``,
164160
+ `> This session has no render summary, usually because an older version saved it, so commits under 16ms were not measured: many cheap re-renders can still add up. Re-profile to measure them.`
164161
+ );
164162
+ } else if (summary.components.length === 0) {
164163
+ lines.push(``, `No component in this session could be named, so there is nothing to list.`);
164164
+ }
164165
+ const { rows, cut } = frequentRerenderRows(input2);
164166
+ lines.push(...renderFrequentRerenders(summary, rows, frequentOutsideSource(input2), cut));
164167
+ lines.push(``, `---`, `## Next Steps`, ``);
164168
+ if (rows.length > 0) {
164169
+ lines.push(
164170
+ `Ask the user which path to take:`,
164171
+ ``,
164172
+ `1. **Investigate further** \u2014 \`profiler-commit-query\` mode=\`render_counts\` for every component's counts, or \`profiler-cpu-query\` mode=\`top_functions\` for the JS work behind them.`,
164173
+ `2. **Cut re-renders** \u2014 if the top rows re-render more often than the screen needs (the Reason column names what changes each time, e.g. a timer or animation kept in React state), reduce that, then re-profile the same scenario and compare.`,
164174
+ `3. **Done for now** \u2014 save the report for reference.`
164175
+ );
164176
+ } else {
164177
+ lines.push(
164178
+ `- Re-profile under heavier load (longer interaction, more data) if this run did not cover the flow you care about.`,
164179
+ `- \`profiler-cpu-query\` mode=\`top_functions\` shows the JS work during the recording.`
164180
+ );
164181
+ if (summary) {
164182
+ lines.push(
164183
+ `- \`profiler-commit-query\` mode=\`render_counts\` lists each component's render count over all ${formatCount(summary.totalCommits)} commits. A high count matters only when its time adds up.`
164184
+ );
164185
+ }
164186
+ }
164187
+ return lines.join("\n");
164188
+ }
164189
+ function frequentRerenderRows(input2) {
164190
+ const all = input2.renderSummary ? selectFrequentRerenders(
164191
+ input2.renderSummary,
164192
+ input2.componentOrigin ?? createComponentOriginClassifier(null),
164193
+ Infinity
164194
+ ) : [];
164195
+ return { rows: all.slice(0, MAX_FREQUENT_ROWS), cut: all.slice(MAX_FREQUENT_ROWS) };
164196
+ }
164197
+ function frequentOutsideSource(input2) {
164198
+ return input2.renderSummary ? selectFrequentOutsideSource(
164199
+ input2.renderSummary,
164200
+ input2.componentOrigin ?? createComponentOriginClassifier(null)
164201
+ ) : [];
164202
+ }
164203
+ function renderFrequentRerenders(summary, rows, outsideSource, cut = []) {
164204
+ if (!summary) return [];
164205
+ const outsideNote = outsideSource.length > 0 ? [``, renderOutsideSourceNote(outsideSource)] : [];
164206
+ const cutNote = cut.length > 0 ? [``, renderCutNote(cut)] : [];
164207
+ if (rows.length === 0) return [...cutNote, ...outsideNote];
164208
+ const unplaced = rows.some((row) => row.origin.origin === "unknown");
164209
+ return [
163735
164210
  ``,
163736
164211
  `---`,
163737
- `## Suggested Improvements`,
164212
+ `## Most Frequent Re-renders`,
163738
164213
  ``,
163739
- `No performance hotspots found. Consider these proactive checks:`,
164214
+ `${unplaced ? "Components" : "App components"} that re-rendered in at least 10 of the ${formatCount(summary.totalCommits)} commits and used at least 1 ms of self time per second of recording, by self time per second. This shows where frequent re-renders add up, not that it is a problem. ${unplaced ? "The project source could not be indexed (check `project_root`), so library components may be listed. " : ""}React Native primitives, list internals, animation wrappers, providers and dev-only components are left out; \`profiler-commit-query\` mode=\`render_counts\` lists every component.`,
163740
164215
  ``,
163741
- `- Run \`react-profiler-component-source\` on your most-rendered components to verify memoization is in place.`,
163742
- `- Run \`react-profiler-renders\` for a live count of mounted instances per component.`,
163743
- `- Re-profile under heavier load (longer interaction, more data) to catch issues that don't appear in short sessions.`
164216
+ `| Component | Re-renders | Per second | Self ms/s | Self total | Reason | File |`,
164217
+ `|---|---|---|---|---|---|---|`,
164218
+ ...rows.map(renderFrequentRow),
164219
+ ...cutNote,
164220
+ ...outsideNote
163744
164221
  ];
163745
- return lines.join("\n");
164222
+ }
164223
+ function renderCutNote(cut) {
164224
+ const shown = cut.slice(0, MAX_OUTSIDE_SOURCE_NAMES).map((row) => `\`${row.component.name}\``).join(", ");
164225
+ const more = cut.length > MAX_OUTSIDE_SOURCE_NAMES ? ` and ${cut.length - MAX_OUTSIDE_SOURCE_NAMES} more` : "";
164226
+ return `Also re-rendered often (in at least 10 commits, with at least 1 ms of self time per second) but not listed above: ${shown}${more}. \`profiler-commit-query\` mode=\`render_counts\` has the counts.`;
164227
+ }
164228
+ function renderOutsideSourceNote(names) {
164229
+ const shown = names.slice(0, MAX_OUTSIDE_SOURCE_NAMES).map((name) => `\`${name}\``).join(", ");
164230
+ const more = names.length > MAX_OUTSIDE_SOURCE_NAMES ? ` and ${names.length - MAX_OUTSIDE_SOURCE_NAMES} more` : "";
164231
+ return `Frequent re-renders left out because the source index has no definition for the name: ${shown}${more}. These are usually library components. Class components, components made by a wrapper such as \`observer()\`, and all of your components when \`project_root\` is wrong land here too. \`profiler-commit-query\` mode=\`render_counts\` has the counts.`;
164232
+ }
164233
+ function renderFrequentRow(row) {
164234
+ const c = row.component;
164235
+ const ann = annotateComponentName(c.name);
164236
+ const file2 = row.origin.file !== void 0 ? `\`${shortenPath(row.origin.file)}${row.origin.line !== void 0 ? `:${row.origin.line}` : ""}\`` : "\u2014";
164237
+ return `| \`${ann.displayName}\`${ann.tag} | ${formatCount(c.rerenders)} | ${row.perSecond.toFixed(1)} | ${row.selfMsPerSecond.toFixed(1)} | ${c.rerenderSelfMs.toFixed(1)}ms | ${formatRenderSummaryReason(c)} | ${file2} |`;
163746
164238
  }
163747
164239
  function renderCompilerStatus(enabled, detectedAtRuntime) {
163748
164240
  if (enabled && detectedAtRuntime) return "**React Compiler:** \u2713";
@@ -163761,6 +164253,7 @@ function buildFullMarkdown(input2, annotations, totalHotCommits) {
163761
164253
  const lines = [
163762
164254
  `# Profiling Analysis \u2014 ${durationS}s session`,
163763
164255
  `${compilerLine} **Hot commits:** ${totalHotCommits} of ${input2.reactCommits} total`,
164256
+ ...input2.renderSummary ? [renderTimeLine(input2, input2.renderSummary)] : [],
163764
164257
  ``,
163765
164258
  `> **Duration columns:** \`self\` = this component's own render work only (exclusive).`,
163766
164259
  `> \`w/children\` = self + the entire subtree it owns (inclusive).`,
@@ -163779,6 +164272,14 @@ function buildFullMarkdown(input2, annotations, totalHotCommits) {
163779
164272
  lines.push("---");
163780
164273
  lines.push("## Top Components by Total Render Cost");
163781
164274
  lines.push("");
164275
+ const renderSummary = input2.renderSummary ?? null;
164276
+ const allRerenders = renderSummary ? new Map(renderSummary.components.map((c) => [c.name, c.rerenders])) : null;
164277
+ if (renderSummary) {
164278
+ lines.push(
164279
+ `> \`Renders\` = re-renders in the stored commits (hot and \xB11 neighbours, which Total/Avg/Max cover) / re-renders in all ${formatCount(renderSummary.totalCommits)} commits.`
164280
+ );
164281
+ lines.push("");
164282
+ }
163782
164283
  lines.push("| Component | Renders | Total | Avg | Max | Reason | File |");
163783
164284
  lines.push("|---|---|---|---|---|---|---|");
163784
164285
  for (const f of input2.componentFindings) {
@@ -163786,8 +164287,10 @@ function buildFullMarkdown(input2, annotations, totalHotCommits) {
163786
164287
  const reasonStr = formatReason(f.dominantReason, f.topChangedProps, f.topChangedHookNames);
163787
164288
  const compilerFlag = f.compilerBailoutSuspected ? " \u26A0\uFE0F" : f.isCompilerOptimized ? " \u2713" : "";
163788
164289
  const ann = annotateComponentName(f.component);
164290
+ const all = allRerenders?.get(f.component);
164291
+ const renders = all !== void 0 ? `${f.renders} / ${formatCount(all)}` : `${f.renders}`;
163789
164292
  lines.push(
163790
- `| \`${ann.displayName}\`${ann.tag}${compilerFlag} | ${f.renders} | ${f.totalMs}ms | ${f.avgMs}ms | ${f.maxMs}ms | ${reasonStr} | ${file2} |`
164293
+ `| \`${ann.displayName}\`${ann.tag}${compilerFlag} | ${renders} | ${f.totalMs}ms | ${f.avgMs}ms | ${f.maxMs}ms | ${reasonStr} | ${file2} |`
163791
164294
  );
163792
164295
  }
163793
164296
  if (sessionContext.reactCompilerEnabled && !anyRuntimeCompilerDetected) {
@@ -163797,6 +164300,21 @@ function buildFullMarkdown(input2, annotations, totalHotCommits) {
163797
164300
  );
163798
164301
  }
163799
164302
  }
164303
+ const { rows: frequent, cut } = frequentRerenderRows(input2);
164304
+ const inTopComponents = new Set(input2.componentFindings.map((f) => f.component));
164305
+ const cutNew = cut.filter((row) => !inTopComponents.has(row.component.name));
164306
+ const outsideSource = frequentOutsideSource(input2).filter((name) => !inTopComponents.has(name));
164307
+ const tableAddsRow = frequent.some((row) => !inTopComponents.has(row.component.name));
164308
+ if (tableAddsRow || outsideSource.length > 0 || cutNew.length > 0) {
164309
+ lines.push(
164310
+ ...renderFrequentRerenders(
164311
+ input2.renderSummary ?? null,
164312
+ tableAddsRow ? frequent : [],
164313
+ outsideSource,
164314
+ cutNew
164315
+ )
164316
+ );
164317
+ }
163800
164318
  const suggestionsSection = renderSuggestedImprovements(
163801
164319
  input2.componentFindings,
163802
164320
  sessionContext.reactCompilerEnabled
@@ -164134,12 +164652,14 @@ Fails if react-profiler-stop has not been called or no profiling data is stored.
164134
164652
  }
164135
164653
  let commitTree;
164136
164654
  let unattributedByCommit;
164655
+ let renderSummary = null;
164137
164656
  if (sessionPaths.commitsPath) {
164138
164657
  const onDisk = await readCommitTree(sessionPaths.commitsPath);
164139
164658
  commitTree = { commits: onDisk.commits, hookNames: /* @__PURE__ */ new Map() };
164140
164659
  if (onDisk.meta?.unattributedByCommit) {
164141
164660
  unattributedByCommit = onDisk.meta.unattributedByCommit;
164142
164661
  }
164662
+ renderSummary = parseRenderSummary(onDisk.meta?.renderSummary);
164143
164663
  } else {
164144
164664
  commitTree = { commits: [], hookNames: /* @__PURE__ */ new Map() };
164145
164665
  }
@@ -164166,7 +164686,10 @@ Fails if react-profiler-stop has not been called or no profiling data is stored.
164166
164686
  ...totalReactCommits !== null && {
164167
164687
  totalReactCommits
164168
164688
  },
164169
- ...unattributedByCommit && { unattributedByCommit }
164689
+ ...unattributedByCommit && { unattributedByCommit },
164690
+ // [] means stop ran and no commit reached the floor; null means no commit data.
164691
+ noHotCommits: hotCommitIndices !== null && hotCommitIndices.length === 0,
164692
+ ...renderSummary && { maxCommitMs: renderSummary.maxCommitMs }
164170
164693
  }
164171
164694
  };
164172
164695
  const pipelineOutput = await runPipeline(input2);
@@ -164178,10 +164701,13 @@ Fails if react-profiler-stop has not been called or no profiling data is stored.
164178
164701
  );
164179
164702
  sessionPaths.cpuSampleIndexPath = indexPath;
164180
164703
  }
164704
+ const needsSourceIndex = pipelineOutput.componentFindings.length > 0 || renderSummary !== null && selectFrequentRerenders(renderSummary, createComponentOriginClassifier(null)).length > 0;
164705
+ let sourceIndex = null;
164181
164706
  try {
164182
- const astIndex = await buildAstIndexWithDiagnostics(params.project_root);
164707
+ const astIndex = needsSourceIndex ? await buildAstIndexWithDiagnostics(params.project_root) : null;
164708
+ if (astIndex?.treeSitterAvailable) sourceIndex = astIndex.index;
164183
164709
  for (const finding of pipelineOutput.componentFindings) {
164184
- const entry = astLookupCandidates(finding.component).map((k) => astIndex.index.get(k)).find(Boolean);
164710
+ const entry = astLookupCandidates(finding.component).map((k) => astIndex?.index.get(k)).find(Boolean);
164185
164711
  if (entry) {
164186
164712
  finding.sourceLocation = {
164187
164713
  file: entry.file,
@@ -164219,8 +164745,11 @@ Fails if react-profiler-stop has not been called or no profiling data is stored.
164219
164745
  reactCommits: pipelineOutput.reactCommits,
164220
164746
  annotations: params.annotations,
164221
164747
  debugDir,
164222
- allClear: pipelineOutput.allClear,
164223
- maxCommitMs: pipelineOutput.maxCommitMs
164748
+ noHotCommits: pipelineOutput.noHotCommits,
164749
+ noReactCommits: totalReactCommits === 0,
164750
+ maxCommitMs: pipelineOutput.maxCommitMs,
164751
+ renderSummary,
164752
+ componentOrigin: createComponentOriginClassifier(sourceIndex)
164224
164753
  });
164225
164754
  const artifacts = requireArtifacts(ctx);
164226
164755
  const result = {
@@ -164511,6 +165040,11 @@ Use when you want a quick look at what is mounted in a live connected app, witho
164511
165040
  Fails if the React DevTools hook is not present in the runtime or the app is not connected.`,
164512
165041
  zodSchema: zodSchema51,
164513
165042
  readOnly: true,
165043
+ // It walks only the top 30 fiber levels, above the screens of a real app
165044
+ // (Bluesky's first feed item sits at depth 446), and its totals double-count
165045
+ // nested instances. Agents read render counts from a profiling session
165046
+ // (profiler-commit-query mode=render_counts); HTTP and SDK callers keep it.
165047
+ hideFromMcp: true,
164514
165048
  interaction: {
164515
165049
  startedMsg: () => "Reading React render activity",
164516
165050
  completedMsg: () => "Read React render activity",
@@ -166154,7 +166688,7 @@ async function renderNativeProfilerReport(input2) {
166154
166688
  const status = Object.keys(exportErrors).length > 0 ? "analysis_failed" : "ok";
166155
166689
  const cpuHotspotsCount = payload.bottlenecks.filter((b) => b.type === "cpu_hotspot").length;
166156
166690
  const uiHangsCount = payload.bottlenecks.filter((b) => b.type === "ui_hang").length;
166157
- const fullReport = bottlenecksTotal === 0 ? renderAllClear2(payload, exportErrors, freshnessNote, cpuDiagnostic, leaksRecorded) : renderFullReport(
166691
+ const fullReport = bottlenecksTotal === 0 ? renderAllClear(payload, exportErrors, freshnessNote, cpuDiagnostic, leaksRecorded) : renderFullReport(
166158
166692
  payload,
166159
166693
  exportErrors,
166160
166694
  {
@@ -166168,7 +166702,7 @@ async function renderNativeProfilerReport(input2) {
166168
166702
  );
166169
166703
  const reportFile = traceFile ? deriveReportPath(traceFile) : null;
166170
166704
  const wroteFile = reportFile ? await writeReport2(reportFile, fullReport) : false;
166171
- const inlineReport = bottlenecksTotal === 0 ? renderAllClear2(payload, exportErrors, freshnessNote, cpuDiagnostic, leaksRecorded) : renderFullReport(
166705
+ const inlineReport = bottlenecksTotal === 0 ? renderAllClear(payload, exportErrors, freshnessNote, cpuDiagnostic, leaksRecorded) : renderFullReport(
166172
166706
  payload,
166173
166707
  exportErrors,
166174
166708
  {
@@ -166229,7 +166763,7 @@ function renderTraceProcessorUnavailable(err) {
166229
166763
  function reportTitle(payload) {
166230
166764
  return payload.metadata.platform.toLowerCase() === "android" ? "Android Perfetto Analysis" : "iOS Instruments Analysis";
166231
166765
  }
166232
- function renderAllClear2(payload, exportErrors, freshnessNote, cpuDiagnostic, leaksRecorded) {
166766
+ function renderAllClear(payload, exportErrors, freshnessNote, cpuDiagnostic, leaksRecorded) {
166233
166767
  const traceName = payload.metadata.traceFile ? `\`${path39.basename(payload.metadata.traceFile)}\`` : "unknown";
166234
166768
  const lines = [
166235
166769
  `# ${reportTitle(payload)}`,
@@ -170312,7 +170846,469 @@ Fails if no recording (running or finished-but-unretrieved) exists for the given
170312
170846
  // ../tool-server/src/tools/profiler/query/profiler-cpu-query.ts
170313
170847
  init_zod();
170314
170848
  init_src2();
170849
+
170850
+ // ../tool-server/src/tools/profiler/query/profiler-commit-query.ts
170851
+ init_zod();
170852
+ init_src2();
170853
+ async function getCommitData(port, deviceId) {
170854
+ const sessionPaths = getCachedProfilerPaths(port, deviceId);
170855
+ if (!sessionPaths?.commitsPath) {
170856
+ throw new FailureError(
170857
+ "No commit data stored. Run react-profiler-start \u2192 exercise app \u2192 react-profiler-stop first.",
170858
+ {
170859
+ error_code: FAILURE_CODES.PROFILER_DATA_NOT_LOADED,
170860
+ failure_stage: "profiler_commit_query_load_data",
170861
+ failure_area: "tool_server",
170862
+ error_kind: "validation"
170863
+ }
170864
+ );
170865
+ }
170866
+ const onDisk = await readCommitTree(sessionPaths.commitsPath);
170867
+ return {
170868
+ commits: Array.isArray(onDisk.commits) ? onDisk.commits : [],
170869
+ hookNames: /* @__PURE__ */ new Map(),
170870
+ renderSummary: parseRenderSummary(onDisk.meta?.renderSummary),
170871
+ totalReactCommits: onDisk.meta?.totalReactCommits ?? sessionPaths.totalReactCommits ?? null
170872
+ };
170873
+ }
170874
+ var NO_COMMITS_RECORDED = "_No React commits were recorded in this session, so there is no commit data to query. Interact with the app while the profiler records._";
170875
+ function renderNoStoredCommits(data) {
170876
+ const summary = data.renderSummary;
170877
+ const total = summary?.totalCommits ?? data.totalReactCommits;
170878
+ if (total === 0) return NO_COMMITS_RECORDED;
170879
+ const peak = summary && summary.maxCommitMs > 0 ? ` (peak ${formatPeakCommit(summary.maxCommitMs)})` : "";
170880
+ const count2 = total !== null ? `its ${formatCount(total)} React commits` : "its React commits";
170881
+ const unnamedSlowCommit = summary !== null && hasUnnamedSlowCommit(summary);
170882
+ const lines = [
170883
+ unnamedSlowCommit ? `_No per-commit detail is stored for this session: among ${count2}, those of 16ms or more${peak} have no component that could be named, so react-profiler-stop kept none of them. This is not a missing session._` : `_No per-commit detail is stored for this session: none of ${count2} reached 16ms${peak}, so react-profiler-stop kept none of them. This is not a missing session._`,
170884
+ ""
170885
+ ];
170886
+ if (summary) {
170887
+ lines.push(
170888
+ `**React render time:** ${formatRenderTime(summary)}.`,
170889
+ ...unnamedSlowCommit ? ["A commit was slow, but it has no breakdown."] : [],
170890
+ "",
170891
+ "Run `profiler-commit-query` mode=`render_counts` for render counts per component over all commits."
170892
+ );
170893
+ } else {
170894
+ lines.push(
170895
+ "This session has no render summary, usually because an older version saved it, so mode=`render_counts` has no data for it either. Re-profile to get counts over all commits."
170896
+ );
170897
+ }
170898
+ return lines.join("\n");
170899
+ }
170900
+ function renderRenderCounts(summary, componentName, topN2) {
170901
+ if (!summary) {
170902
+ return "_This session has no render summary, usually because an older version saved it. Re-profile to get render counts over all commits; the other modes still cover the commits of 16ms or more._";
170903
+ }
170904
+ if (summary.totalCommits === 0) return NO_COMMITS_RECORDED;
170905
+ if (summary.components.length === 0) {
170906
+ return `**React render time:** ${formatRenderTime(summary)}
170907
+
170908
+ No component in this session could be named, so there is nothing to list.`;
170909
+ }
170910
+ const seconds = Math.max(summary.recordingMs / 1e3, 1e-3);
170911
+ let rows = summary.components;
170912
+ let heading = `## Render Counts \u2014 all ${formatCount(summary.totalCommits)} commits`;
170913
+ const lines = [];
170914
+ if (componentName) {
170915
+ const resolution = resolveComponentName(
170916
+ componentName,
170917
+ summary.components.map((c) => c.name)
170918
+ );
170919
+ if (resolution.kind === "ambiguous" || resolution.kind === "missing") {
170920
+ return renderSummaryNameMiss(resolution, summary);
170921
+ }
170922
+ rows = summary.components.filter((c) => c.name === resolution.rawName);
170923
+ heading = `## Render Counts for \`${resolution.rawName}\` \u2014 all ${formatCount(summary.totalCommits)} commits`;
170924
+ const note = describeResolution(resolution);
170925
+ if (note) lines.push(note, "");
170926
+ }
170927
+ const shown = rows.slice(0, topN2);
170928
+ lines.unshift(heading, "");
170929
+ lines.push(
170930
+ `**React render time:** ${formatRenderTime(summary)}`,
170931
+ `**Fiber renders:** ${formatCount(summary.fiberRenders)} (${formatCount(summary.rerenders)} re-renders, ${formatCount(summary.mounts)} mounts, ${formatCount(summary.untrackedRenders)} with no change data) across ${formatCount(summary.components.length)} components`,
170932
+ "",
170933
+ "Every component that rendered, library components included, by re-render self time. The other modes see only commits of 16ms or more and their neighbours; these counts cover every commit.",
170934
+ "",
170935
+ "| Component | Re-renders | Per second | Re-render commits | Self total (ms) | Self ms/s | Max (ms) | Mounts | No change data | Reason |",
170936
+ "|---|---|---|---|---|---|---|---|---|---|"
170937
+ );
170938
+ for (const c of shown) {
170939
+ lines.push(
170940
+ `| \`${c.name}\` | ${formatCount(c.rerenders)} | ${(c.rerenders / seconds).toFixed(1)} | ${formatCount(c.rerenderCommits)} | ${c.rerenderSelfMs.toFixed(1)} | ${(c.rerenderSelfMs / seconds).toFixed(1)} | ${c.maxRerenderSelfMs.toFixed(1)} | ${formatCount(c.mounts)} | ${formatCount(c.untrackedRenders)} | ${formatRenderSummaryReason(c)} |`
170941
+ );
170942
+ }
170943
+ if (rows.length > shown.length) {
170944
+ lines.push("", `_Showing ${shown.length} of ${rows.length} components; raise top_n for more._`);
170945
+ }
170946
+ return lines.join("\n");
170947
+ }
170948
+ function formatReason2(commit) {
170949
+ const cd = commit.changeDescription;
170950
+ if (!cd) return "unknown";
170951
+ if (cd.isFirstMount) return "mount";
170952
+ const reason2 = deriveReason(cd, commit.hookTypes ?? null);
170953
+ const parts2 = [reason2];
170954
+ if (cd.props && cd.props.length > 0) {
170955
+ parts2.push(`[${cd.props.slice(0, 3).join(", ")}]`);
170956
+ }
170957
+ if (cd.hooks && cd.hooks.length > 0 && commit.hookTypes) {
170958
+ const hookNames = cd.hooks.slice(0, 3).map((i) => commit.hookTypes?.[i] ?? `hook[${i}]`);
170959
+ parts2.push(`[${hookNames.join(", ")}]`);
170960
+ }
170961
+ if (cd.context) parts2.push("(context)");
170962
+ return parts2.join(" ");
170963
+ }
170964
+ function renderByComponent(commits, componentName, topN2, summary = null) {
170965
+ const resolution = resolveComponentName(
170966
+ componentName,
170967
+ commits.map((c) => c.componentName)
170968
+ );
170969
+ if (resolution.kind === "missing" && summary) {
170970
+ return renderNameOutsideStoredCommits(componentName, summary);
170971
+ }
170972
+ if (resolution.kind === "ambiguous" || resolution.kind === "missing") {
170973
+ return renderComponentNameMiss(resolution, {
170974
+ fiberRenders: commits.length,
170975
+ commits: new Set(commits.map((c) => c.commitIndex)).size
170976
+ });
170977
+ }
170978
+ const resolvedName = resolution.rawName;
170979
+ const resolutionNote = describeStoredResolution(resolution, summary);
170980
+ const matching = commits.filter((c) => c.componentName === resolvedName);
170981
+ if (matching.length === 0) {
170982
+ return `_Component \`${resolvedName}\` not found in commit data._`;
170983
+ }
170984
+ const byCommit = /* @__PURE__ */ new Map();
170985
+ for (const c of matching) {
170986
+ let group = byCommit.get(c.commitIndex);
170987
+ if (!group) {
170988
+ group = [];
170989
+ byCommit.set(c.commitIndex, group);
170990
+ }
170991
+ group.push(c);
170992
+ }
170993
+ const sortedCommits = [...byCommit.entries()].map(([idx, entries]) => ({
170994
+ commitIndex: idx,
170995
+ instances: entries.length,
170996
+ totalDuration: entries.reduce((s, e) => s + e.actualDuration, 0),
170997
+ commitDuration: entries[0].commitDuration,
170998
+ timestamp: entries[0].timestamp,
170999
+ reason: formatReason2(entries[0]),
171000
+ parentName: entries[0].parentName ?? "\u2014"
171001
+ })).sort((a, b) => b.totalDuration - a.totalDuration).slice(0, topN2);
171002
+ const lines = [
171003
+ `## Commits for \`${resolvedName}\``,
171004
+ "",
171005
+ ...resolutionNote ? [resolutionNote, ""] : [],
171006
+ `**Total occurrences:** ${matching.length} across ${byCommit.size} commits${storedOnlyNote(resolvedName, matching.filter((c) => c.didRender).length, summary)}`,
171007
+ "",
171008
+ "| Commit | Instances | Duration (ms) | Commit Total (ms) | Time (ms) | Reason | Parent |",
171009
+ "|---|---|---|---|---|---|---|"
171010
+ ];
171011
+ for (const c of sortedCommits) {
171012
+ lines.push(
171013
+ `| #${c.commitIndex} | ${c.instances} | ${c.totalDuration.toFixed(1)} | ${c.commitDuration.toFixed(1)} | ${c.timestamp.toFixed(0)} | ${c.reason} | \`${c.parentName}\` |`
171014
+ );
171015
+ }
171016
+ return lines.join("\n");
171017
+ }
171018
+ function unstoredCommits(data) {
171019
+ const stored = new Set(data.commits.map((c) => c.commitIndex)).size;
171020
+ if (data.totalReactCommits === null || data.totalReactCommits <= stored) return null;
171021
+ return {
171022
+ stored,
171023
+ total: data.totalReactCommits,
171024
+ counts: data.renderSummary ? " mode=`render_counts` counts them over the whole session, without timing." : ""
171025
+ };
171026
+ }
171027
+ function renderEmptyTimeRange(data, start2, end) {
171028
+ const range = `${start2.toFixed(0)}ms \u2192 ${end.toFixed(0)}ms`;
171029
+ const unstored = unstoredCommits(data);
171030
+ if (!unstored) {
171031
+ return `_No commits found in the range ${range}._`;
171032
+ }
171033
+ return `_No stored commits in the range ${range}: only commits of 16ms or more and their neighbours are stored, so commits under 16ms in this range are not listed.${unstored.counts}_`;
171034
+ }
171035
+ function renderByTimeRange(data, start2, end, topN2) {
171036
+ const { commits } = data;
171037
+ const matching = commits.filter((c) => c.timestamp >= start2 && c.timestamp <= end);
171038
+ if (matching.length === 0) return renderEmptyTimeRange(data, start2, end);
171039
+ const byCommit = /* @__PURE__ */ new Map();
171040
+ for (const c of matching) {
171041
+ let group = byCommit.get(c.commitIndex);
171042
+ if (!group) {
171043
+ group = [];
171044
+ byCommit.set(c.commitIndex, group);
171045
+ }
171046
+ group.push(c);
171047
+ }
171048
+ const summaries = [...byCommit.entries()].map(([idx, entries]) => ({
171049
+ commitIndex: idx,
171050
+ componentCount: new Set(entries.map((e) => e.componentName)).size,
171051
+ commitDuration: entries[0].commitDuration,
171052
+ timestamp: entries[0].timestamp,
171053
+ topComponents: getTopComponents(entries, 5)
171054
+ })).sort((a, b) => b.commitDuration - a.commitDuration).slice(0, topN2);
171055
+ const unstored = unstoredCommits(data);
171056
+ const lines = [
171057
+ `## Commits in ${start2.toFixed(0)}ms \u2192 ${end.toFixed(0)}ms`,
171058
+ "",
171059
+ `**Commits:** ${byCommit.size} **Fiber renders:** ${matching.length}`,
171060
+ "",
171061
+ ...unstored ? [
171062
+ `_Only commits of 16ms or more and their neighbours are stored (${formatCount(unstored.stored)} of ${formatCount(unstored.total)} commits in this session), so this range can hold commits that are not listed.${unstored.counts}_`,
171063
+ ""
171064
+ ] : []
171065
+ ];
171066
+ for (const s of summaries) {
171067
+ lines.push(
171068
+ `### Commit #${s.commitIndex} \u2014 ${s.commitDuration.toFixed(1)}ms (t=${s.timestamp.toFixed(0)}ms, ${s.componentCount} components)`
171069
+ );
171070
+ lines.push("");
171071
+ for (const comp of s.topComponents) {
171072
+ lines.push(
171073
+ `- \`${comp.name}\` \xD7${comp.count} ${comp.totalDuration.toFixed(1)}ms \u2014 ${comp.reason}`
171074
+ );
171075
+ }
171076
+ lines.push("");
171077
+ }
171078
+ return lines.join("\n");
171079
+ }
171080
+ function renderByIndex(commits, commitIndex, topN2) {
171081
+ const matching = commits.filter((c) => c.commitIndex === commitIndex);
171082
+ if (matching.length === 0) {
171083
+ return `_Commit #${commitIndex} not found in stored data._`;
171084
+ }
171085
+ const commitDuration = matching[0].commitDuration;
171086
+ const timestamp = matching[0].timestamp;
171087
+ const sorted = [...matching].sort((a, b) => b.actualDuration - a.actualDuration);
171088
+ const shown = topN2 !== void 0 ? sorted.slice(0, topN2) : sorted;
171089
+ const hidden = sorted.length - shown.length;
171090
+ const lines = [
171091
+ `## Commit #${commitIndex} \u2014 ${hidden > 0 ? "Top Fibers" : "Full Detail"}`,
171092
+ "",
171093
+ `**Time:** ${timestamp.toFixed(0)}ms **Duration:** ${commitDuration.toFixed(1)}ms **Fibers:** ${matching.length}${hidden > 0 ? ` (showing ${shown.length})` : ""}`,
171094
+ "",
171095
+ "| Component | Duration (ms) | Self (ms) | Reason | Parent | Compiler |",
171096
+ "|---|---|---|---|---|---|"
171097
+ ];
171098
+ for (const c of shown) {
171099
+ const reason2 = formatReason2(c);
171100
+ const parent = c.parentName ?? "\u2014";
171101
+ const compiler = c.isCompilerOptimized ? "\u2713" : "";
171102
+ lines.push(
171103
+ `| \`${c.componentName}\` | ${c.actualDuration.toFixed(1)} | ${c.selfDuration.toFixed(1)} | ${reason2} | \`${parent}\` | ${compiler} |`
171104
+ );
171105
+ }
171106
+ if (hidden > 0) {
171107
+ lines.push("");
171108
+ lines.push(
171109
+ `_Showing the ${shown.length} costliest of ${sorted.length} fibers \u2014 ${hidden} cheaper fibers hidden. Note these are fibers, not components: the full set covers ${new Set(sorted.map((c) => c.componentName)).size} distinct components and this view covers ${new Set(shown.map((c) => c.componentName)).size}. Omit top_n for everything._`
171110
+ );
171111
+ }
171112
+ const withRootCause = matching.find((c) => c.rootCauseParent);
171113
+ if (withRootCause?.rootCauseChain && withRootCause.rootCauseChain.length > 0) {
171114
+ lines.push("");
171115
+ lines.push(
171116
+ `**Root cause chain:** ${withRootCause.rootCauseChain.map((n) => `\`${n}\``).join(" \u2192 ")} \u2192 \`${withRootCause.rootCauseParent}\``
171117
+ );
171118
+ if (withRootCause.rootCauseReason) {
171119
+ lines.push(`**Root cause reason:** ${withRootCause.rootCauseReason}`);
171120
+ }
171121
+ }
171122
+ return lines.join("\n");
171123
+ }
171124
+ function renderCascadeTree(commits, commitIndex) {
171125
+ const matching = commits.filter((c) => c.commitIndex === commitIndex);
171126
+ if (matching.length === 0) {
171127
+ return `_Commit #${commitIndex} not found in stored data._`;
171128
+ }
171129
+ const children = /* @__PURE__ */ new Map();
171130
+ const roots = [];
171131
+ for (const c of matching) {
171132
+ const parentName = c.parentName;
171133
+ if (!parentName || !matching.some((m) => m.componentName === parentName)) {
171134
+ roots.push(c);
171135
+ } else {
171136
+ let list = children.get(parentName);
171137
+ if (!list) {
171138
+ list = [];
171139
+ children.set(parentName, list);
171140
+ }
171141
+ list.push(c);
171142
+ }
171143
+ }
171144
+ const lines = [`## Cascade Tree \u2014 Commit #${commitIndex}`, ""];
171145
+ const rendered = /* @__PURE__ */ new Set();
171146
+ function renderNode(name, depth) {
171147
+ if (rendered.has(`${name}:${depth}`)) return;
171148
+ rendered.add(`${name}:${depth}`);
171149
+ const instances = matching.filter((c) => c.componentName === name);
171150
+ const totalSelf = instances.reduce((s, c) => s + c.selfDuration, 0);
171151
+ const count2 = instances.length;
171152
+ const reason2 = instances[0] ? formatReason2(instances[0]) : "";
171153
+ const indent = " ".repeat(depth);
171154
+ const countStr = count2 > 1 ? ` \xD7${count2}` : "";
171155
+ lines.push(`${indent}- \`${name}\`${countStr} self=${totalSelf.toFixed(1)}ms \u2014 ${reason2}`);
171156
+ const childCommits = children.get(name) ?? [];
171157
+ const childNames = new Set(childCommits.map((c) => c.componentName));
171158
+ for (const childName of childNames) {
171159
+ renderNode(childName, depth + 1);
171160
+ }
171161
+ }
171162
+ const rootNames = new Set(roots.map((r) => r.componentName));
171163
+ for (const name of rootNames) {
171164
+ renderNode(name, 0);
171165
+ }
171166
+ return lines.join("\n");
171167
+ }
171168
+ function getTopComponents(entries, topN2) {
171169
+ const byName = /* @__PURE__ */ new Map();
171170
+ for (const e of entries) {
171171
+ const existing = byName.get(e.componentName);
171172
+ if (existing) {
171173
+ existing.count++;
171174
+ existing.totalDuration += e.actualDuration;
171175
+ } else {
171176
+ byName.set(e.componentName, { count: 1, totalDuration: e.actualDuration, first: e });
171177
+ }
171178
+ }
171179
+ return [...byName.entries()].sort((a, b) => b[1].totalDuration - a[1].totalDuration).slice(0, topN2).map(([name, { count: count2, totalDuration, first }]) => ({
171180
+ name,
171181
+ count: count2,
171182
+ totalDuration,
171183
+ reason: formatReason2(first)
171184
+ }));
171185
+ }
171186
+ var timeRangeSchema = external_exports.object({
171187
+ start: external_exports.coerce.number().describe("Start of range in ms"),
171188
+ end: external_exports.coerce.number().describe("End of range in ms")
171189
+ });
171190
+ var zodSchema58 = external_exports.object({
171191
+ port: metroPortField,
171192
+ device_id: metroDeviceIdParam(
171193
+ "Device logicalDeviceId from debugger-connect (iOS simulator UDID or Android logicalDeviceId)."
171194
+ ),
171195
+ mode: external_exports.enum(["by_component", "by_time_range", "by_index", "cascade_tree", "render_counts"]).describe("Query mode; see Modes in the tool description."),
171196
+ component_name: external_exports.string().optional().describe("Component name; optional for render_counts, which it narrows to one component"),
171197
+ time_range_ms: timeRangeSchema.optional().describe("Time range in ms since profiling started, the clock this tool prints"),
171198
+ commit_index: external_exports.coerce.number().int().optional().describe("Commit index"),
171199
+ top_n: external_exports.coerce.number().int().positive().optional().describe(
171200
+ "Max results to return. Defaults to 20 for by_component / by_time_range, which count commits, and render_counts, which counts components. by_index counts individual fibers and returns all of them unless this is set; a small cap there can show less than the analyze report it is meant to expand on."
171201
+ )
171202
+ });
171203
+ var profilerCommitQueryTool = {
171204
+ id: "profiler-commit-query",
171205
+ description: `Query React commit data for iterative investigation of render performance.
171206
+ Modes:
171207
+ - by_component: All commits where component_name rendered, with causes and durations.
171208
+ - by_time_range: What happened in time_range_ms.
171209
+ - by_index: Full detail dump of the commit at commit_index (all components, props changed, parent cascade).
171210
+ - cascade_tree: Parent-child cascade tree for the commit at commit_index, showing who triggered whom.
171211
+ - render_counts: Re-render count, rate and self time per component over ALL commits, including those under 16ms that the other modes cannot see. Library components included.
171212
+ Use when drilling into specific components or time windows after react-profiler-analyze.
171213
+ Returns a markdown table or tree of commit data matching the requested mode.
171214
+ Fails if react-profiler-stop has not been called.`,
171215
+ zodSchema: zodSchema58,
171216
+ readOnly: true,
171217
+ interaction: {
171218
+ startedMsg: ({ params }) => `Querying React commits ${params.mode.replace(/^by_/, "by ").replaceAll("_", " ")}`,
171219
+ completedMsg: ({ params }) => `Queried React commits ${params.mode.replace(/^by_/, "by ").replaceAll("_", " ")}`,
171220
+ failedMsg: ({ failureSignal: failureSignal2 }) => `Failed to query React commits: ${failureSignal2.error_code}`
171221
+ },
171222
+ // Reads React commit data captured via the React DevTools backend.
171223
+ capability: RN_ONLY_TOOL_CAPABILITY,
171224
+ services: () => ({}),
171225
+ async execute(_services, params) {
171226
+ const commitTree = await getCommitData(metroPort(params), params.device_id);
171227
+ if (params.mode === "render_counts") {
171228
+ return renderRenderCounts(
171229
+ commitTree.renderSummary,
171230
+ params.component_name,
171231
+ params.top_n ?? 20
171232
+ );
171233
+ }
171234
+ if (commitTree.commits.length === 0) return renderNoStoredCommits(commitTree);
171235
+ switch (params.mode) {
171236
+ case "by_component": {
171237
+ if (!params.component_name) {
171238
+ throw new FailureError("by_component mode requires the component_name parameter.", {
171239
+ error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
171240
+ failure_stage: "profiler_commit_query_params",
171241
+ failure_area: "tool_server",
171242
+ error_kind: "validation"
171243
+ });
171244
+ }
171245
+ return renderByComponent(
171246
+ commitTree.commits,
171247
+ params.component_name,
171248
+ params.top_n ?? 20,
171249
+ commitTree.renderSummary
171250
+ );
171251
+ }
171252
+ case "by_time_range": {
171253
+ if (!params.time_range_ms) {
171254
+ throw new FailureError("by_time_range mode requires the time_range_ms parameter.", {
171255
+ error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
171256
+ failure_stage: "profiler_commit_query_params",
171257
+ failure_area: "tool_server",
171258
+ error_kind: "validation"
171259
+ });
171260
+ }
171261
+ return renderByTimeRange(
171262
+ commitTree,
171263
+ params.time_range_ms.start,
171264
+ params.time_range_ms.end,
171265
+ params.top_n ?? 20
171266
+ );
171267
+ }
171268
+ case "by_index": {
171269
+ if (params.commit_index == null) {
171270
+ throw new FailureError("by_index mode requires the commit_index parameter.", {
171271
+ error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
171272
+ failure_stage: "profiler_commit_query_params",
171273
+ failure_area: "tool_server",
171274
+ error_kind: "validation"
171275
+ });
171276
+ }
171277
+ return renderByIndex(commitTree.commits, params.commit_index, params.top_n);
171278
+ }
171279
+ case "cascade_tree": {
171280
+ if (params.commit_index == null) {
171281
+ throw new FailureError("cascade_tree mode requires the commit_index parameter.", {
171282
+ error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
171283
+ failure_stage: "profiler_commit_query_params",
171284
+ failure_area: "tool_server",
171285
+ error_kind: "validation"
171286
+ });
171287
+ }
171288
+ return renderCascadeTree(commitTree.commits, params.commit_index);
171289
+ }
171290
+ default:
171291
+ throw new FailureError(`Unknown mode: ${params.mode}`, {
171292
+ error_code: FAILURE_CODES.PROFILER_QUERY_MODE_INVALID,
171293
+ failure_stage: "profiler_commit_query_mode",
171294
+ failure_area: "tool_server",
171295
+ error_kind: "validation"
171296
+ });
171297
+ }
171298
+ }
171299
+ };
171300
+
171301
+ // ../tool-server/src/tools/profiler/query/profiler-cpu-query.ts
170315
171302
  var import_fs19 = require("fs");
171303
+ async function readStoredCommits(sessionPaths) {
171304
+ if (!sessionPaths.commitsPath) return null;
171305
+ const onDisk = await readCommitTree(sessionPaths.commitsPath);
171306
+ return {
171307
+ commits: onDisk.commits,
171308
+ renderSummary: parseRenderSummary(onDisk.meta?.renderSummary),
171309
+ totalReactCommits: onDisk.meta?.totalReactCommits ?? sessionPaths.totalReactCommits ?? null
171310
+ };
171311
+ }
170316
171312
  async function getIndex(sessionPaths) {
170317
171313
  if (!sessionPaths?.cpuProfilePath) {
170318
171314
  throw new FailureError(
@@ -170329,22 +171325,15 @@ async function getIndex(sessionPaths) {
170329
171325
  try {
170330
171326
  const raw = JSON.parse(await import_fs19.promises.readFile(sessionPaths.cpuSampleIndexPath, "utf8"));
170331
171327
  const index = deserializeCpuSampleIndex(raw);
170332
- let commitTree2 = null;
170333
- if (sessionPaths.commitsPath) {
170334
- const onDisk = await readCommitTree(sessionPaths.commitsPath);
170335
- commitTree2 = { commits: onDisk.commits };
170336
- }
170337
- return { index, commitTree: commitTree2 };
171328
+ return { index, commitTree: await readStoredCommits(sessionPaths) };
170338
171329
  } catch {
170339
171330
  }
170340
171331
  }
170341
171332
  const cpuProfile = await readCpuProfile(sessionPaths.cpuProfilePath);
170342
- let commitTree = null;
170343
- if (sessionPaths.commitsPath) {
170344
- const onDisk = await readCommitTree(sessionPaths.commitsPath);
170345
- commitTree = { commits: onDisk.commits };
170346
- }
170347
- return { index: buildCpuSampleIndex(cpuProfile), commitTree };
171333
+ return {
171334
+ index: buildCpuSampleIndex(cpuProfile),
171335
+ commitTree: await readStoredCommits(sessionPaths)
171336
+ };
170348
171337
  }
170349
171338
  function explainEmptyWindow(res, startMs, endMs) {
170350
171339
  const range = `${res.sampleRangeMs.start.toFixed(1)}\u2013${res.sampleRangeMs.end.toFixed(1)}ms`;
@@ -170492,13 +171481,25 @@ function renderCallTree(index, functionName, topN2, includeCallers) {
170492
171481
  return lines.join("\n");
170493
171482
  }
170494
171483
  function renderComponentCpu(index, commitTree, componentName, topN2) {
170495
- if (!commitTree || commitTree.commits.length === 0) {
171484
+ if (!commitTree) {
170496
171485
  return "_No commit data available. Run react-profiler-analyze first._";
170497
171486
  }
171487
+ if (commitTree.commits.length === 0) {
171488
+ return `${renderNoStoredCommits(commitTree)}
171489
+
171490
+ Use mode=\`top_functions\` for JS CPU.`;
171491
+ }
170498
171492
  const resolution = resolveComponentName(
170499
171493
  componentName,
170500
171494
  commitTree.commits.map((c) => c.componentName)
170501
171495
  );
171496
+ if (resolution.kind === "missing" && commitTree.renderSummary) {
171497
+ return renderNameOutsideStoredCommits(
171498
+ componentName,
171499
+ commitTree.renderSummary,
171500
+ " Use mode=`top_functions` for JS CPU over the whole session."
171501
+ );
171502
+ }
170502
171503
  if (resolution.kind === "ambiguous" || resolution.kind === "missing") {
170503
171504
  return renderComponentNameMiss(resolution, {
170504
171505
  fiberRenders: commitTree.commits.length,
@@ -170506,7 +171507,7 @@ function renderComponentCpu(index, commitTree, componentName, topN2) {
170506
171507
  });
170507
171508
  }
170508
171509
  const resolvedName = resolution.rawName;
170509
- const resolutionNote = describeResolution(resolution);
171510
+ const resolutionNote = describeStoredResolution(resolution, commitTree.renderSummary);
170510
171511
  const componentCommits = commitTree.commits.filter((c) => c.componentName === resolvedName);
170511
171512
  if (componentCommits.length === 0) {
170512
171513
  return `_Component \`${resolvedName}\` not found in commit data._`;
@@ -170548,7 +171549,12 @@ function renderComponentCpu(index, commitTree, componentName, topN2) {
170548
171549
  `## CPU During \`${resolvedName}\` Commits`,
170549
171550
  "",
170550
171551
  ...resolutionNote ? [resolutionNote, ""] : [],
170551
- `**Commits:** ${commitWindows.size} **Total commit time:** ${totalCommitMs.toFixed(1)}ms`,
171552
+ `**Commits:** ${commitWindows.size} **Total commit time:** ${totalCommitMs.toFixed(1)}ms` + storedOnlyNote(
171553
+ resolvedName,
171554
+ componentCommits.filter((c) => c.didRender).length,
171555
+ commitTree.renderSummary,
171556
+ "`profiler-commit-query` mode=`render_counts`"
171557
+ ),
170552
171558
  "",
170553
171559
  "| Function | Self (ms) | Total (ms) | Location |",
170554
171560
  "|---|---|---|---|"
@@ -170569,7 +171575,7 @@ var timeWindowSchema = external_exports.object({
170569
171575
  start: external_exports.coerce.number().describe("Start of window in ms"),
170570
171576
  end: external_exports.coerce.number().describe("End of window in ms")
170571
171577
  });
170572
- var zodSchema58 = external_exports.object({
171578
+ var zodSchema59 = external_exports.object({
170573
171579
  port: metroPortField,
170574
171580
  device_id: metroDeviceIdParam(
170575
171581
  "Device logicalDeviceId from debugger-connect (iOS simulator UDID or Android logicalDeviceId)."
@@ -170590,14 +171596,14 @@ Modes:
170590
171596
  - top_functions: Global CPU hotspots ranked by self-time. Optional time_window_ms to filter.
170591
171597
  - time_window: CPU breakdown for time_window_ms (e.g. during a slow commit or hang).
170592
171598
  - call_tree: For a given function_name, show its callees, and its callers with include_callers.
170593
- - component_cpu: For a given component_name, aggregate CPU activity across all its commits.
171599
+ - component_cpu: For a given component_name, aggregate CPU activity across its stored commits.
170594
171600
  In top_functions and time_window, self-times are the summed sampling intervals of the samples that
170595
171601
  landed in the window, so they measure sampled coverage rather than the window's width and do not
170596
171602
  change if you widen the query. Their tables state how many samples they cover and how much was idle.
170597
171603
  Use when investigating JS CPU hotspots or correlating CPU cost with specific components.
170598
171604
  Returns a markdown table of CPU hotspots, call tree, or per-component CPU breakdown.
170599
171605
  Fails if no CPU profile is stored; run react-profiler-stop (and ideally react-profiler-analyze) first.`,
170600
- zodSchema: zodSchema58,
171606
+ zodSchema: zodSchema59,
170601
171607
  readOnly: true,
170602
171608
  interaction: {
170603
171609
  startedMsg: ({ params }) => `Querying CPU profile by ${params.mode.replaceAll("_", " ")}`,
@@ -170678,351 +171684,6 @@ Fails if no CPU profile is stored; run react-profiler-stop (and ideally react-pr
170678
171684
  }
170679
171685
  };
170680
171686
 
170681
- // ../tool-server/src/tools/profiler/query/profiler-commit-query.ts
170682
- init_zod();
170683
- init_src2();
170684
- async function getCommitTree(port, deviceId) {
170685
- const sessionPaths = getCachedProfilerPaths(port, deviceId);
170686
- if (!sessionPaths?.commitsPath) {
170687
- throw new FailureError(
170688
- "No commit data stored. Run react-profiler-start \u2192 exercise app \u2192 react-profiler-stop first.",
170689
- {
170690
- error_code: FAILURE_CODES.PROFILER_DATA_NOT_LOADED,
170691
- failure_stage: "profiler_commit_query_load_data",
170692
- failure_area: "tool_server",
170693
- error_kind: "validation"
170694
- }
170695
- );
170696
- }
170697
- const onDisk = await readCommitTree(sessionPaths.commitsPath);
170698
- if (onDisk.commits.length === 0) {
170699
- throw new FailureError(
170700
- "No commit data stored. Run react-profiler-start \u2192 exercise app \u2192 react-profiler-stop first.",
170701
- {
170702
- error_code: FAILURE_CODES.PROFILER_DATA_NOT_LOADED,
170703
- failure_stage: "profiler_commit_query_load_data",
170704
- failure_area: "tool_server",
170705
- error_kind: "validation"
170706
- }
170707
- );
170708
- }
170709
- return { commits: onDisk.commits, hookNames: /* @__PURE__ */ new Map() };
170710
- }
170711
- function formatReason2(commit) {
170712
- const cd = commit.changeDescription;
170713
- if (!cd) return "unknown";
170714
- if (cd.isFirstMount) return "mount";
170715
- const reason2 = deriveReason(cd, commit.hookTypes ?? null);
170716
- const parts2 = [reason2];
170717
- if (cd.props && cd.props.length > 0) {
170718
- parts2.push(`[${cd.props.slice(0, 3).join(", ")}]`);
170719
- }
170720
- if (cd.hooks && cd.hooks.length > 0 && commit.hookTypes) {
170721
- const hookNames = cd.hooks.slice(0, 3).map((i) => commit.hookTypes?.[i] ?? `hook[${i}]`);
170722
- parts2.push(`[${hookNames.join(", ")}]`);
170723
- }
170724
- if (cd.context) parts2.push("(context)");
170725
- return parts2.join(" ");
170726
- }
170727
- function renderByComponent(commits, componentName, topN2) {
170728
- const resolution = resolveComponentName(
170729
- componentName,
170730
- commits.map((c) => c.componentName)
170731
- );
170732
- if (resolution.kind === "ambiguous" || resolution.kind === "missing") {
170733
- return renderComponentNameMiss(resolution, {
170734
- fiberRenders: commits.length,
170735
- commits: new Set(commits.map((c) => c.commitIndex)).size
170736
- });
170737
- }
170738
- const resolvedName = resolution.rawName;
170739
- const resolutionNote = describeResolution(resolution);
170740
- const matching = commits.filter((c) => c.componentName === resolvedName);
170741
- if (matching.length === 0) {
170742
- return `_Component \`${resolvedName}\` not found in commit data._`;
170743
- }
170744
- const byCommit = /* @__PURE__ */ new Map();
170745
- for (const c of matching) {
170746
- let group = byCommit.get(c.commitIndex);
170747
- if (!group) {
170748
- group = [];
170749
- byCommit.set(c.commitIndex, group);
170750
- }
170751
- group.push(c);
170752
- }
170753
- const sortedCommits = [...byCommit.entries()].map(([idx, entries]) => ({
170754
- commitIndex: idx,
170755
- instances: entries.length,
170756
- totalDuration: entries.reduce((s, e) => s + e.actualDuration, 0),
170757
- commitDuration: entries[0].commitDuration,
170758
- timestamp: entries[0].timestamp,
170759
- reason: formatReason2(entries[0]),
170760
- parentName: entries[0].parentName ?? "\u2014"
170761
- })).sort((a, b) => b.totalDuration - a.totalDuration).slice(0, topN2);
170762
- const lines = [
170763
- `## Commits for \`${resolvedName}\``,
170764
- "",
170765
- ...resolutionNote ? [resolutionNote, ""] : [],
170766
- `**Total occurrences:** ${matching.length} across ${byCommit.size} commits`,
170767
- "",
170768
- "| Commit | Instances | Duration (ms) | Commit Total (ms) | Time (ms) | Reason | Parent |",
170769
- "|---|---|---|---|---|---|---|"
170770
- ];
170771
- for (const c of sortedCommits) {
170772
- lines.push(
170773
- `| #${c.commitIndex} | ${c.instances} | ${c.totalDuration.toFixed(1)} | ${c.commitDuration.toFixed(1)} | ${c.timestamp.toFixed(0)} | ${c.reason} | \`${c.parentName}\` |`
170774
- );
170775
- }
170776
- return lines.join("\n");
170777
- }
170778
- function renderByTimeRange(commits, start2, end, topN2) {
170779
- const matching = commits.filter((c) => c.timestamp >= start2 && c.timestamp <= end);
170780
- if (matching.length === 0) {
170781
- return `_No commits found in the range ${start2.toFixed(0)}ms \u2192 ${end.toFixed(0)}ms._`;
170782
- }
170783
- const byCommit = /* @__PURE__ */ new Map();
170784
- for (const c of matching) {
170785
- let group = byCommit.get(c.commitIndex);
170786
- if (!group) {
170787
- group = [];
170788
- byCommit.set(c.commitIndex, group);
170789
- }
170790
- group.push(c);
170791
- }
170792
- const summaries = [...byCommit.entries()].map(([idx, entries]) => ({
170793
- commitIndex: idx,
170794
- componentCount: new Set(entries.map((e) => e.componentName)).size,
170795
- commitDuration: entries[0].commitDuration,
170796
- timestamp: entries[0].timestamp,
170797
- topComponents: getTopComponents(entries, 5)
170798
- })).sort((a, b) => b.commitDuration - a.commitDuration).slice(0, topN2);
170799
- const lines = [
170800
- `## Commits in ${start2.toFixed(0)}ms \u2192 ${end.toFixed(0)}ms`,
170801
- "",
170802
- `**Commits:** ${byCommit.size} **Fiber renders:** ${matching.length}`,
170803
- ""
170804
- ];
170805
- for (const s of summaries) {
170806
- lines.push(
170807
- `### Commit #${s.commitIndex} \u2014 ${s.commitDuration.toFixed(1)}ms (t=${s.timestamp.toFixed(0)}ms, ${s.componentCount} components)`
170808
- );
170809
- lines.push("");
170810
- for (const comp of s.topComponents) {
170811
- lines.push(
170812
- `- \`${comp.name}\` \xD7${comp.count} ${comp.totalDuration.toFixed(1)}ms \u2014 ${comp.reason}`
170813
- );
170814
- }
170815
- lines.push("");
170816
- }
170817
- return lines.join("\n");
170818
- }
170819
- function renderByIndex(commits, commitIndex, topN2) {
170820
- const matching = commits.filter((c) => c.commitIndex === commitIndex);
170821
- if (matching.length === 0) {
170822
- return `_Commit #${commitIndex} not found in stored data._`;
170823
- }
170824
- const commitDuration = matching[0].commitDuration;
170825
- const timestamp = matching[0].timestamp;
170826
- const sorted = [...matching].sort((a, b) => b.actualDuration - a.actualDuration);
170827
- const shown = topN2 !== void 0 ? sorted.slice(0, topN2) : sorted;
170828
- const hidden = sorted.length - shown.length;
170829
- const lines = [
170830
- `## Commit #${commitIndex} \u2014 ${hidden > 0 ? "Top Fibers" : "Full Detail"}`,
170831
- "",
170832
- `**Time:** ${timestamp.toFixed(0)}ms **Duration:** ${commitDuration.toFixed(1)}ms **Fibers:** ${matching.length}${hidden > 0 ? ` (showing ${shown.length})` : ""}`,
170833
- "",
170834
- "| Component | Duration (ms) | Self (ms) | Reason | Parent | Compiler |",
170835
- "|---|---|---|---|---|---|"
170836
- ];
170837
- for (const c of shown) {
170838
- const reason2 = formatReason2(c);
170839
- const parent = c.parentName ?? "\u2014";
170840
- const compiler = c.isCompilerOptimized ? "\u2713" : "";
170841
- lines.push(
170842
- `| \`${c.componentName}\` | ${c.actualDuration.toFixed(1)} | ${c.selfDuration.toFixed(1)} | ${reason2} | \`${parent}\` | ${compiler} |`
170843
- );
170844
- }
170845
- if (hidden > 0) {
170846
- lines.push("");
170847
- lines.push(
170848
- `_Showing the ${shown.length} costliest of ${sorted.length} fibers \u2014 ${hidden} cheaper fibers hidden. Note these are fibers, not components: the full set covers ${new Set(sorted.map((c) => c.componentName)).size} distinct components and this view covers ${new Set(shown.map((c) => c.componentName)).size}. Omit top_n for everything._`
170849
- );
170850
- }
170851
- const withRootCause = matching.find((c) => c.rootCauseParent);
170852
- if (withRootCause?.rootCauseChain && withRootCause.rootCauseChain.length > 0) {
170853
- lines.push("");
170854
- lines.push(
170855
- `**Root cause chain:** ${withRootCause.rootCauseChain.map((n) => `\`${n}\``).join(" \u2192 ")} \u2192 \`${withRootCause.rootCauseParent}\``
170856
- );
170857
- if (withRootCause.rootCauseReason) {
170858
- lines.push(`**Root cause reason:** ${withRootCause.rootCauseReason}`);
170859
- }
170860
- }
170861
- return lines.join("\n");
170862
- }
170863
- function renderCascadeTree(commits, commitIndex) {
170864
- const matching = commits.filter((c) => c.commitIndex === commitIndex);
170865
- if (matching.length === 0) {
170866
- return `_Commit #${commitIndex} not found in stored data._`;
170867
- }
170868
- const children = /* @__PURE__ */ new Map();
170869
- const roots = [];
170870
- for (const c of matching) {
170871
- const parentName = c.parentName;
170872
- if (!parentName || !matching.some((m) => m.componentName === parentName)) {
170873
- roots.push(c);
170874
- } else {
170875
- let list = children.get(parentName);
170876
- if (!list) {
170877
- list = [];
170878
- children.set(parentName, list);
170879
- }
170880
- list.push(c);
170881
- }
170882
- }
170883
- const lines = [`## Cascade Tree \u2014 Commit #${commitIndex}`, ""];
170884
- const rendered = /* @__PURE__ */ new Set();
170885
- function renderNode(name, depth) {
170886
- if (rendered.has(`${name}:${depth}`)) return;
170887
- rendered.add(`${name}:${depth}`);
170888
- const instances = matching.filter((c) => c.componentName === name);
170889
- const totalSelf = instances.reduce((s, c) => s + c.selfDuration, 0);
170890
- const count2 = instances.length;
170891
- const reason2 = instances[0] ? formatReason2(instances[0]) : "";
170892
- const indent = " ".repeat(depth);
170893
- const countStr = count2 > 1 ? ` \xD7${count2}` : "";
170894
- lines.push(`${indent}- \`${name}\`${countStr} self=${totalSelf.toFixed(1)}ms \u2014 ${reason2}`);
170895
- const childCommits = children.get(name) ?? [];
170896
- const childNames = new Set(childCommits.map((c) => c.componentName));
170897
- for (const childName of childNames) {
170898
- renderNode(childName, depth + 1);
170899
- }
170900
- }
170901
- const rootNames = new Set(roots.map((r) => r.componentName));
170902
- for (const name of rootNames) {
170903
- renderNode(name, 0);
170904
- }
170905
- return lines.join("\n");
170906
- }
170907
- function getTopComponents(entries, topN2) {
170908
- const byName = /* @__PURE__ */ new Map();
170909
- for (const e of entries) {
170910
- const existing = byName.get(e.componentName);
170911
- if (existing) {
170912
- existing.count++;
170913
- existing.totalDuration += e.actualDuration;
170914
- } else {
170915
- byName.set(e.componentName, { count: 1, totalDuration: e.actualDuration, first: e });
170916
- }
170917
- }
170918
- return [...byName.entries()].sort((a, b) => b[1].totalDuration - a[1].totalDuration).slice(0, topN2).map(([name, { count: count2, totalDuration, first }]) => ({
170919
- name,
170920
- count: count2,
170921
- totalDuration,
170922
- reason: formatReason2(first)
170923
- }));
170924
- }
170925
- var timeRangeSchema = external_exports.object({
170926
- start: external_exports.coerce.number().describe("Start of range in ms"),
170927
- end: external_exports.coerce.number().describe("End of range in ms")
170928
- });
170929
- var zodSchema59 = external_exports.object({
170930
- port: metroPortField,
170931
- device_id: metroDeviceIdParam(
170932
- "Device logicalDeviceId from debugger-connect (iOS simulator UDID or Android logicalDeviceId)."
170933
- ),
170934
- mode: external_exports.enum(["by_component", "by_time_range", "by_index", "cascade_tree"]).describe("Query mode; see Modes in the tool description."),
170935
- component_name: external_exports.string().optional().describe("Component name"),
170936
- time_range_ms: timeRangeSchema.optional().describe("Time range in ms since profiling started, the clock this tool prints"),
170937
- commit_index: external_exports.coerce.number().int().optional().describe("Commit index"),
170938
- top_n: external_exports.coerce.number().int().positive().optional().describe(
170939
- "Max results to return. Defaults to 20 for by_component / by_time_range, which count commits. by_index counts individual fibers and returns all of them unless this is set; a small cap there can show less than the analyze report it is meant to expand on."
170940
- )
170941
- });
170942
- var profilerCommitQueryTool = {
170943
- id: "profiler-commit-query",
170944
- description: `Query React commit data for iterative investigation of render performance.
170945
- Modes:
170946
- - by_component: All commits where component_name rendered, with causes and durations.
170947
- - by_time_range: What happened in time_range_ms.
170948
- - by_index: Full detail dump of the commit at commit_index (all components, props changed, parent cascade).
170949
- - cascade_tree: Parent-child cascade tree for the commit at commit_index, showing who triggered whom.
170950
- Use when drilling into specific components or time windows after react-profiler-analyze.
170951
- Returns a markdown table or tree of commit data matching the requested mode.
170952
- Fails if react-profiler-stop has not been called or no commit data is stored.`,
170953
- zodSchema: zodSchema59,
170954
- readOnly: true,
170955
- interaction: {
170956
- startedMsg: ({ params }) => `Querying React commits ${params.mode.replace(/^by_/, "by ").replaceAll("_", " ")}`,
170957
- completedMsg: ({ params }) => `Queried React commits ${params.mode.replace(/^by_/, "by ").replaceAll("_", " ")}`,
170958
- failedMsg: ({ failureSignal: failureSignal2 }) => `Failed to query React commits: ${failureSignal2.error_code}`
170959
- },
170960
- // Reads React commit data captured via the React DevTools backend.
170961
- capability: RN_ONLY_TOOL_CAPABILITY,
170962
- services: () => ({}),
170963
- async execute(_services, params) {
170964
- const commitTree = await getCommitTree(metroPort(params), params.device_id);
170965
- switch (params.mode) {
170966
- case "by_component": {
170967
- if (!params.component_name) {
170968
- throw new FailureError("by_component mode requires the component_name parameter.", {
170969
- error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
170970
- failure_stage: "profiler_commit_query_params",
170971
- failure_area: "tool_server",
170972
- error_kind: "validation"
170973
- });
170974
- }
170975
- return renderByComponent(commitTree.commits, params.component_name, params.top_n ?? 20);
170976
- }
170977
- case "by_time_range": {
170978
- if (!params.time_range_ms) {
170979
- throw new FailureError("by_time_range mode requires the time_range_ms parameter.", {
170980
- error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
170981
- failure_stage: "profiler_commit_query_params",
170982
- failure_area: "tool_server",
170983
- error_kind: "validation"
170984
- });
170985
- }
170986
- return renderByTimeRange(
170987
- commitTree.commits,
170988
- params.time_range_ms.start,
170989
- params.time_range_ms.end,
170990
- params.top_n ?? 20
170991
- );
170992
- }
170993
- case "by_index": {
170994
- if (params.commit_index == null) {
170995
- throw new FailureError("by_index mode requires the commit_index parameter.", {
170996
- error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
170997
- failure_stage: "profiler_commit_query_params",
170998
- failure_area: "tool_server",
170999
- error_kind: "validation"
171000
- });
171001
- }
171002
- return renderByIndex(commitTree.commits, params.commit_index, params.top_n);
171003
- }
171004
- case "cascade_tree": {
171005
- if (params.commit_index == null) {
171006
- throw new FailureError("cascade_tree mode requires the commit_index parameter.", {
171007
- error_code: FAILURE_CODES.PROFILER_QUERY_REQUIRED_PARAM_MISSING,
171008
- failure_stage: "profiler_commit_query_params",
171009
- failure_area: "tool_server",
171010
- error_kind: "validation"
171011
- });
171012
- }
171013
- return renderCascadeTree(commitTree.commits, params.commit_index);
171014
- }
171015
- default:
171016
- throw new FailureError(`Unknown mode: ${params.mode}`, {
171017
- error_code: FAILURE_CODES.PROFILER_QUERY_MODE_INVALID,
171018
- failure_stage: "profiler_commit_query_mode",
171019
- failure_area: "tool_server",
171020
- error_kind: "validation"
171021
- });
171022
- }
171023
- }
171024
- };
171025
-
171026
171687
  // ../tool-server/src/tools/profiler/query/profiler-stack-query.ts
171027
171688
  init_zod();
171028
171689
  init_src2();
@@ -171425,7 +172086,7 @@ var profilerCombinedReportTool = {
171425
172086
  Maps native hangs to React commits using wall-clock time alignment.
171426
172087
  Call this tool when both profilers were run in parallel on the same session.
171427
172088
  Returns a markdown report correlating hangs with React commits, memory leaks, and investigation hints.
171428
- Fails if either react-profiler-analyze or native-profiler-analyze has not been called first.`,
172089
+ Fails if either react-profiler-analyze or native-profiler-analyze has not been called first, or if the session stored no React commits.`,
171429
172090
  zodSchema: zodSchema61,
171430
172091
  readOnly: true,
171431
172092
  interaction: {
@@ -171517,7 +172178,8 @@ Fails if either react-profiler-analyze or native-profiler-analyze has not been c
171517
172178
  const onDisk = await readCommitTree(sessionPaths.commitsPath);
171518
172179
  const commitTree = { commits: onDisk.commits, hookNames: /* @__PURE__ */ new Map() };
171519
172180
  if (commitTree.commits.length === 0) {
171520
- throw new FailureError("No React commit data. Run react-profiler-analyze first.", {
172181
+ const message = "No React commits are stored for this session: only commits of 16ms or more with named components, and their neighbours, are kept. There is nothing to correlate with the native profile. Use the native-profiler-analyze report on its own.";
172182
+ throw new FailureError(message, {
171521
172183
  error_code: FAILURE_CODES.PROFILER_DATA_NOT_LOADED,
171522
172184
  failure_stage: "profiler_combined_report_load_react_data",
171523
172185
  failure_area: "tool_server",
@@ -171903,11 +172565,12 @@ async function loadReactSession(debugDir, sessionId, port, deviceId) {
171903
172565
  let deviceName = null;
171904
172566
  let projectRoot = null;
171905
172567
  let commitCount = 0;
172568
+ let renderSummary = null;
171906
172569
  let sampleInfo = "not available";
171907
172570
  if (hasCommits) {
171908
172571
  try {
171909
172572
  const onDisk = await readCommitTree(commitsPath);
171910
- commitCount = onDisk.commits.length;
172573
+ commitCount = new Set(onDisk.commits.map((c) => c.commitIndex)).size;
171911
172574
  if (onDisk.meta) {
171912
172575
  detectedArchitecture = onDisk.meta.detectedArchitecture ?? null;
171913
172576
  anyCompilerOptimized = onDisk.meta.anyCompilerOptimized ?? null;
@@ -171916,6 +172579,7 @@ async function loadReactSession(debugDir, sessionId, port, deviceId) {
171916
172579
  appName = onDisk.meta.appName ?? null;
171917
172580
  deviceName = onDisk.meta.deviceName ?? null;
171918
172581
  projectRoot = onDisk.meta.projectRoot ?? null;
172582
+ renderSummary = parseRenderSummary(onDisk.meta.renderSummary);
171919
172583
  }
171920
172584
  } catch {
171921
172585
  }
@@ -171951,6 +172615,8 @@ async function loadReactSession(debugDir, sessionId, port, deviceId) {
171951
172615
  `- CPU profile: ${sampleInfo}`,
171952
172616
  `- Commits persisted (hot \xB11 margin, \u226516ms): ${commitCount}`,
171953
172617
  `- Total React commits: ${totalReactCommits ?? "unknown"}`,
172618
+ // Older sessions lack the summary; say so here, before render_counts does.
172619
+ renderSummary ? `- React render time (all commits): ${formatRenderTime(renderSummary)}` : `- Render counts over all commits: not available for this session`,
171954
172620
  `- Architecture: ${detectedArchitecture ?? "unknown"}`,
171955
172621
  "",
171956
172622
  "Query tools (`profiler-cpu-query`, `profiler-commit-query`) are now ready to use against this data."
@@ -174744,11 +175410,11 @@ function parseFlow(content) {
174744
175410
  );
174745
175411
  }
174746
175412
  if (!("steps" in parsed) || !Array.isArray(parsed.steps)) throw notAFlow();
174747
- const topKeys = ["version", "executionPrerequisite", "requires", "steps"];
174748
- const unknownTop = Object.keys(parsed).filter((k) => !topKeys.includes(k));
175413
+ const topKeys2 = ["version", "executionPrerequisite", "requires", "steps"];
175414
+ const unknownTop = Object.keys(parsed).filter((k) => !topKeys2.includes(k));
174749
175415
  if (unknownTop.length > 0) {
174750
175416
  throw new FailureError(
174751
- `Invalid e2e test file: ${describeUnknownKeys(unknownTop, topKeys)} \u2014 allowed top-level keys: ${topKeys.join(", ")}`,
175417
+ `Invalid e2e test file: ${describeUnknownKeys(unknownTop, topKeys2)} \u2014 allowed top-level keys: ${topKeys2.join(", ")}`,
174752
175418
  {
174753
175419
  error_code: FAILURE_CODES.FLOW_FILE_INVALID,
174754
175420
  failure_stage: "flow_file_parse",