The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Cache native tab text measurements during activity animation (#560)
Dee908430f08d9b
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 29368feba..02ed5677d 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -2479,13 +2479,13 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati}}private var indicatorWidth: CGFloat {- min(72, max(activityLabel == nil ? 0 : Self.activityWidth, shortcutLabel?.size().width ?? 0))+ min(72, max(activityLabel == nil ? 0 : Self.activityWidth, shortcutLayout?.size.width ?? 0))}private var reservedIndicatorSpace: CGFloat { indicatorWidth == 0 ? 0 : indicatorWidth + Self.gap }private var activitySpace: CGFloat {(activityMark?.isEmpty ?? true) && !displaysShortcut ? 0 : reservedIndicatorSpace}- private var naturalTitleWidth: CGFloat { max(label.size().width, emphasizedLabel.size().width) }+ private var naturalTitleWidth: CGFloat { max(labelLayout.size.width, emphasizedLabelLayout.size.width) }var minimumWidth: CGFloat { Self.contentInset * 2 + reservedIndicatorSpace + 16 }var preferredWidth: CGFloat {min(260, max(112, ceil(naturalTitleWidth + reservedIndicatorSpace + Self.contentInset * 2)))@@ -2538,8 +2538,21 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidativar labelFont = NSFont.systemFont(ofSize: 13, weight: .regular) {didSet { if oldValue != labelFont { invalidateLabel() } }}- private var cachedLabel: NSAttributedString?- private var cachedEmphasizedLabel: NSAttributedString?+ // Animation only changes the activity mark. Keep the three bounded text+ // measurements with their attributed strings until label inputs change;+ // AppKit's size() otherwise repeats text layout throughout each dirty-rect+ // calculation and paint, even while Command hints are not being displayed.+ private struct MeasuredLabel {+ let text: NSAttributedString+ let size: NSSize+ init(_ text: NSAttributedString) {+ self.text = text+ size = text.size()+ }+ }+ private var cachedLabel: MeasuredLabel?+ private var cachedEmphasizedLabel: MeasuredLabel?+ private var cachedShortcutLabel: MeasuredLabel?var actionsEnabled = true {didSet {selectButton.isEnabled = actionsEnabled@@ -2595,7 +2608,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiy: contentCenterY - Self.accessorySide / 2, width: min(Self.accessorySide, bounds.width), height: Self.accessorySide)let fullName = name.trimmingCharacters(in: .whitespacesAndNewlines)var hints: [String] = []- if max(label.size().width, emphasizedLabel.size().width) > titleRect.width { hints.append(displayLabel) }+ if naturalTitleWidth > titleRect.width { hints.append(displayLabel) }if !fullName.isEmpty && fullName != displayLabel { hints.append(name) }if let activityLabel { hints.append(activityLabel) }toolTip = hints.isEmpty ? nil : hints.joined(separator: "\n")@@ -2617,44 +2630,52 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatineedsDisplay = truehoverChanged?()}- private var displaysShortcut: Bool { actionsEnabled && showsShortcutHint && shortcutLabel != nil }+ private var displaysShortcut: Bool { actionsEnabled && showsShortcutHint && shortcutHint?.isEmpty == false }private func updateAccessoryVisibility() {closeButton.isHidden = !isHovered}private func invalidateLabel() {cachedLabel = nilcachedEmphasizedLabel = nil+ cachedShortcutLabel = nilupdateAccessoryVisibility()needsDisplay = trueneedsLayout = true}- private var label: NSAttributedString {+ private var label: NSAttributedString { labelLayout.text }+ private var emphasizedLabel: NSAttributedString { emphasizedLabelLayout.text }+ private var shortcutLabel: NSAttributedString? { shortcutLayout?.text }+ private var labelLayout: MeasuredLabel {if let cachedLabel { return cachedLabel }let paragraph = NSMutableParagraphStyle()paragraph.lineBreakMode = .byTruncatingTailparagraph.alignment = .center- let label = NSAttributedString(string: displayLabel,+ let label = MeasuredLabel(NSAttributedString(string: displayLabel,attributes: [.font: labelFont,- .foregroundColor: foreground, .paragraphStyle: paragraph])+ .foregroundColor: foreground, .paragraphStyle: paragraph]))cachedLabel = labelreturn label}- private var emphasizedLabel: NSAttributedString {+ private var emphasizedLabelLayout: MeasuredLabel {if let cachedEmphasizedLabel { return cachedEmphasizedLabel }let emphasized = NSMutableAttributedString(attributedString: label)emphasized.addAttribute(.font, value: NSFont.systemFont(ofSize: labelFont.pointSize, weight: .medium),range: NSRange(location: 0, length: emphasized.length))- cachedEmphasizedLabel = emphasized- return emphasized+ let measured = MeasuredLabel(emphasized)+ cachedEmphasizedLabel = measured+ return measured}- private var shortcutLabel: NSAttributedString? {+ private var shortcutLayout: MeasuredLabel? {guard let shortcutHint, !shortcutHint.isEmpty else { return nil }+ if let cachedShortcutLabel { return cachedShortcutLabel }let paragraph = NSMutableParagraphStyle()paragraph.alignment = .centerparagraph.lineBreakMode = .byTruncatingTail- return NSAttributedString(string: shortcutHint, attributes: [+ let measured = MeasuredLabel(NSAttributedString(string: shortcutHint, attributes: [.font: NSFont.systemFont(ofSize: 12, weight: .regular),- .foregroundColor: foreground.withAlphaComponent(0.75), .paragraphStyle: paragraph])+ .foregroundColor: foreground.withAlphaComponent(0.75), .paragraphStyle: paragraph]))+ cachedShortcutLabel = measured+ return measured}private var tabShape: NSBezierPath {let path = NSBezierPath()@@ -2702,10 +2723,10 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatifocus.lineWidth = 1.5focus.stroke()}- let text = selected ? emphasizedLabel : label+ let text = selected ? emphasizedLabelLayout : labelLayoutif bounds.width >= minimumWidth {- text.draw(in: NSRect(x: titleRect.minX, y: contentCenterY - text.size().height / 2,- width: titleRect.width, height: text.size().height))+ text.text.draw(in: NSRect(x: titleRect.minX, y: contentCenterY - text.size.height / 2,+ width: titleRect.width, height: text.size.height))}if !displaysShortcut, let activityMark {NSGraphicsContext.saveGraphicsState()@@ -2715,9 +2736,9 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidaticolor: activity?.color ?? .systemOrange)NSGraphicsContext.restoreGraphicsState()}- if displaysShortcut, let shortcut = shortcutLabel {- shortcut.draw(in: NSRect(x: indicatorRect.minX, y: contentCenterY - shortcut.size().height / 2,- width: indicatorRect.width, height: shortcut.size().height))+ if displaysShortcut, let shortcut = shortcutLayout {+ shortcut.text.draw(in: NSRect(x: indicatorRect.minX, y: contentCenterY - shortcut.size.height / 2,+ width: indicatorRect.width, height: shortcut.size.height))}}// Overflowed tabs might not be drawn. Their names and selection still needdiff --git a/desktop/test/benchmarks/terminal_hidden_protocol_benchmark.dart b/desktop/test/benchmarks/terminal_hidden_protocol_benchmark.dartnew file mode 100644index 000000000..156a173a1--- /dev/null+++ b/desktop/test/benchmarks/terminal_hidden_protocol_benchmark.dart@@ -0,0 +1,143 @@+// Diagnostic workload: protocol decoding, hidden terminal parsing, and any+// resulting Flutter work. This is headless Debug, not whole-app energy.+import 'dart:convert';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:xterm/xterm.dart';++import '../support/cpu_profile.dart';+import '../swarm_screen_test.dart' show mount;+import '../swarm_state_test.dart' show createApp;+import 'swarm_benchmark.dart' show distribution;++void main() {+ for (final count in [16, 48]) {+ testWidgets('$count hidden terminals receiving protocol output', (+ tester,+ ) async {+ final app = createApp();+ final sessions = <TerminalSession>[];+ final sequences = <int>[];+ var inputCount = 0;+ for (var i = 0; i < count; i++) {+ if (i > 0 && i % 4 == 0) app.newSwarm();+ final session =+ TerminalSession(+ machineId: 'm',+ agentId: 'a$i',+ agentName: 'Session $i',+ engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (_) async {+ inputCount++;+ return true;+ },+ )+ ..streamId =+ '00000000-0000-4000-8000-${(i + 1).toString().padLeft(12, '0')}';+ await session.handleBinary(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.keyframe,+ streamId: session.streamId!,+ seq: 0,+ bytes: utf8.encode(+ List.generate(1000, (line) => 'History line $line\r\n').join(),+ ),+ compressed: false,+ cols: 120,+ rows: 30,+ ),+ );+ sessions.add(session);+ sequences.add(1);+ app.adoptSessionForTest(session);+ }+ await mount(tester, app);+ for (final tab in app.swarms.toList()) {+ app.selectSwarm(tab.id);+ await tester.pump();+ }+ app.newSwarm();+ await tester.pumpAndSettle();+ final views = tester+ .stateList<TerminalViewState>(+ find.byType(TerminalView, skipOffstage: false),+ )+ .toList();+ expect(views, hasLength(count));+ expect(find.byType(TerminalView), findsNothing);+ expect(app.panes, isEmpty);+ final output = utf8.encode(+ '\x1b7\x1b[H${List.generate(8, (row) => '\x1b[2K\x1b[32mAgent row $row: ${'x' * 80}\x1b[0m\r\n').join()}\x1b8',+ );+ Future<void> burst() async {+ for (var i = 0; i < count; i++) {+ final frame = TerminalBinaryFrame(+ kind: TerminalBinaryKind.output,+ streamId: sessions[i].streamId!,+ seq: sequences[i]++,+ bytes: output,+ compressed: false,+ );+ await app.handleTerminalBinaryForTest(+ 'm',+ encodeTerminalLocal(frame)!,+ );+ }+ }++ for (var i = 0; i < 20; i++) {+ await burst();+ await tester.pump(const Duration(milliseconds: 50));+ }+ final profilePath = Platform.environment['HARNESS_HIDDEN_CPU_PROFILE'];+ final profile = profilePath == null+ ? null+ : await tester.runAsync(BenchmarkCpuProfile.start);+ if (profile != null) {+ addTearDown(() => tester.runAsync(profile.close));+ }+ final samples = <int>[];+ var scheduledByOutput = 0;+ for (var sample = 0; sample < 300; sample++) {+ final watch = Stopwatch()..start();+ await burst();+ if (tester.binding.hasScheduledFrame) scheduledByOutput++;+ await tester.pump(const Duration(milliseconds: 50));+ samples.add(watch.elapsedMicroseconds);+ }+ if (profile != null) {+ await tester.runAsync(() => profile.save('$profilePath-$count.json'));+ }+ final rebuilds = <String, int>{};+ debugOnRebuildDirtyWidget = (element, _) {+ final type = element.widget.runtimeType.toString();+ rebuilds.update(type, (value) => value + 1, ifAbsent: () => 1);+ };+ try {+ await burst();+ await tester.pump(const Duration(milliseconds: 50));+ } finally {+ debugOnRebuildDirtyWidget = null;+ }+ expect(inputCount, 0);+ expect(+ views.where((view) => view.renderTerminal.debugNeedsLayout),+ isEmpty,+ );+ expect(+ sessions.every((s) => s.status == TerminalSessionStatus.controlling),+ isTrue,+ );+ debugPrint(+ 'HIDDEN_PROTOCOL_BENCH ${jsonEncode({'kind': 'headless_debug', 'hiddenTerminals': count, 'bytesPerBurst': output.length * count, 'samples': samples.length, 'simulatedBurstIntervalMs': 50, 'scheduledFrameBeforePump': scheduledByOutput, 'burstAndPump': distribution(samples), 'rebuildsOnSeparateBurst': rebuilds})}',+ );+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+ }+}diff --git a/desktop/tool/check_swarm_titlebar.sh b/desktop/tool/check_swarm_titlebar.shindex 7da55e29b..f5ccf13d4 100644--- a/desktop/tool/check_swarm_titlebar.sh+++ b/desktop/tool/check_swarm_titlebar.sh@@ -24,6 +24,10 @@ fiif [[ "${2:-}" == "--history-performance" ]]; thenoptimization=(-O)fi+if [[ "${2:-}" == "--tab-performance" ]]; then+ check_source="$desktop_dir/tool/tab_activity_benchmark.swift"+ optimization=(-O)+fiif [[ "${2:-}" == "--window-zoom" ]]; thencheck_source="$desktop_dir/tool/window_zoom_checks.swift"fidiff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex 6cd1be135..9eddcffd6 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -116,6 +116,88 @@ private extension SwarmTabStrip {}private extension SwarmTabButton {+ func checkLabelMeasurementChanges() throws {+ // Reuse one populated tab through each single-property change. Compare it+ // with a newly constructed tab so an unrelated invalidation cannot hide+ // a stale width, stale shortcut, old font, or old foreground color.+ func compareWithFresh(_ reason: String) throws {+ let fresh = SwarmTabButton(id: "fresh-label-check")+ fresh.name = name+ fresh.displayLabel = displayLabel+ fresh.shortcutHint = shortcutHint+ fresh.foreground = foreground+ fresh.labelFont = labelFont+ fresh.selected = selected+ fresh.attention = attention+ fresh.activity = activity+ fresh.activityFrame = activityFrame+ fresh.showsShortcutHint = showsShortcutHint+ fresh.actionsEnabled = actionsEnabled+ fresh.frame = frame+ layoutSubtreeIfNeeded()+ fresh.layoutSubtreeIfNeeded()+ try checkTitlebar(naturalTitleWidth == max(label.size().width, emphasizedLabel.size().width),+ "\(reason): measured title matches AppKit's actual text")+ try checkTitlebar(titleRect == fresh.titleRect && indicatorRect == fresh.indicatorRect &&+ preferredWidth == fresh.preferredWidth && minimumWidth == fresh.minimumWidth,+ "\(reason): retained and fresh tab geometry agree")+ try checkTitlebar(toolTip == fresh.toolTip && renderedPixels() == fresh.renderedPixels(),+ "\(reason): retained and fresh tab pixels and tooltip agree")+ }+ frame = NSRect(x: 0, y: 0, width: 230, height: 40)+ displayLabel = "desktop"+ shortcutHint = "⌘1"+ activity = HarnessNativeActivity(["mark": "⠋", "label": "Working", "working": true,+ "color": Int64(0xff64d2ff)])+ try compareWithFresh("Initial populated tab")+ for title in ["a-very-long-project-name-that-truncates", "", "设备 日本語", "🧑🏽💻 café مرحبا", "desktop"] {+ displayLabel = title+ try compareWithFresh("Rename displayed title")+ }+ for font in [NSFont.systemFont(ofSize: 20), NSFont.monospacedSystemFont(ofSize: 36, weight: .regular),+ NSFont.systemFont(ofSize: 13)] {+ labelFont = font+ try compareWithFresh("Change font")+ }+ for hint in ["⌃⌥⌘R", nil, "", "⌘8"] as [String?] {+ shortcutHint = hint+ try compareWithFresh("Remap or remove shortcut")+ }+ for color in [NSColor.systemRed, NSColor.black, NSColor.white] {+ foreground = color+ try compareWithFresh("Change foreground")+ }+ for active in [true, false] {+ selected = active+ try compareWithFresh("Change selected weight")+ }+ for tick in 0..<10 {+ activityFrame = tick+ try compareWithFresh("Animate frame \(tick)")+ }+ for shown in [true, false, true] {+ showsShortcutHint = shown+ try compareWithFresh("Show or hide Command hints")+ }+ for enabled in [false, true] {+ actionsEnabled = enabled+ try compareWithFresh("Enter or leave a modal")+ }+ activity = nil+ try compareWithFresh("Remove activity")+ for needsInput in [true, false] {+ attention = needsInput+ try compareWithFresh("Change legacy attention")+ }+ for width in [CGFloat(28), 56, 125, 400] {+ frame.size.width = width+ needsLayout = true+ try compareWithFresh("Resize tab to \(width)")+ }+ name = "Renamed full title"+ try compareWithFresh("Rename full tooltip")+ }+func checkActivityDrawing(states: [(String, String)]) throws {func payload(_ mark: String, _ label: String) -> [String: Any] {["mark": mark, "label": label, "color": Int64(0xff64d2ff)]@@ -2466,6 +2548,7 @@ do {try strip.checkTopActions()try checkIconTooltipTracking()try strip.checkActivityMarks()+ try SwarmTabButton(id: "label-measurements").checkLabelMeasurementChanges()try SwarmTabButton(id: "close-shortcuts").checkHoverCloseAndShortcutHints()try strip.checkTabPresentationAndCapture()try SwarmTabButton(id: "hover-fixture").checkHoverStyleAndTooltips()diff --git a/desktop/tool/tab_activity_benchmark.swift b/desktop/tool/tab_activity_benchmark.swiftnew file mode 100644index 000000000..dea633ae0--- /dev/null+++ b/desktop/tool/tab_activity_benchmark.swift@@ -0,0 +1,69 @@+// Appended to the actual native source by check_swarm_titlebar.sh.+// No Flutter engine, window, timer, connection, or saved workspace is opened.+// Measures eight tabs' geometry and offscreen activity drawing, not app energy.+private extension SwarmTabButton {+ func activityGeometryForBenchmark(_ tick: Int) -> Double {+ activityFrame = tick % 10+ return Double(activityRect.minX + activityRect.width + preferredWidth)+ }+}++private func tabBenchmarkDistribution(_ values: [Double]) -> [String: Double] {+ let sorted = values.sorted()+ return ["medianMs": sorted[sorted.count / 2],+ "minMs": sorted[0], "maxMs": sorted.last!]+}++let tabBenchmarkApp = NSApplication.shared+tabBenchmarkApp.setActivationPolicy(.prohibited)+tabBenchmarkApp.appearance = NSAppearance(named: .darkAqua)+private let tabBenchmarkViews = (0..<8).map { index -> SwarmTabButton in+ let tab = SwarmTabButton(id: "fixture-\(index)")+ tab.name = ["desktop office", "desktop m2", "device", "tui", "swarm", "daemons", "growth", "New Tab"][index]+ tab.displayLabel = tab.name+ tab.shortcutHint = "⌘\(index + 1)"+ tab.activity = HarnessNativeActivity(["mark": "⠋", "label": "Working",+ "working": true, "color": Int64(0xff64d2ff)])+ tab.frame = NSRect(x: 0, y: 0, width: tab.preferredWidth, height: 40)+ tab.layoutSubtreeIfNeeded()+ return tab+}+let tabBenchmarkBitmap = NSBitmapImageRep(bitmapDataPlanes: nil,+ pixelsWide: 280, pixelsHigh: 40, bitsPerSample: 8, samplesPerPixel: 4,+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,+ bytesPerRow: 0, bitsPerPixel: 0)!+var tabBenchmarkChecksum = 0.0+var tabBenchmarkResults: [String: Any] = [:]+for drawing in [false, true] {+ let frames = drawing ? 80 : 400+ var observations: [Double] = []+ for sample in -2..<9 {+ let start = ProcessInfo.processInfo.systemUptime+ autoreleasepool {+ if drawing {+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: tabBenchmarkBitmap)+ }+ defer { if drawing { NSGraphicsContext.restoreGraphicsState() } }+ for tick in 0..<frames {+ for tab in tabBenchmarkViews {+ tabBenchmarkChecksum += tab.activityGeometryForBenchmark(tick)+ if drawing { tab.draw(tab.bounds) }+ }+ }+ }+ if sample >= 0 {+ observations.append((ProcessInfo.processInfo.systemUptime - start) * 1000)+ }+ }+ tabBenchmarkResults[drawing ? "offscreenDrawing" : "geometry"] = [+ "framesPerSample": frames, "tabsPerFrame": tabBenchmarkViews.count,+ "samplesMs": observations, "distribution": tabBenchmarkDistribution(observations),+ ]+}+precondition(tabBenchmarkApp.windows.isEmpty)+tabBenchmarkResults["kind"] = "native_optimized_geometry_and_offscreen_drawing"+tabBenchmarkResults["checksum"] = tabBenchmarkChecksum+tabBenchmarkResults["os"] = ProcessInfo.processInfo.operatingSystemVersionString+let tabBenchmarkData = try JSONSerialization.data(withJSONObject: tabBenchmarkResults, options: [.sortedKeys])+print(String(data: tabBenchmarkData, encoding: .utf8)!)diff --git a/docs/performance/2026-10-01-native-tab-label-metrics.json b/docs/performance/2026-10-01-native-tab-label-metrics.jsonnew file mode 100644index 000000000..da6e8265c--- /dev/null+++ b/docs/performance/2026-10-01-native-tab-label-metrics.json@@ -0,0 +1,105 @@+{+ "kind": "native_optimized_geometry_and_offscreen_drawing",+ "date": "2026-10-01",+ "baselineRevision": "24128bec34cf24d83f18b6d93f1e20801eac5ca0",+ "baselineSourceSha256": "40cfb9d3063bbf5c79cbfca91fd31245170fc3fe374f96dda01f0e404ff3461a",+ "candidateSourceSha256": "4f08da3ef32b69041b970051a608f536f4a6162862f708dfc1aca8920a75f41a",+ "warmupsPerWorkload": 2,+ "measuredSamplesPerWorkload": 9,+ "before": {+ "checksum": 11472865.325174332,+ "geometry": {+ "distribution": {+ "maxMs": 1029.9154999956954,+ "medianMs": 505.5080416641431,+ "minMs": 500.4567500000121+ },+ "framesPerSample": 400,+ "samplesMs": [+ 508.55895833228715,+ 504.4144999992568,+ 505.5080416641431,+ 503.64900000568014,+ 1029.9154999956954,+ 635.2457083266927,+ 500.4567500000121,+ 500.9061666642083,+ 506.6379583440721+ ],+ "tabsPerFrame": 8+ },+ "kind": "native_optimized_geometry_and_offscreen_drawing",+ "offscreenDrawing": {+ "distribution": {+ "maxMs": 268.38179166952614,+ "medianMs": 266.2456249963725,+ "minMs": 261.26520833349787+ },+ "framesPerSample": 80,+ "samplesMs": [+ 268.38179166952614,+ 267.659958335571,+ 268.35870833019726,+ 266.83745832997374,+ 263.0457083287183,+ 261.26520833349787,+ 263.4036249946803,+ 266.2456249963725,+ 262.57270833593793+ ],+ "tabsPerFrame": 8+ },+ "os": "Version 26.6.2 (Build 25G83)"+ },+ "after": {+ "checksum": 11472865.325174332,+ "geometry": {+ "distribution": {+ "maxMs": 1.6524999955436215,+ "medianMs": 1.5353333292296156,+ "minMs": 1.463166656321846+ },+ "framesPerSample": 400,+ "samplesMs": [+ 1.6524999955436215,+ 1.6227916639763862,+ 1.574916677782312,+ 1.5979583258740604,+ 1.5343333361670375,+ 1.5353333292296156,+ 1.4855416666250676,+ 1.464666667743586,+ 1.463166656321846+ ],+ "tabsPerFrame": 8+ },+ "kind": "native_optimized_geometry_and_offscreen_drawing",+ "offscreenDrawing": {+ "distribution": {+ "maxMs": 28.966124998987652,+ "medianMs": 28.71466666692868,+ "minMs": 28.189249991555698+ },+ "framesPerSample": 80,+ "samplesMs": [+ 28.804791669244878,+ 28.71466666692868,+ 28.966124998987652,+ 28.88024999992922,+ 28.80879167059902,+ 28.67912499641534,+ 28.206416667671874,+ 28.506125003332272,+ 28.189249991555698+ ],+ "tabsPerFrame": 8+ },+ "os": "Version 26.6.2 (Build 25G83)"+ },+ "validation": {+ "nativeChecksBefore": 4544,+ "nativeChecksAfter": 4544,+ "byteIdenticalRenderedPngs": 28+ },+ "scope": "Eight synthetic native tabs. Geometry and offscreen drawing include production activity updates. No Flutter engine, real session, compositor/display timing, or whole-app energy measurement."+}diff --git a/docs/performance/2026-10-01-native-tab-label-metrics.md b/docs/performance/2026-10-01-native-tab-label-metrics.mdnew file mode 100644index 000000000..7ccd21612--- /dev/null+++ b/docs/performance/2026-10-01-native-tab-label-metrics.md@@ -0,0 +1,60 @@+# Native tab label measurements — October 1, 2026++A live macOS development-app sample showed repeated AppKit text measurement+inside `SwarmTabButton.indicatorWidth`, `reservedIndicatorSpace`, and tab geometry.+Each 100 ms activity tick reconstructed the shortcut attributed string and+remeasured it, along with unchanged title text, throughout geometry and drawing.++The tab now retains the regular title, emphasized title, and shortcut with their+measured sizes. Existing label invalidation clears all three on a name, font,+color, shortcut, selection, or activity change. The cache is bounded to three+labels per tab; animation frames reuse it. Animation cadence and visibility+rules, hit targets, text, colors, and terminal behavior are unchanged.++## Matched native component benchmark++The same fixture was compiled against the original and changed production+AppKit source with Swift `-O` on ARM64 macOS 26.6.2. Each workload uses eight+working tabs, two warmup batches, and nine measured batches. All observations,+including the slower baseline batch, are in the [raw results](2026-10-01-native-tab-label-metrics.json).++| Workload per batch | Before median | After median | Reduction |+| --- | ---: | ---: | ---: |+| 400 geometry/activity steps across eight tabs | 505.51 ms | 1.54 ms | 99.7% |+| 80 geometry/activity steps plus offscreen drawing across eight tabs | 266.25 ms | 28.71 ms | 89.2% |++These are component elapsed times, **not whole-app CPU, energy, or battery-life+savings**. The fixture does not start Flutter, connect to agents, display a+window, or include GPU presentation. The complete cause of the reported+whole-app CPU spike remains under investigation.++Reproduce from the repository root:++```sh+bash desktop/tool/check_swarm_titlebar.sh /path/to/flutter --tab-performance+```++## Validation++- 4,544 AppKit checks pass on both original and changed source, including actual+ hidden-window layout and native controls. No window is displayed.+- All 28 rendered PNGs captured by the activity fixture are byte-identical.+- A retained tab is compared with a fresh tab after each individual mutation:+ short/long/empty/Unicode titles, font changes, shortcut remapping/removal,+ foreground changes, selected weight, all ten activity frames, Command hints,+ modal availability, legacy attention, and narrow/wide bounds. Geometry,+ tooltips, and rendered pixels agree.+- The separate hidden-protocol diagnostic feeds 16 and 48 retained terminals+ through the production binary decoder and parser while New Tab is visible.+ Both cases pass with no input sent, no hidden renderer needing layout, and no+ widgets rebuilt by the separately observed output burst. The benchmark is+ headless Debug and cannot establish the connected app's native energy cost.++```sh+bash desktop/tool/check_swarm_titlebar.sh /path/to/flutter --window-layout+cd desktop+flutter test --no-pub --concurrency=1 test/benchmarks/terminal_hidden_protocol_benchmark.dart+```++Set `HARNESS_HIDDEN_CPU_PROFILE` to a temporary output prefix and add+`--enable-vmservice` to collect a Dart CPU profile of that synthetic workload.