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,