Add server health page with native controls and bounded refresh

This commit is contained in:
2026-11-07 01:43:54 +00:00
parent 81955059de
commit 8bf8cd9507
17 changed files with 1156 additions and 2 deletions
@@ -0,0 +1,48 @@
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import 'health_models.dart';
class HealthController extends ChangeNotifier {
HealthController(this.gateway);
final ApiGateway gateway;
JsonMap? stats;
String? error;
bool busy = false;
bool _disposed = false;
Future<void> load() async {
if (busy || _disposed) return;
busy = true;
error = null;
_notify();
try {
final reply = await gateway.call('server_stats');
if (reply['error'] case final String message when message.isNotEmpty) {
throw StateError(message);
}
if (reply['server_stats'] is! Map) {
throw StateError(
'Server health information is unavailable on this server.',
);
}
stats = healthMap(reply['server_stats']);
} catch (exception) {
error = exception is StateError
? exception.message.toString()
: '$exception';
} finally {
busy = false;
_notify();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,63 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../settings_theme.dart';
import 'health_models.dart';
import 'health_widgets.dart';
class HealthHeader extends StatelessWidget {
const HealthHeader({
super.key,
required this.host,
required this.sampled,
required this.busy,
required this.autoRefresh,
required this.onRefresh,
required this.onAutoRefresh,
});
final JsonMap host;
final Object? sampled;
final bool busy, autoRefresh;
final VoidCallback onRefresh;
final ValueChanged<bool> onAutoRefresh;
@override
Widget build(BuildContext context) => HealthCard(
title: healthText(host['hostname']),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (host['error'] case final String error) Text(error),
Text(
'${healthText(host['platform'])} ${healthText(host['platform_version'])} · ${healthText(host['os'])}',
),
Text(
'Uptime ${healthDuration(host['uptime_seconds'])} · ${healthAge(sampled, DateTime.now())}',
),
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
HealthAction(label: 'Refresh', onPressed: busy ? null : onRefresh),
Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Auto-refresh'),
const SizedBox(width: 8),
Semantics(
label: 'Auto-refresh',
child: usesCupertinoControls(context)
? CupertinoSwitch(
value: autoRefresh,
onChanged: onAutoRefresh,
)
: Switch(value: autoRefresh, onChanged: onAutoRefresh),
),
],
),
],
),
],
),
);
}
@@ -0,0 +1,62 @@
import '../../../core/api_gateway.dart';
JsonMap healthMap(Object? value) =>
value is Map ? Map<String, dynamic>.from(value) : <String, dynamic>{};
String healthText(Object? value) =>
value is String && value.isNotEmpty ? value : '—';
String healthNumber(Object? value) =>
value is num ? _number(value.toDouble()) : '—';
String _number(double value) => value.isFinite
? value.toStringAsFixed(value == value.roundToDouble() ? 0 : 1)
: '—';
String healthPercent(Object? value) =>
value is num ? '${_number(value.toDouble())}%' : '—';
String healthBytes(Object? value) {
if (value is! num || value < 0) return '—';
final bytes = value.toDouble();
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
var unit = 0;
var amount = bytes;
while (amount >= 1024 && unit < units.length - 1) {
amount /= 1024;
unit++;
}
return '${_number(amount)} ${units[unit]}';
}
String healthDuration(Object? value) {
if (value is! num || value < 0) return '—';
final seconds = value.toInt();
final days = seconds ~/ 86400;
final hours = seconds ~/ 3600 % 24;
final minutes = seconds ~/ 60 % 60;
return days > 0
? '${days}d ${hours}h'
: hours > 0
? '${hours}h ${minutes}m'
: '${minutes}m';
}
String healthAge(Object? value, DateTime now) {
final sampled = DateTime.tryParse(value?.toString() ?? '')?.toLocal();
if (sampled == null) return 'Sampled —';
final seconds = now.difference(sampled).inSeconds.clamp(0, 999999);
return 'Sampled ${seconds}s ago';
}
double? healthRatio(Object? value) => value is num && value.isFinite
? (value.toDouble() / 100).clamp(0, 1)
: null;
const healthMeterHigh = 80.0;
const healthMeterCritical = 95.0;
/// Missing byte counts remain unknown rather than appearing as zero usage.
double? healthUsageRatio(Object? used, Object? total) =>
used is num && total is num && used.isFinite && total.isFinite && total > 0
? (used / total).clamp(0, 1).toDouble()
: null;
@@ -0,0 +1,157 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../settings_page_body.dart';
import '../settings_theme.dart';
import 'health_controller.dart';
import 'health_models.dart';
import 'health_sections.dart';
import 'health_header.dart';
import 'health_widgets.dart';
class HealthScreen extends StatefulWidget {
const HealthScreen({super.key, required this.gateway});
final ApiGateway gateway;
@override
State<HealthScreen> createState() => _HealthScreenState();
}
class _HealthScreenState extends State<HealthScreen>
with WidgetsBindingObserver {
late HealthController _controller;
Timer? _timer;
ModalRoute<dynamic>? _route;
Animation<double>? _secondaryAnimation;
AppLifecycleState? _lifecycleState;
bool _autoRefresh = true;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_lifecycleState = WidgetsBinding.instance.lifecycleState;
_connect();
}
void _connect() {
_controller = HealthController(widget.gateway)..addListener(_changed);
unawaited(_controller.load());
}
void _changed() {
if (mounted) setState(() {});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final route = ModalRoute.of(context);
if (route == _route) {
_updateVisibility();
return;
}
_secondaryAnimation?.removeListener(_updateVisibility);
_route = route;
_secondaryAnimation = route?.secondaryAnimation;
_secondaryAnimation?.addListener(_updateVisibility);
_updateVisibility();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
_lifecycleState = state;
_updateVisibility();
}
void _updateVisibility() {
final route = _route;
final visible =
route?.isCurrent == true &&
(_lifecycleState == null ||
_lifecycleState == AppLifecycleState.resumed) &&
(_secondaryAnimation?.value ?? 0) == 0;
if (visible) {
_schedule();
} else {
_timer?.cancel();
_timer = null;
}
}
void _schedule() {
if (!_autoRefresh || _route?.isCurrent != true) {
_timer?.cancel();
_timer = null;
return;
}
if (_timer != null) return;
_timer = Timer.periodic(
const Duration(seconds: 5),
(_) => unawaited(_controller.load()),
);
}
@override
void didUpdateWidget(covariant HealthScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.dispose();
_connect();
}
}
@override
void dispose() {
_timer?.cancel();
_secondaryAnimation?.removeListener(_updateVisibility);
WidgetsBinding.instance.removeObserver(this);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final stats = _controller.stats;
final content = SettingsPageBody(
children: [
if (_controller.busy && stats == null)
const Center(child: CircularProgressIndicator.adaptive()),
if (_controller.error case final String error) ...[
Text(error),
HealthAction(
label: 'Retry',
onPressed: _controller.busy
? null
: () => unawaited(_controller.load()),
),
],
if (stats case final JsonMap data) ...[
HealthHeader(
host: healthMap(data['host']),
sampled: data['sampled_at'],
busy: _controller.busy,
autoRefresh: _autoRefresh,
onRefresh: () => unawaited(_controller.load()),
onAutoRefresh: (value) {
setState(() => _autoRefresh = value);
_updateVisibility();
},
),
HealthSections(stats: data),
],
],
);
return usesCupertinoControls(context)
? CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Server health'),
),
child: SafeArea(child: content),
)
: Scaffold(
appBar: AppBar(title: const Text('Server health')),
body: content,
);
}
}
@@ -0,0 +1,219 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../settings_theme.dart';
import 'health_models.dart';
import 'health_widgets.dart';
import 'health_storage.dart';
class HealthSections extends StatelessWidget {
const HealthSections({super.key, required this.stats});
final JsonMap stats;
Widget _errorOrRows(JsonMap data, List<(String, String)> rows) {
final error = data['error'];
return error is String && error.isNotEmpty ? Text(error) : HealthRows(rows);
}
Widget _cpu(JsonMap data) {
if (data['error'] case final String error when error.isNotEmpty) {
return HealthCard(title: 'CPU', child: Text(error));
}
final cores =
(data['per_core_percent'] as List?)?.whereType<num>().toList() ?? [];
return HealthCard(
title: 'CPU',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HealthMeter(
label: 'Overall',
value: healthRatio(data['usage_percent']),
),
const SizedBox(height: 10),
_errorOrRows(data, [
('Model', healthText(data['model'])),
('Logical cores', healthNumber(data['logical_cores'])),
('Physical cores', healthNumber(data['physical_cores'])),
(
'Load averages',
[
data['load1'],
data['load5'],
data['load15'],
].every((x) => x is num)
? '${healthNumber(data['load1'])} · ${healthNumber(data['load5'])} · ${healthNumber(data['load15'])}'
: '—',
),
]),
if (cores.isNotEmpty) ...[
const SizedBox(height: 8),
const Text('Per-core usage'),
const SizedBox(height: 4),
Wrap(
spacing: 3,
runSpacing: 3,
children: [
for (final core in cores)
SizedBox(
width: 18,
child: LinearProgressIndicator(value: healthRatio(core)),
),
],
),
],
],
),
);
}
Widget _memory(JsonMap data) => HealthCard(
title: 'Memory',
child: data['error'] is String
? Text(data['error'] as String)
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HealthMeter(
label: 'Used',
value: healthRatio(data['used_percent']),
),
const SizedBox(height: 8),
_errorOrRows(data, [
(
'Used',
'${healthBytes(data['used_bytes'])} of ${healthBytes(data['total_bytes'])}',
),
('Available', healthBytes(data['available_bytes'])),
(
'Swap',
'${healthBytes(data['swap_used_bytes'])} of ${healthBytes(data['swap_total_bytes'])}',
),
]),
const SizedBox(height: 8),
HealthMeter(
label: 'Swap',
value:
data['swap_total_bytes'] is num &&
(data['swap_total_bytes'] as num) > 0
? healthUsageRatio(
data['swap_used_bytes'],
data['swap_total_bytes'],
)
: null,
),
],
),
);
Widget _gpu(BuildContext context, JsonMap data) {
if (data['error'] case final String error when error.isNotEmpty) {
return HealthCard(title: 'GPU', child: Text(error));
}
final devices =
(data['devices'] as List?)?.whereType<Map>().map(healthMap).toList() ??
[];
if (data['available'] != true || devices.isEmpty) {
return HealthCard(title: 'GPU', child: Text(healthText(data['reason'])));
}
return HealthCard(
title: 'GPU',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final (index, device) in devices.indexed) ...[
if (index > 0) const Divider(),
Text(
healthText(device['name']),
style: settingsTextStyle(context, title: true),
),
HealthRows([('Vendor', healthText(device['vendor']))]),
HealthMeter(
label: 'Utilization',
value: healthRatio(device['utilization_percent']),
),
const SizedBox(height: 6),
HealthMeter(
label: 'Memory',
value:
(device['memory_total_bytes'] is num &&
(device['memory_total_bytes'] as num) > 0)
? healthUsageRatio(
device['memory_used_bytes'],
device['memory_total_bytes'],
)
: null,
),
Text(
'${healthBytes(device['memory_used_bytes'])} of ${healthBytes(device['memory_total_bytes'])} · ${healthNumber(device['temperature_c'])} °C',
),
],
],
),
);
}
Widget _data(JsonMap data) => HealthCard(
title: 'Pipelines data',
child: _errorOrRows(data, [
('Directory', healthText(data['dir'])),
('Database', healthBytes(data['db_bytes'])),
('Artifacts', healthBytes(data['artifacts_bytes'])),
('Total', healthBytes(data['total_bytes'])),
]),
);
Widget _process(JsonMap data) => HealthCard(
title: 'Process',
child: _errorOrRows(data, [
('PID', healthNumber(data['pid'])),
('RSS', healthBytes(data['rss_bytes'])),
('CPU', healthPercent(data['cpu_percent'])),
('Goroutines', healthNumber(data['goroutines'])),
('Heap', healthBytes(data['heap_bytes'])),
('Threads', healthNumber(data['threads'])),
('Go version', healthText(data['go_version'])),
('Build', healthText(data['build'])),
('Started', healthText(data['started_at'])),
]),
);
@override
Widget build(BuildContext context) {
final cpu = {
...healthMap(stats['cpu']),
...{
for (final key in ['load1', 'load5', 'load15'])
key: healthMap(stats['host'])[key],
},
};
final sections = [
_cpu(cpu),
_memory(healthMap(stats['memory'])),
_gpu(context, healthMap(stats['gpu'])),
HealthStorage(value: stats['storage']),
_data(healthMap(stats['data'])),
_process(healthMap(stats['process'])),
];
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 720) return Column(children: sections);
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (var column = 0; column < 2; column++) ...[
if (column > 0) const SizedBox(width: 12),
Expanded(
child: Column(
children: [
for (var i = column; i < sections.length; i += 2)
sections[i],
],
),
),
],
],
);
},
);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/material.dart';
import 'health_models.dart';
import 'health_widgets.dart';
class HealthStorage extends StatelessWidget {
const HealthStorage({super.key, this.value});
final Object? value;
@override
Widget build(BuildContext context) {
final value = this.value;
if (value is Map) {
final error = value['error'];
if (error is String && error.isNotEmpty) {
return HealthCard(title: 'Storage', child: Text(error));
}
}
final values = value is List ? value : const <dynamic>[];
return HealthCard(
title: 'Storage',
child: Column(
children: [
for (final raw in values.whereType<Map>())
Builder(
builder: (context) {
final row = healthMap(raw);
if (row['error'] case final String error
when error.isNotEmpty) {
return HealthRows([(healthText(row['mount']), error)]);
}
final total = row['total_bytes'] is num
? (row['total_bytes'] as num).toDouble()
: 0;
final used = row['used_bytes'];
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'${healthText(row['mount'])} · ${healthBytes(row['free_bytes'])} free of ${healthBytes(row['total_bytes'])}',
),
HealthMeter(
label: 'Used',
value:
healthRatio(row['used_percent']) ??
healthUsageRatio(used, total),
),
],
),
);
},
),
],
),
);
}
}
@@ -0,0 +1,117 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../settings_theme.dart';
import 'health_models.dart';
class HealthCard extends StatelessWidget {
const HealthCard({super.key, required this.title, required this.child});
final String title;
final Widget child;
@override
Widget build(BuildContext context) {
final content = Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(title, style: settingsTextStyle(context, title: true)),
const SizedBox(height: 12),
child,
],
),
);
if (!usesCupertinoControls(context)) return Card(child: content);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: DecoratedBox(
decoration: BoxDecoration(
color: CupertinoColors.secondarySystemGroupedBackground.resolveFrom(
context,
),
borderRadius: BorderRadius.circular(12),
),
child: DefaultTextStyle(
style: settingsTextStyle(context),
child: content,
),
),
);
}
}
class HealthMeter extends StatelessWidget {
const HealthMeter({super.key, required this.label, required this.value});
final String label;
final double? value;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final percent = value == null ? null : value! * 100;
final cupertino = usesCupertinoControls(context);
final normal = cupertino
? CupertinoTheme.of(context).primaryColor
: scheme.primary;
final high = cupertino
? CupertinoColors.systemOrange.resolveFrom(context)
: scheme.tertiary;
final critical = cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: scheme.error;
final color = percent == null
? scheme.outline
: percent >= healthMeterCritical
? critical
: percent >= healthMeterHigh
? high
: normal;
return Row(
children: [
Expanded(
child: ExcludeSemantics(
excluding: value == null,
child: LinearProgressIndicator(
value: value?.clamp(0, 1) ?? 0,
color: color,
semanticsLabel: label,
),
),
),
const SizedBox(width: 10),
Flexible(
child: Text(
'$label ${percent == null ? '—' : '${percent.toStringAsFixed(1)}%'}',
),
),
],
);
}
}
class HealthRows extends StatelessWidget {
const HealthRows(this.rows, {super.key});
final List<(String, String)> rows;
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final row in rows)
Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [Text(row.$1), Text(row.$2)],
),
),
],
);
}
class HealthAction extends StatelessWidget {
const HealthAction({super.key, required this.label, this.onPressed});
final String label;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) => usesCupertinoControls(context)
? CupertinoButton(onPressed: onPressed, child: Text(label))
: TextButton(onPressed: onPressed, child: Text(label));
}
@@ -0,0 +1,30 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../settings_row.dart';
import '../settings_theme.dart';
import 'health_screen.dart';
class SettingsHealthSection extends StatelessWidget {
const SettingsHealthSection({super.key, required this.gateway});
final ApiGateway gateway;
@override
Widget build(BuildContext context) => SettingsRow(
leading: Icon(
usesCupertinoControls(context)
? CupertinoIcons.heart
: Icons.monitor_heart_outlined,
),
title: const Text('Server health'),
subtitle: const Text('CPU, memory, GPU, storage and process'),
chevron: true,
onTap: () {
final page = HealthScreen(gateway: gateway);
Navigator.of(context).push(
usesCupertinoControls(context)
? CupertinoPageRoute<void>(builder: (_) => page)
: MaterialPageRoute<void>(builder: (_) => page),
);
},
);
}
@@ -14,6 +14,7 @@ import 'settings_font_section.dart';
import '../../ui/theme/app_font_controller.dart';
import 'settings_group.dart';
import 'storage/settings_storage_section.dart';
import 'health/settings_health_section.dart';
import 'settings_page_body.dart';
import 'settings_notifications_section.dart';
import 'settings_ntfy_section.dart';
@@ -201,6 +202,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
'Data management',
SettingsStorageSection(gateway: widget.client),
),
_single('Server', SettingsHealthSection(gateway: widget.client)),
// A device-local choice: a browser and a phone keep their own.
SettingsFontSection(
controller: widget.fonts ?? AppFontController.instance,
@@ -0,0 +1,88 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/settings/health/health_controller.dart';
class _Gateway implements ApiGateway {
final calls = <String>[];
JsonMap reply;
_Gateway(this.reply);
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
expect(fields, isEmpty);
return reply;
}
}
void main() {
test(
'reads the server_stats envelope without inventing missing values',
() async {
final gateway = _Gateway({
'server_stats': {
'host': {'hostname': 'fixture-host'},
'cpu': {'usage_percent': 42.5},
},
});
final controller = HealthController(gateway);
await controller.load();
expect(gateway.calls, ['server_stats']);
expect(controller.stats!['host']['hostname'], 'fixture-host');
expect(controller.error, isNull);
controller.dispose();
},
);
test('malformed or unsupported replies are actionable errors', () async {
final controller = HealthController(
_Gateway({'error': 'Unknown command: server_stats'}),
);
await controller.load();
expect(controller.stats, isNull);
expect(controller.error, contains('Unknown command'));
controller.dispose();
});
test('a section error remains available for inline rendering', () async {
final controller = HealthController(
_Gateway({
'server_stats': {
'gpu': {'error': 'GPU metrics unavailable'},
},
}),
);
await controller.load();
expect(controller.stats!['gpu']['error'], 'GPU metrics unavailable');
controller.dispose();
});
test('does not overlap requests or notify after disposal', () async {
final completer = Completer<JsonMap>();
final gateway = _PendingGateway(completer.future);
final controller = HealthController(gateway);
var notifications = 0;
controller.addListener(() => notifications++);
final first = controller.load();
await controller.load();
expect(gateway.calls, 1);
controller.dispose();
completer.complete({'server_stats': {}});
await first;
expect(notifications, 1);
});
}
class _PendingGateway implements ApiGateway {
_PendingGateway(this.result);
final Future<JsonMap> result;
int calls = 0;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls++;
return result;
}
}
@@ -0,0 +1,69 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/health/health_models.dart';
import 'package:pipelines_app/features/settings/health/health_widgets.dart';
void main() {
test('missing usage remains unknown', () {
expect(healthUsageRatio(null, 100), isNull);
expect(healthUsageRatio(5, null), isNull);
expect(healthUsageRatio(5, 0), isNull);
expect(healthUsageRatio(150, 100), 1);
});
testWidgets('meter applies consistent high and critical thresholds', (
tester,
) async {
final scheme = ColorScheme.fromSeed(seedColor: Colors.blue);
for (final (value, color) in [
(0.799, scheme.primary),
(0.8, scheme.tertiary),
(0.949, scheme.tertiary),
(0.95, scheme.error),
]) {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(colorScheme: scheme),
home: Scaffold(
body: HealthMeter(label: 'CPU', value: value),
),
),
);
expect(
tester
.widget<LinearProgressIndicator>(
find.byType(LinearProgressIndicator),
)
.color,
color,
);
}
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: HealthMeter(label: 'CPU', value: null)),
),
);
expect(
tester
.widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator))
.value,
0,
);
expect(find.text('CPU —'), findsOneWidget);
});
testWidgets('meter label fits narrow large text', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2)),
child: const SizedBox(
width: 200,
child: HealthMeter(label: 'Utilization', value: 0.97),
),
),
),
),
);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/settings/health/health_screen.dart';
class _Gateway implements ApiGateway {
int calls = 0;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls++;
return {
'server_stats': {
'sampled_at': DateTime.now().toUtc().toIso8601String(),
'host': {
'hostname': 'test-host',
'platform': 'Linux',
'platform_version': '1',
},
'cpu': {'usage_percent': 90, 'logical_cores': 4},
'memory': {'used_percent': 20, 'total_bytes': 100, 'used_bytes': 20},
'storage': [
{'mount': '/secure', 'error': 'Storage metrics unavailable'},
],
'gpu': {'available': false, 'reason': 'No GPU'},
'data': {},
'process': {},
},
};
}
}
Future<void> _mount(WidgetTester tester, _Gateway gateway) async {
tester.view.physicalSize = const Size(800, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(home: HealthScreen(gateway: gateway)));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
}
void main() {
testWidgets('renders honest health sections and threshold meter', (
tester,
) async {
final gateway = _Gateway();
await _mount(tester, gateway);
expect(find.text('test-host'), findsOneWidget);
expect(find.text('Storage metrics unavailable'), findsOneWidget);
expect(find.text('Overall 90.0%'), findsOneWidget);
final meter = tester.widget<LinearProgressIndicator>(
find.byType(LinearProgressIndicator).first,
);
final context = tester.element(find.byType(HealthScreen));
expect(meter.color, Theme.of(context).colorScheme.tertiary);
expect(tester.takeException(), isNull);
});
testWidgets('auto-refreshes only while the page is visible', (tester) async {
final gateway = _Gateway();
await _mount(tester, gateway);
expect(gateway.calls, 1);
await tester.pump(const Duration(seconds: 5));
expect(gateway.calls, 2);
final context = tester.element(find.byType(HealthScreen));
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (_) => const Scaffold(body: Text('Covered')),
),
);
await tester.pump(const Duration(milliseconds: 500));
final coveredCalls = gateway.calls;
await tester.pump(const Duration(seconds: 6));
expect(gateway.calls, coveredCalls);
});
testWidgets('stops refreshing after disposal and while backgrounded', (
tester,
) async {
final gateway = _Gateway();
await _mount(tester, gateway);
final observer =
tester.state(find.byType(HealthScreen)) as WidgetsBindingObserver;
observer.didChangeAppLifecycleState(AppLifecycleState.paused);
await tester.pump(const Duration(seconds: 12));
expect(gateway.calls, 1);
observer.didChangeAppLifecycleState(AppLifecycleState.resumed);
await tester.pump();
await tester.pump(const Duration(seconds: 5));
expect(gateway.calls, 2);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(seconds: 12));
expect(gateway.calls, 2);
});
}
+6 -2
View File
@@ -19,7 +19,9 @@ no longer matches the app.
`tool/search_selection_probe_entry.dart` is the real `PipelinesApp` running on
an in-process fixture channel. It never contacts a server. It has run 7 (three
visits plus the artifact `release-report.txt`), run 6, pipelines 24 and 22, and
search hits for `release`. Build it once per change, from `app/`:
search hits for `release`. It also answers `server_stats`, so the Settings route
can be captured before the server command is available. Build it once per
change, from `app/`:
```sh
/Users/alan/development/flutter/bin/flutter build web \
@@ -29,7 +31,9 @@ search hits for `release`. Build it once per change, from `app/`:
URL parameters (the kit sets them from `open=` and the options):
`route=<app route>`, `q=<search>`, `platform=material|cupertino`,
`theme=light|dark`; `--params` (or a step's or script's `params`) adds fixture
options such as `chats=2&rich=1`. Without `theme`, the app follows the browser's colour
options such as `chats=2&rich=1`. Use `route=/settings` to open Settings and then
click `Server health`; the fixture channel returns `server_stats` automatically.
Without `theme`, the app follows the browser's colour
scheme. `--theme` also sets that colour scheme through Chrome emulation.
## Steps
+20
View File
@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
import 'package:pipelines_app/features/settings/health/health_screen.dart';
import 'health_probe_fixture.dart';
void main() => runApp(const _HealthProbeApp());
class _HealthProbeApp extends StatelessWidget {
const _HealthProbeApp();
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Server health fixture',
debugShowCheckedModeBanner: false,
theme: ThemeData(colorSchemeSeed: Colors.blue),
darkTheme: ThemeData(
brightness: Brightness.dark,
colorSchemeSeed: Colors.blue,
),
home: HealthScreen(gateway: HealthProbeGateway()),
);
}
+95
View File
@@ -0,0 +1,95 @@
import 'package:pipelines_app/core/api_gateway.dart';
/// In-memory server_stats reply for browser captures before the server command
/// is available. It deliberately uses the production envelope shape.
class HealthProbeGateway implements ApiGateway {
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type != 'server_stats') return {'error': 'Unknown command: $type'};
return {'server_stats': healthProbeSnapshot()};
}
}
JsonMap healthProbeSnapshot() => {
'sampled_at': DateTime.now().toUtc().toIso8601String(),
'host': {
'hostname': 'capture-host',
'os': 'linux',
'platform': 'Ubuntu',
'platform_version': '24.04',
'uptime_seconds': 86400,
'load1': 1.2,
'load5': 1.0,
'load15': 0.8,
},
'cpu': {
'model': 'Capture CPU',
'logical_cores': 8,
'physical_cores': 4,
'usage_percent': 42.5,
'load1': 1.2,
'load5': 1.0,
'load15': 0.8,
'per_core_percent': [20, 35, 42, 55, 61, 30, 48, 39],
},
'memory': {
'total_bytes': 17179869184,
'used_bytes': 7516192768,
'available_bytes': 9663676416,
'used_percent': 43.7,
'swap_total_bytes': 4294967296,
'swap_used_bytes': 536870912,
},
'storage': [
{
'mount': '/data',
'device': '/dev/sdb',
'fs_type': 'ext4',
'total_bytes': 2199023255552,
'used_bytes': 1759218604441,
'free_bytes': 439804651111,
'used_percent': 80,
},
{
'mount': '/',
'device': '/dev/sda',
'fs_type': 'ext4',
'total_bytes': 107374182400,
'used_bytes': 53687091200,
'free_bytes': 53687091200,
'used_percent': 50,
},
],
'data': {
'dir': '/var/lib/pipelines',
'db_bytes': 1073741824,
'artifacts_bytes': 12884901888,
'total_bytes': 13958643712,
},
'process': {
'pid': 42,
'started_at': '2026-11-06T12:00:00Z',
'rss_bytes': 268435456,
'cpu_percent': 4.5,
'goroutines': 84,
'heap_bytes': 134217728,
'threads': 12,
'go_version': 'go1.24.1',
'build': 'capture',
},
'gpu': {
'available': true,
'devices': [
{
'name': 'NVIDIA RTX 4070',
'vendor': 'NVIDIA',
'utilization_percent': 36,
'memory_total_bytes': 12884901888,
'memory_used_bytes': 3221225472,
'temperature_c': 54,
},
],
},
};
@@ -1,3 +1,4 @@
import 'health_probe_fixture.dart';
// Standalone fixture entry for real-browser Search result-selection evidence.
//
// Build and probe (from app/):
@@ -479,6 +480,12 @@ JsonMap? probeReply(JsonMap request) {
'build': {'version': 'Search selection probe fixture'},
'time': '2026-10-20T09:00:00Z',
};
case 'server_stats':
return {
'id': id,
'type': 'server_stats_result',
'server_stats': healthProbeSnapshot(),
};
case 'list_runs':
return {
'id': id,
+17
View File
@@ -0,0 +1,17 @@
# Server stats
## Client
Settings → Server health shows the machine's CPU, memory and swap, GPU,
local mounts, Pipelines data directory and server process. Native Material and
Cupertino controls follow the active host. Meters use the theme primary colour,
high usage from 80%, and critical from 95%. Missing measurements display “—”;
section and mount errors remain visible alongside available sections.
Auto-refresh samples every five seconds while the route is current and the app
is active, stops when covered or disposed, and never overlaps a pending request.
Manual refresh and an auto-refresh toggle are available in the host summary.
The full-app capture fixture answers `server_stats` from a shared snapshot with
one GPU and two mounts. Open `/settings` and choose Server health; fixture
captures do not prove live host metrics or device behaviour.