From 97f190e1b11a7e371d53adce2605753c2bdb2c08 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 8 Nov 2026 00:14:53 +0000 Subject: [PATCH] Offer platform-specific updates at startup and foreground return --- app/lib/application/app_router.dart | 3 + app/lib/application/pipelines_app.dart | 98 +++++++ app/lib/features/updates/launch_update.dart | 109 ++++++++ .../updates/launch_update_dialog.dart | 188 +++++++++++++ app/lib/features/updates/web_release.dart | 8 + .../features/updates/web_release_stub.dart | 2 + app/lib/features/updates/web_release_web.dart | 26 ++ app/notes/startup-update-check.md | 46 +++ .../startup_update_check_test.dart | 96 +++++++ .../application/startup_update_flow_test.dart | 264 ++++++++++++++++++ .../updates/launch_update_checker_test.dart | 121 ++++++++ .../features/updates/launch_update_test.dart | 35 +++ 12 files changed, 996 insertions(+) create mode 100644 app/lib/features/updates/launch_update.dart create mode 100644 app/lib/features/updates/launch_update_dialog.dart create mode 100644 app/lib/features/updates/web_release.dart create mode 100644 app/lib/features/updates/web_release_stub.dart create mode 100644 app/lib/features/updates/web_release_web.dart create mode 100644 app/notes/startup-update-check.md create mode 100644 app/test/application/startup_update_check_test.dart create mode 100644 app/test/application/startup_update_flow_test.dart create mode 100644 app/test/features/updates/launch_update_checker_test.dart create mode 100644 app/test/features/updates/launch_update_test.dart diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index d6b00af1..f7fec32d 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -96,6 +96,9 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { /// Whether a dialog, popup, or other route is covering the shell page. bool get hasTransientRoute => _navigatorKey.currentState?.canPop() ?? false; + /// Context for app-level native dialogs owned by the mounted navigator. + BuildContext? get navigatorContext => _navigatorKey.currentContext; + bool get searchOpen => _route.kind == AppRouteKind.search; bool get templatesOpen => _route.kind == AppRouteKind.templates; diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 746ab006..69530ce3 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -24,6 +24,10 @@ import '../features/runs/ui/run_search_selection.dart'; import '../features/search/domain/search_target.dart'; import '../features/settings/settings_screen.dart'; import '../features/settings/settings_store.dart'; +import '../features/updates/app_updates.dart'; +import '../features/updates/launch_update.dart'; +import '../features/updates/launch_update_dialog.dart'; +import '../features/updates/web_release.dart'; import '../features/settings/server_connections.dart'; import 'app.dart'; import 'app_route.dart'; @@ -63,6 +67,15 @@ class PipelinesApp extends StatefulWidget { this.servers, this.resetRoute = false, this.legacyPendingEndpoints = const [], + this.webPlatform = kIsWeb, + this.webBuildId = compiledWebBuildId, + this.webPageUri, + this.androidSupported, + this.webReleaseReader = fetchLatestWebBuild, + this.installedVersionReader = installedVersionCode, + this.androidFeedReader = fetchLatestUpdate, + this.androidInstaller = downloadAndInstall, + this.webRefresher = refreshWebPage, }); final ServerEndpoint server; @@ -79,6 +92,15 @@ class PipelinesApp extends StatefulWidget { final ServerConnections? servers; final bool resetRoute; final List legacyPendingEndpoints; + final bool webPlatform; + final String webBuildId; + final Uri? webPageUri; + final bool? androidSupported; + final Future Function(Uri) webReleaseReader; + final Future Function() installedVersionReader; + final Future Function(Uri) androidFeedReader; + final UpdateInstaller androidInstaller; + final Future Function() webRefresher; @override State createState() => _PipelinesAppState(); @@ -105,6 +127,9 @@ class _PipelinesAppState extends State /// Prevents duplicate resumed notifications from refreshing twice before /// the next background transition starts another foreground visit. bool _foregroundVisitHandled = false; + final _launchUpdates = LaunchUpdateChecker(); + bool _launchUpdateBusy = false; + Uri? _launchUpdateEndpoint; /// One run detail request from Search, delivered through the shell so the /// mounted run detail can resolve it once the named run's steps have loaded. @@ -212,6 +237,7 @@ class _PipelinesAppState extends State .where((frame) => frame['type'] == 'run_event') .listen(_attention.observeFrame); _session.addListener(_attentionSessionChanged); + _session.addListener(_updateEndpointChanged); _attention.addListener(_attentionChanged); _delegate = AppRouterDelegate( initial: initial, @@ -245,6 +271,75 @@ class _PipelinesAppState extends State backButtonDispatcher: RootBackButtonDispatcher(), ); unawaited(_session.start()); + WidgetsBinding.instance.addPostFrameCallback((_) { + unawaited(_checkLaunchUpdate()); + }); + } + + void _updateEndpointChanged() { + if (_launchUpdateEndpoint == _session.endpoint) return; + _launchUpdateEndpoint = _session.endpoint; + WidgetsBinding.instance.addPostFrameCallback((_) { + unawaited(_checkLaunchUpdate()); + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + + Future _checkLaunchUpdate() async { + if (!mounted || _launchUpdateBusy) return; + final dialogContext = _delegate.navigatorContext; + if (dialogContext == null || !dialogContext.mounted) return; + _launchUpdateBusy = true; + final endpoint = _session.endpoint; + try { + final update = await _launchUpdates.check( + web: widget.webPlatform, + android: widget.androidSupported ?? appUpdatesSupported, + webBuildId: widget.webBuildId, + page: widget.webPageUri ?? Uri.base, + endpoint: endpoint, + readWeb: widget.webReleaseReader, + installedVersion: widget.installedVersionReader, + readAndroid: widget.androidFeedReader, + ); + if (!mounted || update == null || !dialogContext.mounted) return; + if (!widget.webPlatform && endpoint != _session.endpoint) return; + _launchUpdates.markOffered(update); + final accepted = await showLaunchUpdateDialog( + dialogContext, + web: update is WebLaunchUpdate, + cupertino: _cupertino, + ); + if (accepted != true || !mounted || !dialogContext.mounted) return; + if (!widget.webPlatform && endpoint != _session.endpoint) return; + try { + if (update is WebLaunchUpdate) { + await widget.webRefresher(); + } else { + await installLaunchUpdate( + dialogContext, + (update as AndroidLaunchUpdate).update, + installer: widget.androidInstaller, + cupertino: _cupertino, + ); + } + } catch (error) { + if (mounted && dialogContext.mounted) { + await showLaunchUpdateFailure( + dialogContext, + error, + cupertino: _cupertino, + ); + } + } + } catch (_) { + // An offline or signed-out update feed never interrupts opening the app. + } finally { + _launchUpdateBusy = false; + if (mounted && endpoint != _session.endpoint) { + unawaited(_checkLaunchUpdate()); + } + } } @override @@ -252,6 +347,7 @@ class _PipelinesAppState extends State WidgetsBinding.instance.removeObserver(this); _deliveryHandoff?.dispose(); _session.removeListener(_attentionSessionChanged); + _session.removeListener(_updateEndpointChanged); unawaited(_attentionFrames?.cancel()); _attention.removeListener(_attentionChanged); _attention.dispose(); @@ -285,6 +381,8 @@ class _PipelinesAppState extends State } if (_foregroundVisitHandled) return; _foregroundVisitHandled = true; + _launchUpdates.beginVisit(); + unawaited(_checkLaunchUpdate()); final connection = _session.connection.kind; if (shouldReconnectOnForeground(connection)) { unawaited(_session.retry()); diff --git a/app/lib/features/updates/launch_update.dart b/app/lib/features/updates/launch_update.dart new file mode 100644 index 00000000..b5c46554 --- /dev/null +++ b/app/lib/features/updates/launch_update.dart @@ -0,0 +1,109 @@ +import 'dart:convert'; + +import 'app_updates.dart'; + +typedef UpdateInstaller = + Future Function( + AppUpdate update, { + void Function(double progress)? onProgress, + }); + +sealed class LaunchUpdate { + const LaunchUpdate(); +} + +class WebLaunchUpdate extends LaunchUpdate { + const WebLaunchUpdate(this.buildId); + final String buildId; +} + +class AndroidLaunchUpdate extends LaunchUpdate { + const AndroidLaunchUpdate(this.update); + final AppUpdate update; +} + +LaunchUpdate? webUpdateFor(String compiled, String body) { + final current = compiled.trim(); + if (current.isEmpty) return null; + try { + final value = jsonDecode(body); + if (value is! Map || value['schema'] != 1 || value['platform'] != 'web') { + return null; + } + final latest = '${value['buildId'] ?? ''}'.trim(); + return latest.isEmpty || latest == current ? null : WebLaunchUpdate(latest); + } on FormatException { + return null; + } +} + +AndroidLaunchUpdate? androidUpdateFor(AppUpdate latest, int? installed) { + if (installed == null || latest.versionCode <= installed) return null; + return AndroidLaunchUpdate(latest); +} + +/// Page hosting and RPC servers may differ; web releases belong to the page. +Uri webReleaseUri(Uri page) => Uri( + scheme: page.scheme, + host: page.host, + port: page.hasPort ? page.port : null, + path: '/release.json', +); + +/// One opportunistic request per foreground visit and feed. Declined releases +/// stay dismissed for this application session, while a newer release can ask. +class LaunchUpdateChecker { + String? _attempt; + final _offered = {}; + + void beginVisit() => _attempt = null; + + Future check({ + required bool web, + required bool android, + required String webBuildId, + required Uri page, + required Uri? endpoint, + required Future Function(Uri) readWeb, + required Future Function() installedVersion, + required Future Function(Uri) readAndroid, + }) async { + final feed = web + ? webReleaseUri(page) + : endpoint == null + ? null + : updatesBaseFor(endpoint); + if (feed == null || (web ? webBuildId.trim().isEmpty : !android)) { + return null; + } + final key = '${web ? 'web' : 'android'}:$feed'; + if (_attempt == key) return null; + _attempt = key; + LaunchUpdate? update; + if (web) { + final body = await readWeb(feed).timeout(const Duration(seconds: 15)); + if (body != null) update = webUpdateFor(webBuildId, body); + } else { + final installed = await installedVersion().timeout( + const Duration(seconds: 15), + ); + if (installed != null) { + update = androidUpdateFor( + await readAndroid(feed).timeout(const Duration(seconds: 15)), + installed, + ); + } + } + return update == null || _offered.contains(_identity(update)) + ? null + : update; + } + + void markOffered(LaunchUpdate update) => _offered.add(_identity(update)); + + String _identity(LaunchUpdate update) => switch (update) { + WebLaunchUpdate(:final buildId) => 'web:$buildId', + AndroidLaunchUpdate(:final update) => + 'android:${update.apk}:${update.versionCode}', + }; +} diff --git a/app/lib/features/updates/launch_update_dialog.dart b/app/lib/features/updates/launch_update_dialog.dart new file mode 100644 index 00000000..44a1bef8 --- /dev/null +++ b/app/lib/features/updates/launch_update_dialog.dart @@ -0,0 +1,188 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'app_updates.dart'; +import 'launch_update.dart'; + +Future showLaunchUpdateDialog( + BuildContext context, { + required bool web, + required bool cupertino, +}) => cupertino + ? showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: const Text('Update available'), + content: Text( + web + ? 'A newer Pipelines web build is available.' + : 'A newer Android build is available.', + ), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context, false), + child: const Text('Later'), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () => Navigator.pop(context, true), + child: Text(web ? 'Refresh' : 'Download'), + ), + ], + ), + ) + : showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Update available'), + content: Text( + web + ? 'A newer Pipelines web build is available.' + : 'A newer Android build is available.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Later'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: Text(web ? 'Refresh' : 'Download'), + ), + ], + ), + ); + +Future showLaunchUpdateFailure( + BuildContext context, + Object error, { + required bool cupertino, +}) async { + if (cupertino) { + await showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: const Text('Update failed'), + content: Text('$error'), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context), + child: const Text('OK'), + ), + ], + ), + ); + } else { + await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Update failed'), + content: Text('$error'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('OK'), + ), + ], + ), + ); + } +} + +/// Reuses the Settings installer while keeping download progress visible. +Future installLaunchUpdate( + BuildContext context, + AppUpdate update, { + required UpdateInstaller installer, + required bool cupertino, +}) async { + final result = cupertino + ? await showCupertinoDialog<_InstallResult>( + context: context, + builder: (_) => _InstallProgress( + update: update, + installer: installer, + cupertino: true, + ), + ) + : await showDialog<_InstallResult>( + context: context, + barrierDismissible: false, + builder: (_) => _InstallProgress( + update: update, + installer: installer, + cupertino: false, + ), + ); + if (result?.error case final Object error) throw error; +} + +class _InstallResult { + const _InstallResult([this.error]); + final Object? error; +} + +class _InstallProgress extends StatefulWidget { + const _InstallProgress({ + required this.update, + required this.installer, + required this.cupertino, + }); + final AppUpdate update; + final UpdateInstaller installer; + final bool cupertino; + + @override + State<_InstallProgress> createState() => _InstallProgressState(); +} + +class _InstallProgressState extends State<_InstallProgress> { + double? _progress; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) async { + Object? error; + try { + await widget.installer( + widget.update, + onProgress: (progress) { + if (mounted) setState(() => _progress = progress.clamp(0, 1)); + }, + ); + } catch (failure) { + error = failure; + } + if (mounted) Navigator.of(context).pop(_InstallResult(error)); + }); + } + + @override + Widget build(BuildContext context) { + final progress = _progress; + final content = Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + progress == null + ? 'Downloading update…' + : 'Downloading update… ${(progress * 100).round()}%', + ), + const SizedBox(height: 16), + widget.cupertino + ? const CupertinoActivityIndicator() + : LinearProgressIndicator(value: progress), + ], + ); + return PopScope( + canPop: false, + child: widget.cupertino + ? CupertinoAlertDialog( + title: const Text('App update'), + content: content, + ) + : AlertDialog(title: const Text('App update'), content: content), + ); + } +} diff --git a/app/lib/features/updates/web_release.dart b/app/lib/features/updates/web_release.dart new file mode 100644 index 00000000..aa9afee2 --- /dev/null +++ b/app/lib/features/updates/web_release.dart @@ -0,0 +1,8 @@ +import 'web_release_stub.dart' + if (dart.library.js_interop) 'web_release_web.dart' + as impl; + +const compiledWebBuildId = String.fromEnvironment('PIPELINES_WEB_BUILD_ID'); + +Future fetchLatestWebBuild(Uri uri) => impl.fetchLatestWebBuild(uri); +Future refreshWebPage() => impl.refreshWebPage(); diff --git a/app/lib/features/updates/web_release_stub.dart b/app/lib/features/updates/web_release_stub.dart new file mode 100644 index 00000000..c6885aa7 --- /dev/null +++ b/app/lib/features/updates/web_release_stub.dart @@ -0,0 +1,2 @@ +Future fetchLatestWebBuild(Uri uri) async => null; +Future refreshWebPage() async {} diff --git a/app/lib/features/updates/web_release_web.dart b/app/lib/features/updates/web_release_web.dart new file mode 100644 index 00000000..28eb2a7a --- /dev/null +++ b/app/lib/features/updates/web_release_web.dart @@ -0,0 +1,26 @@ +import 'dart:js_interop'; + +@JS('fetch') +external JSPromise<_ReleaseResponse> _fetch(JSString input, _FetchOptions init); +@JS('location.reload') +external void _reload(); + +extension type _FetchOptions._(JSObject _) implements JSObject { + external factory _FetchOptions({JSString credentials, JSString cache}); +} + +extension type _ReleaseResponse._(JSObject _) implements JSObject { + external int get status; + external JSPromise text(); +} + +Future fetchLatestWebBuild(Uri uri) async { + final response = await _fetch( + uri.toString().toJS, + _FetchOptions(credentials: 'same-origin'.toJS, cache: 'no-store'.toJS), + ).toDart; + if (response.status != 200) return null; + return (await response.text().toDart).toDart; +} + +Future refreshWebPage() async => _reload(); diff --git a/app/notes/startup-update-check.md b/app/notes/startup-update-check.md new file mode 100644 index 00000000..49825e87 --- /dev/null +++ b/app/notes/startup-update-check.md @@ -0,0 +1,46 @@ +# Startup and foreground update check + +The single `PipelinesApp` session checks the platform's own feed when it opens +and when it returns to the foreground. Web compares the compiled +`PIPELINES_WEB_BUILD_ID` with `/release.json` on the page's origin, even when +its RPC server lives elsewhere. Android compares its installed version code +with the existing Settings APK feed. Appearance never selects the platform. +The web release metadata/install support is the companion manager-owned change +`f05ad62e`; it must land before publishing this client. + +Web offers Refresh and Android offers Download, with Later on both native +Material and Cupertino dialogs. Nothing reloads or downloads without consent. +Android uses the existing Settings installer, shows download progress and +reports user-requested install failures. Unavailable, signed-out, malformed and +offline checks stay quiet; a subsequent foreground visit can retry. Feed reads +have a 15-second timeout and never gate the application UI. + +Checks coalesce within a foreground visit and offered releases are remembered +for the application session. Endpoint changes are observed so Android also +checks after saved server configuration becomes available. Missing installed +version/build identity skips the comparison rather than guessing an update. + +Focused tests and browser evidence will be recorded below after verification. + +## Verification + +16 focused tests passed (`/tmp/memwatch/out.laN5Vl`) across update parsing, +feed/platform routing, per-visit/per-version behavior and full-app startup flows. +The app regressions cover a saved endpoint arriving later, a server switch while +an old APK lookup is pending, offline startup followed by foreground retry, +consent before refresh/download, and Android progress plus surfaced failures. +The stale-feed guard runs again after consent, before installing anything. +Analyzer clean (`flutter-analyze.U1eqhg`). + +The full-app fake-gateway web fixture was built with +`PIPELINES_WEB_BUILD_ID=web-fixture-current` and served a same-origin +`release.json` naming `web-fixture-new`. Browser interaction verified Material +Later dismissal and Cupertino Refresh actually reloads the document (a JS +sentinel was cleared). Captures under `/tmp/review/startup-update-material-steady` +and `/tmp/review/startup-update-cupertino-final` were inspected. Fixture appearance +uses a URL-only parameter, so the refreshed fixture returns to its default host; +production appearance settings are unchanged. The static fixture intentionally +keeps serving the old compiled build, so its update prompt recurs after reload. +Both private browser/server processes are awaited by the capture driver. +No production session, APK feed, or device was changed. Real Android download and +installer behavior remain unverified without an authorized connected test device. diff --git a/app/test/application/startup_update_check_test.dart b/app/test/application/startup_update_check_test.dart new file mode 100644 index 00000000..0533d84e --- /dev/null +++ b/app/test/application/startup_update_check_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/widgets.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/updates/app_updates.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +ServerEndpoint server() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, + ); + +void main() { + testWidgets('web launch check is injected, asks once, and does not refresh', + (tester) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + var reads = 0; + var refreshes = 0; + + await tester.pumpWidget(PipelinesApp( + server: server(), + client: client, + cupertino: false, + routeInformationProvider: provider, + webPlatform: true, + webBuildId: 'web-old', + webReleaseReader: (_) async { + reads++; + return '{"schema":1,"platform":"web","buildId":"web-new"}'; + }, + webRefresher: () async => refreshes++, + )); + await tester.pump(); + await tester.pump(); + expect(find.text('Update available'), findsOneWidget); + expect(reads, 1); + + await tester.tap(find.text('Later')); + await tester.pump(); + await tester.pumpWidget(PipelinesApp( + server: server(), + client: client, + cupertino: false, + routeInformationProvider: provider, + webPlatform: true, + webBuildId: 'web-old', + webReleaseReader: (_) async { + reads++; + return '{"schema":1,"platform":"web","buildId":"web-new"}'; + }, + webRefresher: () async => refreshes++, + )); + await tester.pump(); + expect(find.text('Update available'), findsNothing); + expect(refreshes, 0); + }); + + testWidgets('Android launch choice uses the injected installer', (tester) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + var installs = 0; + final update = AppUpdate( + versionCode: 4, + versionName: '4', + apk: Uri.parse('https://example.test/pipelines.apk'), + ); + await tester.pumpWidget(PipelinesApp( + server: server(), + client: client, + cupertino: false, + routeInformationProvider: provider, + webPlatform: false, + androidSupported: true, + installedVersionReader: () async => 3, + androidFeedReader: (_) async => update, + androidInstaller: (_, {onProgress}) async => installs++, + )); + await tester.pump(); + await tester.pump(); + expect(find.text('Download'), findsOneWidget); + await tester.tap(find.text('Download')); + await tester.pump(); + expect(installs, 1); + }); +} diff --git a/app/test/application/startup_update_flow_test.dart b/app/test/application/startup_update_flow_test.dart new file mode 100644 index 00000000..36c0789e --- /dev/null +++ b/app/test/application/startup_update_flow_test.dart @@ -0,0 +1,264 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/updates/app_updates.dart'; +import 'package:pipelines_app/features/updates/launch_update.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +void main() { + Future mount( + WidgetTester tester, { + bool web = true, + bool cupertino = false, + Future Function(Uri)? read, + Future Function()? refresh, + UpdateInstaller? installer, + }) async { + final channel = FakeChannel()..readyCompleter.complete(); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + await tester.pumpWidget( + PipelinesApp( + server: ServerEndpoint.resolve( + base: Uri.parse('https://rpc.test/'), + web: true, + ), + client: PipelinesClient(channelFactory: (_) => channel), + cupertino: cupertino, + routeInformationProvider: provider, + webPlatform: web, + webPageUri: Uri.parse('https://app.test/chats?selected=1'), + webBuildId: 'web-old', + androidSupported: true, + webReleaseReader: + read ?? + (_) async => '{"schema":1,"platform":"web","buildId":"web-new"}', + webRefresher: refresh ?? () async {}, + installedVersionReader: () async => 3, + androidFeedReader: (_) async => AppUpdate( + versionCode: 4, + versionName: '4', + apk: Uri.parse('https://rpc.test/updates/pipelines.apk'), + ), + androidInstaller: installer ?? (_, {onProgress}) async {}, + ), + ); + await tester.pump(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + } + + Future resume(WidgetTester tester) async { + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + } + + testWidgets('Android checks after a saved endpoint becomes available', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + var reads = 0; + await tester.pumpWidget( + PipelinesApp( + server: ServerEndpoint.resolve(base: Uri(), web: false), + client: client, + cupertino: false, + routeInformationProvider: provider, + webPlatform: false, + androidSupported: true, + installedVersionReader: () async => 3, + androidFeedReader: (uri) async { + reads++; + expect(uri, Uri.parse('https://restored.test/updates/')); + return AppUpdate( + versionCode: 4, + versionName: '4', + apk: uri.resolve('pipelines.apk'), + ); + }, + ), + ); + await tester.pump(); + expect(reads, 0); + await client.connect(Uri.parse('wss://restored.test/connect')); + await tester.pump(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(reads, 1); + expect(find.text('Download'), findsOneWidget); + await tester.tap(find.text('Later')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + }); + + testWidgets( + 'changing servers during Android check never offers the stale APK', + (tester) async { + final client = PipelinesClient( + channelFactory: (_) => FakeChannel()..readyCompleter.complete(), + ); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + final stale = Completer(); + final requested = []; + Uri? installed; + await tester.pumpWidget( + PipelinesApp( + server: ServerEndpoint.resolve( + base: Uri.parse('https://original.test/'), + web: true, + ), + client: client, + cupertino: false, + routeInformationProvider: provider, + webPlatform: false, + androidSupported: true, + installedVersionReader: () async => 3, + androidFeedReader: (uri) async { + requested.add(uri); + if (uri.host == 'original.test') return stale.future; + return AppUpdate( + versionCode: 5, + versionName: '5', + apk: uri.resolve('new.apk'), + ); + }, + androidInstaller: (update, {onProgress}) async { + installed = update.apk; + }, + ), + ); + await tester.pump(); + await tester.pump(); + expect(requested, [Uri.parse('https://original.test/updates/')]); + unawaited(client.connect(Uri.parse('wss://selected.test/connect'))); + await tester.pump(); + await tester.pump(); + stale.complete( + AppUpdate( + versionCode: 4, + versionName: '4', + apk: Uri.parse('https://original.test/old.apk'), + ), + ); + await tester.pump(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(requested, [ + Uri.parse('https://original.test/updates/'), + Uri.parse('https://selected.test/updates/'), + ]); + expect(find.text('Download'), findsOneWidget); + await tester.tap(find.text('Download')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(installed, Uri.parse('https://selected.test/updates/new.apk')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + }, + ); + + testWidgets('web refresh requires consent and uses same page origin', ( + tester, + ) async { + var refreshes = 0; + await mount( + tester, + cupertino: true, + read: (uri) async { + expect(uri, Uri.parse('https://app.test/release.json')); + return '{"schema":1,"platform":"web","buildId":"web-new"}'; + }, + refresh: () async { + refreshes++; + }, + ); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(refreshes, 0); + await tester.tap(find.text('Refresh')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(refreshes, 1); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text('Update available'), findsNothing); + }); + + testWidgets( + 'offline startup is quiet, resume retries and later dismisses that release', + (tester) async { + var reads = 0; + await mount( + tester, + read: (_) async { + reads++; + if (reads == 1) throw StateError('offline'); + return '{"schema":1,"platform":"web","buildId":"web-new"}'; + }, + ); + expect(find.text('Update available'), findsNothing); + expect(tester.takeException(), isNull); + await resume(tester); + expect(reads, 2); + expect(find.text('Update available'), findsOneWidget); + await tester.tap(find.text('Later')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + await resume(tester); + expect(reads, 3); + expect(find.text('Update available'), findsNothing); + }, + ); + + testWidgets( + 'Android download shows progress, reports failure and leaves app usable', + (tester) async { + final finish = Completer(); + void Function(double)? progress; + var installs = 0; + await mount( + tester, + web: false, + installer: (_, {onProgress}) async { + installs++; + progress = onProgress; + await finish.future; + }, + ); + expect(installs, 0); + await tester.tap(find.text('Download')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(installs, 1); + progress!(0.5); + await tester.pump(); + expect(find.text('Downloading update… 50%'), findsOneWidget); + finish.completeError(StateError('download failed')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(); + expect(find.text('Update failed'), findsOneWidget); + expect(find.textContaining('download failed'), findsOneWidget); + await tester.tap(find.text('OK')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text('Update failed'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); +} diff --git a/app/test/features/updates/launch_update_checker_test.dart b/app/test/features/updates/launch_update_checker_test.dart new file mode 100644 index 00000000..9c352a23 --- /dev/null +++ b/app/test/features/updates/launch_update_checker_test.dart @@ -0,0 +1,121 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/updates/app_updates.dart'; +import 'package:pipelines_app/features/updates/launch_update.dart'; + +void main() { + final page = Uri.parse('https://app.test/chat/a?hello=1#part'); + final endpoint = Uri.parse('wss://rpc.test/connect'); + final apk = AppUpdate( + versionCode: 8, + versionName: '8', + apk: Uri.parse('https://rpc.test/updates/pipelines.apk'), + ); + + test( + 'web reads page origin even when appearance and RPC host differ', + () async { + final checker = LaunchUpdateChecker(); + Uri? requested; + final result = await checker.check( + web: true, + android: true, + webBuildId: 'web-old', + page: page, + endpoint: endpoint, + readWeb: (uri) async { + requested = uri; + return '{"schema":1,"platform":"web","buildId":"web-new"}'; + }, + installedVersion: () async => + throw StateError('Android API used on web'), + readAndroid: (_) async => throw StateError('APK feed used on web'), + ); + expect(requested, Uri.parse('https://app.test/release.json')); + expect(result, isA()); + }, + ); + + test( + 'one check per visit, dismissed version stays quiet, later version asks', + () async { + final checker = LaunchUpdateChecker(); + var reads = 0; + var latest = 'web-two'; + Future check() => checker.check( + web: true, + android: false, + webBuildId: 'web-one', + page: page, + endpoint: null, + readWeb: (_) async { + reads++; + return '{"schema":1,"platform":"web","buildId":"$latest"}'; + }, + installedVersion: () async => null, + readAndroid: (_) async => apk, + ); + final offered = await check(); + expect(offered, isA()); + checker.markOffered(offered!); + expect(await check(), isNull); + expect(reads, 1); + checker.beginVisit(); + expect(await check(), isNull); + latest = 'web-three'; + checker.beginVisit(); + expect(await check(), isA()); + expect(reads, 3); + }, + ); + + test( + 'Android defers until endpoint exists and uses its update feed', + () async { + final checker = LaunchUpdateChecker(); + Uri? feed; + Future check(Uri? server) => checker.check( + web: false, + android: true, + webBuildId: '', + page: page, + endpoint: server, + readWeb: (_) async => throw StateError('web feed used on Android'), + installedVersion: () async => 7, + readAndroid: (uri) async { + feed = uri; + return apk; + }, + ); + expect(await check(null), isNull); + expect(await check(endpoint), isA()); + expect(feed, Uri.parse('https://rpc.test/updates/')); + }, + ); + + test( + 'unknown installed version skips APK feed; blank web identity skips web', + () async { + final checker = LaunchUpdateChecker(); + var reads = 0; + Future check(bool web) => checker.check( + web: web, + android: true, + webBuildId: '', + page: page, + endpoint: endpoint, + readWeb: (_) async { + reads++; + return null; + }, + installedVersion: () async => null, + readAndroid: (_) async { + reads++; + return apk; + }, + ); + expect(await check(false), isNull); + expect(await check(true), isNull); + expect(reads, 0); + }, + ); +} diff --git a/app/test/features/updates/launch_update_test.dart b/app/test/features/updates/launch_update_test.dart new file mode 100644 index 00000000..fa2af45a --- /dev/null +++ b/app/test/features/updates/launch_update_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/updates/app_updates.dart'; +import 'package:pipelines_app/features/updates/launch_update.dart'; + +void main() { + test('web compares release identity and ignores Android metadata', () { + expect( + webUpdateFor('web-current', + '{"schema":1,"platform":"web","buildId":"web-current"}'), + isNull, + ); + expect( + webUpdateFor('web-current', + '{"schema":1,"platform":"web","buildId":"web-new"}'), + isA(), + ); + expect( + webUpdateFor('web-current', + '{"schema":1,"platform":"android","buildId":"web-new"}'), + isNull, + ); + expect(webUpdateFor('', '{"buildId":"web-new"}'), isNull); + }); + + test('Android compares version code and never prompts for an older feed', () { + final update = AppUpdate( + versionCode: 8, + versionName: '8', + apk: Uri.parse('https://example.test/app.apk'), + ); + expect(androidUpdateFor(update, 7), isA()); + expect(androidUpdateFor(update, 8), isNull); + expect(androidUpdateFor(update, null), isNull); + }); +}