Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 22 additions & 0 deletions lib/process/serverpod_process.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> 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<MigrationResult?> createMigration({bool force = false}) =>
_migration(
Expand Down
75 changes: 54 additions & 21 deletions lib/ui/preview_pane.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,35 +66,50 @@ class PreviewPaneState extends State<PreviewPane> {

bool get _shouldLoad => widget.process.previewReady;

Future<void> 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<void> reload({bool recoverIfStalled = false}) async {
if (!_shouldLoad) return;
final controller = _controller;
if (controller == null || !controller.value) {
await _ensureWebView();
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) {
Expand Down Expand Up @@ -254,7 +269,7 @@ class PreviewPaneState extends State<PreviewPane> {
// 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;
Expand All @@ -266,7 +281,15 @@ class PreviewPaneState extends State<PreviewPane> {
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();
}
}
}

Expand Down Expand Up @@ -305,14 +328,18 @@ class PreviewPaneState extends State<PreviewPane> {

Future<void> _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(() {});
}
Expand Down Expand Up @@ -344,25 +371,31 @@ class PreviewPaneState extends State<PreviewPane> {
}
}

/// Keeps the overlay up until Flutter web has actually started (or we time out).
Future<void> _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<bool> _waitForFlutterMain(
WebViewController controller, {
required bool Function() isCancelled,
}) async {
// Bootstrap may wait ~2.5s for DWDS before calling `$dartRunMain`.
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<void>.delayed(delay);
}
return false;
}

Future<void> _disposeController() async {
Expand Down
65 changes: 65 additions & 0 deletions test/process/serverpod_process_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,71 @@ void main() {
expect(process.previewReloadToken, before);
});

group('a preview whose app never started', () {
Future<FakeRunner> 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<RunnerLogRecord>()
.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
Expand Down
Loading