Merge main into the Compact design branch

This commit is contained in:
2026-12-03 22:00:25 +00:00
34 changed files with 1162 additions and 118 deletions
+5 -3
View File
@@ -1,5 +1,4 @@
import '../ui/adaptive/window_margins.dart';
import '../ui/theme/app_design.dart';
import '../ui/theme/app_design_controller.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/scale/ui_scale.dart';
@@ -55,11 +54,12 @@ class MyApp extends StatelessWidget {
final designs = this.designs ?? AppDesignController.instance;
return ListenableBuilder(
listenable: Listenable.merge([fonts, designs]),
builder: (context, _) => _host(designs.design, fonts.family),
builder: (context, _) => _host(designs, fonts.family),
);
}
Widget _host(AppDesign design, String? fontFamily) {
Widget _host(AppDesignController designs, String? fontFamily) {
final design = designs.design;
final router = routerConfig;
if (router != null) {
return MaterialApp.router(
@@ -68,6 +68,7 @@ class MyApp extends StatelessWidget {
builder: _scaled,
theme: design.light(fontFamily: fontFamily),
darkTheme: design.dark(fontFamily: fontFamily),
themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
routerConfig: router,
);
@@ -78,6 +79,7 @@ class MyApp extends StatelessWidget {
builder: _scaled,
theme: design.light(fontFamily: fontFamily),
darkTheme: design.dark(fontFamily: fontFamily),
themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
home: AdaptiveShell(
destinationBodies: destinationBodies,
@@ -223,6 +223,7 @@ class _DetachedWindowAppState extends State<DetachedWindowApp> {
),
theme: designs.design.light(fontFamily: fonts.family),
darkTheme: designs.design.dark(fontFamily: fonts.family),
themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
// The window's one page is named by its route, so the address bar
// (and a reload) keeps the detached location instead of `/`.
+1
View File
@@ -388,6 +388,7 @@ class _PipelinesRootState extends State<PipelinesRoot> {
),
theme: designs.design.light(fontFamily: fonts.family),
darkTheme: designs.design.dark(fontFamily: fonts.family),
themeAnimationDuration: designs.themeAnimationDuration,
debugShowCheckedModeBanner: false,
home: flow,
),
@@ -38,7 +38,9 @@ class DiffSearchBar extends StatelessWidget {
: '$position of $count';
return Material(
elevation: 3,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(28)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(28)),
color: Theme.of(context).colorScheme.surfaceContainerHigh,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4),
@@ -17,12 +17,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.
@@ -69,7 +69,9 @@ class _ChatFindBarState extends State<ChatFindBar> {
child: Material(
elevation: 3,
color: scheme.surfaceContainerHigh,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
@@ -70,7 +70,9 @@ class _ChatShellTerminalFindBarState extends State<ChatShellTerminalFindBar> {
child: Material(
elevation: 3,
color: scheme.surfaceContainerHigh,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
@@ -221,7 +221,9 @@ class ChatUndoBar extends StatelessWidget {
);
return Material(
elevation: 3,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: content,
);
@@ -148,7 +148,9 @@ class ChatCompactSidebar extends StatelessWidget {
data: row,
feedback: Material(
elevation: 4,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(20)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(20)),
child: Chip(
avatar: ChatCompactAvatar(
title: title,
@@ -91,7 +91,9 @@ class ChatSessionRow extends StatelessWidget {
data: session,
feedback: Material(
elevation: 4,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(20)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(20)),
child: Chip(
avatar: ChatSessionAvatar(session: session),
label: Text(chatSessionTitle(session)),
@@ -100,7 +100,9 @@ class RunCheckCommandRow extends StatelessWidget {
DecoratedBox(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
),
child: Padding(
padding: const EdgeInsets.all(12),
@@ -232,7 +232,9 @@ Widget _materialBlock(BuildContext context, DetailSummaryRow row) {
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(8)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
),
child: SelectableText(
row.value,
@@ -117,7 +117,9 @@ class RunTimelineRow extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.14),
borderRadius: AppDesignTokens.of(context).denseCorners(BorderRadius.circular(10)),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(10)),
),
child: Text(
label,
@@ -96,7 +96,10 @@ class DesignSwatchPreview extends StatelessWidget {
Container(height: lines > 2 ? 1 : 2, color: swatch.ink),
FractionallySizedBox(
widthFactor: 0.6,
child: Container(height: lines > 2 ? 1 : 2, color: swatch.ink),
child: Container(
height: lines > 2 ? 1 : 2,
color: swatch.ink,
),
),
],
),
+32 -33
View File
@@ -107,41 +107,40 @@ class ShellNavigationRail extends StatelessWidget {
DesignDensity density, {
required bool pinSettings,
}) => NavigationRail(
key: const ValueKey('shell.navigation-rail'),
backgroundColor: surface,
minWidth: density.railWidth,
// An icon-only rail names each tab in its tooltip alone.
labelType: density.railLabels
? NavigationRailLabelType.all
: NavigationRailLabelType.none,
selectedIndex: index < 0 ? null : index,
onDestinationSelected: (value) =>
onSelected(shellTabDestinations[value]),
destinations: [
for (final destination in shellTabDestinations)
NavigationRailDestination(
icon: KeyedSubtree(
key: ValueKey('shell.destination.${destination.name}'),
// The bar it replaces named each tab in a tooltip too.
// The destination's label already names it for assistive
// technology; the tooltip must not repeat it.
child: Tooltip(
message: destinationDetails(destination).label,
excludeFromSemantics: true,
child: icon(destination),
),
),
label: Text(destinationDetails(destination).label),
key: const ValueKey('shell.navigation-rail'),
backgroundColor: surface,
minWidth: density.railWidth,
// An icon-only rail names each tab in its tooltip alone.
labelType: density.railLabels
? NavigationRailLabelType.all
: NavigationRailLabelType.none,
selectedIndex: index < 0 ? null : index,
onDestinationSelected: (value) => onSelected(shellTabDestinations[value]),
destinations: [
for (final destination in shellTabDestinations)
NavigationRailDestination(
icon: KeyedSubtree(
key: ValueKey('shell.destination.${destination.name}'),
// The bar it replaces named each tab in a tooltip too.
// The destination's label already names it for assistive
// technology; the tooltip must not repeat it.
child: Tooltip(
message: destinationDetails(destination).label,
excludeFromSemantics: true,
child: icon(destination),
),
],
scrollable: true,
trailingAtBottom: pinSettings,
trailing: _SettingsRailItem(
density: density,
selected: selected == AppDestination.settings,
onTap: () => onSelected(AppDestination.settings),
),
label: Text(destinationDetails(destination).label),
),
);
],
scrollable: true,
trailingAtBottom: pinSettings,
trailing: _SettingsRailItem(
density: density,
selected: selected == AppDestination.settings,
onTap: () => onSelected(AppDestination.settings),
),
);
}
/// Settings at the rail's foot, drawn as a [NavigationRailDestination] is: an
+1 -5
View File
@@ -2,11 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'window_frame.dart'
show
WindowOutline,
WindowResizeGrip,
windowCorners,
windowTitleBarHeight;
show WindowOutline, WindowResizeGrip, windowCorners, windowTitleBarHeight;
import 'window_scope.dart';
/// A floating window's own page stack. Pages pushed from the window's
+3 -1
View File
@@ -423,7 +423,9 @@ class _SegmentedBarState extends State<SegmentedBar> {
titleShare ??
(widget.separateActionIslands ? .10 : SegmentedBar.minTitleShare);
final besideTitle =
width - (leading == null ? 0 : segmentedPieceHeight(context) + 8) - 8;
width -
(leading == null ? 0 : segmentedPieceHeight(context) + 8) -
8;
// Actions that cannot move (a model picker) may take the room down
// to the title's minimum share; the rest leave for the More menu
// before the title goes under its own width.
+38 -13
View File
@@ -6,6 +6,11 @@ import 'compact_theme.dart';
import 'paper_theme.dart';
import 'terminal_theme.dart';
/// 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 = {};
/// An app-wide design: how every surface is shaped, typed and coloured, not
/// only a colour. Each design builds a light and a dark [ThemeData] carrying
/// its [AppDesignTokens], so widgets that draw design-specific shapes read the
@@ -16,12 +21,14 @@ import 'terminal_theme.dart';
/// [description] (the Settings picker lists [AppDesign.values]);
/// 2. write its theme builder (`<name>_theme.dart` beside this file, with a
/// palette and, when it needs one, its own typography) and return it from
/// [light] and [dark];
/// [build] ([light] and [dark] cache it); keep the theme value-equal when
/// rebuilt (no fresh `Decoration`s or extensions without `==`);
/// 3. give the theme an [AppDesignTokens] extension: set only the tokens it
/// changes (corners, flat surfaces, frame, panel fill, transcript,
/// composer and selected-row styles, reading type); every token defaults
/// to the Default look;
/// 4. give it a [swatch] for the picker and say whether it [usesInterfaceFont].
/// 5. run the design budget (app/tool/perf/README.md) and keep it passing.
/// Widgets read the tokens, so most surfaces follow without per-widget code.
enum AppDesign {
/// The app's own Material look.
@@ -72,20 +79,38 @@ 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),
paper => paperTheme(Brightness.light, fontFamily: fontFamily),
compact => compactTheme(Brightness.light, fontFamily: fontFamily),
};
/// 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),
paper => paperTheme(Brightness.dark, fontFamily: fontFamily),
compact => compactTheme(Brightness.dark, fontFamily: fontFamily),
};
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),
(paper, _) => paperTheme(brightness, fontFamily: fontFamily),
(compact, _) => compactTheme(brightness, fontFamily: fontFamily),
};
/// Whether this design packs the interface densely
/// ([DesignDensity.dense]); its theme hosts switch to and from it without
/// a blend ([AppDesignController.themeAnimationDuration]).
bool get dense =>
light().extension<AppDesignTokens>()?.density.dense ?? false;
/// Whether the device's interface font applies under this design (Paper
/// keeps it for its interface text and sets reading text in its serif).
+18 -2
View File
@@ -1,4 +1,5 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show kThemeAnimationDuration;
import 'package:shared_preferences/shared_preferences.dart';
import 'app_design.dart';
@@ -77,6 +78,21 @@ class AppDesignController extends ChangeNotifier {
AppDesign get design => _design;
/// How long the theme hosts blend into the current design (their
/// `themeAnimationDuration`): Material's blend between designs of the same
/// density, none for a switch into or out of a dense design. A dense
/// design's sizes (icons, controls) have no value in a comfortable theme to
/// blend from, so a blend would pass every icon through size zero, and in
/// the browser (skwasm) laying out the near-zero icon glyphs could hang.
Duration get themeAnimationDuration =>
_snapTheme ? Duration.zero : kThemeAnimationDuration;
bool _snapTheme = false;
void _apply(AppDesign design) {
_snapTheme = _design.dense || design.dense;
_design = design;
}
/// The last choice could not be stored on this device.
bool get saveFailed => _saveFailed;
@@ -87,7 +103,7 @@ class AppDesignController extends ChangeNotifier {
if (revision != _revision || id == null) return;
final design = AppDesign.fromId(id);
if (design == _design) return;
_design = design;
_apply(design);
notifyListeners();
}
@@ -96,7 +112,7 @@ class AppDesignController extends ChangeNotifier {
_revision++;
final revision = _revision;
if (design != _design) {
_design = design;
_apply(design);
notifyListeners();
}
final saved = await _store.save(design.id);
+14
View File
@@ -97,4 +97,18 @@ class ReadingType {
letterSpacing: family == null ? null : 0,
);
}
@override
bool operator ==(Object other) =>
other is ReadingType &&
other.family == family &&
other.height == height &&
other.measure == measure &&
other.scale == scale &&
other.figureWidth == figureWidth &&
other.paragraphGap == paragraphGap;
@override
int get hashCode =>
Object.hash(family, height, measure, scale, figureWidth, paragraphGap);
}
+50
View File
@@ -25,6 +25,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:
@@ -171,6 +184,43 @@ class AppDesignTokens extends ThemeExtension<AppDesignTokens> {
density: density ?? this.density,
);
// 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.panel == panel &&
other.ansi == ansi &&
other.promptGlyph == promptGlyph &&
other.transcript == transcript &&
other.composer == composer &&
other.selectedRow == selectedRow &&
other.reading == reading &&
other.chatColorSaturation == chatColorSaturation &&
other.density == density;
@override
int get hashCode => Object.hash(
design,
radius,
flat,
frame,
panel,
ansi,
promptGlyph,
transcript,
composer,
selectedRow,
reading,
chatColorSaturation,
density,
);
/// Designs switch whole: a theme animation snaps halfway rather than
/// blending two designs' shapes.
@override
+5 -28
View File
@@ -8,12 +8,14 @@ const RoundedRectangleBorder _rounded = RoundedRectangleBorder(
);
/// [base] with Compact's controls: Default's Material components at dense
/// heights, in [compactRadius] corners, with 4px-grid paddings. Floating
/// heights, in [compactRadius] corners, with 4px-grid paddings. Their text
/// keeps each component's own Material role (already at Compact's sizes):
/// a component theme that sets a text-theme style cannot be lerped against
/// Default's unset one, which breaks a live design switch. Floating
/// surfaces (menus, dialogs, sheets, tooltips, snack bars) keep Material's
/// elevation and fills; only their corners and insets change.
ThemeData compactControls(ThemeData base) {
final scheme = base.colorScheme;
final text = base.textTheme;
const icon = 18.0;
// Buttons: 32px tall under compact density, 12px side padding, 18px icons.
ButtonStyle buttons() => const ButtonStyle(
@@ -49,10 +51,7 @@ ThemeData compactControls(ThemeData base) {
),
),
segmentedButtonTheme: SegmentedButtonThemeData(
style: buttons().copyWith(
visualDensity: VisualDensity.compact,
textStyle: WidgetStatePropertyAll(text.labelLarge),
),
style: buttons().copyWith(visualDensity: VisualDensity.compact),
),
// A 40px action (Material's small FAB) and a 40px extended one.
floatingActionButtonTheme: FloatingActionButtonThemeData(
@@ -66,34 +65,25 @@ ThemeData compactControls(ThemeData base) {
),
extendedPadding: const EdgeInsetsDirectional.only(start: 12, end: 16),
extendedIconLabelSpacing: 8,
extendedTextStyle: text.labelLarge,
),
menuTheme: MenuThemeData(style: menu),
dropdownMenuTheme: DropdownMenuThemeData(
menuStyle: menu,
textStyle: text.bodyMedium,
inputDecorationTheme: const InputDecorationTheme(isDense: true),
),
menuButtonTheme: MenuButtonThemeData(
style: MenuItemButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 12),
minimumSize: const Size(0, 32),
textStyle: text.bodyMedium,
iconSize: icon,
),
),
popupMenuTheme: PopupMenuThemeData(
shape: _rounded,
menuPadding: const EdgeInsets.symmetric(vertical: 4),
labelTextStyle: WidgetStatePropertyAll(text.bodyMedium),
textStyle: text.bodyMedium,
),
dialogTheme: DialogThemeData(
shape: _rounded,
titleTextStyle: text.titleLarge?.copyWith(color: scheme.onSurface),
contentTextStyle: text.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
),
@@ -106,9 +96,6 @@ ThemeData compactControls(ThemeData base) {
),
snackBarTheme: SnackBarThemeData(
shape: _rounded,
contentTextStyle: text.bodyMedium?.copyWith(
color: scheme.onInverseSurface,
),
insetPadding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
),
tooltipTheme: TooltipThemeData(
@@ -117,7 +104,6 @@ ThemeData compactControls(ThemeData base) {
borderRadius: _corners,
),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
textStyle: text.bodySmall?.copyWith(color: scheme.onInverseSurface),
waitDuration: const Duration(milliseconds: 400),
),
// A hairline on every card variant: the theme's shape replaces each
@@ -133,7 +119,6 @@ ThemeData compactControls(ThemeData base) {
shape: _rounded,
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
labelPadding: const EdgeInsets.symmetric(horizontal: 4),
labelStyle: text.labelLarge,
iconTheme: const IconThemeData(size: 16),
),
inputDecorationTheme: const InputDecorationTheme(
@@ -146,10 +131,6 @@ ThemeData compactControls(ThemeData base) {
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 12),
),
textStyle: WidgetStatePropertyAll(text.bodyMedium),
hintStyle: WidgetStatePropertyAll(
text.bodyMedium?.copyWith(color: scheme.onSurfaceVariant),
),
),
listTileTheme: const ListTileThemeData(
dense: true,
@@ -184,19 +165,15 @@ ThemeData compactControls(ThemeData base) {
navigationBarTheme: NavigationBarThemeData(
height: 64,
indicatorShape: _rounded,
labelTextStyle: WidgetStatePropertyAll(text.labelMedium),
iconTheme: const WidgetStatePropertyAll(IconThemeData(size: icon)),
),
tabBarTheme: TabBarThemeData(
labelStyle: text.labelLarge,
unselectedLabelStyle: text.labelLarge,
labelPadding: const EdgeInsets.symmetric(horizontal: 12),
),
dividerTheme: const DividerThemeData(space: 8, thickness: 1),
badgeTheme: BadgeThemeData(
smallSize: 6,
largeSize: 14,
textStyle: text.labelSmall?.copyWith(fontSize: 10),
padding: const EdgeInsets.symmetric(horizontal: 4),
),
checkboxTheme: const CheckboxThemeData(
+13 -6
View File
@@ -4,6 +4,12 @@ import 'paper_theme.dart';
const Color _clear = Color(0x00000000);
// Kept per colour: a tab indicator and a resolver compare by identity, so
// fresh ones would make a rebuilt theme unequal to the last
// (test/perf/design_bench_test.dart).
final Map<Color, Decoration> _tabIndicators = {};
final Map<(Color, Color), WidgetStateProperty<Color?>> _trackOutlines = {};
/// [base] with Paper's controls: buttons, menus, chips, fields, search bars,
/// tabs, segmented buttons, switches, checkboxes, sliders, badges and
/// progress, all in [paperRadius] corners with hairline outlines, no
@@ -104,16 +110,17 @@ ThemeData paperControls(ThemeData base, PaperSurfaces surfaces) {
labelColor: scheme.onSurface,
unselectedLabelColor: scheme.onSurfaceVariant,
indicatorSize: TabBarIndicatorSize.label,
indicator: UnderlineTabIndicator(
indicator: _tabIndicators[scheme.primary] ??= UnderlineTabIndicator(
borderSide: BorderSide(color: scheme.primary, width: 2),
),
),
switchTheme: SwitchThemeData(
trackOutlineColor: WidgetStateProperty.resolveWith(
(states) => states.contains(WidgetState.selected)
? scheme.primary
: scheme.outline,
),
trackOutlineColor: _trackOutlines[(scheme.primary, scheme.outline)] ??=
WidgetStateProperty.resolveWith(
(states) => states.contains(WidgetState.selected)
? scheme.primary
: scheme.outline,
),
trackOutlineWidth: const WidgetStatePropertyAll(1),
),
checkboxTheme: CheckboxThemeData(
+5 -1
View File
@@ -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,
@@ -196,7 +200,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),
),
),
+94
View File
@@ -0,0 +1,94 @@
# Compact design
Default's Material 3 look, packed tight for a big monitor and long runs and
chats (Settings > Design > Compact). It has the same colours and glass bars
as Default. Type is smaller: body 13px, labels 11-12px, chat reading 14px on a
1.5 line. Spacing sits on a 4px grid. Rows are 36px with one line and about
54px with two. Icons are 18px, avatars 28px, and every corner is 6px.
## Tokens
- `density` (`DesignDensity`, `design_density.dart`; `comfortable` for every
other design). It holds `spacing` (0.6), `iconSize` (18), `avatarSize`
(28), `railWidth` (64), `railLabels` (false) and `titleBarHeight` (32).
- `space(v)` scales a widget's own spacing and snaps it to the 4px grid.
- `inset(v)` does the same for side insets, halfway between: 16 becomes 12.
- `minTouchRow` is 40 on touch devices and 0 on pointer devices.
- `dense` and `pointerPlatform` are also available. All of them return the
input unchanged when the density is comfortable, so other designs keep
their numbers.
- `ReadingType.paragraphGap` is the gap between paragraphs of an answer, in
lines. Default is 0.9; Compact is 0.6.
- `AppDesignTokens.denseCorners(r)` gives the design's radius only under a
dense design. It is for surfaces whose own corners the comfortable designs
keep: floating windows (12), search thumbnails, find bars, run detail
boxes and the search field stadium.
- `AppDesign.dense` and `AppDesign.swatchLines` (the picker preview draws 4
thin lines for Compact).
## Themed surfaces
- `compact_theme.dart`, `compact_controls.dart`, `compact_typography.dart`:
- visual density is `compact`;
- the tap target is `shrinkWrap` on desktop and `padded` (40px) on touch;
- Material 3 icon buttons need their own `visualDensity`, otherwise they
ignore the theme's; they are 32px with a padding of 7;
- buttons, chips, fields, the search bar, list tiles, menus, popups,
dialogs, sheets, snack bars, tooltips, FABs (40px), the rail, the
navigation bar, tabs, badges, the scrollbar, date and time pickers all
take 6px corners and dense paddings;
- cards get a hairline, so `Card.outlined` (graph nodes) keeps its outline.
- `AppListRow` / `AppListAvatar`: dense insets, padding and avatar size, plus
the touch minimum.
- `ShellNavigationRail`: 64px wide, icons only with tooltips. Settings uses
the same 56x32 indicator as the tabs.
- The shell and window host read the rail width through
`navigationRailSpaceOf`.
- Chat:
- the operator bubble has 6px corners and 12/8 padding;
- turn gaps and the paragraph gap are tighter;
- the activity line is 28px (40px on touch);
- turn chips, follow-up and automatic-continue cards are tighter;
- code blocks use 8px insets with monospace at 13/14;
- the composer is a 40px pill, and its field padding is 10 because
density takes 4px off each side.
- Top bars: segmented pieces are 40px (`segmentedPieceHeight(context)`) and
title pill padding is 12. Chat bar text buttons have a 32px minimum.
- Floating windows: a 32px title bar with 16px icons and 6px corners on the
frame, outline and page clip.
- Graph: nodes use 12/8 insets with a 32px minimum height.
`graphMetricsOf(context)` tightens the gaps, lanes and padding.
- Settings: `settingsSectionGapOf` and `settingsRowInsetOf` give 16 and 12,
and the group header, footer and item paddings are dense.
## Live switch
A switch into or out of a dense design does not blend
(`AppDesignController.themeAnimationDuration` is zero). The reason:
`ThemeData.lerp` takes a component theme's unset size as 0, so every icon
(and any text style set in a component theme) passes through size 0. In
skwasm, laying out glyphs at nearly zero size hung the page. This was
bisected with `tool/perf/design_bench.mjs`, and the pause stack showed
`paragraph_layout`.
For the same reason, Compact's component themes set no text styles. Each
component keeps its Material role, which is already at Compact's size.
`test/ui/theme/compact_switch_test.dart` checks every frame of a switch.
Default, Terminal and Paper keep their blend.
## Perf budget changes
- `test/perf/design_bench_test.dart` budgets `scrollRebuildsPerRow`, not
per frame. A denser design shows more rows in each 120px step.
- `design_bench.mjs` gives the chat-switch clicks per-design points
(`compact: [x, y]`), checked with `tool/capture`.
## Still Default
- Sliders and switches keep their size.
- Tab heights are not themeable.
- The walkthrough's bullet dot sits off the baseline in every design.
- The glass bar margins (`kFloatingBarMargin`) and `GlassBarMetrics` (artifact
viewer, chevron pager) keep 48px.
- Fields that set their own `OutlineInputBorder()` keep 4px corners.
@@ -129,7 +129,9 @@ void main() {
);
expect(swatch.lines, greaterThan(2));
expect(find.text(AppDesign.compact.description), findsOneWidget);
final before = tester.getSize(find.byKey(settingsDesignKey(AppDesign.paper)));
final before = tester.getSize(
find.byKey(settingsDesignKey(AppDesign.paper)),
);
await tester.tap(find.text(AppDesign.compact.label));
await tester.pumpAndSettle();
@@ -139,7 +141,9 @@ void main() {
expect(tokens.density.dense, isTrue);
expect(tokens.transcript, TranscriptStyle.bubbles);
// The rows themselves tighten at once.
final after = tester.getSize(find.byKey(settingsDesignKey(AppDesign.paper)));
final after = tester.getSize(
find.byKey(settingsDesignKey(AppDesign.paper)),
);
expect(after.height, lessThan(before.height));
final next = AppDesignController(store: MemoryAppDesignStore(store.id));
+302
View File
@@ -0,0 +1,302 @@
// 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;
// A denser design shows more rows in the same 120px, so it builds
// more per frame for the same per-row cost: the budget is per row
// scrolled past (rows over the transcript's whole extent).
final position = controller.position;
final extent = position.maxScrollExtent + position.viewportDimension;
final rowsScrolled = frames * 120 * _rows.length / extent;
row['scrollRebuildsPerRow'] = rebuilds.count / rowsScrolled;
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 [
'scrollRebuildsPerRow',
'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]})',
);
}
}
}
});
}
+31 -6
View File
@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.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_design_tokens.dart';
import 'package:pipelines_app/ui/theme/app_theme.dart';
@@ -128,10 +129,7 @@ void main() {
expect(_radiusOf(theme.floatingActionButtonTheme.shape), six);
expect(_radiusOf(theme.listTileTheme.shape), six);
expect(_radiusOf(theme.navigationRailTheme.indicatorShape), six);
expect(
_radiusOf(theme.menuTheme.style?.shape?.resolve(const {})),
six,
);
expect(_radiusOf(theme.menuTheme.style?.shape?.resolve(const {})), six);
expect(
_radiusOf(theme.filledButtonTheme.style?.shape?.resolve(const {})),
six,
@@ -162,13 +160,40 @@ void main() {
(TargetPlatform.iOS, false),
]) {
debugDefaultTargetPlatformOverride = platform;
final theme = AppDesign.compact.light();
// Built afresh: the cached theme is the device's, built once.
final theme = AppDesign.compact.build(Brightness.light);
expect(
theme.materialTapTargetSize,
pointer ? MaterialTapTargetSize.shrinkWrap : MaterialTapTargetSize.padded,
pointer
? MaterialTapTargetSize.shrinkWrap
: MaterialTapTargetSize.padded,
);
expect(DesignDensity.compact.minTouchRow, pointer ? 0 : 40);
}
debugDefaultTargetPlatformOverride = null;
});
test(
'a switch into or out of Compact snaps; others keep the blend',
() async {
final designs = AppDesignController(store: MemoryAppDesignStore());
expect(AppDesign.compact.dense, isTrue);
for (final design in [
AppDesign.standard,
AppDesign.terminal,
AppDesign.paper,
]) {
expect(design.dense, isFalse);
}
expect(designs.themeAnimationDuration, kThemeAnimationDuration);
await designs.select(AppDesign.terminal);
expect(designs.themeAnimationDuration, kThemeAnimationDuration);
await designs.select(AppDesign.compact);
expect(designs.themeAnimationDuration, Duration.zero);
await designs.select(AppDesign.paper);
expect(designs.themeAnimationDuration, Duration.zero);
await designs.select(AppDesign.standard);
expect(designs.themeAnimationDuration, kThemeAnimationDuration);
},
);
}
@@ -8,11 +8,14 @@ import 'package:pipelines_app/shell/windows/window_frame.dart';
import 'package:pipelines_app/ui/layout/app_list_avatar.dart';
import 'package:pipelines_app/ui/layout/app_list_row.dart';
import 'package:pipelines_app/ui/theme/app_design.dart';
import 'package:pipelines_app/ui/theme/app_design_tokens.dart';
/// Compact as drawn: thin rows, a narrow icon-only rail, 32px icon buttons
/// (40px targets on touch), tight bubbles, a slim window title bar, and no
/// clipping at a large text scale.
void main() {
tearDown(() => debugDefaultTargetPlatformOverride = null);
Future<void> pump(
WidgetTester tester,
Widget child, {
@@ -26,7 +29,8 @@ void main() {
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
theme: design.light(),
// Built afresh, so the platform this test sets is the theme's.
theme: design.build(Brightness.light),
home: MediaQuery(
data: MediaQueryData(
size: Size(width, 900),
@@ -189,7 +193,10 @@ void main() {
matching: find.byType(Padding),
),
);
expect(padding.padding, const EdgeInsets.symmetric(horizontal: 12, vertical: 8));
expect(
padding.padding,
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
);
final gap = chatParagraphGap(tester.element(find.text('Ship it')), 14);
expect(gap, closeTo(14 * 0.6, 0.01));
});
+121
View File
@@ -0,0 +1,121 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.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/ui/theme/app_design.dart';
final _rows = transcriptRows([
for (var i = 0; i < 6; i++) ...[
{
'id': 'u$i',
'role': 'user',
'parts': [
{'type': 'text', 'text': 'Step $i'},
],
},
{
'id': 'a$i',
'role': 'assistant',
'parts': [
{
'type': 'tool',
'id': 't$i',
'name': 'Bash',
'state': {
'status': 'completed',
'input': {'command': 'go test'},
},
},
{'type': 'text', 'text': 'Fixed `x`.\n\n- one\n\n```go\nreturn 1\n```'},
],
},
],
]);
/// A live design switch to and from Compact animates the theme without an
/// error in any frame. A component theme that set a text-theme style failed
/// to lerp against Default's unset one, and in the browser the broken
/// frames stopped the app drawing.
void main() {
testWidgets('switching to and from Compact lerps every frame cleanly', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.linux;
final design = ValueNotifier(AppDesign.compact);
await tester.pumpWidget(
ValueListenableBuilder<AppDesign>(
valueListenable: design,
builder: (_, d, _) => MaterialApp(
theme: d.dark(),
darkTheme: d.dark(),
home: Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('New run'),
),
body: Row(
children: [
NavigationRail(
destinations: const [
NavigationRailDestination(
icon: Icon(Icons.add),
label: Text('a'),
),
NavigationRailDestination(
icon: Icon(Icons.add),
label: Text('b'),
),
],
selectedIndex: 0,
),
Expanded(
child: ListView(
children: [
IconButton(onPressed: () {}, icon: const Icon(Icons.add)),
IconButton.filled(
onPressed: () {},
icon: const Icon(Icons.add),
),
Checkbox(value: true, onChanged: (_) {}),
Switch(value: true, onChanged: (_) {}),
const ListTile(title: Text('t'), subtitle: Text('s')),
const TextField(),
Chip(label: const Text('c'), onDeleted: () {}),
SegmentedButton<int>(
segments: const [
ButtonSegment(value: 1, label: Text('one')),
ButtonSegment(value: 2, label: Text('two')),
],
selected: const {1},
),
for (final row in _rows) ChatMessageView(row: row),
],
),
),
],
),
),
),
),
);
await tester.pumpAndSettle();
for (var round = 0; round < 3; round++) {
for (final other in [
AppDesign.standard,
AppDesign.terminal,
AppDesign.paper,
AppDesign.compact,
]) {
design.value = other;
for (var f = 0; f < 20; f++) {
await tester.pump(const Duration(milliseconds: 16));
final e = tester.takeException();
if (e != null) fail('to ${other.id} frame $f: $e');
}
}
}
debugDefaultTargetPlatformOverride = null;
});
}
+3 -5
View File
@@ -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.
+115
View File
@@ -0,0 +1,115 @@
# 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: `scrollRebuildsPerRow`,
`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 medians per design (frames, build/raster mean per frame, sums and
maxima, frames over 16 ms) and exits 1 when a design's mean build or raster
time per frame is above `--ratio` (1.35) x Default + `--slack` (1 ms). Means,
not sums: a cheaper design draws more frames in the same gesture. It also
fails 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, and give the
step its own point keyed by design id (Compact: y=150/210/266).
The widget test budgets transcript rebuilds per row scrolled past
(`scrollRebuildsPerRow`), not per frame: a denser design shows more rows in
each 120px step for the same per-row cost. `scrollRebuildsPerFrame` stays
informational.
## 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.
## Known costs (December 2026 baseline)
Default is the heaviest design on the CPU raster path: its bars and floating
pieces blur what scrolls behind them (`GlassPill`, sigma 4), and its bubbles
add clip-path layers. Terminal and Paper draw flat pieces and come in at about
a third of Default's raster time per frame when scrolling a transcript. A
**Glass** design is gated against Default, which already blurs its bars, so it
has room for the same blur but not for more pieces: keep blur on the bars,
composer and floating pieces only (never rows, bubbles or the transcript),
sigma at most `GlassPill.blurSigma`, one grouped filter per piece, no blur
animating per frame (fade the fill, not the sigma), and solid fills under high
contrast. Run `design_bench.mjs` with and without `--gpu`; the CPU run is the
weak-device proxy.
A live design switch costs about 15 ms of build per frame for MaterialApp's
200 ms theme animation (about 12 frames of the whole app rebuilt with a lerped
theme), in every design. It is a deliberate blend, run only when the operator
picks a design.
+228
View File
@@ -0,0 +1,228 @@
#!/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:
// - mean build or raster time per frame 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: '1' },
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,
// Chat 2, chat 3, chat 1. Compact's thinner rows sit higher (verified
// with tool/capture at 1280x800), so it names its own points.
act: [
{ click: [300, 260], compact: [300, 210] },
{ click: [300, 335], compact: [300, 266] },
{ click: [300, 170], compact: [300, 150] },
] },
{ 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 * 100) / 100;
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 });
}
// A step's point under [design]: its own (`step[design]`) when the design
// moves the target, else the shared one.
async function run(steps, design) {
for (const step of steps ?? []) {
if (step.click) { await tap(step[design] ?? 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, design);
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;
const mean = (i) => (f.length ? sum(i) / f.length : 0);
return { ...out, frames: f.length, buildMean: mean(0), rasterMean: mean(1),
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) {
// Per-frame means, not sums: a cheaper design draws more frames in
// the same gesture, so its sum can exceed a slower design's.
for (const key of ['buildMean', 'rasterMean']) {
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');
+30
View File
@@ -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;
}