// Per-design cost budget: every registered AppDesign must cost what Default // costs (tool/perf/README.md). Each scenario prints `BENCH design ...` lines // and fails when a design rebuilds, animates or composites more than Default: // - building a design's themes is cached: the same objects for the same // (design, brightness, font), and equal values when rebuilt; // - a host rebuild for an unrelated reason (a detached window's title, a // font notification) rebuilds no theme dependent and starts no theme // animation; // - scrolling a long transcript rebuilds and composites no more than // Default (saveLayer-style layers: opacity, backdrop filter, clips); // - switching designs back and forth leaves no listener behind. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/app.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; import 'package:pipelines_app/shell/destination.dart'; import 'package:pipelines_app/ui/theme/app_design.dart'; import 'package:pipelines_app/ui/theme/app_design_controller.dart'; import 'package:pipelines_app/ui/theme/app_font_controller.dart'; import 'package:pipelines_app/ui/theme/app_font_store.dart'; /// Exposes whether anything still listens. class _Designs extends AppDesignController { _Designs() : super(store: MemoryAppDesignStore()); bool get listened => hasListeners; } JsonMap _tool(String id, String status) => { 'type': 'tool', 'id': id, 'name': 'Bash', 'state': { 'status': status, 'input': {'command': 'go test ./internal/notes/...'}, 'content': [ {'type': 'text', 'text': 'ok notes 0.2s\nPASS'}, ], if (status == 'error') 'error': {'message': 'exit status 1'}, }, }; /// A long CLI-agent transcript: operator turns, tool calls and markdown. final List _rows = transcriptRows([ for (var i = 0; i < 60; i++) ...[ { 'id': 'u$i', 'role': 'user', 'parts': [ {'type': 'text', 'text': 'Step $i: fix the Windows paths in notes.'}, ], }, { 'id': 'a$i', 'role': 'assistant', 'parts': [ _tool('t$i-1', 'completed'), _tool('t$i-2', i % 4 == 0 ? 'error' : 'completed'), { 'type': 'text', 'text': 'Fixed **step $i**: `filepath.Join` now.\n\n' '- one\n- two\n\n```go\nreturn filepath.Join(root, name)\n```', }, ], }, ], ]); class _ThemeProbe extends StatelessWidget { const _ThemeProbe(); static int builds = 0; @override Widget build(BuildContext context) { Theme.of(context); builds++; return const SizedBox(); } } class _Rebuilds { int count = 0; void install() => debugOnRebuildDirtyWidget = (_, _) => count++; void uninstall() => debugOnRebuildDirtyWidget = null; } /// Layers that cost a saveLayer or a clip on every raster. Map _layers(WidgetTester tester) { final counts = {}; void visit(Layer layer) { final kind = switch (layer) { OpacityLayer() => 'opacity', BackdropFilterLayer() => 'backdrop', ImageFilterLayer() => 'imageFilter', ColorFilterLayer() => 'colorFilter', ShaderMaskLayer() => 'shaderMask', ClipPathLayer() => 'clipPath', ClipRRectLayer() => 'clipRRect', ClipRectLayer() => 'clipRect', _ => null, }; if (kind != null) counts.update(kind, (n) => n + 1, ifAbsent: () => 1); if (layer is ContainerLayer) { for ( var child = layer.firstChild; child != null; child = child.nextSibling ) { visit(child); } } } visit(tester.binding.renderViews.first.debugLayer!); return counts; } int _sum(Map m, [bool Function(String)? where]) => m.entries .where((e) => where == null || where(e.key)) .fold(0, (a, e) => a + e.value); void main() { final results = >{}; Future sizeView(WidgetTester tester) async { tester.view.physicalSize = const Size(900, 1000); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); } for (final design in AppDesign.values) { group(design.id, () { final row = results[design] = {}; test('themes are cached and value-equal', () { for (final family in [null, 'Inter']) { expect( design.light(fontFamily: family), same(design.light(fontFamily: family)), ); expect( design.dark(fontFamily: family), same(design.dark(fontFamily: family)), ); } // Rebuilt from scratch, a design's theme still equals the cached one, // so a host with its own copy never restarts a theme animation. expect(design.build(Brightness.dark), design.dark()); final watch = Stopwatch()..start(); for (var i = 0; i < 20; i++) { design.build(Brightness.light); design.build(Brightness.dark); } row['themeBuildUs'] = watch.elapsedMicroseconds ~/ 40; row['cachedLookupUs'] = () { final cached = Stopwatch()..start(); for (var i = 0; i < 1000; i++) { design.light(); design.dark(); } return cached.elapsedMicroseconds / 2000; }(); }); testWidgets('an unrelated host rebuild touches no theme dependent', ( tester, ) async { await sizeView(tester); final designs = _Designs(); await designs.select(design); final fonts = AppFontController( store: MemoryAppFontStore(), loader: (family, assets) async {}, ); final tick = ValueNotifier(0); // A const probe: only a theme change can make it rebuild. final bodies = { AppDestination.settings: (_) => const _ThemeProbe(), }; await tester.pumpWidget( ValueListenableBuilder( valueListenable: tick, builder: (_, _, _) => MyApp( fonts: fonts, designs: designs, destination: AppDestination.settings, destinationBodies: bodies, ), ), ); await tester.pumpAndSettle(); _ThemeProbe.builds = 0; var frames = 0; for (var i = 0; i < 10; i++) { tick.value++; frames += await tester.pumpAndSettle(); } final themed = _ThemeProbe.builds; row['unrelatedThemeRebuilds'] = themed; row['unrelatedFrames'] = frames; expect(themed, 0, reason: 'theme dependents rebuilt'); // One frame per rebuild; a theme animation would add ~12 each. expect(frames, lessThanOrEqualTo(10)); // Switching designs back and forth leaves nothing behind. var switchFrames = 0; for (var i = 0; i < 10; i++) { for (final other in AppDesign.values) { await designs.select(other); switchFrames += await tester.pumpAndSettle(); } await designs.select(design); switchFrames += await tester.pumpAndSettle(); } row['switchFramesPerSwitch'] = switchFrames / (10 * (AppDesign.values.length + 1)); await tester.pumpWidget(const SizedBox()); expect(designs.listened, isFalse, reason: 'a host kept listening'); tick.dispose(); }); testWidgets('scrolling a long transcript', (tester) async { await sizeView(tester); final controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( theme: design.light(), darkTheme: design.dark(), themeMode: ThemeMode.dark, home: Scaffold( body: ListView.builder( controller: controller, itemCount: _rows.length, itemBuilder: (_, i) => ChatMessageView(row: _rows[i]), ), ), ), ); await tester.pumpAndSettle(); final rebuilds = _Rebuilds()..install(); final layers = {}; var frames = 0; final watch = Stopwatch()..start(); for (var i = 0; i < 60; i++) { controller.jumpTo(controller.offset + 120); await tester.pump(); frames++; _layers(tester).forEach( (k, v) => layers.update(k, (n) => n + v, ifAbsent: () => v), ); } row['scrollFrameUs'] = watch.elapsedMicroseconds ~/ frames; rebuilds.uninstall(); row['scrollRebuildsPerFrame'] = rebuilds.count / frames; row['scrollLayersPerFrame'] = _sum(layers) / frames; row['scrollSaveLayersPerFrame'] = _sum(layers, (k) => !k.startsWith('clip')) / frames; // ignore: avoid_print print('BENCH ${design.id} layers $layers'); }); }); } tearDownAll(() { for (final MapEntry(key: design, value: row) in results.entries) { // ignore: avoid_print print('BENCH ${design.id.padRight(10)} $row'); } final base = results[AppDesign.standard]!; for (final MapEntry(key: design, value: row) in results.entries) { if (design == AppDesign.standard) continue; // Counts are deterministic: a design may not exceed Default's by more // than a quarter (its own rows are allowed to differ a little). for (final key in [ 'scrollRebuildsPerFrame', 'scrollLayersPerFrame', 'scrollSaveLayersPerFrame', 'switchFramesPerSwitch', ]) { final limit = base[key]! * 1.25 + 1; if (row[key]! > limit) { fail( '${design.id}: $key ${row[key]} over budget $limit ' '(Default ${base[key]})', ); } } } }); }