Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: add download progress percentage to desktop updater and UI

0xken15419e9a0508c6
diff --git a/desktop/lib/settings/sections/about_section.dart b/desktop/lib/settings/sections/about_section.dart
index 77653fb83..0ac86538a 100644
--- a/desktop/lib/settings/sections/about_section.dart
+++ b/desktop/lib/settings/sections/about_section.dart
@@ -297,8 +297,11 @@ class _PillState {
static _PillState of(AppNotifier notifier, {required bool checking}) {
if (notifier.isInstallingUpdate) {
+ // The same number the banner and the dialog show; without one the
+ // download has not started reporting yet, or is being unpacked.
+ final percent = notifier.updateDownloadPercent;
return _PillState(
- 'Installing…',
+ percent == null ? 'Installing…' : 'Installing… $percent%',
grid.AppPalette.accentOnSurface,
wash: true,
);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 1f362f9f5..62ce6003d 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -593,6 +593,12 @@ class AppNotifier extends ChangeNotifier {
UpdateInfo? availableUpdate;
bool isCheckingForUpdate = false;
bool isInstallingUpdate = false;
+
+ /// How much of the new build has arrived, 0..1, while it is downloading;
+ /// null before the first byte and again once the bytes are in — verifying and
+ /// unpacking have no counter, so the bar goes back to indeterminate rather
+ /// than sitting at a 100% that has not finished anything.
+ double? updateDownloadFraction;
String? updateError;
final Set<String> _offlinePollsInFlight = {};
final Map<String, Object> _offlineRecoveryInFlight = {};
@@ -1640,6 +1646,13 @@ class AppNotifier extends ChangeNotifier {
String get autonomousEnv => _autonomousEnv;
bool get hasAvailableUpdate => availableUpdate != null;
+ /// [updateDownloadFraction] as whole percent, for the one word the banner,
+ /// the dialog and Settings all show.
+ int? get updateDownloadPercent {
+ final fraction = updateDownloadFraction;
+ return fraction == null ? null : (fraction * 100).clamp(0, 100).floor();
+ }
+
static const offlineRetryInterval = Duration(seconds: 5);
static const localDaemonReconnectDelay = Duration(seconds: 1);
static const agentSyncInterval = Duration(seconds: 60);
@@ -3355,11 +3368,30 @@ class AppNotifier extends ChangeNotifier {
// responses cannot change the installation or the offer a failure retains.
availableUpdate = info;
isInstallingUpdate = true;
+ updateDownloadFraction = null;
updateError = null;
notifyListeners();
try {
final updater = _updater;
- final staged = await updater.downloadAndStage(info);
+ // One notify per whole percent. Dio reports every chunk, and each notify
+ // rebuilds the whole app shell (the banner lives in its ListenableBuilder),
+ // so a 45 MB build would repaint thousands of times for a bar 200px wide.
+ var shown = -1;
+ final staged = await updater.downloadAndStage(
+ info,
+ onProgress: (received, total) {
+ if (_disposed || total <= 0) return;
+ final fraction = (received / total).clamp(0.0, 1.0);
+ // The bytes are all in: verifying and unpacking follow, and neither
+ // can be measured, so stop claiming a number for them.
+ final next = fraction >= 1 ? null : fraction;
+ final percent = next == null ? 100 : (next * 100).floor();
+ if (percent == shown) return;
+ shown = percent;
+ updateDownloadFraction = next;
+ notifyListeners();
+ },
+ );
if (staged == null) {
updateError = 'Could not download and verify Harness ${info.version}.';
return false;
@@ -3376,6 +3408,7 @@ class AppNotifier extends ChangeNotifier {
return false;
} finally {
isInstallingUpdate = false;
+ updateDownloadFraction = null;
if (!_disposed) notifyListeners();
}
}
diff --git a/desktop/lib/update/desktop_updater.dart b/desktop/lib/update/desktop_updater.dart
index 6fc4a5d06..954949674 100644
--- a/desktop/lib/update/desktop_updater.dart
+++ b/desktop/lib/update/desktop_updater.dart
@@ -326,13 +326,25 @@ class DesktopUpdater {
/// single AppImage file), so the sha256 check already covers everything there is: it is made
/// executable and staged as-is, with nothing to unpack or recheck.
/// Returns null (and cleans up anything partially written) on any verification failure.
- Future<StagedUpdate?> downloadAndStage(UpdateInfo info) async {
+ /// [onProgress] reports the DOWNLOAD only — bytes received out of
+ /// [UpdateInfo.size]. The manifest's size is the denominator rather than the
+ /// response's, because a CDN that omits `Content-Length` leaves Dio reporting
+ /// `-1` and the manifest is the authority the hash is checked against anyway.
+ /// Verifying and unpacking afterwards have no counter, so a caller showing a
+ /// percentage stops at 100 and keeps saying "installing" until this returns.
+ Future<StagedUpdate?> downloadAndStage(
+ UpdateInfo info, {
+ void Function(int received, int total)? onProgress,
+ }) async {
if (!_enabled) return null;
Directory? stagingDir;
try {
final response = await _dio.get<List<int>>(
info.url,
options: Options(responseType: ResponseType.bytes),
+ onReceiveProgress: onProgress == null
+ ? null
+ : (received, _) => onProgress(received, info.size),
);
final bytes = response.data;
if (bytes == null || bytes.length != info.size) {
diff --git a/desktop/lib/widgets/update_notice.dart b/desktop/lib/widgets/update_notice.dart
index 4150b628d..a642f122d 100644
--- a/desktop/lib/widgets/update_notice.dart
+++ b/desktop/lib/widgets/update_notice.dart
@@ -40,6 +40,10 @@ class UpdateNotice extends StatelessWidget {
if (update == null) return const SizedBox.shrink();
final installing = notifier.isInstallingUpdate;
+ // Null until the first bytes land, and again while the download is being
+ // verified and unpacked — the bar is honest about not knowing then.
+ final fraction = installing ? notifier.updateDownloadFraction : null;
+ final percent = installing ? notifier.updateDownloadPercent : null;
final error = notifier.updateError;
final failed = error != null && !installing;
@@ -133,7 +137,21 @@ class UpdateNotice extends StatelessWidget {
),
),
),
- if (!installing && !failed && update.size > 0) ...[
+ // The size answers "how long will this take?" before
+ // the download; the percent answers it during, and
+ // says it alone — the two together read as arithmetic
+ // homework in a band this narrow.
+ if (percent != null) ...[
+ const SizedBox(width: 8),
+ Text(
+ '· $percent%',
+ style: grid.AppType.monoMeta(
+ color: grid.AppPalette.textFaint,
+ ),
+ ),
+ ] else if (!installing &&
+ !failed &&
+ update.size > 0) ...[
const SizedBox(width: 8),
Text(
'· ${formatDownloadSize(update.size)}',
@@ -184,15 +202,17 @@ class UpdateNotice extends StatelessWidget {
],
),
),
- // Indeterminate on purpose: downloadAndStage() resolves once, with
- // no byte counter to read, so a percentage here would be invented.
+ // Determinate while the bytes are arriving; indeterminate for the
+ // verify-and-unpack tail, which has nothing to count.
if (installing)
Positioned(
left: 0,
right: 0,
bottom: 0,
child: LinearProgressIndicator(
+ key: const ValueKey('update-progress-bar'),
minHeight: 2,
+ value: fraction,
backgroundColor: Colors.transparent,
color: grid.AppPalette.accentOnSurface,
),
@@ -344,55 +364,68 @@ Future<void> showUpdateCheckDialog(
}
return PopScope(
canPop: !installing,
- child: _UpdateDialog(
- icon: LucideIcons.arrowDownToLine300,
- title: installing
- ? 'Installing Harness ${update.version}…'
- : 'Harness ${update.version} is available',
- body: installing
- ? 'Don’t quit Harness. It will restart on its own.'
- : current.isSkipped
- ? 'You skipped this version earlier. You can still install it.'
- : 'Download and install it now? Harness will restart when it '
- 'finishes.',
- busy: installing,
- update: installing ? null : update,
- actions: installing
- ? const []
- : [
- _DialogAction(
- key: const Key('close-update-dialog-button'),
- label: 'Close',
- onPressed: () async {
- Navigator.of(dialogContext).pop();
- },
- ),
- if (!current.isSkipped)
+ // The percentage moves while this dialog is up, and the
+ // StatefulBuilder above only rebuilds on ITS own setState — which
+ // the download never calls. Listening to the notifier is what lets
+ // the number here count along with the band behind it.
+ child: ListenableBuilder(
+ listenable: notifier,
+ builder: (context, _) => _UpdateDialog(
+ icon: LucideIcons.arrowDownToLine300,
+ title: installing
+ ? 'Installing Harness ${update.version}…'
+ : 'Harness ${update.version} is available',
+ body: installing
+ ? [
+ if (notifier.updateDownloadPercent case final percent?)
+ 'Downloading… $percent%.',
+ 'Don’t quit Harness. It will restart on its own.',
+ ].join(' ')
+ : current.isSkipped
+ ? 'You skipped this version earlier. You can still install it.'
+ : 'Download and install it now? Harness will restart when it '
+ 'finishes.',
+ busy: installing,
+ update: installing ? null : update,
+ actions: installing
+ ? const []
+ : [
_DialogAction(
- label: 'Skip ${update.version}',
+ key: const Key('close-update-dialog-button'),
+ label: 'Close',
onPressed: () async {
- await notifier.skipAvailableUpdate(update: update);
- if (dialogContext.mounted) {
- Navigator.of(dialogContext).pop();
- }
+ Navigator.of(dialogContext).pop();
},
),
- _DialogAction(
- label: 'Update',
- primary: true,
- onPressed: () async {
- setState(() => installing = true);
- final installed = await notifier
- .installAvailableUpdate(update: update);
- // A successful install never returns — the process is
- // replaced. Reaching here means it failed, and the banner
- // behind this dialog is already showing why.
- if (!context.mounted || installed) return;
- setState(() => installing = false);
- Navigator.of(dialogContext).pop();
- },
- ),
- ],
+ if (!current.isSkipped)
+ _DialogAction(
+ label: 'Skip ${update.version}',
+ onPressed: () async {
+ await notifier.skipAvailableUpdate(
+ update: update,
+ );
+ if (dialogContext.mounted) {
+ Navigator.of(dialogContext).pop();
+ }
+ },
+ ),
+ _DialogAction(
+ label: 'Update',
+ primary: true,
+ onPressed: () async {
+ setState(() => installing = true);
+ final installed = await notifier
+ .installAvailableUpdate(update: update);
+ // A successful install never returns — the process is
+ // replaced. Reaching here means it failed, and the banner
+ // behind this dialog is already showing why.
+ if (!context.mounted || installed) return;
+ setState(() => installing = false);
+ Navigator.of(dialogContext).pop();
+ },
+ ),
+ ],
+ ),
),
);
},
diff --git a/desktop/test/desktop_updater_test.dart b/desktop/test/desktop_updater_test.dart
index 4e23e7f67..0ac6d10c3 100644
--- a/desktop/test/desktop_updater_test.dart
+++ b/desktop/test/desktop_updater_test.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:io';
+import 'dart:math' show min;
import 'package:cryptography/cryptography.dart';
import 'package:dio/dio.dart';
@@ -107,6 +108,10 @@ void main() {
required String manifestVersion,
String? shaOverride,
int? sizeOverride,
+
+ /// Writes the body in pieces, as a CDN does, so a progress callback has
+ /// more than one number to report.
+ bool chunked = false,
}) async {
server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final base = 'http://127.0.0.1:${server!.port}';
@@ -124,7 +129,18 @@ void main() {
}),
);
} else if (request.uri.path == '/Harness-macos.zip') {
- request.response.add(zipBytes);
+ if (chunked) {
+ const pieces = 4;
+ final step = (zipBytes.length / pieces).ceil();
+ for (var at = 0; at < zipBytes.length; at += step) {
+ request.response.add(
+ zipBytes.sublist(at, min(at + step, zipBytes.length)),
+ );
+ await request.response.flush();
+ }
+ } else {
+ request.response.add(zipBytes);
+ }
} else {
request.response.statusCode = HttpStatus.notFound;
}
@@ -289,6 +305,32 @@ void main() {
},
);
+ // What the banner counts. The manifest's size is the denominator, so the
+ // fraction is right even from a server that sends no Content-Length.
+ test('downloadAndStage reports the bytes as they arrive', () async {
+ await serveMetadataAndZip(manifestVersion: newVersion, chunked: true);
+ final updater = DesktopUpdater(enabled: true, dio: Dio(), isLinux: false);
+ final info = UpdateInfo(
+ version: newVersion,
+ url: 'http://127.0.0.1:${server!.port}/Harness-macos.zip',
+ sha256: zipSha,
+ size: zipBytes.length,
+ );
+ final seen = <(int, int)>[];
+ final staged = await updater.downloadAndStage(
+ info,
+ onProgress: (received, total) => seen.add((received, total)),
+ );
+ expect(staged, isNotNull, reason: 'the download itself must still verify');
+ expect(seen, isNotEmpty);
+ expect(seen.every((row) => row.$2 == zipBytes.length), isTrue);
+ expect(
+ seen.map((row) => row.$1).toList(),
+ orderedEquals(seen.map((row) => row.$1).toList()..sort()),
+ );
+ expect(seen.last.$1, zipBytes.length);
+ }, skip: _macOnly);
+
test(
'downloadAndStage verifies sha256 before trusting the download',
() async {
diff --git a/desktop/test/manual_update_check_test.dart b/desktop/test/manual_update_check_test.dart
index 4e88b0b02..09bfcbe64 100644
--- a/desktop/test/manual_update_check_test.dart
+++ b/desktop/test/manual_update_check_test.dart
@@ -81,9 +81,17 @@ class _Installer extends DesktopUpdater {
final staged = Completer<StagedUpdate?>();
UpdateInfo? requested;
+ /// The progress hook the real updater calls per chunk; tests drive it by
+ /// hand to check what the UI makes of a number arriving mid-download.
+ void Function(int received, int total)? progress;
+
@override
- Future<StagedUpdate?> downloadAndStage(UpdateInfo info) {
+ Future<StagedUpdate?> downloadAndStage(
+ UpdateInfo info, {
+ void Function(int received, int total)? onProgress,
+ }) {
requested = info;
+ progress = onProgress;
return staged.future;
}
}
diff --git a/desktop/test/update_progress_test.dart b/desktop/test/update_progress_test.dart
new file mode 100644
index 000000000..31fcb09c5
--- /dev/null
+++ b/desktop/test/update_progress_test.dart
@@ -0,0 +1,174 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/settings/sections/about_section.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/update/desktop_updater.dart';
+import 'package:harness/update/manual_update_check.dart';
+import 'package:harness/widgets/update_notice.dart';
+
+/// A 45 MB build on a slow link used to look like a hang: the band said
+/// "Installing…" behind an indeterminate bar. The manifest carries the exact
+/// byte count, so the download can be counted — and is, in the one number the
+/// banner, the dialog and Settings all read.
+class _Installer extends DesktopUpdater {
+ _Installer() : super(enabled: false);
+ final staged = Completer<StagedUpdate?>();
+ void Function(int received, int total)? progress;
+
+ @override
+ Future<StagedUpdate?> downloadAndStage(
+ UpdateInfo info, {
+ void Function(int received, int total)? onProgress,
+ }) {
+ progress = onProgress;
+ return staged.future;
+ }
+}
+
+const _update = UpdateInfo(
+ version: '1.2.3',
+ url: 'https://updates.example.test/1.2.3.zip',
+ sha256: 'unused',
+ size: 1000,
+);
+
+void main() {
+ late _Installer installer;
+ late AppNotifier app;
+
+ setUp(() {
+ installer = _Installer();
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _update;
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> startInstall(WidgetTester tester) async {
+ unawaited(app.installAvailableUpdate());
+ await tester.pump();
+ expect(installer.progress, isNotNull, reason: 'the hook must be passed in');
+ }
+
+ testWidgets('the banner counts the download, then goes quiet to unpack', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => UpdateNotice(notifier: app),
+ ),
+ ),
+ );
+ expect(find.text('· 18 KB'), findsNothing);
+ await startInstall(tester);
+
+ LinearProgressIndicator bar() => tester.widget<LinearProgressIndicator>(
+ find.byKey(const ValueKey('update-progress-bar')),
+ );
+ // Nothing has arrived yet: no number to show, so the bar keeps moving.
+ expect(bar().value, isNull);
+
+ installer.progress!(420, 1000);
+ await tester.pump();
+ expect(find.text('· 42%'), findsOneWidget);
+ expect(bar().value, closeTo(0.42, 0.001));
+ expect(app.updateDownloadPercent, 42);
+
+ // The bytes are all in; verifying and unpacking cannot be counted.
+ installer.progress!(1000, 1000);
+ await tester.pump();
+ expect(find.textContaining('%'), findsNothing);
+ expect(bar().value, isNull);
+ expect(app.updateDownloadFraction, isNull);
+
+ installer.staged.complete(null);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('Settings says the same number as the band', (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => AboutSection(notifier: app),
+ ),
+ ),
+ ),
+ );
+ await startInstall(tester);
+ installer.progress!(70, 1000);
+ await tester.pump();
+ expect(find.text('Installing… 7%'), findsOneWidget);
+ installer.staged.complete(null);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('the dialog counts along with the band behind it', (
+ tester,
+ ) async {
+ await tester.pumpWidget(const MaterialApp(home: Placeholder()));
+ final dialog = showUpdateCheckDialog(
+ tester.element(find.byType(Placeholder)),
+ app,
+ const ManualUpdateCheck(check: DesktopUpdateCheck.available(_update)),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Update'));
+ await tester.pump();
+ expect(installer.progress, isNotNull);
+
+ installer.progress!(330, 1000);
+ await tester.pump();
+ expect(find.textContaining('Downloading… 33%'), findsOneWidget);
+ installer.progress!(660, 1000);
+ await tester.pump();
+ expect(find.textContaining('Downloading… 66%'), findsOneWidget);
+ // Unpacking has no number, so the sentence drops back to the plain one.
+ installer.progress!(1000, 1000);
+ await tester.pump();
+ expect(find.textContaining('Downloading…'), findsNothing);
+ expect(
+ find.text('Don’t quit Harness. It will restart on its own.'),
+ findsOneWidget,
+ );
+
+ installer.staged.complete(null);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ await tester.pumpWidget(const SizedBox());
+ unawaited(dialog);
+ });
+
+ testWidgets('one repaint per whole percent, not per chunk', (tester) async {
+ await tester.pumpWidget(const MaterialApp(home: Placeholder()));
+ await startInstall(tester);
+ var notifications = 0;
+ void count() => notifications++;
+ app.addListener(count);
+ addTearDown(() => app.removeListener(count));
+ // Three chunks inside the same percent: the band has nothing new to say.
+ for (final received in [10, 12, 15]) {
+ installer.progress!(received, 1000);
+ }
+ expect(notifications, 1);
+ installer.progress!(25, 1000);
+ expect(notifications, 2);
+ installer.staged.complete(null);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ });
+}