forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatters.ts
More file actions
1620 lines (1407 loc) · 51.7 KB
/
Copy pathformatters.ts
File metadata and controls
1620 lines (1407 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Text formatters for CommandResult types.
* These functions convert structured JSON results into human-readable text output.
*/
import type {
StatusResult,
SessionContext,
WithContext,
FunctionExpandResult,
FunctionInfoResult,
FunctionAnnotateResult,
ViewRangeResult,
FilterStackResult,
ThreadInfoResult,
MarkerStackResult,
MarkerInfoResult,
ProfileInfoResult,
ThreadSamplesResult,
ThreadSamplesTopDownResult,
ThreadSamplesBottomUpResult,
ThreadMarkersResult,
ThreadFunctionsResult,
ThreadNetworkResult,
ThreadPageLoadResult,
NetworkPhaseTimings,
MarkerGroupData,
CallTreeNode,
InlineStatus,
FilterEntry,
SampleFilterSpec,
ProfileLogsResult,
ThreadSelectResult,
CounterSummary,
CounterListResult,
CounterInfoResult,
} from './protocol';
import { truncateFunctionName } from '../../src/profile-query/function-list';
import { describeSpec } from '../../src/profile-query/filter-stack';
import { formatTimestamp as formatDuration } from 'firefox-profiler/utils/format-numbers';
// Maximum display width for function names in call-tree and sample views.
const FUNC_NAME_WIDTH = 120;
/**
* Suffix appended to a function name to indicate inline status.
* Empty string if the frame is not inlined.
*/
function inlineSuffix(status: InlineStatus | undefined): string {
if (status === 'inlined') {
return ' (inl)';
}
if (status === 'divergent') {
return ' (inl?)';
}
return '';
}
const INLINE_LEGEND =
'Note: (inl) = inlined by the compiler into the nearest non-inlined ancestor above. ' +
'(inl?) = some calls were inlined by the compiler.';
/**
* Format a SessionContext as a compact header line.
* Shows current thread selection, zoom range, and full profile duration.
*/
export function formatContextHeader(
context: SessionContext,
activeFilters?: FilterEntry[],
ephemeralFilters?: SampleFilterSpec[]
): string {
// Thread info
let threadInfo = 'No thread selected';
if (context.selectedThreadHandle && context.selectedThreads.length > 0) {
if (context.selectedThreads.length === 1) {
const thread = context.selectedThreads[0];
threadInfo = `${context.selectedThreadHandle} (${thread.name})`;
} else {
const names = context.selectedThreads
.map((t: { name: string }) => t.name)
.join(', ');
threadInfo = `${context.selectedThreadHandle} (${names})`;
}
}
// View range info
const rootDuration = context.rootRange.end - context.rootRange.start;
let viewInfo = 'Full profile';
if (context.currentViewRange) {
const range = context.currentViewRange;
const rangeDuration = range.end - range.start;
viewInfo = `${range.startName}→${range.endName} (${formatDuration(rangeDuration)})`;
}
const fullInfo = formatDuration(rootDuration);
const totalFilterCount =
(activeFilters?.length ?? 0) + (ephemeralFilters?.length ?? 0);
const filterInfo =
totalFilterCount > 0 ? ` | Filters: ${totalFilterCount}` : '';
return `[Thread: ${threadInfo} | View: ${viewInfo} | Full: ${fullInfo}${filterInfo}]`;
}
/**
* Format a StatusResult as plain text.
*/
export function formatStatusResult(result: StatusResult): string {
let threadInfo = 'No thread selected';
if (result.selectedThreadHandle && result.selectedThreads.length > 0) {
if (result.selectedThreads.length === 1) {
const thread = result.selectedThreads[0];
threadInfo = `${result.selectedThreadHandle} (${thread.name})`;
} else {
const names = result.selectedThreads.map((t) => t.name).join(', ');
threadInfo = `${result.selectedThreadHandle} (${names})`;
}
}
let rangesInfo = 'Full profile';
if (result.viewRanges.length > 0) {
const rangeStrs = result.viewRanges.map((range) => {
return `${range.startName} to ${range.endName}`;
});
rangesInfo = rangeStrs.join(' > ');
}
const filterLines: string[] = [];
for (const stack of result.filterStacks) {
if (stack.filters.length === 0) {
continue;
}
filterLines.push(` Filters for ${stack.threadHandle}:`);
for (const f of stack.filters) {
filterLines.push(` ${f.index}. ${f.description}`);
}
}
const filterSection =
filterLines.length > 0
? '\n' + filterLines.join('\n')
: '\n Filters: none';
return `\
Session Status:
Selected thread: ${threadInfo}
View range: ${rangesInfo}${filterSection}`;
}
/**
* Format a FilterStackResult as plain text.
*/
export function formatFilterStackResult(result: FilterStackResult): string {
const lines: string[] = [];
if (result.message) {
lines.push(result.message);
}
if (result.filters.length === 0) {
lines.push(`No active filters for ${result.threadHandle}`);
} else {
lines.push(`Filters for ${result.threadHandle} (applied in order):`);
for (const f of result.filters) {
lines.push(` ${f.index}. ${f.description}`);
}
}
return lines.join('\n');
}
/**
* Format a FunctionExpandResult as plain text.
*/
export function formatFunctionExpandResult(
result: WithContext<FunctionExpandResult>
): string {
const contextHeader = formatContextHeader(result.context);
return `${contextHeader}
Function ${result.functionHandle}:
${result.fullName}`;
}
/**
* Format a FunctionInfoResult as plain text.
*/
export function formatFunctionInfoResult(
result: WithContext<FunctionInfoResult>
): string {
const contextHeader = formatContextHeader(result.context);
let output = `${contextHeader}
Function ${result.functionHandle}:
Full name: ${result.fullName}
Short name: ${result.name}
Is JS: ${result.isJS}
Relevant for JS: ${result.relevantForJS}`;
if (result.resource) {
output += `\n Resource: ${result.resource.name}`;
}
if (result.library) {
output += `\n Library: ${result.library.name}`;
output += `\n Library path: ${result.library.path}`;
if (result.library.debugName) {
output += `\n Debug name: ${result.library.debugName}`;
}
if (result.library.debugPath) {
output += `\n Debug path: ${result.library.debugPath}`;
}
if (result.library.breakpadId) {
output += `\n Breakpad ID: ${result.library.breakpadId}`;
}
}
return output;
}
/**
* Format a ViewRangeResult as plain text.
*/
export function formatViewRangeResult(result: ViewRangeResult): string {
// Start with the basic message
let output = result.message;
// For 'push' action, add enhanced information if available
if (result.action === 'push' && result.duration !== undefined) {
output += ` (duration: ${formatDuration(result.duration)})`;
// If this is a marker zoom, show marker details
if (result.markerInfo) {
output += `\n Zoomed to: Marker ${result.markerInfo.markerHandle} - ${result.markerInfo.markerName}`;
output += `\n Thread: ${result.markerInfo.threadHandle} (${result.markerInfo.threadName})`;
}
// Show zoom depth if available
if (result.zoomDepth !== undefined) {
output += `\n Zoom depth: ${result.zoomDepth}${result.zoomDepth > 1 ? ' (use "profiler-cli zoom pop" to go back)' : ''}`;
}
}
if (result.warning) {
output += `\nWarning: ${result.warning}`;
}
return output;
}
/**
* Format a ThreadInfoResult as plain text.
*/
export function formatThreadInfoResult(
result: WithContext<ThreadInfoResult>
): string {
const contextHeader = formatContextHeader(result.context);
const endedAtStr = result.endedAtName || 'still alive at end of recording';
let output = `${contextHeader}
Name: ${result.friendlyName}
TID: ${result.tid}
Created at: ${result.createdAtName}
Ended at: ${endedAtStr}
This thread contains ${result.sampleCount} samples and ${result.markerCount} markers.
CPU activity over time:`;
if (result.cpuActivity && result.cpuActivity.length > 0) {
for (const activity of result.cpuActivity) {
const indent = ' '.repeat(activity.depthLevel);
const duration = activity.endTime - activity.startTime;
const percentage =
duration > 0 ? Math.round((activity.cpuMs / duration) * 100) : 0;
output += `\n${indent}- ${percentage}% for ${activity.cpuMs.toFixed(1)}ms: [${activity.startTimeName} → ${activity.endTimeName}] (${activity.startTimeStr} - ${activity.endTimeStr})`;
}
} else {
output += '\nNo significant activity.';
}
return output;
}
/**
* Format a MarkerStackResult as plain text.
*/
export function formatMarkerStackResult(
result: WithContext<MarkerStackResult>
): string {
const contextHeader = formatContextHeader(result.context);
let output = `${contextHeader}
Stack trace for marker ${result.markerHandle}: ${result.markerName}\n`;
output += `Thread: ${result.threadHandle} (${result.friendlyThreadName})`;
if (!result.stack || result.stack.frames.length === 0) {
return output + '\n\n(This marker has no stack trace)';
}
if (result.stack.capturedAt !== undefined) {
const rootStart = result.context.rootRange.start;
output += `\nCaptured at: ${formatDuration(result.stack.capturedAt - rootStart)}\n`;
}
for (let i = 0; i < result.stack.frames.length; i++) {
const frame = result.stack.frames[i];
output += `\n [${i + 1}] ${frame.nameWithLibrary}`;
}
if (result.stack.truncated) {
output += '\n ... (truncated)';
}
return output;
}
/**
* Format a MarkerInfoResult as plain text.
*/
export function formatMarkerInfoResult(
result: WithContext<MarkerInfoResult>
): string {
const contextHeader = formatContextHeader(result.context);
let output = `${contextHeader}
Marker ${result.markerHandle}: ${result.name}`;
if (result.tooltipLabel) {
output += ` - ${result.tooltipLabel}`;
}
output += '\n\n';
// Basic info
output += `Type: ${result.markerType ?? 'None'}\n`;
output += `Category: ${result.category.name}\n`;
// Time and duration (relative to profile root start)
const rootStart = result.context.rootRange.start;
const startStr = formatDuration(result.start - rootStart);
if (result.end !== null) {
const endStr = formatDuration(result.end - rootStart);
const durationStr = formatDuration(result.duration!);
output += `Time: ${startStr} - ${endStr} (${durationStr})\n`;
} else {
output += `Time: ${startStr} (instant)\n`;
}
output += `Thread: ${result.threadHandle} (${result.friendlyThreadName})\n`;
// Marker data fields
if (result.fields && result.fields.length > 0) {
output += '\nFields:\n';
for (const field of result.fields) {
output += ` ${field.label}: ${field.formattedValue}\n`;
}
}
// Schema description
if (result.schema?.description) {
output += '\nDescription:\n';
output += ` ${result.schema.description}\n`;
}
// Stack trace (truncated to 20 frames)
if (result.stack && result.stack.frames.length > 0) {
output += '\nStack trace:\n';
if (result.stack.capturedAt !== undefined) {
output += ` Captured at: ${formatDuration(result.stack.capturedAt - rootStart)}\n`;
}
for (let i = 0; i < result.stack.frames.length; i++) {
const frame = result.stack.frames[i];
output += ` [${i + 1}] ${frame.nameWithLibrary}\n`;
}
if (result.stack.truncated) {
output += `\nUse 'profiler-cli marker stack ${result.markerHandle}' for the full stack trace.\n`;
}
}
return output;
}
/**
* Format a ProfileInfoResult as plain text.
*/
export function formatProfileInfoResult(
result: WithContext<ProfileInfoResult>
): string {
const contextHeader = formatContextHeader(result.context);
let output = `${contextHeader}
Name: ${result.name}\n`;
output += `Platform: ${result.platform}\n\n`;
output += `This profile contains ${result.threadCount} threads across ${result.processCount} processes.\n`;
if (result.processes.length === 0) {
output += '\n(CPU time information not available)';
return output;
}
let processesHeading: string;
if (result.searchQuery !== undefined) {
processesHeading = `Processes and threads matching '${result.searchQuery}':`;
} else if (result.showAll) {
processesHeading = 'All processes and threads by CPU usage:';
} else {
processesHeading = 'Top processes and threads by CPU usage:';
}
output += `\n${processesHeading}\n`;
for (const process of result.processes) {
// Format process timing information
let timingInfo = '';
if (process.startTime !== undefined && process.startTimeName) {
if (process.endTime !== null && process.endTimeName !== null) {
timingInfo = ` [${process.startTimeName} → ${process.endTimeName}]`;
} else {
timingInfo = ` [${process.startTimeName} → end]`;
}
}
const etld1Suffix = process.etld1 ? ` [${process.etld1}]` : '';
output += ` p-${process.processIndex}: ${process.name}${etld1Suffix} [pid ${process.pid}]${timingInfo} - ${process.cpuMs.toFixed(3)}ms\n`;
for (const thread of process.threads) {
output += ` ${thread.threadHandle}: ${thread.name} [tid ${thread.tid}] - ${thread.cpuMs.toFixed(3)}ms\n`;
}
if (process.remainingThreads) {
output += ` + ${process.remainingThreads.count} more threads with combined CPU time ${process.remainingThreads.combinedCpuMs.toFixed(3)}ms and max CPU time ${process.remainingThreads.maxCpuMs.toFixed(3)}ms (use --all to see all)\n`;
}
for (const counter of process.counters ?? []) {
output += ` ${counter.counterHandle}: ${counter.label}${formatCounterStats(counter)}\n`;
}
}
if (result.remainingProcesses) {
output += ` + ${result.remainingProcesses.count} more processes with combined CPU time ${result.remainingProcesses.combinedCpuMs.toFixed(3)}ms and max CPU time ${result.remainingProcesses.maxCpuMs.toFixed(3)}ms (use --all to see all)\n`;
}
output += '\nCPU activity over time:\n';
if (result.cpuActivity && result.cpuActivity.length > 0) {
for (const activity of result.cpuActivity) {
const indent = ' '.repeat(activity.depthLevel);
const duration = activity.endTime - activity.startTime;
const percentage =
duration > 0 ? Math.round((activity.cpuMs / duration) * 100) : 0;
output += `${indent}- ${percentage}% for ${activity.cpuMs.toFixed(1)}ms: [${activity.startTimeName} → ${activity.endTimeName}] (${activity.startTimeStr} - ${activity.endTimeStr})\n`;
}
} else {
output += 'No significant activity.\n';
}
return output;
}
function formatCounterStatInline(
stat: CounterSummary['stats'][number]
): string {
const value = stat.carbon
? `${stat.formattedValue} (${stat.carbon})`
: stat.formattedValue;
return `${stat.label}: ${value}`;
}
/** The ` - stat; stat [N samples]` trailer shared by counter list and profile info. */
function formatCounterStats(counter: CounterSummary): string {
const stats =
counter.stats.length > 0
? ` - ${counter.stats.map(formatCounterStatInline).join('; ')}`
: '';
return `${stats} [${counter.rangeSampleCount} samples]`;
}
function formatCounterSummaryLine(counter: CounterSummary): string {
return ` ${counter.counterHandle}: ${counter.label} (${counter.category})${formatCounterStats(counter)}`;
}
/**
* Format a CounterListResult as plain text.
*/
export function formatCounterListResult(
result: WithContext<CounterListResult>
): string {
const contextHeader = formatContextHeader(result.context);
if (result.counters.length === 0) {
return `${contextHeader}\n\nNo counters in this profile.`;
}
const lines = result.counters.map(formatCounterSummaryLine);
return `${contextHeader}\n\nCounters (${result.counters.length}):\n${lines.join('\n')}`;
}
/**
* Format a CounterInfoResult as plain text.
*/
export function formatCounterInfoResult(
result: WithContext<CounterInfoResult>
): string {
const contextHeader = formatContextHeader(result.context);
const lines = [
contextHeader,
'',
`Counter ${result.counterHandle}: ${result.label}`,
` Name: ${result.name}`,
` Category: ${result.category}`,
];
if (result.description) {
lines.push(` Description: ${result.description}`);
}
lines.push(` Unit: ${result.unit || '(none)'}`);
lines.push(` Graph type: ${result.graphType}`);
lines.push(
` Main thread: ${result.mainThreadHandle} (${result.mainThreadName})`
);
lines.push(
` Samples: ${result.sampleCount} total, ${result.rangeSampleCount} in current range`
);
if (result.rangeStart !== null && result.rangeEnd !== null) {
const zeroAt = result.context.rootRange.start;
lines.push(
` Time span: ${formatDuration(result.rangeStart - zeroAt)} → ${formatDuration(result.rangeEnd - zeroAt)}`
);
}
if (result.stats.length > 0) {
lines.push(' Stats (current range):');
for (const stat of result.stats) {
const value = stat.carbon
? `${stat.formattedValue} (${stat.carbon})`
: stat.formattedValue;
lines.push(` ${stat.label}: ${value}`);
}
}
return lines.join('\n');
}
/**
* Helper function to format a call tree node recursively.
*
* This formatter uses a "stack fragment" approach for single-child chains:
* - Root-level nodes always indent their children with tree symbols
* - Single-child continuations are rendered without tree symbols (as stack fragments)
* - Only nodes with multiple children use tree symbols to show branching
*/
function formatCallTreeNode(
node: CallTreeNode,
baseIndent: string,
useTreeSymbol: boolean,
isLastSibling: boolean,
depth: number,
lines: string[]
): void {
const totalPct = node.totalPercentage.toFixed(1);
const selfPct = node.selfPercentage.toFixed(1);
const displayName = truncateFunctionName(
node.nameWithLibrary,
FUNC_NAME_WIDTH
);
// Build the line prefix
let linePrefix: string;
if (useTreeSymbol) {
const symbol = isLastSibling ? '└─ ' : '├─ ';
linePrefix = baseIndent + symbol;
} else {
linePrefix = baseIndent;
}
// Add function handle prefix if available
const handlePrefix = node.functionHandle ? `${node.functionHandle}. ` : '';
const inlineMark = inlineSuffix(node.inlineStatus);
lines.push(
`${linePrefix}${handlePrefix}${displayName}${inlineMark} [total: ${totalPct}%, self: ${selfPct}%]`
);
// Handle children and truncation
const hasChildren = node.children && node.children.length > 0;
const hasTruncatedChildren = node.childrenTruncated;
if (hasChildren || hasTruncatedChildren) {
// Calculate the base indent for children
let childBaseIndent: string;
if (useTreeSymbol) {
// We used a tree symbol, so children need appropriate spine continuation
const spine = isLastSibling ? ' ' : '│ ';
childBaseIndent = baseIndent + spine;
} else {
// We didn't use a tree symbol (stack fragment), children keep the same base indent
childBaseIndent = baseIndent;
}
if (hasChildren) {
const hasMultipleChildren =
node.children.length > 1 || !!hasTruncatedChildren;
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
const isLast = i === node.children.length - 1 && !hasTruncatedChildren;
// Children use tree symbols if:
// - There are multiple children (branching), OR
// - We're at root level (depth 0) - root children always get tree symbols
const childUsesTreeSymbol = hasMultipleChildren || depth === 0;
formatCallTreeNode(
child,
childBaseIndent,
childUsesTreeSymbol,
isLast,
depth + 1,
lines
);
}
}
// Show combined elision info if children were omitted or depth limit reached
// Combine both types of elision into a single marker
if (hasTruncatedChildren) {
const truncPrefix = childBaseIndent + '└─ ';
const truncInfo = node.childrenTruncated!;
const combinedPct = truncInfo.combinedPercentage.toFixed(1);
const maxPct = truncInfo.maxPercentage.toFixed(1);
lines.push(
`${truncPrefix}... (${truncInfo.count} more children: combined ${combinedPct}%, max ${maxPct}%)`
);
}
}
}
/**
* Helper function to format a call tree.
*/
function formatCallTree(
tree: CallTreeNode,
title: string,
emptyMessage?: string
): string {
const lines: string[] = [`${title} Call Tree:`];
if (tree.hasInlinedFrames) {
lines.push(INLINE_LEGEND);
lines.push('');
}
// The root node is virtual, so format its children
if (tree.children && tree.children.length > 0) {
for (let i = 0; i < tree.children.length; i++) {
const child = tree.children[i];
const isLast = i === tree.children.length - 1;
// Root-level nodes don't use tree symbols (they are the starting points)
formatCallTreeNode(child, '', false, isLast, 0, lines);
}
} else if (emptyMessage) {
lines.push(emptyMessage);
}
return lines.join('\n');
}
function formatSamplesPreamble(result: {
context: SessionContext;
activeFilters?: FilterEntry[];
ephemeralFilters?: SampleFilterSpec[];
activeOnly?: boolean;
search?: string;
friendlyThreadName: string;
}): string {
const contextHeader = formatContextHeader(
result.context,
result.activeFilters,
result.ephemeralFilters
);
const activeOnlyNote = result.activeOnly
? 'Note: active samples only (idle excluded) — use --include-idle to include idle samples.\n\n'
: '';
const searchNote = result.search ? `Search: "${result.search}"\n\n` : '';
const filtersParts: string[] = [
...(result.activeFilters?.map((f) => `[${f.index}] ${f.description}`) ??
[]),
...(result.ephemeralFilters?.map((f) => `[~] ${describeSpec(f)}`) ?? []),
];
const filtersNote =
filtersParts.length > 0 ? `Filters: ${filtersParts.join(', ')}\n\n` : '';
return `${contextHeader}\n\nThread: ${result.friendlyThreadName}\n\n${activeOnlyNote}${searchNote}${filtersNote}`;
}
/**
* Format a ThreadSamplesResult as plain text.
*/
export function formatThreadSamplesResult(
result: WithContext<ThreadSamplesResult>
): string {
let output = formatSamplesPreamble(result);
if (result.search && result.topFunctionsByTotal.length === 0) {
output +=
`No samples matched --search "${result.search}".\n` +
'Tip: --search keeps samples with a matching frame anywhere in the stack.\n' +
' Use comma to require multiple terms (all must appear), e.g. --search "foo,bar".\n' +
' "|" is treated as a literal character, not OR.\n';
return output;
}
// Top functions by total time
output += 'Top Functions (by total time):\n';
output +=
' (For a call tree starting from these functions, use: profiler-cli thread samples-top-down)\n\n';
for (const func of result.topFunctionsByTotal) {
const totalCount = Math.round(func.totalSamples);
const totalPct = func.totalPercentage.toFixed(1);
const displayName = truncateFunctionName(
func.nameWithLibrary,
FUNC_NAME_WIDTH
);
output += ` ${func.functionHandle}. ${displayName} - total: ${totalCount} (${totalPct}%)\n`;
}
output += '\n';
// Top functions by self time
output += 'Top Functions (by self time):\n';
output +=
' (For a call tree showing what calls these functions, use: profiler-cli thread samples-bottom-up)\n\n';
for (const func of result.topFunctionsBySelf) {
const selfCount = Math.round(func.selfSamples);
const selfPct = func.selfPercentage.toFixed(1);
const displayName = truncateFunctionName(
func.nameWithLibrary,
FUNC_NAME_WIDTH
);
output += ` ${func.functionHandle}. ${displayName} - self: ${selfCount} (${selfPct}%)\n`;
}
output += '\n';
// Heaviest stack
const stack = result.heaviestStack;
output += `Heaviest stack (${stack.selfSamples.toFixed(1)} samples, ${stack.frameCount} frames):\n`;
if (stack.hasInlinedFrames) {
output += ` ${INLINE_LEGEND}\n\n`;
}
if (stack.frames.length === 0) {
output += ' (empty)\n';
} else if (stack.frameCount <= 200) {
// Show all frames
for (let i = 0; i < stack.frames.length; i++) {
output += formatHeaviestStackFrame(stack.frames[i], i);
}
} else {
// Show first 100
for (let i = 0; i < 100; i++) {
output += formatHeaviestStackFrame(stack.frames[i], i);
}
// Show placeholder for skipped frames
const skippedCount = stack.frameCount - 200;
output += ` ... (${skippedCount} frames skipped)\n`;
// Show last 100
for (let i = stack.frameCount - 100; i < stack.frameCount; i++) {
output += formatHeaviestStackFrame(stack.frames[i], i);
}
}
return output;
}
function formatHeaviestStackFrame(
frame: ThreadSamplesResult['heaviestStack']['frames'][number],
i: number
): string {
const displayName = truncateFunctionName(
frame.nameWithLibrary,
FUNC_NAME_WIDTH
);
const inlineMark = inlineSuffix(frame.inlineStatus);
const totalCount = Math.round(frame.totalSamples);
const totalPct = frame.totalPercentage.toFixed(1);
const selfCount = Math.round(frame.selfSamples);
const selfPct = frame.selfPercentage.toFixed(1);
return ` ${i + 1}. ${displayName}${inlineMark} - total: ${totalCount} (${totalPct}%), self: ${selfCount} (${selfPct}%)\n`;
}
/**
* Format a ThreadSamplesTopDownResult as plain text.
*/
export function formatThreadSamplesTopDownResult(
result: WithContext<ThreadSamplesTopDownResult>
): string {
let output = formatSamplesPreamble(result);
// Top-down call tree
const topDownEmpty = result.search
? `No samples matched --search "${result.search}".\n` +
'Tip: use comma to require multiple terms (all must appear), e.g. --search "foo,bar".\n' +
' "|" is treated as a literal character, not OR.'
: undefined;
output += formatCallTree(result.regularCallTree, 'Top-Down', topDownEmpty);
return output;
}
/**
* Format a ThreadSamplesBottomUpResult as plain text.
*/
export function formatThreadSamplesBottomUpResult(
result: WithContext<ThreadSamplesBottomUpResult>
): string {
let output = formatSamplesPreamble(result);
// Bottom-up call tree (inverted tree shows callers)
if (result.invertedCallTree) {
const bottomUpEmpty = result.search
? `No samples matched --search "${result.search}".\n` +
'Tip: use comma to require multiple terms (all must appear), e.g. --search "foo,bar".\n' +
' "|" is treated as a literal character, not OR.'
: undefined;
output += formatCallTree(
result.invertedCallTree,
'Bottom-Up',
bottomUpEmpty
);
} else {
output += 'Bottom-Up Call Tree:\n (unable to create bottom-up tree)';
}
return output;
}
/**
* Format a ThreadMarkersResult as plain text.
*/
export function formatThreadMarkersResult(
result: WithContext<ThreadMarkersResult>
): string {
const contextHeader = formatContextHeader(result.context);
const lines: string[] = [contextHeader, ''];
// Check if filters are active
const hasFilters = result.filters !== undefined;
const filterSuffix =
hasFilters && result.filteredMarkerCount !== result.totalMarkerCount
? ` (filtered from ${result.totalMarkerCount})`
: '';
lines.push(
`Markers in thread ${result.threadHandle} (${result.friendlyThreadName}) — ${result.filteredMarkerCount} markers${filterSuffix}`
);
lines.push('Legend: ✓ = has stack trace, ✗ = no stack trace\n');
if (result.filteredMarkerCount === 0) {
if (hasFilters) {
lines.push('No markers match the specified filters.');
} else {
lines.push('No markers in this thread.');
}
return lines.join('\n');
}
// Flat list mode: one row per marker in chronological order
if (result.flatMarkers) {
const rootStart = result.context.rootRange.start;
for (const m of result.flatMarkers) {
const stackIndicator = m.hasStack ? '✓' : '✗';
const startStr = `t=${formatDuration(m.start - rootStart)}`;
const durationStr =
m.duration !== undefined ? formatDuration(m.duration) : 'instant';
const labelSuffix = m.label !== m.name ? ` ${m.label}` : '';
lines.push(
` ${m.handle.padEnd(8)} ${m.name.padEnd(30)} ${startStr.padEnd(14)} ${durationStr.padEnd(10)} ${stackIndicator}${labelSuffix}`
);
}
return lines.join('\n');
}
// Handle custom grouping if present
if (result.customGroups && result.customGroups.length > 0) {
formatMarkerGroupsForDisplay(lines, result.customGroups, 0);
} else {
// Default aggregation by marker name
const W_STAT_NAME = 25;
const W_STAT_COUNT = 5;
lines.push('By Name (top 15):');
const topTypes = result.byType.slice(0, 15);
for (const stats of topTypes) {
let line = ` ${stats.markerName.padEnd(W_STAT_NAME)} ${stats.count.toString().padStart(W_STAT_COUNT)} markers`;
if (stats.durationStats) {
const { min, avg, max } = stats.durationStats;
line += ` (interval: min=${formatDuration(min)}, avg=${formatDuration(avg)}, max=${formatDuration(max)})`;
} else {
line += ' (instant)';
}
lines.push(line);
// Show top markers with handles (for easy inspection)
if (!stats.subGroups && stats.topMarkers.length > 0) {
const handleList = stats.topMarkers
.slice(0, 3)
.map((m) => {
const stackIndicator = m.hasStack ? '✓' : '✗';
const handleWithIndicator = `${m.handle} ${stackIndicator}`;
if (m.duration !== undefined) {
return `${handleWithIndicator} (${formatDuration(m.duration)})`;
}
return handleWithIndicator;
})
.join(', ');
lines.push(` Examples: ${handleList}`);
}
// Show sub-groups if present (from auto-grouping)
if (stats.subGroups && stats.subGroups.length > 0) {
if (stats.subGroupKey) {
lines.push(` Grouped by ${stats.subGroupKey}:`);
}
formatMarkerGroupsForDisplay(lines, stats.subGroups, 2);
}
}
if (result.byType.length > 15) {
lines.push(` ... (${result.byType.length - 15} more marker names)`);
}
lines.push('');
// Aggregate by category
lines.push('By Category:');
for (const stats of result.byCategory) {
lines.push(
` ${stats.categoryName.padEnd(W_STAT_NAME)} ${stats.count.toString().padStart(W_STAT_COUNT)} markers (${stats.percentage.toFixed(1)}%)`
);
}
lines.push('');
// Frequency analysis for top markers
lines.push('Frequency Analysis:');
const topRateTypes = result.byType
.filter((s) => s.rateStats && s.rateStats.markersPerSecond > 0)
.slice(0, 5);
for (const stats of topRateTypes) {
if (!stats.rateStats) {
continue;
}
const { markersPerSecond, minGap, avgGap, maxGap } = stats.rateStats;
lines.push(
` ${stats.markerName}: ${markersPerSecond.toFixed(1)} markers/sec (interval: min=${formatDuration(minGap)}, avg=${formatDuration(avgGap)}, max=${formatDuration(maxGap)})`
);
}
lines.push('');
}
lines.push(
'Use --search <term>, --category <name>, --min-duration <ms>, --max-duration <ms>, --has-stack, --limit <N>, --group-by <keys>, --auto-group, or --top-n <N> to filter/group markers, or m-<N> handles to inspect individual markers or zoom into their time range (profiler-cli zoom push m-<N>).'
);
return lines.join('\n');
}
/**
* Helper function to format marker groups hierarchically.
*/
function formatMarkerGroupsForDisplay(
lines: string[],
groups: MarkerGroupData[],
baseIndent: number
): void {
for (const group of groups) {
const indent = ' '.repeat(baseIndent);
let line = `${indent}${group.groupName}: ${group.count} markers`;
if (group.durationStats) {
const { avg, max } = group.durationStats;
line += ` (avg=${formatDuration(avg)}, max=${formatDuration(max)})`;
}
lines.push(line);
// Show top markers if no sub-groups
if (!group.subGroups && group.topMarkers.length > 0) {
const handleList = group.topMarkers
.slice(0, 3)
.map((m) => {
const stackIndicator = m.hasStack ? '✓' : '✗';
const handleWithIndicator = `${m.handle} ${stackIndicator}`;
if (m.duration !== undefined) {
return `${handleWithIndicator} (${formatDuration(m.duration)})`;
}
return handleWithIndicator;
})