Designs: cache themes, value-equal tokens, and a per-design perf budget
A rebuilt Terminal theme never equalled the last one (AppDesignTokens, AnsiAccents and the tab indicator compared by identity), so any host rebuild (a detached window's title, a font notification) rebuilt every Theme.of dependent and ran MaterialApp's 200 ms theme animation. Themes are now cached per (design, brightness, font) and compare by value; chat colour seeded schemes are cached too. test/perf/design_bench_test.dart and tool/perf/design_bench.mjs check every registered AppDesign against Default (tool/perf/README.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,12 +16,17 @@ const double chatBarInactiveFade = 0.5;
|
||||
/// A Material tonal scheme seeded from [shade] in the page's brightness: its
|
||||
/// `onPrimaryContainer` labels the tinted bar and its `primary` (tone 40 on
|
||||
/// light, 80 on dark) draws the composer's focus ring.
|
||||
/// Cached per shade and brightness: deriving a tonal scheme is far dearer
|
||||
/// than a lookup, and the bar, header and composer ask on every build.
|
||||
ColorScheme chatSeededScheme(Color shade, {required bool dark}) =>
|
||||
ColorScheme.fromSeed(
|
||||
_seeded[(shade, dark)] ??= ColorScheme.fromSeed(
|
||||
seedColor: shade,
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
);
|
||||
|
||||
/// The chat palette's few shades in two brightnesses.
|
||||
final Map<(Color, bool), ColorScheme> _seeded = {};
|
||||
|
||||
/// A coloured chat's bar: the glass pieces' [fill] (translucent as every
|
||||
/// glass piece is, unless solid) and the [foreground] its labels, icons and
|
||||
/// controls draw in.
|
||||
|
||||
@@ -11,6 +11,11 @@ import 'terminal_theme.dart';
|
||||
///
|
||||
/// Adding a design means one more value here and its theme builder; the
|
||||
/// Settings picker lists [AppDesign.values].
|
||||
/// Every theme a design has built, by design, brightness and interface font.
|
||||
/// ThemeData is immutable; a handful of fonts and two brightnesses per design
|
||||
/// keep this small.
|
||||
final Map<(AppDesign, Brightness, String?), ThemeData> _themes = {};
|
||||
|
||||
enum AppDesign {
|
||||
/// The app's own Material look.
|
||||
standard('default', 'Default', 'The app’s Material look.'),
|
||||
@@ -44,16 +49,30 @@ enum AppDesign {
|
||||
|
||||
/// The design's light theme. [fontFamily] is the device's interface font;
|
||||
/// a design with its own family (Terminal's monospace) keeps that instead.
|
||||
ThemeData light({String? fontFamily}) => switch (this) {
|
||||
standard => appLightTheme(fontFamily: fontFamily),
|
||||
terminal => terminalTheme(Brightness.light),
|
||||
};
|
||||
/// Cached: the same object for the same design and font, so a host that
|
||||
/// rebuilds for another reason hands its subtree the same theme.
|
||||
ThemeData light({String? fontFamily}) =>
|
||||
_cached(Brightness.light, fontFamily);
|
||||
|
||||
/// The design's dark theme; see [light].
|
||||
ThemeData dark({String? fontFamily}) => switch (this) {
|
||||
standard => appDarkTheme(fontFamily: fontFamily),
|
||||
terminal => terminalTheme(Brightness.dark),
|
||||
};
|
||||
ThemeData dark({String? fontFamily}) => _cached(Brightness.dark, fontFamily);
|
||||
|
||||
ThemeData _cached(Brightness brightness, String? fontFamily) {
|
||||
final family = usesInterfaceFont ? fontFamily : null;
|
||||
return _themes[(this, brightness, family)] ??= build(
|
||||
brightness,
|
||||
fontFamily: family,
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the design's theme for [brightness] from scratch, uncached;
|
||||
/// [light] and [dark] keep the result.
|
||||
ThemeData build(Brightness brightness, {String? fontFamily}) =>
|
||||
switch ((this, brightness)) {
|
||||
(standard, Brightness.light) => appLightTheme(fontFamily: fontFamily),
|
||||
(standard, Brightness.dark) => appDarkTheme(fontFamily: fontFamily),
|
||||
(terminal, _) => terminalTheme(brightness),
|
||||
};
|
||||
|
||||
/// Whether the device's interface font applies under this design.
|
||||
bool get usesInterfaceFont => this == standard;
|
||||
|
||||
@@ -21,6 +21,19 @@ class AnsiAccents {
|
||||
final Color red;
|
||||
final Color magenta;
|
||||
final Color blue;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is AnsiAccents &&
|
||||
other.green == green &&
|
||||
other.cyan == cyan &&
|
||||
other.yellow == yellow &&
|
||||
other.red == red &&
|
||||
other.magenta == magenta &&
|
||||
other.blue == blue;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(green, cyan, yellow, red, magenta, blue);
|
||||
}
|
||||
|
||||
/// The design-specific facts widgets read instead of hard-coding one look:
|
||||
@@ -100,6 +113,23 @@ class AppDesignTokens extends ThemeExtension<AppDesignTokens> {
|
||||
promptGlyph: promptGlyph ?? this.promptGlyph,
|
||||
);
|
||||
|
||||
// Value equality keeps a rebuilt theme equal to the one it replaces, so
|
||||
// Theme dependents do not rebuild and MaterialApp starts no theme
|
||||
// animation when a host rebuilds for another reason.
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is AppDesignTokens &&
|
||||
other.design == design &&
|
||||
other.radius == radius &&
|
||||
other.flat == flat &&
|
||||
other.frame == frame &&
|
||||
other.ansi == ansi &&
|
||||
other.promptGlyph == promptGlyph;
|
||||
|
||||
@override
|
||||
int get hashCode =>
|
||||
Object.hash(design, radius, flat, frame, ansi, promptGlyph);
|
||||
|
||||
/// Designs switch whole: a theme animation snaps halfway rather than
|
||||
/// blending two designs' shapes.
|
||||
@override
|
||||
|
||||
@@ -12,6 +12,10 @@ import 'terminal_typography.dart';
|
||||
/// enough not to alias.
|
||||
const double terminalRadius = 3;
|
||||
|
||||
/// One tab indicator per brightness: [UnderlineTabIndicator] compares by
|
||||
/// identity, so a fresh one would make a rebuilt theme unequal to the last.
|
||||
final Map<Brightness, Decoration> _tabIndicators = {};
|
||||
|
||||
const BorderRadius _corners = BorderRadius.all(Radius.circular(terminalRadius));
|
||||
|
||||
/// The Terminal design's theme: the bundled monospace family everywhere,
|
||||
@@ -194,7 +198,7 @@ ThemeData terminalTheme(Brightness brightness) {
|
||||
tabBarTheme: TabBarThemeData(
|
||||
dividerColor: scheme.outlineVariant,
|
||||
indicatorSize: TabBarIndicatorSize.tab,
|
||||
indicator: UnderlineTabIndicator(
|
||||
indicator: _tabIndicators[brightness] ??= UnderlineTabIndicator(
|
||||
borderSide: BorderSide(color: scheme.primary, width: 2),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
// 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<JsonMap> _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<String, int> _layers(WidgetTester tester) {
|
||||
final counts = <String, int>{};
|
||||
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<String, int> 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 = <AppDesign, Map<String, num>>{};
|
||||
|
||||
Future<void> 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] = <String, num>{};
|
||||
|
||||
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, WidgetBuilder>{
|
||||
AppDestination.settings: (_) => const _ThemeProbe(),
|
||||
};
|
||||
await tester.pumpWidget(
|
||||
ValueListenableBuilder<int>(
|
||||
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 = <String, int>{};
|
||||
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]})',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import 'package:web/web.dart' as web;
|
||||
|
||||
import '../perf/backdrop_census.dart';
|
||||
import '../perf/chat_scroll_probe.dart';
|
||||
import '../perf/design_probe.dart';
|
||||
import '../perf/frame_log.dart';
|
||||
|
||||
/// The fixture options: the page URL's query.
|
||||
@@ -14,15 +15,12 @@ void installHostProbes(Map<String, String> params) {
|
||||
installBackdropCensus();
|
||||
installFrameLog(params);
|
||||
installChatScrollProbe();
|
||||
installDesignProbe(params);
|
||||
}
|
||||
|
||||
/// Moves the browser to [route] before the app reads its location.
|
||||
void openFixtureRoute(String route) {
|
||||
web.window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
route,
|
||||
);
|
||||
web.window.history.replaceState(null, '', route);
|
||||
}
|
||||
|
||||
/// The browser build's endpoint is its own page origin.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Performance tools
|
||||
|
||||
Benches and fixtures for the full-app fixture
|
||||
(`tool/search_selection_probe_entry.dart`) and widget-test benchmarks in
|
||||
`test/perf/`. Each script's header documents its own options.
|
||||
|
||||
## Design budget: run it for every new design
|
||||
|
||||
Every `AppDesign` (Settings → Design) must cost about what Default costs. A
|
||||
design agent runs both checks below before landing, and again after any change
|
||||
to a design's theme or to code that reads `AppDesignTokens`. Both pick up new
|
||||
`AppDesign` values on their own: no list to edit.
|
||||
|
||||
### 1. Widget-test budget (fast, deterministic, part of the test suite)
|
||||
|
||||
```sh
|
||||
tool/memwatch/full.sh test/perf/design_bench_test.dart
|
||||
```
|
||||
|
||||
Per design it checks and prints (`BENCH <design> {...}` in the log):
|
||||
|
||||
- `light()`/`dark()` return the same cached `ThemeData` for the same design and
|
||||
font, and a theme rebuilt from scratch (`AppDesign.build`) equals the cached
|
||||
one. A design whose theme holds an object without value equality (a
|
||||
`Decoration`, a `ThemeExtension` without `==`) fails here: hoist it to a
|
||||
constant or a per-brightness cache.
|
||||
- `unrelatedThemeRebuilds` / `unrelatedFrames`: ten host rebuilds that do not
|
||||
change the design rebuild no `Theme.of` dependent and start no theme
|
||||
animation (one frame each).
|
||||
- `switchFramesPerSwitch`: frames to settle a live design switch; after the
|
||||
switches, no listener is left on the design controller.
|
||||
- Scrolling a 120-row CLI transcript: `scrollRebuildsPerFrame`,
|
||||
`scrollLayersPerFrame` and `scrollSaveLayersPerFrame` (opacity, backdrop,
|
||||
image/colour filter and shader-mask layers), plus the layer kinds.
|
||||
- `themeBuildUs` (one uncached build) and `scrollFrameUs` are informational
|
||||
only (debug-mode times).
|
||||
|
||||
It fails when a design's counts exceed Default's by more than 25% + 1.
|
||||
|
||||
### 2. Browser frame budget (real renderer, wasm/skwasm)
|
||||
|
||||
```sh
|
||||
flutter build web --profile --wasm --no-web-resources-cdn --source-maps \
|
||||
--target tool/search_selection_probe_entry.dart --output build/design-profile
|
||||
CHROME_PATH=/usr/bin/chromium CAPTURE_ISOLATE=1 \
|
||||
node tool/perf/design_bench.mjs --build build/design-profile --out /tmp/design
|
||||
```
|
||||
|
||||
For every design (`window.__perfDesigns()`, `tool/perf/design_probe.dart`) it
|
||||
runs, at 1280x800 dark with `chats=3&msgs=200&cli=1&rich=1` or 560x900:
|
||||
|
||||
| scenario | what |
|
||||
| --- | --- |
|
||||
| `scroll` | wheel a 200-message transcript up and back |
|
||||
| `switch` | open chat 2, chat 3, chat 1 from the list |
|
||||
| `runs` | wheel 400 runs |
|
||||
| `graph` | open run 7's graph full screen and pan it |
|
||||
| `design` | switch live to every other design and back, 10 rounds (`window.__perfDesign(id)`), with JS heap growth after GC |
|
||||
|
||||
It prints median build/raster sums and maxima per design and exits 1 when a
|
||||
design's build or raster sum is above `--ratio` (1.35) x Default + `--slack`
|
||||
(25 ms), when live switches grow the heap by more than `--leak` (8) MB, or
|
||||
when a design makes an off-origin request (a font fallback fetch) that Default
|
||||
does not. `--designs paper` limits the run (Default is always included),
|
||||
`--only scroll,design` the scenarios, `--repeat` the repetitions (3), `--gpu`
|
||||
keeps WebGL. Headless Chrome without `--gpu` rasterises on the CPU: compare
|
||||
designs with each other, not with a device.
|
||||
|
||||
Click points assume the chat list's row positions at 1280x800 (chats at
|
||||
y=170/260/335); a design that changes list density a lot should check
|
||||
with `tool/capture` that those points still open the chats.
|
||||
|
||||
## Rules the budget enforces
|
||||
|
||||
- Build theme objects once: no `ThemeData`, `ColorScheme.fromSeed`, `TextStyle`
|
||||
sets or decorations per build. Keep design facts in `AppDesignTokens` and read
|
||||
them with `AppDesignTokens.of(context)` (a map lookup).
|
||||
- Paint glyphs and frames with `CustomPainter`s whose `shouldRepaint` compares
|
||||
their fields; no `saveLayer` (`Opacity` over content, `ShaderMask`,
|
||||
`ColorFiltered`) per row.
|
||||
- Blur only the app's bars and floating pieces, never list rows or bubbles:
|
||||
`GlassPill.blurSigma` (4) is the most a piece may use, one
|
||||
`BackdropFilter.grouped` per piece inside a `BackdropGroup`, and a solid
|
||||
fill under high contrast and flat designs.
|
||||
- Bundle every font a design needs (`pubspec.yaml` `fonts:` for always-used
|
||||
families, on-demand assets otherwise). A design may not add network font
|
||||
fetches; Default's own (Roboto and Noto Sans Symbols from fonts.gstatic.com,
|
||||
fetched by the web engine) are the baseline.
|
||||
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env node
|
||||
// Per-design frame budget over the full-app fixture (tool/perf/README.md).
|
||||
//
|
||||
// For every registered AppDesign (read from the build through
|
||||
// `window.__perfDesigns()`, tool/perf/design_probe.dart) it runs the same
|
||||
// scenarios, records Flutter's FrameTiming (tool/perf/frame_log.dart) and
|
||||
// compares each design's medians with Default's. It exits 1 when a design
|
||||
// goes over budget:
|
||||
// - build or raster sum of a scenario above `--ratio` x Default + `--slack` ms;
|
||||
// - a request leaving the loopback origin (a font fallback fetch) that the
|
||||
// design makes and Default does not (Default's own are listed as baseline);
|
||||
// - live design switches growing the JS heap by more than `--leak` MB.
|
||||
//
|
||||
// node tool/perf/design_bench.mjs --build build/design-profile --out /tmp/design \
|
||||
// [--repeat 3] [--only scroll,switch] [--designs default,terminal] [--gpu]
|
||||
//
|
||||
// Build the fixture in profile mode (readable names, real timings):
|
||||
// flutter build web --profile --wasm --no-web-resources-cdn --source-maps \
|
||||
// --target tool/search_selection_probe_entry.dart --output build/design-profile
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { parseArgs } from 'node:util';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { openBrowser } from '../capture/browser.mjs';
|
||||
import { serveBuild } from '../capture/serve.mjs';
|
||||
|
||||
const { values: opts } = parseArgs({
|
||||
options: {
|
||||
build: { type: 'string' }, out: { type: 'string' },
|
||||
repeat: { type: 'string', default: '3' }, only: { type: 'string' },
|
||||
designs: { type: 'string' }, gpu: { type: 'boolean' },
|
||||
ratio: { type: 'string', default: '1.35' }, slack: { type: 'string', default: '25' },
|
||||
switches: { type: 'string', default: '10' }, leak: { type: 'string', default: '8' },
|
||||
},
|
||||
});
|
||||
if (!opts.build || !opts.out) throw new Error('usage: --build <dir> --out <dir>');
|
||||
|
||||
// Desktop chat fixture: three chats of 200 messages each, with a CLI-agent
|
||||
// exchange (tool calls, glyph rows), the transcript beside its list.
|
||||
const CHAT = { size: '1280x800', route: '/chat/perf-chat-0', q: { chats: '3', msgs: '200', cli: '1', rich: '1' } };
|
||||
const SCENARIOS = [
|
||||
{ name: 'scroll', label: 'scroll a 200-message transcript', ...CHAT,
|
||||
act: [{ wheel: [860, 400, -240, 40] }, { wheel: [860, 400, 240, 20] }] },
|
||||
{ name: 'switch', label: 'switch chats', ...CHAT,
|
||||
act: [{ click: [300, 260] }, { click: [300, 335] }, { click: [300, 170] }] },
|
||||
{ name: 'runs', label: 'scroll 400 runs', size: '560x900', route: '/runs', q: { runs: '400' },
|
||||
act: [{ wheel: [280, 450, 240, 40] }] },
|
||||
{ name: 'graph', label: 'open and pan the run graph', size: '560x900', route: '/runs/7', q: { graph: '1' },
|
||||
act: [{ click: [512, 152] }, { drag: [280, 500, -200, -150] }] },
|
||||
{ name: 'design', label: 'switch designs live (to and back)', ...CHAT, live: true },
|
||||
];
|
||||
|
||||
const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] ?? 0; };
|
||||
const r1 = (x) => Math.round(x * 10) / 10;
|
||||
|
||||
const server = await serveBuild(opts.build);
|
||||
const browser = await openBrowser({ gpu: Boolean(opts.gpu) });
|
||||
const { send, on } = browser;
|
||||
const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value;
|
||||
let frames = [];
|
||||
let firstFrame = null;
|
||||
let offOrigin = new Set();
|
||||
const fetchesBy = {};
|
||||
const errors = [];
|
||||
on('Runtime.consoleAPICalled', (p) => {
|
||||
const text = p.args.map((a) => a.value ?? '').join(' ');
|
||||
if (text.startsWith('PERF_FRAME ')) frames.push(text.split(' ').slice(1).map(Number));
|
||||
else if (text.startsWith('PERF_FIRST_FRAME ')) firstFrame = Number(text.split(' ')[1]);
|
||||
else if (p.type === 'error') errors.push(text.slice(0, 200));
|
||||
});
|
||||
on('Network.requestWillBeSent', (p) => {
|
||||
const url = p.request.url;
|
||||
if (/^https?:/.test(url) && !url.startsWith(server.origin)) offOrigin.add(url);
|
||||
});
|
||||
|
||||
async function tap([x, y]) {
|
||||
for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) {
|
||||
await send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 });
|
||||
}
|
||||
}
|
||||
async function drag([x, y, dx, dy]) {
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
|
||||
await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
|
||||
for (let i = 1; i <= 40; i++) {
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: x + (dx * i) / 40, y: y + (dy * i) / 40, button: 'left', buttons: 1 });
|
||||
await delay(16);
|
||||
}
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: x + dx, y: y + dy, button: 'left', clickCount: 1 });
|
||||
}
|
||||
async function run(steps) {
|
||||
for (const step of steps ?? []) {
|
||||
if (step.click) { await tap(step.click); await delay(1000); }
|
||||
if (step.drag) { await drag(step.drag); await delay(400); }
|
||||
if (step.wheel) {
|
||||
const [x, y, deltaY, count] = step.wheel;
|
||||
for (let i = 0; i < count; i++) {
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x, y, deltaX: 0, deltaY });
|
||||
await delay(16);
|
||||
}
|
||||
await delay(400);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The engine hands timings over in batches; two late frames flush them.
|
||||
async function settle(ms = 1500) {
|
||||
await delay(ms);
|
||||
for (let i = 0; i < 2; i++) { await evaluate('window.__perfKick?.()'); await delay(250); }
|
||||
}
|
||||
async function heapMB() {
|
||||
await send('HeapProfiler.collectGarbage');
|
||||
const { metrics } = await send('Performance.getMetrics');
|
||||
return (metrics.find((m) => m.name === 'JSHeapUsedSize')?.value ?? 0) / 1048576;
|
||||
}
|
||||
|
||||
async function load(s, design) {
|
||||
const [w, h] = s.size.split('x').map(Number);
|
||||
await send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: false });
|
||||
const url = new URL('/', server.origin);
|
||||
url.searchParams.set('route', s.route);
|
||||
url.searchParams.set('theme', 'dark');
|
||||
url.searchParams.set('perf', '1');
|
||||
url.searchParams.set('design', design);
|
||||
for (const [k, v] of Object.entries(s.q ?? {})) url.searchParams.set(k, v);
|
||||
frames = []; firstFrame = null; offOrigin = new Set();
|
||||
await send('Page.navigate', { url: url.href });
|
||||
for (let i = 0; i < 300 && firstFrame === null; i++) await delay(50);
|
||||
await settle(2000);
|
||||
}
|
||||
|
||||
// One measured repetition of [s] under [design]: frame sums and maxima.
|
||||
async function measure(s, design, others) {
|
||||
await load(s, design);
|
||||
const start = frames.length;
|
||||
const out = { firstFrame };
|
||||
if (s.live) {
|
||||
// Each round switches to every other design and back to this one.
|
||||
const before = await heapMB();
|
||||
for (let i = 0; i < Number(opts.switches); i++) {
|
||||
for (const other of others) {
|
||||
await evaluate(`window.__perfDesign(${JSON.stringify(other)})`); await delay(350);
|
||||
await evaluate(`window.__perfDesign(${JSON.stringify(design)})`); await delay(350);
|
||||
}
|
||||
}
|
||||
await settle();
|
||||
out.switches = Number(opts.switches) * others.length * 2;
|
||||
out.heapGrowthMB = (await heapMB()) - before;
|
||||
} else {
|
||||
await run(s.act);
|
||||
await settle();
|
||||
}
|
||||
fetchesBy[design] ??= new Set();
|
||||
for (const url of offOrigin) fetchesBy[design].add(url.replace(/\?.*/, ''));
|
||||
const f = frames.slice(start).filter((x) => x[0] + x[1] > 300);
|
||||
const sum = (i) => f.reduce((a, x) => a + x[i], 0) / 1000;
|
||||
const max = (i) => f.reduce((a, x) => Math.max(a, x[i]), 0) / 1000;
|
||||
return { ...out, frames: f.length, buildSum: sum(0), buildMax: max(0), rasterSum: sum(1),
|
||||
rasterMax: max(1), over16: f.filter((x) => x[2] > 16667).length };
|
||||
}
|
||||
|
||||
await mkdir(opts.out, { recursive: true });
|
||||
const results = {};
|
||||
const failures = [];
|
||||
try {
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Network.enable');
|
||||
await send('Performance.enable');
|
||||
await send('Page.addScriptToEvaluateOnNewDocument', {
|
||||
source: 'try { localStorage.clear(); sessionStorage.clear(); } catch (_) {}',
|
||||
});
|
||||
await load(SCENARIOS[0], 'default');
|
||||
const registered = JSON.parse(await evaluate('window.__perfDesigns?.() ?? "[]"'));
|
||||
if (!registered.length) throw new Error('build has no window.__perfDesigns (rebuild the fixture with ?perf=1 support)');
|
||||
const designs = opts.designs ? opts.designs.split(',') : registered;
|
||||
if (designs[0] !== 'default') designs.unshift('default');
|
||||
console.log(`designs: ${designs.join(', ')} renderer: ${await evaluate(`(window._flutter_skwasmInstance ? 'skwasm' : 'canvaskit')`)}`);
|
||||
const only = opts.only?.split(',');
|
||||
for (const s of SCENARIOS.filter((s) => !only || only.includes(s.name))) {
|
||||
for (const design of designs) {
|
||||
const others = registered.filter((d) => d !== design);
|
||||
const reps = [];
|
||||
for (let rep = 0; rep < Number(opts.repeat); rep++) reps.push(await measure(s, design, others));
|
||||
const keys = Object.keys(reps[0]).filter((k) => typeof reps[0][k] === 'number');
|
||||
const row = Object.fromEntries(keys.map((k) => [k, r1(median(reps.map((r) => r[k])))]));
|
||||
(results[s.name] ??= {})[design] = row;
|
||||
console.log(`${s.name.padEnd(7)} ${design.padEnd(10)} ${JSON.stringify(row)}`);
|
||||
const base = results[s.name].default;
|
||||
if (design !== 'default' && base) {
|
||||
for (const key of ['buildSum', 'rasterSum']) {
|
||||
const limit = base[key] * Number(opts.ratio) + Number(opts.slack);
|
||||
if (row[key] > limit) failures.push(`${s.name}/${design}: ${key} ${row[key]} ms > ${r1(limit)} ms (Default ${base[key]})`);
|
||||
}
|
||||
}
|
||||
if (s.live && row.heapGrowthMB > Number(opts.leak)) {
|
||||
failures.push(`${s.name}/${design}: heap grew ${row.heapGrowthMB} MB over ${row.switches} switches`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const baseline = fetchesBy.default ?? new Set();
|
||||
for (const [design, urls] of Object.entries(fetchesBy)) {
|
||||
console.log(`off-origin ${design.padEnd(10)} ${[...urls].join(' ') || 'none'}`);
|
||||
const added = [...urls].filter((url) => !baseline.has(url));
|
||||
if (design !== 'default' && added.length) failures.push(`${design}: fetches Default does not: ${added.join(', ')}`);
|
||||
}
|
||||
if (errors.length) console.log('page errors (first 5):', [...new Set(errors)].slice(0, 5));
|
||||
await writeFile(join(opts.out, 'design-bench.json'), JSON.stringify({ build: opts.build, gpu: Boolean(opts.gpu), results, fetches: Object.fromEntries(Object.entries(fetchesBy).map(([k, v]) => [k, [...v]])), failures }, null, 2));
|
||||
} finally {
|
||||
await browser.close().catch(() => {});
|
||||
await server.close();
|
||||
}
|
||||
if (failures.length) {
|
||||
console.log(`FAIL\n ${failures.join('\n ')}`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('PASS: every design within budget of Default');
|
||||
@@ -0,0 +1,30 @@
|
||||
// Design switches for the design bench (tool/perf/design_bench.mjs).
|
||||
//
|
||||
// With `?perf=1` the full-app fixture exposes:
|
||||
// `window.__perfDesigns()` the registered designs' ids as a JSON array, so
|
||||
// the bench covers every `AppDesign` without a
|
||||
// list of its own;
|
||||
// `window.__perfDesign(id)` chooses that design live, as Settings → Design
|
||||
// does (the same controller, no reload).
|
||||
// Without the flag nothing is installed.
|
||||
import 'dart:convert';
|
||||
import 'dart:js_interop';
|
||||
|
||||
import 'package:pipelines_app/ui/theme/app_design.dart';
|
||||
import 'package:pipelines_app/ui/theme/app_design_controller.dart';
|
||||
|
||||
@JS('__perfDesigns')
|
||||
external set _perfDesigns(JSFunction probe);
|
||||
|
||||
@JS('__perfDesign')
|
||||
external set _perfDesign(JSFunction select);
|
||||
|
||||
void installDesignProbe(Map<String, String> params) {
|
||||
if (params['perf'] != '1') return;
|
||||
_perfDesigns = (() => jsonEncode([
|
||||
for (final design in AppDesign.values) design.id,
|
||||
]).toJS).toJS;
|
||||
_perfDesign = ((JSString id) {
|
||||
AppDesignController.instance.select(AppDesign.fromId(id.toDart));
|
||||
}).toJS;
|
||||
}
|
||||
Reference in New Issue
Block a user