From 87cbb44414d4d40077db07e43a6a74cd26ddc9f7 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Sun, 15 Nov 2026 17:14:01 +0100 Subject: [PATCH] fix: A preview whose app never started is hot-restarted, not shown blank. The pane waits 8 s for the app's main() and used to mark the preview live regardless, which dropped the overlay onto a white page, reported it as running and raised "Your project has started" over it. Seen after creating a project; pressing Hot Restart cured it. The first load (and the reload a project switch does) now falls back to the runner's hot restart, whose hard reload reveals the page. Once per load, and revealed as before when no restart is possible. Process changes that landed while the webview was initializing were also dropped until the runner next notified; the pane now catches up on them once init finishes. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 17 ++++++ lib/process/serverpod_process.dart | 22 +++++++ lib/ui/preview_pane.dart | 75 +++++++++++++++++------- test/process/serverpod_process_test.dart | 65 ++++++++++++++++++++ 4 files changed, 158 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0c629d8..43a494a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1187,6 +1187,23 @@ install. Sparkle would also catch it, but later and less clearly. localStorage survives a Full Restart within one session. Keeping the profile in-memory (the `cache_path` note below) is unchanged — this is about state crossing projects inside one app run, not across launches. +- **A page whose app never started is hot-restarted, not revealed.** + `_waitForFlutterMain` gives up after 8 s; it used to call + `markPreviewLive()` regardless, which dropped the overlay onto a blank page, + set the phase to ready and raised "Your project has started" over it — + seen after creating a project, and cured by pressing Hot Restart. Now the + first load (and the reload a project switch does) calls + `recoverStalledPreview()` instead: the runner's hot restart, whose own hard + reload reveals the page. Once per load — a reload a hot restart asked for + never recovers, or a page that never starts would restart forever — and + when no restart is possible the page is revealed as before. A Full Restart + costs minutes and is not the fallback. The root cause of the stall was not + found; a second `main()` and a reload mid-load were both tested and ruled + out. +- **Process changes that land while the webview initializes are caught up + afterwards** (`_ensureWebView`'s `finally`). They used to be dropped until + the runner next notified. Not after a failed init, which would retry at once + forever. - **The runner is not racing us.** The runner's `hotRestart` awaits the full compile, the server reboot, the Flutter apps' hot restart and its own browser refresh before it answers — so by the time `ServerpodProcessController` bumps the token, the web server is already serving the new output. If the preview still shows old code, it is a cache and not timing. - The header's reload button is **gone on purpose.** Hot Restart now force-reloads the preview itself, so the button's only remaining job was papering over a reload that had not happened — and the honest fix for that is the token, not a second control that does the same thing by hand. - **Backdrop:** CEF composites with alpha, so an opaque `ColoredBox` (`previewBackdropColor`) sits under the surface, following the *previewed* app's brightness, not the shell's. diff --git a/lib/process/serverpod_process.dart b/lib/process/serverpod_process.dart index 2b1c2ca..8645012 100644 --- a/lib/process/serverpod_process.dart +++ b/lib/process/serverpod_process.dart @@ -939,6 +939,28 @@ class ServerpodProcessController extends ChangeNotifier if (ok ?? false) requestPreviewReload(); } + /// Hot-restarts a preview whose app never started in the page. + /// + /// The pane calls this when it has waited out a load and the app's `main()` + /// still has not run, which otherwise leaves a blank page reported as + /// running. A hot restart is what brings such a page back by hand, and a + /// Full Restart costs minutes. + /// + /// True when the restart went through and asked for the preview's hard + /// reload, which then reveals the page itself. False when nothing was + /// restarted — the app is already live, no restart is possible now, or the + /// runner refused — and the pane has to reveal what it has. + Future recoverStalledPreview() async { + if (!previewReady || _live || !canHotRestart) return false; + log.addLocal( + 'The app did not start in the preview. Hot restarting it.', + level: RunnerLogLevel.warning, + ); + final token = _previewReloadToken; + await hotRestart(); + return _previewReloadToken != token; + } + @override Future createMigration({bool force = false}) => _migration( diff --git a/lib/ui/preview_pane.dart b/lib/ui/preview_pane.dart index c0de457..6894439 100644 --- a/lib/ui/preview_pane.dart +++ b/lib/ui/preview_pane.dart @@ -66,7 +66,13 @@ class PreviewPaneState extends State { bool get _shouldLoad => widget.process.previewReady; - Future reload() async { + /// Hard-reloads the preview. + /// + /// [recoverIfStalled] is for a reload that is part of the first load — the + /// one a project switch does. A reload that a hot restart asked for must + /// not recover through another hot restart, or a page that never starts + /// would restart the app forever. + Future reload({bool recoverIfStalled = false}) async { if (!_shouldLoad) return; final controller = _controller; if (controller == null || !controller.value) { @@ -74,27 +80,36 @@ class PreviewPaneState extends State { return; } final revealGeneration = ++_revealGeneration; + bool isCancelled() => + !mounted || + _controller != controller || + revealGeneration != _revealGeneration; try { // Hard reload, and it has to be hard on both sides: a service worker or a // Cache Storage entry outlives the navigation and would answer the new // document out of the previous build, and a plain navigation re-serves // the cached `main.dart.js` — so a rebuilt app would look unchanged. await _purgePageCaches(controller); - if (!mounted || revealGeneration != _revealGeneration) return; + if (isCancelled()) return; await controller.reloadIgnoreCache(); - await _waitForFlutterMain( + final started = await _waitForFlutterMain( controller, - isCancelled: () => - !mounted || - _controller != controller || - revealGeneration != _revealGeneration, + isCancelled: isCancelled, ); - if (!mounted || revealGeneration != _revealGeneration) return; + if (isCancelled()) return; + // A page whose app never started would be revealed blank and + // announced as running. A hot restart is what brings it back by hand. + if (!started && + recoverIfStalled && + await widget.process.recoverStalledPreview()) { + return; + } + if (isCancelled()) return; // The theme shim is injected at load start with the brightness captured // when the webview was created, so a reload resets it — re-apply. _appliedBrightness = null; await _applyPreviewTheme(widget.mode.previewBrightness); - if (!mounted || revealGeneration != _revealGeneration) return; + if (isCancelled()) return; widget.process.markPreviewLive(); if (mounted) setState(() {}); } catch (e) { @@ -254,7 +269,7 @@ class PreviewPaneState extends State { // The initial navigation above may already have been answered out of // the old state; reload() re-fetches past every cache and keeps the // overlay up until this project's own app is live. - await reload(); + await reload(recoverIfStalled: true); } else { if (projectPath != null) { _cefProfileProjectPath = projectPath; @@ -266,7 +281,15 @@ class PreviewPaneState extends State { await _disposeController(); } finally { _initializing = false; - if (mounted) setState(() {}); + if (mounted) { + setState(() {}); + // Every process change that landed mid-init was skipped — a new URL, + // a stop, a reload — and nothing would ask again until the runner + // next notified, which a page that never connects never makes it do. + // Not after a failure: that would retry the failed init at once, and + // forever. + if (_error == null) _onProcessChanged(); + } } } @@ -305,14 +328,18 @@ class PreviewPaneState extends State { Future _revealWhenAppReady(WebViewController controller) async { final revealGeneration = ++_revealGeneration; - await _waitForFlutterMain( + bool isCancelled() => + !mounted || + _controller != controller || + revealGeneration != _revealGeneration; + final started = await _waitForFlutterMain( controller, - isCancelled: () => - !mounted || - _controller != controller || - revealGeneration != _revealGeneration, + isCancelled: isCancelled, ); - if (!mounted || revealGeneration != _revealGeneration) return; + if (isCancelled()) return; + // See [reload]: a hot restart's own hard reload reveals the page instead. + if (!started && await widget.process.recoverStalledPreview()) return; + if (isCancelled()) return; widget.process.markPreviewLive(); if (mounted) setState(() {}); } @@ -344,8 +371,13 @@ class PreviewPaneState extends State { } } - /// Keeps the overlay up until Flutter web has actually started (or we time out). - Future _waitForFlutterMain( + /// Keeps the overlay up until Flutter web has actually started. True once + /// it has; false when it was cancelled or timed out first. + /// + /// A freshly created project's app reaches `main()` about 2.3 s after + /// navigation on an idle Mac, so the 8 s here leaves room for one that is + /// still compiling the server and starting Postgres. + Future _waitForFlutterMain( WebViewController controller, { required bool Function() isCancelled, }) async { @@ -353,16 +385,17 @@ class PreviewPaneState extends State { const maxAttempts = 40; const delay = Duration(milliseconds: 200); for (var i = 0; i < maxAttempts; i++) { - if (isCancelled()) return; + if (isCancelled()) return false; try { final result = await controller.evaluateJavascript( 'window.\$dartMainExecuted === true || ' 'document.querySelector("flt-glass-pane, flt-scene-host, flutter-view") != null', ); - if (result == true || result == 'true') return; + if (result == true || result == 'true') return true; } catch (_) {} await Future.delayed(delay); } + return false; } Future _disposeController() async { diff --git a/test/process/serverpod_process_test.dart b/test/process/serverpod_process_test.dart index dab8c47..df5c65a 100644 --- a/test/process/serverpod_process_test.dart +++ b/test/process/serverpod_process_test.dart @@ -471,6 +471,71 @@ void main() { expect(process.previewReloadToken, before); }); + group('a preview whose app never started', () { + Future previewing() async { + final runner = await projectWithRunner( + snapshot: { + 'flutterApps': [demoApp], + 'runningFlutterApps': ['demo'], + 'flutterAppUrls': {'demo': 'http://localhost:51234'}, + }, + ); + await open(runner); + expect(process.phase, PreviewPhase.connecting); + return runner; + } + + test('is hot-restarted, and the reload reveals it', () async { + final runner = await previewing(); + final before = process.previewReloadToken; + + expect(await process.recoverStalledPreview(), isTrue); + + expect(runner.calls, contains('hotRestart')); + expect(process.previewReloadToken, before + 1); + // Still waiting: the reload's own wait is what marks it live. + expect(process.phase, PreviewPhase.connecting); + expect( + process.log.serverItems + .whereType() + .map((r) => r.message), + contains('The app did not start in the preview. Hot restarting it.'), + ); + }); + + test('is left to the pane when the restart is refused', () async { + final runner = await previewing(); + runner.failures['hotRestart'] = 'Compilation failed.'; + final before = process.previewReloadToken; + + expect(await process.recoverStalledPreview(), isFalse); + expect(process.previewReloadToken, before); + }); + + test('is not restarted once it is live', () async { + final runner = await previewing(); + process.markPreviewLive(); + + expect(await process.recoverStalledPreview(), isFalse); + expect(runner.calls, isNot(contains('hotRestart'))); + }); + + test('is not restarted before the server is running', () async { + final runner = await projectWithRunner( + stage: 'starting', + snapshot: { + 'flutterApps': [demoApp], + 'runningFlutterApps': ['demo'], + 'flutterAppUrls': {'demo': 'http://localhost:51234'}, + }, + ); + await open(runner); + + expect(await process.recoverStalledPreview(), isFalse); + expect(runner.calls, isNot(contains('hotRestart'))); + }); + }); + test('a migration refused for warnings comes back for a force', () async { final runner = await projectWithRunner(); runner.replies['createMigration'] = (params) => params['force'] == true