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: refresh update manifest before installation to prevent downgrades and handle pulled builds

0xken151a16b526670f
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 243d62da2..bf234cc88 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -3555,6 +3555,38 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// The build to install now: the newest the manifest offers, or [captured]
+ /// when the manifest cannot be read or has nothing newer. Null means the
+ /// manifest no longer offers anything at all — the build was pulled.
+ ///
+ /// Only ever forward: a manifest that regressed (a bad publish, a stale
+ /// mirror) must not talk this into a downgrade, which is what `semverGt`
+ /// settles. And never onto a version this person SKIPPED — pressing Update
+ /// on one build is not consent to a different one they already said no to,
+ /// and nothing is lost by installing what they pressed: the skipped newer
+ /// one raises no offer afterwards either (`_recordUpdateCheck`).
+ Future<UpdateInfo?> _freshestUpdate(UpdateInfo captured) async {
+ final DesktopUpdateCheck result;
+ try {
+ result = await _updater.check();
+ } catch (error) {
+ // A network that cannot answer is not a reason to refuse an update whose
+ // bytes are verified against their own sha256 anyway.
+ debugPrint('AppNotifier.installAvailableUpdate: refresh failed · $error');
+ return captured;
+ }
+ if (_disposed) return captured;
+ lastUpdateCheck = result;
+ final latest = result.update;
+ if (latest != null) {
+ final newer =
+ semverGt(latest.version, captured.version) &&
+ _skippedDesktopUpdateVersion != latest.version;
+ return newer ? latest : captured;
+ }
+ return result.status == DesktopUpdateCheckStatus.upToDate ? null : captured;
+ }
+
/// Clears a failed install without burying the offer.
///
/// Skipping is permanent — it records the version so the background check
@@ -3582,19 +3614,43 @@ class AppNotifier extends ChangeNotifier {
/// Downloads, verifies, and installs only after an explicit user action.
/// A failed operation leaves the running app untouched and retryable.
Future<bool> installAvailableUpdate({UpdateInfo? update}) async {
- final info = update ?? availableUpdate;
- if (_disposed || viewer != null || info == null || isInstallingUpdate) {
+ final chosen = update ?? availableUpdate;
+ if (_disposed || viewer != null || chosen == null || isInstallingUpdate) {
return false;
}
- // The displayed version is the one the user chose. Later manifest
- // responses cannot change the installation or the offer a failure retains.
- availableUpdate = info;
+ // Reassigned once the manifest has been re-read below; the failure messages
+ // at the end name whichever build was actually attempted.
+ var info = chosen;
isInstallingUpdate = true;
updateDownloadFraction = null;
updateError = null;
notifyListeners();
try {
final updater = _updater;
+ // One press, the newest build. What is on screen can be minutes old, and
+ // installing THAT only to be offered the next one on the way back is two
+ // updates for one thing. The check costs a small GET against a manifest
+ // the download already depends on.
+ //
+ // `isInstallingUpdate` is set above first, so the answer cannot race
+ // `_recordUpdateCheck` — which bows out while an install is running —
+ // and the offer is published here instead, once the version is settled.
+ final fresh = await _freshestUpdate(info);
+ if (fresh == null) {
+ // Withdrawn from the channel between the offer and the press. Installing
+ // a build that has just been pulled is the one outcome here worth
+ // refusing; everything else falls through to the captured one.
+ //
+ // Not an `updateError`: nothing failed, and the banner that would carry
+ // one is keyed on there being an offer — which there is not any more.
+ // Dropping the offer IS the state, and the dialog that asked turns
+ // itself into "You're up to date" on the false return.
+ availableUpdate = null;
+ updateError = null;
+ return false;
+ }
+ info = fresh;
+ availableUpdate = 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.
diff --git a/desktop/lib/update/desktop_updater.dart b/desktop/lib/update/desktop_updater.dart
index 2ccfb5d13..0bfe21538 100644
--- a/desktop/lib/update/desktop_updater.dart
+++ b/desktop/lib/update/desktop_updater.dart
@@ -177,7 +177,16 @@ class DesktopUpdater {
final String _architecture;
final _checksInFlight = <String?, Future<DesktopUpdateCheck>>{};
- static const checkInterval = Duration(hours: 6);
+ /// How often the background poll asks the manifest.
+ ///
+ /// Five minutes, not the six hours this used to be, because the offer on
+ /// screen has to be close to the build Update will actually install: a person
+ /// who leaves a notice sitting for an afternoon should not be shown a version
+ /// that was superseded hours ago. The request is one small GET that GCS
+ /// serves `no-cache`, the overlap guard in [startChecking] and the in-flight
+ /// map above mean a slow answer never stacks up a second one, and the CLI's
+ /// own self-updater polls on the same order (`cli/src/lib/selfUpdate.ts`).
+ static const checkInterval = Duration(minutes: 5);
bool get canCheck => _enabled && _releaseMode;
diff --git a/desktop/lib/widgets/update_notice.dart b/desktop/lib/widgets/update_notice.dart
index a642f122d..79a0db85a 100644
--- a/desktop/lib/widgets/update_notice.dart
+++ b/desktop/lib/widgets/update_notice.dart
@@ -370,62 +370,85 @@ Future<void> showUpdateCheckDialog(
// 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(
- key: const Key('close-update-dialog-button'),
- label: 'Close',
- onPressed: () async {
- Navigator.of(dialogContext).pop();
- },
- ),
- if (!current.isSkipped)
+ builder: (context, _) {
+ // Update re-reads the manifest and installs the newest build,
+ // which may be newer than the one this dialog opened on. Name
+ // the one going in, not the one that was reviewed.
+ final installingVersion =
+ notifier.availableUpdate?.version ?? update.version;
+ return _UpdateDialog(
+ icon: LucideIcons.arrowDownToLine300,
+ title: installing
+ ? 'Installing Harness $installingVersion…'
+ : '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(
+ key: const Key('close-update-dialog-button'),
+ label: 'Close',
+ onPressed: () async {
+ 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: 'Skip ${update.version}',
+ label: 'Update',
+ primary: true,
onPressed: () async {
- await notifier.skipAvailableUpdate(
- update: update,
- );
- if (dialogContext.mounted) {
- Navigator.of(dialogContext).pop();
+ setState(() => installing = true);
+ final installed = await notifier
+ .installAvailableUpdate(update: update);
+ // A successful install never returns — the process is
+ // replaced. Reaching here means it did not happen.
+ if (!context.mounted || installed) return;
+ // The install re-reads the manifest, and the build
+ // can be gone from it by then. There is no error to
+ // show for that and no offer left to carry one, so
+ // say the true thing here rather than closing on
+ // nothing.
+ if (notifier.availableUpdate == null) {
+ setState(() {
+ installing = false;
+ current = const ManualUpdateCheck(
+ check: DesktopUpdateCheck.upToDate(),
+ );
+ });
+ return;
}
+ // Otherwise it failed, and the banner behind this
+ // dialog is already showing why.
+ setState(() => installing = false);
+ 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/manual_update_check_test.dart b/desktop/test/manual_update_check_test.dart
index 09bfcbe64..41e1d33b3 100644
--- a/desktop/test/manual_update_check_test.dart
+++ b/desktop/test/manual_update_check_test.dart
@@ -77,10 +77,22 @@ class _Manifest {
}
class _Installer extends DesktopUpdater {
- _Installer() : super(enabled: false);
+ _Installer({this.refresh}) : super(enabled: false);
+
+ /// What the manifest says when the install re-reads it. Null leaves the
+ /// disabled updater's own answer, which no-ops the refresh — the shape of
+ /// every test here that is not about it.
+ final DesktopUpdateCheck? refresh;
+ int refreshes = 0;
final staged = Completer<StagedUpdate?>();
UpdateInfo? requested;
+ @override
+ Future<DesktopUpdateCheck> check({String? currentVersion}) async {
+ refreshes++;
+ return refresh ?? await super.check(currentVersion: currentVersion);
+ }
+
/// 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;
@@ -309,7 +321,7 @@ void main() {
});
testWidgets(
- 'background checks wait six hours, avoid overlap, and stop after cancellation',
+ 'background checks wait five minutes, avoid overlap, and stop after cancellation',
(tester) async {
final manifest = _Manifest();
final observed = <DesktopUpdateCheck>[];
@@ -321,9 +333,9 @@ void main() {
manifest.answer(version: '1.0.0');
await tester.pump();
expect(observed, hasLength(1));
- await tester.pump(const Duration(hours: 5, minutes: 59));
+ await tester.pump(const Duration(minutes: 4, seconds: 59));
expect(manifest.requests, isEmpty);
- await tester.pump(const Duration(minutes: 1));
+ await tester.pump(const Duration(seconds: 1));
await manifest.waitForRequest(tester);
await tester.pump(const Duration(hours: 12));
expect(manifest.requests, hasLength(1));
@@ -448,9 +460,14 @@ void main() {
});
testWidgets(
- 'Update uses the reviewed version and stays open during installation',
+ 'Update installs the newest build, not the one that was on screen',
(tester) async {
- final installer = _Installer();
+ // One press has to be enough. Installing what the dialog opened on, and
+ // then being offered the next version on the way back, is two updates for
+ // one thing — which is what this used to do on purpose.
+ final installer = _Installer(
+ refresh: const DesktopUpdateCheck.available(_laterUpdate),
+ );
final app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
@@ -467,10 +484,10 @@ void main() {
),
);
await tester.pumpAndSettle();
- // A newer background result must not change what the visible action does.
- app.availableUpdate = _laterUpdate;
await tester.tap(find.text('Update'));
await tester.pump();
+ // The dialog names the build going in, not the one that was reviewed.
+ expect(find.textContaining('Installing Harness 1.0.5'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump(const Duration(milliseconds: 200));
final stayedOpen = find.byType(Dialog).evaluate().length == 1;
@@ -478,13 +495,133 @@ void main() {
await tester.pumpAndSettle();
await dialog;
expect(stayedOpen, isTrue);
- expect(installer.requested?.version, '1.0.4');
- expect(app.updateError, contains('1.0.4'));
- expect(app.availableUpdate?.version, '1.0.4');
+ expect(installer.requested?.version, '1.0.5');
+ expect(app.updateError, contains('1.0.5'));
+ expect(app.availableUpdate?.version, '1.0.5');
expect(find.byType(Dialog), findsNothing);
},
);
+ testWidgets('a manifest that cannot be read installs what was offered', (
+ tester,
+ ) async {
+ // Refusing an update because the network blinked would be worse than
+ // installing bytes that still have to match their own sha256.
+ final installer = _Installer(refresh: const DesktopUpdateCheck.failed());
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _reviewedUpdate;
+ addTearDown(app.dispose);
+ final install = app.installAvailableUpdate();
+ await tester.pump();
+ installer.staged.complete(null);
+ expect(await install, isFalse);
+ expect(installer.refreshes, 1);
+ expect(installer.requested?.version, '1.0.4');
+ expect(app.availableUpdate?.version, '1.0.4');
+ });
+
+ testWidgets('a build pulled from the channel is not installed', (
+ tester,
+ ) async {
+ final installer = _Installer(refresh: const DesktopUpdateCheck.upToDate());
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _reviewedUpdate;
+ addTearDown(app.dispose);
+ expect(await app.installAvailableUpdate(), isFalse);
+ expect(installer.requested, isNull, reason: 'nothing was downloaded');
+ expect(app.availableUpdate, isNull);
+ // Nothing failed, and there is no offer left for a banner to carry an
+ // error on; the dialog below is what tells the person.
+ expect(app.updateError, isNull);
+ });
+
+ testWidgets('the dialog says you are up to date when the build was pulled', (
+ tester,
+ ) async {
+ final installer = _Installer(refresh: const DesktopUpdateCheck.upToDate());
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _reviewedUpdate;
+ addTearDown(app.dispose);
+ await tester.pumpWidget(const MaterialApp(home: Placeholder()));
+ final dialog = showUpdateCheckDialog(
+ tester.element(find.byType(Placeholder)),
+ app,
+ const ManualUpdateCheck(
+ check: DesktopUpdateCheck.available(_reviewedUpdate),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Update'));
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsOneWidget, reason: 'it does not vanish');
+ expect(find.textContaining('up to date'), findsWidgets);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await dialog;
+ });
+
+ testWidgets('Update does not jump to a version the person skipped', (
+ tester,
+ ) async {
+ // Pressing Update on 1.0.4 is not consent to 1.0.5, which they said no to.
+ final installer = _Installer(
+ refresh: const DesktopUpdateCheck.available(_laterUpdate),
+ );
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _laterUpdate;
+ addTearDown(app.dispose);
+ await app.skipAvailableUpdate(update: _laterUpdate);
+ app.availableUpdate = _reviewedUpdate;
+ final install = app.installAvailableUpdate();
+ await tester.pump();
+ installer.staged.complete(null);
+ expect(await install, isFalse);
+ expect(installer.requested?.version, '1.0.4');
+ });
+
+ testWidgets('a manifest that went backwards cannot downgrade the offer', (
+ tester,
+ ) async {
+ final installer = _Installer(
+ refresh: const DesktopUpdateCheck.available(
+ UpdateInfo(
+ version: '1.0.3',
+ url: 'https://updates.example.test/1.0.3.zip',
+ sha256: 'unused',
+ size: 1024,
+ ),
+ ),
+ );
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _reviewedUpdate;
+ addTearDown(app.dispose);
+ final install = app.installAvailableUpdate();
+ await tester.pump();
+ installer.staged.complete(null);
+ expect(await install, isFalse);
+ expect(installer.requested?.version, '1.0.4');
+ });
+
testWidgets('Skip uses the reviewed version without hiding a newer offer', (
tester,
) async {