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.

Web: first visit under 5 s (terminal font with the workspace, main.dart.js before the engine) (#1786)

0xdiego258568e93c8db8
diff --git a/desktop/lib/web/parts/terminal_fonts.dart b/desktop/lib/web/parts/terminal_fonts.dart
new file mode 100644
index 000000000..615e99d1f
--- /dev/null
+++ b/desktop/lib/web/parts/terminal_fonts.dart
@@ -0,0 +1,42 @@
+import 'package:flutter/services.dart';
+
+import '../../terminal/terminal_typography.dart';
+
+/// Roboto Mono's files, as pubspec.yaml lists them under [webTerminalFontFamily].
+///
+/// A release leaves the family out of the fonts every page waits for
+/// (scripts/build-web-release.sh): the sign-in page draws no terminal, and the
+/// two files are 0.23 MB a first visit waited for before its first frame.
+/// The workspace part loads them ([downloadWorkspace]).
+const terminalFontAssets = [
+ 'assets/fonts/roboto-mono/RobotoMono.ttf',
+ 'assets/fonts/roboto-mono/RobotoMono-Italic.ttf',
+];
+
+/// Registers [terminalFontAssets] as [webTerminalFontFamily]. A screen already
+/// drawn re-lays out its text when they land (xterm re-measures its cells too).
+Future<void> loadTerminalFonts() {
+ final loader = FontLoader(webTerminalFontFamily);
+ for (final asset in terminalFontAssets) {
+ loader.addFont(rootBundle.load(asset));
+ }
+ return loader.load();
+}
+
+/// How long the workspace waits for [terminalFontAssets] once its library is in.
+const terminalFontsGrace = Duration(seconds: 3);
+
+/// The workspace's [library] and the terminal's [fonts], side by side. The
+/// workspace waits for the fonts so no terminal is first drawn in a fallback
+/// face, but fonts that fail, or are still on their way [fontsGrace] after the
+/// library, do not keep it away: the fallback draws, and xterm re-measures its
+/// cells when the fonts land.
+Future<void> downloadWorkspace({
+ required Future<void> Function() library,
+ required Future<void> Function() fonts,
+ Duration fontsGrace = terminalFontsGrace,
+}) async {
+ final fontsIn = fonts().then((_) {}, onError: (Object _) {});
+ await library();
+ await fontsIn.timeout(fontsGrace, onTimeout: () {});
+}
diff --git a/desktop/lib/web/parts/workspace_part.dart b/desktop/lib/web/parts/workspace_part.dart
index 0252f8cd9..9b76e9b27 100644
--- a/desktop/lib/web/parts/workspace_part.dart
+++ b/desktop/lib/web/parts/workspace_part.dart
@@ -5,11 +5,18 @@ import 'package:flutter/widgets.dart';
import '../../state/app_state.dart';
import '../shell/web_workspace.dart' deferred as workspace;
import 'deferred_part.dart';
+import 'terminal_fonts.dart';
/// The signed-in workspace, most of the app (about 4.4 of 10.9 MB of
-/// script): a first visit's sign-in page draws without it, and it is
-/// downloaded once that first frame is up ([WorkspacePrefetch]).
-final workspacePart = DeferredPart(workspace.loadLibrary);
+/// script), and its terminal font: a first visit's sign-in page draws
+/// without them, and they are downloaded once that first frame is up
+/// ([WorkspacePrefetch]).
+final workspacePart = DeferredPart(
+ () => downloadWorkspace(
+ library: workspace.loadLibrary,
+ fonts: loadTerminalFonts,
+ ),
+);
/// The browser's workspace once [workspacePart] is in.
class DeferredWorkspace extends StatelessWidget {
diff --git a/desktop/scripts/build-web-release.sh b/desktop/scripts/build-web-release.sh
index f223abe76..2cfc6a4d3 100644
--- a/desktop/scripts/build-web-release.sh
+++ b/desktop/scripts/build-web-release.sh
@@ -23,6 +23,10 @@ api_url='https://harness-api.autonomous.ai'
# lucide_icons_flutter lists seven fonts and the browser fetches every one on first load, but
# the app draws only weight 400 (lib/shared/theme/app_icons.dart): the other six are 1.5 MB
# compressed. Dropped here, not in pubspec.yaml, so the Desktop bundle is unchanged.
+# Roboto Mono, the terminal's face, leaves the manifest too but stays in the release: the engine
+# waits for every font the manifest lists before its first frame, and the sign-in page draws no
+# terminal, so a first visit waited for 0.23 MB it never used. The workspace part loads it
+# (lib/web/parts/terminal_fonts.dart).
python3 - <<'PY'
import json
from pathlib import Path
@@ -30,17 +34,20 @@ import sys
package = 'packages/lucide_icons_flutter/'
used = package + 'Lucide400'
+late = 'Roboto Mono'
assets = Path('build/web-release/assets')
manifest_path = assets / 'FontManifest.json'
manifest = json.loads(manifest_path.read_text())
-if used not in {entry['family'] for entry in manifest}:
- sys.exit(f'{used} is not in the font manifest; update the unused-font step in build-web-release.sh.')
+for family in (used, late):
+ if family not in {entry['family'] for entry in manifest}:
+ sys.exit(f'{family} is not in the font manifest; update the font step in build-web-release.sh.')
unused = [e for e in manifest if e['family'].startswith(package) and e['family'] != used]
for entry in unused:
for font in entry['fonts']:
(assets / font['asset']).unlink()
-manifest_path.write_text(json.dumps([e for e in manifest if e not in unused], separators=(',', ':')))
-print(f"Dropped {len(unused)} unused icon fonts from the web release.")
+manifest_path.write_text(json.dumps(
+ [e for e in manifest if e not in unused and e['family'] != late], separators=(',', ':')))
+print(f"Dropped {len(unused)} unused icon fonts from the web release; {late} loads with the workspace.")
PY
# Flutter asks for the font manifest, then its fonts, only once main.dart.js has run: a step in
diff --git a/desktop/test/web/web_focus_ring_web_test.dart b/desktop/test/web/web_focus_ring_web_test.dart
index 379e3e9e8..2ba3fe76e 100644
--- a/desktop/test/web/web_focus_ring_web_test.dart
+++ b/desktop/test/web/web_focus_ring_web_test.dart
@@ -10,6 +10,7 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/web/parts/terminal_fonts.dart';
import 'package:harness/web/parts/workspace_part.dart';
import 'package:harness/web/web_entry.dart';
@@ -57,8 +58,9 @@ void main() {
await tester.pump();
expect(ring, findsNothing);
// The frame's first frame started the workspace's download; a test build
- // has no part to fetch, so it lands on the next timer.
- await tester.pump(const Duration(milliseconds: 1));
+ // has no part to fetch, and a test browser never answers for the terminal
+ // font, so the part is in once the font's grace is over.
+ await tester.pump(terminalFontsGrace);
expect(workspacePart.loaded, isTrue);
});
}
diff --git a/desktop/test/web/web_frame_key_hints_test.dart b/desktop/test/web/web_frame_key_hints_test.dart
index 59c6bdc39..336979f7f 100644
--- a/desktop/test/web/web_frame_key_hints_test.dart
+++ b/desktop/test/web/web_frame_key_hints_test.dart
@@ -10,6 +10,7 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/shortcuts/shortcuts_browser.dart';
+import 'package:harness/web/parts/terminal_fonts.dart';
import 'package:harness/web/web_entry.dart';
import 'package:harness/widgets/key_hints.dart';
@@ -57,5 +58,8 @@ void main() {
expect(find.byKey(const ValueKey('shortcuts-search')), findsOneWidget);
expect(find.text('↑↓ Browse'), findsNothing);
expect(find.text('Return Practice'), findsNothing);
+ // The frame started the workspace's download, which waits for the terminal
+ // font a test browser never sends: let its grace run out.
+ await tester.pump(terminalFontsGrace);
});
}
diff --git a/desktop/test/web_page_startup_test.dart b/desktop/test/web_page_startup_test.dart
new file mode 100644
index 000000000..731e10709
--- /dev/null
+++ b/desktop/test/web_page_startup_test.dart
@@ -0,0 +1,52 @@
+// The web page's own startup (web/index.html, web/flutter_bootstrap.js). The
+// loader waits for the main.dart.js preload; these keep the guards that stop it
+// waiting forever, which no browser test sees until a returning visit stays on
+// the loading screen.
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ final page = File('web/index.html').readAsStringSync();
+ final bootstrap = File('web/flutter_bootstrap.js').readAsStringSync();
+ final preload = RegExp(
+ r'<link rel="preload" href="main\.dart\.js"[^>]*>',
+ ).firstMatch(page)?[0];
+
+ test('the page preloads main.dart.js under the id the loader reads', () {
+ expect(preload, isNotNull);
+ expect(preload, contains('as="script"'));
+ expect(preload, contains('id="harness-main-preload"'));
+ expect(bootstrap, contains("getElementById('harness-main-preload')"));
+ });
+
+ test('the preload marks itself done, so a finish nobody heard still counts', () {
+ // From the cache it can finish before flutter_bootstrap.js is parsed.
+ expect(preload, contains('''onload="this.dataset.done = 'loaded'"'''));
+ expect(preload, contains('''onerror="this.dataset.done = 'failed'"'''));
+ expect(bootstrap, contains('link.dataset.done'));
+ });
+
+ test('the preload is in the head, ahead of every script', () {
+ final at = page.indexOf(preload!);
+ expect(at, lessThan(page.indexOf('</head>')));
+ expect(at, lessThan(page.indexOf('<script')));
+ });
+
+ test('a preload that never reports back holds the loader only so long', () {
+ expect(bootstrap, contains('setTimeout(resolve, 30000)'));
+ // Chrome fires load without waiting for a preload: the engine would share
+ // the line with main.dart.js again.
+ expect(bootstrap, isNot(contains("addEventListener('load', resolve")));
+ });
+
+ test('the loader call stays the one the website rewrites for each release', () {
+ // website/scripts/harness-web-assets.mjs: exactly one call with an object
+ // literal, the last statement of the script.
+ expect('_flutter.loader.load({'.allMatches(bootstrap), hasLength(1));
+ expect(
+ bootstrap.trimRight(),
+ matches(RegExp(r'_flutter\.loader\.load\(\{[^;]*\}\);$')),
+ );
+ });
+}
diff --git a/desktop/test/web_release_script_test.dart b/desktop/test/web_release_script_test.dart
index f9f35522b..cefba613a 100644
--- a/desktop/test/web_release_script_test.dart
+++ b/desktop/test/web_release_script_test.dart
@@ -14,7 +14,8 @@ const _unusedLucide = [
'$_lucide/Lucide500',
'$_lucide/Lucide600',
];
-const _others = ['MaterialIcons', 'Roboto Mono'];
+const _mono = 'Roboto Mono';
+const _others = ['MaterialIcons'];
String _assetOf(String family) => switch (family) {
'$_lucide/Lucide' => '$_lucide/assets/lucide.ttf',
@@ -71,9 +72,8 @@ Future<void> _git(Directory repo, List<String> args) async {
/// whose `flutter` writes [families].
Future<ProcessResult> _release(Directory repo, List<String> families) async {
Directory(p.join(repo.path, 'scripts')).createSync();
- File(
- 'scripts/build-web-release.sh',
- ).copySync(p.join(repo.path, 'scripts', 'build-web-release.sh'));
+ File('scripts/build-web-release.sh')
+ .copySync(p.join(repo.path, 'scripts', 'build-web-release.sh'));
final flutter = File(p.join(repo.path, 'fake-flutter.sh'))
..writeAsStringSync(_fakeFlutter(families));
await Process.run('chmod', ['+x', flutter.path]);
@@ -116,7 +116,12 @@ void main() {
final skip = Platform.isWindows ? 'needs bash and python3' : null;
test('the web release drops the Lucide weights the app never uses', () async {
- final result = await _release(repo, [..._others, ..._unusedLucide, _used]);
+ final result = await _release(repo, [
+ ..._others,
+ _mono,
+ ..._unusedLucide,
+ _used,
+ ]);
expect(result.exitCode, 0, reason: '${result.stderr}');
expect(_manifestFamilies(repo), [..._others, _used]);
@@ -129,7 +134,7 @@ void main() {
}, skip: skip);
test('the archive carries only the fonts the manifest lists', () async {
- await _release(repo, [..._others, ..._unusedLucide, _used]);
+ await _release(repo, [..._others, _mono, ..._unusedLucide, _used]);
final listing = await Process.run('tar', [
'-tzf',
@@ -144,23 +149,37 @@ void main() {
expect(files.where((file) => file.endsWith('lucide.ttf')), isEmpty);
}, skip: skip);
- test('the page fetches the fonts it ships beside the app, not after it', () async {
- final result = await _release(repo, [..._others, ..._unusedLucide, _used]);
-
- expect(result.exitCode, 0, reason: '${result.stderr}');
- final index = _builtIndex(repo);
- final head = index.substring(0, index.indexOf('</head>'));
- expect(head, contains(_preload('FontManifest.json')));
- for (final family in [..._others, _used]) {
- expect(head, contains(_preload(_assetOf(family))), reason: family);
- }
- for (final family in _unusedLucide) {
- expect(index, isNot(contains(_assetOf(family))), reason: family);
- }
- }, skip: skip);
+ test(
+ 'the page fetches the fonts it ships beside the app, not after it',
+ () async {
+ final result = await _release(repo, [
+ ..._others,
+ _mono,
+ ..._unusedLucide,
+ _used,
+ ]);
+
+ expect(result.exitCode, 0, reason: '${result.stderr}');
+ final index = _builtIndex(repo);
+ final head = index.substring(0, index.indexOf('</head>'));
+ expect(head, contains(_preload('FontManifest.json')));
+ for (final family in [..._others, _used]) {
+ expect(head, contains(_preload(_assetOf(family))), reason: family);
+ }
+ for (final family in _unusedLucide) {
+ expect(index, isNot(contains(_assetOf(family))), reason: family);
+ }
+ },
+ skip: skip,
+ );
test('the page connects to the API while the app downloads', () async {
- final result = await _release(repo, [..._others, ..._unusedLucide, _used]);
+ final result = await _release(repo, [
+ ..._others,
+ _mono,
+ ..._unusedLucide,
+ _used,
+ ]);
expect(result.exitCode, 0, reason: '${result.stderr}');
final index = _builtIndex(repo);
@@ -180,10 +199,53 @@ void main() {
expect(release['apiUrl'], 'https://harness-api.autonomous.ai');
}, skip: skip);
- test('a build with no Lucide 400 font fails instead of shipping blind', () async {
- final result = await _release(repo, [..._others, ..._unusedLucide]);
+ test(
+ 'the terminal font leaves the first visit and stays in the release',
+ () async {
+ final result = await _release(repo, [
+ ..._others,
+ _mono,
+ ..._unusedLucide,
+ _used,
+ ]);
+
+ expect(result.exitCode, 0, reason: '${result.stderr}');
+ // Nothing waits for it before the first frame: not the engine's font
+ // list, not the page's preloads. The workspace part loads it by name.
+ expect(_manifestFamilies(repo), isNot(contains(_mono)));
+ expect(_builtIndex(repo), isNot(contains(_assetOf(_mono))));
+ expect(_shipped(repo, _mono), isTrue);
+ },
+ skip: skip,
+ );
+
+ test(
+ 'a build with no terminal font fails instead of shipping blind',
+ () async {
+ final result = await _release(repo, [
+ ..._others,
+ ..._unusedLucide,
+ _used,
+ ]);
+
+ expect(result.exitCode, isNot(0));
+ expect('${result.stderr}', contains(_mono));
+ },
+ skip: skip,
+ );
- expect(result.exitCode, isNot(0));
- expect('${result.stderr}', contains(_used));
- }, skip: skip);
+ test(
+ 'a build with no Lucide 400 font fails instead of shipping blind',
+ () async {
+ final result = await _release(repo, [
+ ..._others,
+ _mono,
+ ..._unusedLucide,
+ ]);
+
+ expect(result.exitCode, isNot(0));
+ expect('${result.stderr}', contains(_used));
+ },
+ skip: skip,
+ );
}
diff --git a/desktop/test/web_workspace_part_test.dart b/desktop/test/web_workspace_part_test.dart
index 5f131018a..54b46073b 100644
--- a/desktop/test/web_workspace_part_test.dart
+++ b/desktop/test/web_workspace_part_test.dart
@@ -1,7 +1,11 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/web/parts/deferred_part.dart';
+import 'package:harness/web/parts/terminal_fonts.dart';
import 'package:harness/web/parts/workspace_part.dart';
import 'package:harness/web/shell/web_workspace.dart';
@@ -65,4 +69,69 @@ void main() {
expect(tester.takeException(), isNull);
expect(part.loaded, isFalse);
});
+
+ test('the workspace part waits for the terminal font as well', () async {
+ final library = Completer<void>();
+ final fonts = Completer<void>();
+ var done = false;
+ unawaited(
+ downloadWorkspace(
+ library: () => library.future,
+ fonts: () => fonts.future,
+ ).then((_) => done = true),
+ );
+
+ library.complete();
+ await pumpEventQueue();
+ expect(done, isFalse);
+
+ fonts.complete();
+ await pumpEventQueue();
+ expect(done, isTrue);
+ });
+
+ test('a terminal font that fails does not keep the workspace away', () async {
+ await downloadWorkspace(
+ library: () async {},
+ fonts: () => Future.error(Exception('offline')),
+ );
+ });
+
+ test('fonts that never arrive hold the workspace only so long', () async {
+ final stalled = Completer<void>();
+ var done = false;
+ unawaited(
+ downloadWorkspace(
+ library: () async {},
+ fonts: () => stalled.future,
+ fontsGrace: const Duration(milliseconds: 50),
+ ).then((_) => done = true),
+ );
+
+ await pumpEventQueue();
+ expect(done, isFalse);
+
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ expect(done, isTrue);
+ });
+
+ test('a workspace library that fails fails the part', () async {
+ await expectLater(
+ downloadWorkspace(
+ library: () => Future.error(Exception('offline')),
+ fonts: () async {},
+ ),
+ throwsException,
+ );
+ });
+
+ test('the terminal font files are in the bundle the browser reads', () async {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ expect(terminalFontAssets, hasLength(2));
+ for (final asset in terminalFontAssets) {
+ final bytes = await rootBundle.load(asset);
+ // A TrueType file opens with its version, 0x00010000.
+ expect(bytes.getUint32(0), 0x00010000, reason: asset);
+ }
+ });
}
diff --git a/desktop/tool/web_ux/load-time.mjs b/desktop/tool/web_ux/load-time.mjs
index 731116f83..7f000fc9b 100644
--- a/desktop/tool/web_ux/load-time.mjs
+++ b/desktop/tool/web_ux/load-time.mjs
@@ -19,6 +19,17 @@
// requests that failed and the page's console errors, and whether the loading
// screen was gone by the end. The last screen of each profile is saved in
// [out-dir], beside results.json.
+//
+// CHROME_ARGS adds flags to the browser, space-separated. The page is timed
+// with DevTools attached, as a person measuring with DevTools has it, and that
+// costs a cold load on the phone profiles about 0.8 s that nobody else pays:
+// V8 re-parses all of main.dart.js for source positions while the script
+// starts. CHROME_ARGS=--js-flags=--no-enable-lazy-source-positions times it
+// as a page nobody inspects runs.
+//
+// ALLOW_HOSTS names hosts, space-separated, that the page reaches for real
+// (fonts.gstatic.com, where the engine finds fallback fonts). Each run lists
+// what it fetched from them under `elsewhere`, in KB as sent.
import { chromium } from './playwright.mjs';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -135,6 +146,8 @@ async function once(context, origin, profile) {
.map((r) => [name(r.url), +(r.bytes / 1e3).toFixed(1)])),
fetchedTwice: [...counts].filter(([, n]) => n > 1).map(([file]) => file),
revalidated: fetched.filter((r) => r.status === 304).map((r) => name(r.url)),
+ elsewhere: Object.fromEntries([...requests.values()].filter((r) => !r.url.startsWith(origin) && r.bytes > 0)
+ .map((r) => [r.url, +(r.bytes / 1e3).toFixed(1)])),
failed, consoleErrors, splashRemoved, shot,
};
}
@@ -158,7 +171,11 @@ if (outDir) mkdirSync(outDir, { recursive: true });
const server = await serveRelease(root);
// Requests off the page fail at name lookup rather than through Playwright's
// routing, which would turn the browser's HTTP cache off and every warm load cold.
-const args = ['--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'];
+const allowed = (process.env.ALLOW_HOSTS ?? '').split(' ').filter(Boolean);
+const args = [
+ `--host-resolver-rules=${['MAP * ~NOTFOUND', ...['127.0.0.1', ...allowed].map((h) => `EXCLUDE ${h}`)].join(', ')}`,
+ ...(process.env.CHROME_ARGS ?? '').split(' ').filter(Boolean),
+];
const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, args });
// One load nobody times, so the server has compressed every file before the first timed one.
const prime = await browser.newContext();
diff --git a/desktop/tool/web_ux/loader-hold.mjs b/desktop/tool/web_ux/loader-hold.mjs
new file mode 100644
index 000000000..a330694d7
--- /dev/null
+++ b/desktop/tool/web_ux/loader-hold.mjs
@@ -0,0 +1,57 @@
+// The loader waits for main.dart.js (web/flutter_bootstrap.js), so it must hear that the preload
+// in web/index.html is done even when that finished first. Here the page's HTML stops for 0.5 s
+// after </head>, as a slow network can deliver it, while main.dart.js is already in the browser's
+// cache. The app must still draw on every visit; exits 1 on a visit that never draws.
+// Each visit forgets the mark that lets a browser skip the wait, so every one of them waits.
+//
+// node tool/web_ux/loader-hold.mjs <release-build> [visits]
+//
+// <release-build> is build/web-release from scripts/build-web-release.sh. Run from desktop/ with
+// PLAYWRIGHT_DIR set (see playwright.mjs).
+import { chromium } from './playwright.mjs';
+import { createServer, request } from 'node:http';
+import { brotliDecompressSync } from 'node:zlib';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { serveRelease } from './serve-release.mjs';
+const [root, visitsArg = '4'] = process.argv.slice(2);
+const upstream = await serveRelease(root);
+const up = new URL(upstream.origin);
+const proxy = createServer((req, res) => {
+ const out = request({ host: up.hostname, port: up.port, path: req.url, method: req.method, headers: req.headers }, (r) => {
+ const isPage = (r.headers['content-type'] ?? '').startsWith('text/html');
+ if (!isPage) { res.writeHead(r.statusCode, r.headers); r.pipe(res); return; }
+ const chunks = [];
+ r.on('data', (c) => chunks.push(c));
+ r.on('end', () => {
+ const html = brotliDecompressSync(Buffer.concat(chunks)).toString();
+ const cut = html.indexOf('</head>');
+ const headers = { ...r.headers }; delete headers['content-encoding']; delete headers['content-length'];
+ res.writeHead(r.statusCode, headers);
+ res.write(html.slice(0, cut));
+ setTimeout(() => res.end(html.slice(cut)), 500);
+ });
+ });
+ req.pipe(out);
+});
+await new Promise((r) => proxy.listen(0, '127.0.0.1', r));
+const origin = `http://127.0.0.1:${proxy.address().port}`;
+const dir = mkdtempSync(join(tmpdir(), 'split-'));
+const context = await chromium.launchPersistentContext(dir, { executablePath: process.env.CHROME_PATH, args: ['--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'] });
+await context.addInitScript(() => {
+ addEventListener('flutter-first-frame', () => { window.__ff = 1; }, { once: true });
+ // Forget that this browser loaded the script before, so the loader waits for it every visit.
+ try { localStorage.removeItem('harness.web.v1.main_script_loaded'); } catch (e) { /* about:blank */ }
+});
+let stuck = 0;
+for (let i = 0; i < Number(visitsArg); i++) {
+ const page = await context.newPage();
+ await page.goto(`${origin}/harness-web/`, { waitUntil: 'commit' });
+ const ok = await page.waitForFunction(() => window.__ff, null, { timeout: i === 0 ? 300000 : 20000 }).then(() => true, () => false);
+ if (!ok) stuck++;
+ console.log(`visit ${i + 1}: ${ok ? 'drawn' : 'STUCK, no first frame in 20 s'}`);
+ await page.close();
+}
+await context.close(); rmSync(dir, { recursive: true, force: true }); proxy.close(); upstream.close();
+process.exit(stuck ? 1 : 0);
diff --git a/desktop/web/flutter_bootstrap.js b/desktop/web/flutter_bootstrap.js
new file mode 100644
index 000000000..677431eed
--- /dev/null
+++ b/desktop/web/flutter_bootstrap.js
@@ -0,0 +1,43 @@
+{{flutter_js}}
+{{flutter_build_config}}
+// Flutter's own startup, with one change: the loader waits for main.dart.js, which index.html
+// preloads first. Started together, the app and the engine (canvaskit.wasm) shared the line and
+// arrived together, and only then did the app's script run. Now it runs while the engine is still
+// downloading. No preload, or one that fails, starts the loader as before. A preload already done
+// (from the cache, before this script was parsed) has marked itself in index.html. A browser that
+// has loaded this release's script before has both in its cache and nothing to wait for: waiting
+// for the script there only delays the engine, so the loader starts at once. A preload that never
+// reports back holds the loader 30 s at most. Not until the page's load event: Chrome fires that
+// without waiting for a preload, a quarter second in, and the engine shared the line again.
+(function () {
+ var link = document.getElementById('harness-main-preload');
+ var key = 'harness.web.v1.main_script_loaded';
+ function loadedBefore() {
+ try { return localStorage.getItem(key) === link.href; } catch (e) { return false; }
+ }
+ function remember() {
+ try { localStorage.setItem(key, link.href); } catch (e) { /* storage refused: wait next time too */ }
+ }
+ var downloaded = new Promise(function (resolve) {
+ if (!link || !link.relList || !link.relList.supports || !link.relList.supports('preload') ||
+ link.dataset.done || loadedBefore()) {
+ if (link && link.dataset.done === 'loaded') remember();
+ resolve();
+ return;
+ }
+ link.addEventListener('load', function () { remember(); resolve(); });
+ link.addEventListener('error', resolve);
+ setTimeout(resolve, 30000);
+ });
+ var load = _flutter.loader.load.bind(_flutter.loader);
+ _flutter.loader.load = function (options) {
+ return downloaded.then(function () { return load(options); });
+ };
+})();
+// The website rewrites the call below for each release (website/scripts/harness-web-assets.mjs): it
+// must stay the last statement and the only call with an object literal.
+_flutter.loader.load({
+ serviceWorkerSettings: {
+ serviceWorkerVersion: {{flutter_service_worker_version}}
+ }
+});
diff --git a/desktop/web/index.html b/desktop/web/index.html
index 444900358..479ab3dcc 100644
--- a/desktop/web/index.html
+++ b/desktop/web/index.html
@@ -13,6 +13,13 @@
<link rel="icon" href="favicon.ico?v=5" sizes="16x16 32x32 48x48">
<link rel="apple-touch-icon" href="icons/apple-touch-icon.png?v=5">
<title>Harness</title>
+ <!-- The app's script, first and at high priority: the loader in flutter_bootstrap.js waits for
+ it, so it runs while the engine downloads instead of after. The website moves the href into
+ the release's folder, where the loader asks for it (website/scripts/harness-web-assets.mjs).
+ It marks itself done: from the cache it can finish before the loader's script is parsed,
+ and a load event fired before anyone listened would leave the loader waiting forever. -->
+ <link rel="preload" href="main.dart.js" as="script" fetchpriority="high" id="harness-main-preload"
+ onload="this.dataset.done = 'loaded'" onerror="this.dataset.done = 'failed'">
<!-- The page the visitor sees until Flutter's first frame: the app is megabytes of script
and WebAssembly, so on a phone this is all there is for seconds. Plain HTML and CSS,
nothing to fetch. It follows the palette the app will open in (Graphite, or the light
diff --git a/website/scripts/harness-web-assets.test.mjs b/website/scripts/harness-web-assets.test.mjs
index ab5e24755..665727261 100644
--- a/website/scripts/harness-web-assets.test.mjs
+++ b/website/scripts/harness-web-assets.test.mjs
@@ -42,6 +42,23 @@ describe('release asset caching', () => {
]);
});
+ it('preloads main.dart.js from the archive namespace, keeping the marks the loader reads', () => {
+ // desktop/web/index.html and flutter_bootstrap.js: the loader waits for this preload, and the
+ // preload marks itself done in case it finishes before the loader listens.
+ const preload = '<link rel="preload" href="main.dart.js" as="script" fetchpriority="high" id="harness-main-preload"\n'
+ + ' onload="this.dataset.done = \'loaded\'" onerror="this.dataset.done = \'failed\'">';
+ const hold = 'var load = _flutter.loader.load.bind(_flutter.loader);\n'
+ + '_flutter.loader.load = function (options) { return load(options); };\n';
+ const page = html.replace('<html>', `<html><head>${preload}</head>`).replace('<script>\n', `<script>\n${hold}`);
+ const output = configureReleaseAssets(page, release);
+ const root = 'https://harness.example/harness-web/';
+ const href = output.match(/<link rel="preload" href="([^"]+)" as="script"/)[1];
+ expect(new URL(href, root).href).toBe(`${root}releases/0.1.4-aaaaaaaaaaaa/main.dart.js`);
+ expect(output).toContain(preload.replace('href="main.dart.js"', `href="${href}"`));
+ expect(output).toContain(hold);
+ expect(output).toContain(`_flutter.loader.load(${JSON.stringify({ config: startup(release).options.config })});`);
+ });
+
it('changes all browser cache keys when the version or archive changes', () => {
const before = startup(release).options.config;
for (const next of [{ ...release, version: '0.1.5' }, { ...release, sha256: 'b'.repeat(64) }]) {