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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Web UX speed: first load and connect (pre-compressed brotli, deferred workspace and Finder, saved computers, font and API preloads) (#1736)
Jacob Pham541974f2e9fe
diff --git a/cli/packages/harness-mcp/mcpb/manifest.json b/cli/packages/harness-mcp/mcpb/manifest.jsonindex 0e138e320..89106bad1 100644--- a/cli/packages/harness-mcp/mcpb/manifest.json+++ b/cli/packages/harness-mcp/mcpb/manifest.json@@ -54,6 +54,14 @@"name": "harness_read","description": "A harness's state and its last turn: what it was asked and what it answered."},+ {+ "name": "harness_tell",+ "description": "Give more work to a harness you started, on any machine, in the conversation it already has. Only while the person allows it."+ },+ {+ "name": "harness_settings",+ "description": "What agents may do here, the person's settings: each one and whether it is on, or turn one on (once the person says yes) or off."+ },{"name": "harness_close","description": "Close a harness you started, once it is done. Its conversation is kept: the person can resume it."diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 828b99524..2bfd2bf4c 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -161,6 +161,14 @@ without touching zoom or the synced layout, so the same desk keeps its grid on aarrangement (`Swarm.arranged`), because that is what a split divides: without it the menu's Split pane could never run on a phone. Do not change desktop behavior for theweb, and do not copy shared screens into `lib/web/` — add a seam instead.+**A browser downloads the app in parts** (`lib/web/parts/`, `DeferredPart`/`DeferredPartView`): the+signed-in workspace (`web_entry.dart` → `workspace_part.dart`, fetched once the first frame is up, so a+first visit's sign-in page skips its 4.4 MB), the Finder and its editor (`pane_grid.dart`), and the chat's+text viewer (`attachment_chips.dart`). Shared code reaches the last two through a compile-time import+switch (`if (dart.library.js_interop)`, as `main.dart` picks the web entry), so a computer compiles the+same files as ever (`test/pane_grid_finder_test.dart`). Importing one of these libraries directly from+shared code puts it back in `main.dart.js`. Check a real build with `tool/web_ux/deferred-parts.mjs`.+A browser on a phone or tablet (iOS, Android by `defaultTargetPlatform`, whatever the window's width) gets a bar overevery screen, sign-in and shared harnesses included, sending it to the Harness app in its store(`web/shell/web_store_banner.dart`). It is the app's frame — `startHarness(frame:)`, which `main.dart` takes from thediff --git a/desktop/design/web-ux-audit/README.md b/desktop/design/web-ux-audit/README.mdindex f41fad9ac..f61d070c1 100644--- a/desktop/design/web-ux-audit/README.md+++ b/desktop/design/web-ux-audit/README.md@@ -55,23 +55,25 @@ export PLAYWRIGHT_DIR=~/.cache/web-ux-playwright # CHROME_PATH may name annode tool/web_ux/capture.mjs /tmp/web-ux out # out/screens/<flow>/<width>-<theme>.pngFIXTURE=super-tab node tool/web_ux/capture.mjs /tmp/web-ux-super-tab out # the super-tab-* flowsnode tool/web_ux/checks.mjs /tmp/web-ux out # tap sizes, wheel, swipe, hover, focus-flutter build web --release --no-wasm-dry-run --no-web-resources-cdn \- --base-href=/harness-web/ -o /tmp/web-release-node tool/web_ux/load-time.mjs /tmp/web-release out # first load, three network profiles+bash scripts/build-web-release.sh 1.0.0 # build/web-release, as released+node tool/web_ux/load-time.mjs build/web-release out # cold, second and returning visits, three profiles+node tool/web_ux/deferred-parts.mjs /tmp/web-ux build/web-release out # the parts main.dart.js leaves out, online and off```| File | What it is || --- | --- || `tool/web_ux_fixture.dart` | Runs the real `HarnessApp` (store bar, `RootShell`, browser workspace) on a fake account || `tool/web_ux_scenarios.dart` | Merges every fix group's scenarios into the `?scenario=` names |-| `tool/web_ux/scenarios/<group>.dart` | One file per fix group (`menus`, `store`, `first_computer`, `first_load`, `pane`, `welcome`, `states`) plus `base`: the state each scenario seeds |+| `tool/web_ux/scenarios/<group>.dart` | One file per fix group (`menus`, `store`, `first_computer`, `first_load`, `pane`, `welcome`, `states`, `speed`) plus `base`: the state each scenario seeds || `tool/web_ux_seed.dart` | Fake person, computers, tabs and terminal text || `test/support/web_ux_app.dart` | The fake `AppNotifier`: never signs in, reads or dials; API base is a closed loopback port || `test/web_ux_app_test.dart` | Its test || `tool/web_ux/flows/<group>.mjs` | One file per fix group, same keys: each flow is a scenario plus the clicks a person makes, by accessible name. `load-flows.mjs` reads every file in the folder || `tool/web_ux/capture.mjs`, `serve.mjs` | Screenshots; blocks every request that leaves the page (`blocked*.json` is empty) || `tool/web_ux/checks.mjs` | Cross-cutting interaction checks, results in `checks.json` and `checks/` |-| `tool/web_ux/load-time.mjs` | First load of a release build; results in `load-time.json` |+| `tool/web_ux/load-time.mjs` | Cold, second and returning visits of a release build (the last two in a profile kept on disk: Chrome keeps no compiled script in a private window); results in `results.json` |+| `tool/web_ux/serve-release.mjs` | Serves a release build as the website does: versioned folder, cache headers, pre-compressed brotli |+| `tool/web_ux/deferred-parts.mjs` | The deferred parts (`lib/web/parts/`) in a real build: served immutable, downloaded, and Retry after a failed download || `tool/web_ux/playwright.mjs` | Finds Playwright in `PLAYWRIGHT_DIR` |A fix group adds its scenarios and flows to its own two files and edits nothing else; a namediff --git a/desktop/lib/settings/sections/account_section.dart b/desktop/lib/settings/sections/account_section.dartindex 3e89dbb98..1fcbd7122 100644--- a/desktop/lib/settings/sections/account_section.dart+++ b/desktop/lib/settings/sections/account_section.dart@@ -91,7 +91,10 @@ class AccountSection extends StatelessWidget {children: [account,const SizedBox(height: 12),- SavedSuperTabsRow(superTabs: notifier.superTabs),+ SavedSuperTabsRow(+ superTabs: notifier.superTabs,+ copies: notifier.browserCopies,+ ),],): account,diff --git a/desktop/lib/settings/sections/saved_super_tabs_row.dart b/desktop/lib/settings/sections/saved_super_tabs_row.dartindex e60887207..92847aaf9 100644--- a/desktop/lib/settings/sections/saved_super_tabs_row.dart+++ b/desktop/lib/settings/sections/saved_super_tabs_row.dart@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';import '../../shared/theme/app_theme.dart' as grid;import '../../shared/widgets/setting_row.dart';+import '../../state/browser_copies.dart';import '../../super_tabs/client.dart';/// Where views of Super Tabs are kept on this device (the web's reading,@@ -11,10 +12,17 @@ import '../../super_tabs/client.dart';/// they go, and clears them now. It says Cleared only when they went, and/// only until a Super Tab is kept again.class SavedSuperTabsRow extends StatefulWidget {- const SavedSuperTabsRow({super.key, required this.superTabs});+ const SavedSuperTabsRow({+ super.key,+ required this.superTabs,+ required this.copies,+ });final SuperTabClient superTabs;+ /// The host's other copies (the web's computer list), cleared with the views.+ final BrowserCopies copies;+@overrideState<SavedSuperTabsRow> createState() => _SavedSuperTabsRowState();}@@ -44,7 +52,10 @@ class _SavedSuperTabsRowState extends State<SavedSuperTabsRow> {setState(() => _state = _Clearing.busy);var cleared = true;try {- await widget.superTabs.clearSavedViews();+ await Future.wait([+ widget.superTabs.clearSavedViews(),+ widget.copies.clear(),+ ]);} catch (_) {// A browser that refuses its storage (full, private mode).cleared = false;@@ -57,8 +68,8 @@ class _SavedSuperTabsRowState extends State<SavedSuperTabsRow> {Widget build(BuildContext context) => SettingRow(title: 'Super Tabs in this browser',detail:- 'This browser keeps a copy of the Super Tabs you open, so they show '- 'at once. Signing out removes it.',+ 'This browser keeps a copy of the Super Tabs you open and the names '+ 'of your computers, so they show at once. Signing out removes it.',control: OutlinedButton(key: const Key('settings-clear-saved-super-tabs'),// A thumb's target on a phone.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b17d3c844..b2b37cb35 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -6,6 +6,7 @@ import '../core/crash_log.dart';import '../core/guest_folders.dart';import '../measurement/desktop_setup_report.dart';import 'attached_task_delivery.dart';+import 'browser_copies.dart';import 'harness_attachments.dart';import 'task_route.dart';import '../core/permission_modes.dart';@@ -1715,6 +1716,10 @@ class AppNotifier extends ChangeNotifier {return best;}+ /// What a host keeps of the account on this device beside the Super Tab+ /// views; Settings ▸ Account's Clear now clears it with them.+ final browserCopies = BrowserCopies();+late final superTabs = SuperTabClient(storage: localStore ?? HarnessFileStore.shared,upload: uploadWith(() => api),diff --git a/desktop/lib/state/browser_copies.dart b/desktop/lib/state/browser_copies.dartnew file mode 100644index 000000000..680282ad4--- /dev/null+++ b/desktop/lib/state/browser_copies.dart@@ -0,0 +1,15 @@+/// What a host keeps of the account on this device, beside the Super Tab+/// views the Swarm client keeps, so it can draw it at once: the web keeps the+/// account's computers (`web/onboarding/saved_computers.dart`). Each adds how+/// to clear its copy, and Settings ▸ Account's Clear now clears them with the+/// views. Desktop adds none.+class BrowserCopies {+ final _clears = <Future<void> Function()>[];++ void add(Future<void> Function() clear) => _clears.add(clear);++ /// Every copy; fails as the first that fails does, after trying them all.+ Future<void> clear() async {+ await Future.wait([for (final clear in _clears) clear()]);+ }+}diff --git a/desktop/lib/super_tabs/attachment_chips.dart b/desktop/lib/super_tabs/attachment_chips.dartindex 4242f4e4a..9eb48a1b5 100644--- a/desktop/lib/super_tabs/attachment_chips.dart+++ b/desktop/lib/super_tabs/attachment_chips.dart@@ -7,6 +7,9 @@ import '../widgets/desktop_chrome.dart';import '../widgets/finger_target.dart';import '../widgets/update_notice.dart' show formatDownloadSize;import 'attachment_upload.dart';+// A browser leaves the text viewer, and the Finder editor under it, out of main.dart.js.+import 'attachment_text_viewer.dart'+ if (dart.library.js_interop) '../web/parts/attachment_text_viewer.dart';import 'attachment_viewer.dart';import 'model.dart';diff --git a/desktop/lib/super_tabs/attachment_text_viewer.dart b/desktop/lib/super_tabs/attachment_text_viewer.dartnew file mode 100644index 000000000..b56664178--- /dev/null+++ b/desktop/lib/super_tabs/attachment_text_viewer.dart@@ -0,0 +1,155 @@+import 'dart:convert';+import 'dart:math' as math;+import 'dart:typed_data';++import 'package:flutter/material.dart';+import 'package:re_editor/re_editor.dart';++import '../core/open_in_browser.dart';+import '../finder/finder_file_kind.dart';+import '../finder/finder_language.dart';+import '../finder/finder_text_format.dart';+import '../finder/widgets/finder_code_editor.dart';+import '../finder/widgets/finder_markdown_view.dart';+import '../shared/theme/app_icons.dart';+import '../shared/widgets/app_icon_button.dart';+import '../shared/widgets/empty_state.dart';+import '../shared/widgets/skeleton.dart';+import '../widgets/desktop_chrome.dart';+import 'attachment_viewer.dart';+import 'model.dart';++/// A text file from the chat, read only: Markdown rendered with its source a+/// click away, anything else in Finder's editor. Fetched when this opens.+class AttachmentTextViewer extends StatefulWidget {+ const AttachmentTextViewer({+ super.key,+ required this.file,+ required this.url,+ });++ final SuperTabAttachment file;+ final Uri url;++ @override+ State<AttachmentTextViewer> createState() => _AttachmentTextViewerState();+}++class _AttachmentTextViewerState extends State<AttachmentTextViewer> {+ late final Future<Uint8List> _bytes = readAttachment(+ widget.url,+ maxBytes: kAttachmentTextMaxBytes,+ );++ @override+ void initState() {+ super.initState();+ // Larger than its size said: read it in the browser, as a large file is.+ _bytes.then<void>(+ (_) {},+ onError: (Object error) {+ if (error is! AttachmentTooLarge || !mounted) return;+ Navigator.pop(context);+ openInBrowser(widget.url);+ },+ );+ }++ CodeLineEditingController? _text;+ bool _source = false;++ bool get _markdown =>+ finderFileKind(widget.file.name) == FinderFileKind.markdown;++ @override+ void dispose() {+ _text?.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final screen = MediaQuery.sizeOf(context);+ return Dialog(+ child: SizedBox(+ width: math.min(960, screen.width * .9),+ height: screen.height * .85,+ child: FutureBuilder(+ future: _bytes,+ builder: (context, read) => Padding(+ padding: const EdgeInsets.all(16),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ widget.file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),+ ),+ ),+ if (_markdown && _textOf(read) != null)+ AppIconButton(+ icon: _source ? AppIcons.eye : AppIcons.code,+ tooltip: _source ? 'Show preview' : 'Show source',+ onPressed: () => setState(() => _source = !_source),+ ),+ ],+ ),+ const SizedBox(height: 12),+ Expanded(child: _body(read)),+ const SizedBox(height: 12),+ AttachmentViewerActions(file: widget.file, url: widget.url),+ ],+ ),+ ),+ ),+ ),+ );+ }++ /// The file's text once it has arrived and reads as text; null otherwise.+ CodeLineEditingController? _textOf(AsyncSnapshot<Uint8List> read) {+ final bytes = read.data;+ if (bytes == null || !looksLikeText(bytes)) {+ return null;+ }+ return _text ??= () {+ final text = utf8.decode(bytes, allowMalformed: true);+ return CodeLineEditingController.fromText(text, detectTextFormat(text));+ }();+ }++ Widget _body(AsyncSnapshot<Uint8List> read) {+ if (read.hasError) {+ return const EmptyState(+ icon: AppIcons.circleAlert,+ title: 'Can’t open this file',+ message: 'It couldn’t be downloaded. Try again in the browser.',+ compact: true,+ );+ }+ if (read.connectionState != ConnectionState.done) {+ return const SkeletonList(rows: 12);+ }+ final text = _textOf(read);+ if (text == null) {+ return const EmptyState(+ icon: AppIcons.file,+ title: 'No preview',+ message: 'This file isn’t text that can be shown here.',+ compact: true,+ );+ }+ if (_markdown && !_source) return FinderMarkdownView(text.text);+ return FinderCodeEditor(+ controller: text,+ language: finderLanguageOf(widget.file.name),+ readOnly: true,+ onSave: () {},+ );+ }+}diff --git a/desktop/lib/super_tabs/attachment_viewer.dart b/desktop/lib/super_tabs/attachment_viewer.dartindex 91420282a..392c35dec 100644--- a/desktop/lib/super_tabs/attachment_viewer.dart+++ b/desktop/lib/super_tabs/attachment_viewer.dart@@ -1,24 +1,13 @@-import 'dart:convert';import 'dart:io';-import 'dart:math' as math;import 'dart:typed_data';import 'package:dio/dio.dart';import 'package:file_selector/file_selector.dart';import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';-import 'package:re_editor/re_editor.dart';import '../core/open_in_browser.dart';import '../finder/finder_file_kind.dart';-import '../finder/finder_language.dart';-import '../finder/finder_text_format.dart';-import '../finder/widgets/finder_code_editor.dart';-import '../finder/widgets/finder_markdown_view.dart';-import '../shared/theme/app_icons.dart';-import '../shared/widgets/app_icon_button.dart';-import '../shared/widgets/empty_state.dart';-import '../shared/widgets/skeleton.dart';import '../widgets/desktop_chrome.dart';import 'model.dart';@@ -31,6 +20,11 @@ const kAttachmentTextMaxBytes = 2 * 1024 * 1024;Future<Uint8List> Function(Uri url, {int? maxBytes}) attachmentFetcher =fetchAttachment;+/// The file at [url] through [attachmentFetcher], for the text viewer+/// (`attachment_text_viewer.dart`), which a browser downloads apart.+Future<Uint8List> readAttachment(Uri url, {int? maxBytes}) =>+ attachmentFetcher(url, maxBytes: maxBytes);+/// A file past the text viewer's limit; it opens in the browser instead.class AttachmentTooLarge implements Exception {const AttachmentTooLarge();@@ -87,141 +81,6 @@ Future<bool> downloadAttachment(SuperTabAttachment file, Uri url) async {return true;}-/// A text file from the chat, read only: Markdown rendered with its source a-/// click away, anything else in Finder's editor. Fetched when this opens.-class AttachmentTextViewer extends StatefulWidget {- const AttachmentTextViewer({- super.key,- required this.file,- required this.url,- });-- final SuperTabAttachment file;- final Uri url;-- @override- State<AttachmentTextViewer> createState() => _AttachmentTextViewerState();-}--class _AttachmentTextViewerState extends State<AttachmentTextViewer> {- late final Future<Uint8List> _bytes = attachmentFetcher(- widget.url,- maxBytes: kAttachmentTextMaxBytes,- );-- @override- void initState() {- super.initState();- // Larger than its size said: read it in the browser, as a large file is.- _bytes.then<void>(- (_) {},- onError: (Object error) {- if (error is! AttachmentTooLarge || !mounted) return;- Navigator.pop(context);- openInBrowser(widget.url);- },- );- }-- CodeLineEditingController? _text;- bool _source = false;-- bool get _markdown =>- finderFileKind(widget.file.name) == FinderFileKind.markdown;-- @override- void dispose() {- _text?.dispose();- super.dispose();- }-- @override- Widget build(BuildContext context) {- final screen = MediaQuery.sizeOf(context);- return Dialog(- child: SizedBox(- width: math.min(960, screen.width * .9),- height: screen.height * .85,- child: FutureBuilder(- future: _bytes,- builder: (context, read) => Padding(- padding: const EdgeInsets.all(16),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Row(- children: [- Expanded(- child: Text(- widget.file.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(medium: true),- ),- ),- if (_markdown && _textOf(read) != null)- AppIconButton(- icon: _source ? AppIcons.eye : AppIcons.code,- tooltip: _source ? 'Show preview' : 'Show source',- onPressed: () => setState(() => _source = !_source),- ),- ],- ),- const SizedBox(height: 12),- Expanded(child: _body(read)),- const SizedBox(height: 12),- AttachmentViewerActions(file: widget.file, url: widget.url),- ],- ),- ),- ),- ),- );- }-- /// The file's text once it has arrived and reads as text; null otherwise.- CodeLineEditingController? _textOf(AsyncSnapshot<Uint8List> read) {- final bytes = read.data;- if (bytes == null || !looksLikeText(bytes)) {- return null;- }- return _text ??= () {- final text = utf8.decode(bytes, allowMalformed: true);- return CodeLineEditingController.fromText(text, detectTextFormat(text));- }();- }-- Widget _body(AsyncSnapshot<Uint8List> read) {- if (read.hasError) {- return const EmptyState(- icon: AppIcons.circleAlert,- title: 'Can’t open this file',- message: 'It couldn’t be downloaded. Try again in the browser.',- compact: true,- );- }- if (read.connectionState != ConnectionState.done) {- return const SkeletonList(rows: 12);- }- final text = _textOf(read);- if (text == null) {- return const EmptyState(- icon: AppIcons.file,- title: 'No preview',- message: 'This file isn’t text that can be shown here.',- compact: true,- );- }- if (_markdown && !_source) return FinderMarkdownView(text.text);- return FinderCodeEditor(- controller: text,- language: finderLanguageOf(widget.file.name),- readOnly: true,- onSave: () {},- );- }-}-/// A viewer's buttons: save the file, open it in the browser, or close.class AttachmentViewerActions extends StatefulWidget {const AttachmentViewerActions({diff --git a/desktop/lib/web/onboarding/computer_row.dart b/desktop/lib/web/onboarding/computer_row.dartnew file mode 100644index 000000000..61b2bd45c--- /dev/null+++ b/desktop/lib/web/onboarding/computer_row.dart@@ -0,0 +1,68 @@+import 'package:flutter/material.dart';++import '../../shared/theme/app_icons.dart';+import '../../widgets/desktop_chrome.dart';++/// One computer on the connect page: its name, where it stands in words, and+/// a spinner or a button at the end.+class ComputerRow extends StatelessWidget {+ const ComputerRow({+ super.key,+ required this.name,+ required this.status,+ this.offline = false,+ this.trailing,+ });++ final String name;+ final String status;+ final bool offline;+ final Widget? trailing;++ @override+ Widget build(BuildContext context) => Container(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ border: Border.all(color: DesktopChrome.rim),+ borderRadius: BorderRadius.circular(DesktopChrome.dialogRadius),+ ),+ child: Row(+ children: [+ Icon(+ offline ? AppIcons.monitorOff : AppIcons.laptop,+ size: 18,+ color: DesktopChrome.foreground,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(name, style: DesktopChrome.text(medium: true)),+ Semantics(+ liveRegion: true,+ child: Text(status, style: DesktopChrome.metadata()),+ ),+ ],+ ),+ ),+ ?trailing,+ ],+ ),+ );+}++/// A spinner the size the rows use.+class ComputerRowSpinner extends StatelessWidget {+ const ComputerRowSpinner({super.key});++ @override+ Widget build(BuildContext context) => SizedBox.square(+ dimension: 14,+ child: CircularProgressIndicator(+ strokeWidth: 1.5,+ color: DesktopChrome.muted,+ ),+ );+}diff --git a/desktop/lib/web/onboarding/saved_computer_rows.dart b/desktop/lib/web/onboarding/saved_computer_rows.dartnew file mode 100644index 000000000..494ac13a6--- /dev/null+++ b/desktop/lib/web/onboarding/saved_computer_rows.dart@@ -0,0 +1,27 @@+import 'package:flutter/material.dart';++import 'computer_row.dart';+import 'saved_computers.dart';++/// The computers this browser kept, while the machine list is read: their+/// names only, each checking, and nothing to press until the list answers.+class SavedComputerRows extends StatelessWidget {+ const SavedComputerRows(this.computers, {super.key});++ final List<SavedComputer> computers;++ @override+ Widget build(BuildContext context) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final computer in computers) ...[+ ComputerRow(+ name: computer.name,+ status: 'Checking…',+ trailing: const ComputerRowSpinner(),+ ),+ const SizedBox(height: 10),+ ],+ ],+ );+}diff --git a/desktop/lib/web/onboarding/saved_computers.dart b/desktop/lib/web/onboarding/saved_computers.dartnew file mode 100644index 000000000..69d9eb4e6--- /dev/null+++ b/desktop/lib/web/onboarding/saved_computers.dart@@ -0,0 +1,248 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';++import '../../core/harness_file_store.dart';+import '../../core/local_key_value_store.dart';+import '../../state/app_state.dart';+import 'web_your_computers.dart';++/// One of the account's computers as the connect page last listed it: its+/// name and id, nothing about how to reach it.+@immutable+class SavedComputer {+ const SavedComputer({required this.id, required this.name});++ final String id;+ final String name;++ Map<String, String> toJson() => {'id': id, 'name': name};++ static SavedComputer? fromJson(Object? raw) =>+ raw is Map && raw['id'] is String && raw['name'] is String+ ? SavedComputer(id: raw['id'] as String, name: raw['name'] as String)+ : null;++ @override+ bool operator ==(Object other) =>+ other is SavedComputer && other.id == id && other.name == name;++ @override+ int get hashCode => Object.hash(id, name);++ @override+ String toString() => 'SavedComputer($id, $name)';+}++/// The account's computers kept in this browser, so the connect page can list+/// them before the machine list answers. Kept like a saved Super Tab view+/// (`super_tabs/saved_view.dart`): for the one account using this browser, and+/// forgotten when another signs in or this one signs out.+class SavedComputers {+ SavedComputers(this.storage);++ final LocalKeyValueStore storage;++ String _key(String account) => 'web.computers.$account';++ /// The account whose computers this browser keeps.+ static const _owner = 'web.computers.saved_by';++ Future<void> _tail = Future.value();++ /// One operation at a time here, and across this browser's tabs under its lock.+ Future<T> _serial<T>(Future<T> Function() action) {+ final run = _tail.then(+ (_) => storage.synchronized('web.computers', action),+ );+ _tail = run.then((_) {}, onError: (Object _) {});+ return run;+ }++ /// [account]'s computers, or null: none kept, unreadable, or a storage that+ /// refuses (full, private mode). It never throws.+ Future<List<SavedComputer>?> read(String account) => _serial(() async {+ try {+ if (await storage.read(_owner) != account) return null;+ final raw = await storage.read(_key(account));+ if (raw == null) return null;+ final list = jsonDecode(raw);+ if (list is! List) return null;+ return [for (final row in list) ?SavedComputer.fromJson(row)];+ } catch (_) {+ return null;+ }+ });++ /// Keeps [computers] for [account]. Only for the account using this+ /// browser: a late write after a sign-out or another account's claim keeps+ /// nothing.+ Future<void> write(String account, List<SavedComputer> computers) =>+ _serial(() async {+ try {+ if (await storage.read(_owner) != account) return;+ await storage.write(_key(account), jsonEncode(computers));+ } catch (_) {}+ });++ /// Clear now: [account]'s computers go; the browser stays [account]'s.+ Future<void> clear(String account) => _serial(() async {+ if (await storage.read(_owner) == account) {+ await storage.delete(_key(account));+ }+ });++ /// [account] (null when signed out) is the one using this browser now:+ /// any other's computers, kept before a reload too, are forgotten.+ Future<void> claim(String? account) => _serial(() async {+ try {+ final owner = await storage.read(_owner);+ if (owner == account) return;+ if (owner != null) await storage.delete(_key(owner));+ if (account == null) {+ await storage.delete(_owner);+ } else {+ await storage.write(_owner, account);+ }+ } catch (_) {}+ });+}++/// Keeps the computers the connect page lists in [store] whenever the machine+/// list answers, and offers the kept ones ([shown]) until it does: a+/// returning browser sees its computers at once rather than "Finding your+/// computers…" for as long as the list takes.+class SavedComputersWatch extends ChangeNotifier {+ SavedComputersWatch(this.app, this.store) {+ app.addListener(_changed);+ _changed();+ }++ final AppNotifier app;+ final SavedComputers store;++ String? _account;++ /// Whether the browser was found signed out and the last account's+ /// computers forgotten: a boot into an expired session never had an+ /// account to leave.+ bool _forgotten = false;+ List<SavedComputer>? _kept;+ List<SavedComputer>? _written;+ List<SavedComputer>? _wasShown;++ /// The kept computers while the machine list has not answered; null once+ /// it has, or with none kept.+ List<SavedComputer>? get shown => app.machineInventoryLoaded ? null : _kept;++ void _changed() {+ final signedOut = app.status == AppStatus.unauthenticated;+ // Booting, nobody is known yet and nothing is forgotten; signed out (by+ // hand, or a session that expired, at boot too), the last account's go.+ final account = signedOut ? null : app.currentUser?.id;+ if (account != _account || (signedOut && !_forgotten)) _bind(account);+ // The list answering takes the kept computers off the page.+ if (!identical(shown, _wasShown)) {+ _wasShown = shown;+ notifyListeners();+ }+ if (account == null || !app.machineInventoryLoaded) return;+ final listed = [+ for (final state in WebYourComputers.listed(app))+ SavedComputer(+ id: state.machine.machineId,+ name: state.machine.displayName,+ ),+ ];+ if (listEquals(listed, _written)) return;+ _written = listed;+ unawaited(store.write(account, listed));+ }++ /// Settings ▸ Account's Clear now: the kept computers go. The list on+ /// screen is not kept again until it changes.+ Future<void> clear() async {+ final account = _account;+ _kept = null;+ _changed();+ if (account != null) await store.clear(account);+ }++ void _bind(String? account) {+ _account = account;+ _forgotten = account == null;+ _kept = null;+ _written = null;+ final claimed = store.claim(account);+ if (account == null) return;+ unawaited(+ claimed.then((_) => store.read(account)).then((kept) {+ if (_account != account || kept == null || kept.isEmpty) return;+ _kept = kept;+ _changed();+ }),+ );+ }++ @override+ void dispose() {+ app.removeListener(_changed);+ super.dispose();+ }+}++/// The one [SavedComputersWatch] of [app], kept in this browser's storage and+/// cleared by Clear now ([AppNotifier.browserCopies]). The web workspace asks+/// for it when it is first drawn, so the list is kept whenever it answers, not+/// only once the connect page shows.+SavedComputersWatch savedComputersOf(AppNotifier app) =>+ _watches[app] ??= _watch(app);++SavedComputersWatch _watch(AppNotifier app) {+ final watch = SavedComputersWatch(+ app,+ SavedComputers(app.localStore ?? HarnessFileStore.shared),+ );+ app.browserCopies.add(watch.clear);+ return watch;+}++final _watches = Expando<SavedComputersWatch>('savedComputersOf');++/// Above every screen of the browser build (`web_entry.dart`'s frame): the+/// app's [SavedComputersWatch] from its start, so a browser that opens signed+/// out, or into an expired session, forgets the last account's computers+/// even though no workspace is ever drawn.+class KeptComputers extends StatefulWidget {+ const KeptComputers({super.key, required this.child});++ final Widget child;++ @override+ State<KeptComputers> createState() => _KeptComputersState();+}++class _KeptComputersState extends State<KeptComputers> {+ bool _started = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ if (_started) return;+ _started = true;+ // The app comes from the ProviderScope around HarnessApp; a frame drawn+ // without one (a widget test of the frame alone) keeps nothing.+ final scope = context+ .getElementForInheritedWidgetOfExactType<UncontrolledProviderScope>();+ if (scope == null) return;+ savedComputersOf(+ ProviderScope.containerOf(context, listen: false).read(appStateProvider),+ );+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/desktop/lib/web/onboarding/web_first_machine.dart b/desktop/lib/web/onboarding/web_first_machine.dartindex 156d16a4d..150180b79 100644--- a/desktop/lib/web/onboarding/web_first_machine.dart+++ b/desktop/lib/web/onboarding/web_first_machine.dart@@ -11,6 +11,8 @@ import '../../widgets/desktop_chrome.dart';import '../../widgets/link_another_machine_dialog.dart'show kLinkServerInstallCommand, kLinkServerLoginCommand;import '../../widgets/web_download_button.dart';+import 'saved_computer_rows.dart';+import 'saved_computers.dart';import 'web_your_computers.dart';/// What a browser shows while none of the account's computers is connected,@@ -25,18 +27,23 @@ import 'web_your_computers.dart';/// for the machine list while this page shows — and the workspace takes over/// the moment one connects.///-/// Until the machine list first answers it only says it is looking, and if-/// that list cannot be read, says so with Retry — it never shows setup steps-/// an account may not need.+/// Until the machine list first answers it lists the computers this browser+/// kept from the last answer ([saved]), each checking; with none kept it only+/// says it is looking. If that list cannot be read, it says so with Retry. It+/// never shows setup steps an account may not need.class WebFirstMachine extends StatefulWidget {const WebFirstMachine({super.key,required this.app,+ this.saved,this.openPage = openInNewTab,});final AppNotifier app;+ /// The computers kept in this browser; null keeps none.+ final SavedComputersWatch? saved;+/// How the download page opens; tests pass a recorder.final Future<bool> Function(Uri uri) openPage;@@ -72,13 +79,25 @@ class _WebFirstMachineState extends State<WebFirstMachine> {@overrideWidget build(BuildContext context) {+ final saved = widget.saved;+ if (saved == null) return _page(null);+ return ListenableBuilder(+ listenable: saved,+ builder: (context, _) => _page(saved.shown),+ );+ }++ /// [kept]: the computers to list, checking, until the machine list answers.+ Widget _page(List<SavedComputer>? kept) {grid.AppTheme.watch(context);if (!widget.app.machineInventoryLoaded) {final error = widget.app.machineListError;- if (error == null) {+ if (error != null) {+ return _ListFailed(error: error, onRetry: widget.app.retryMachines);+ }+ if (kept == null || kept.isEmpty) {return const Center(child: _Waiting('Finding your computers…'));}- return _ListFailed(error: error, onRetry: widget.app.retryMachines);}final email = widget.app.currentUser?.email;final account = email == null || email.isEmpty ? 'this account' : email;@@ -109,7 +128,8 @@ class _WebFirstMachineState extends State<WebFirstMachine> {],),];- final hasComputers = WebYourComputers.listed(widget.app).isNotEmpty;+ final hasComputers =+ kept != null || WebYourComputers.listed(widget.app).isNotEmpty;return LayoutBuilder(builder: (context, constraints) {final sideBySide = constraints.maxWidth >= 640;@@ -137,7 +157,9 @@ class _WebFirstMachineState extends State<WebFirstMachine> {),const SizedBox(height: 28),if (hasComputers) ...[- WebYourComputers(app: widget.app),+ kept != null+ ? SavedComputerRows(kept)+ : WebYourComputers(app: widget.app),const SizedBox(height: 18),Text('Or set up another computer',diff --git a/desktop/lib/web/onboarding/web_your_computers.dart b/desktop/lib/web/onboarding/web_your_computers.dartindex 72cb931e4..6bb5bafb4 100644--- a/desktop/lib/web/onboarding/web_your_computers.dart+++ b/desktop/lib/web/onboarding/web_your_computers.dart@@ -3,11 +3,10 @@ import 'dart:async';import 'package:flutter/material.dart';import '../../core/models.dart';-import '../../shared/theme/app_icons.dart';import '../../shared/theme/app_theme.dart' as grid;import '../../state/app_state.dart';-import '../../widgets/desktop_chrome.dart';import '../../widgets/machine_picker_form.dart';+import 'computer_row.dart';/// The account's computers this browser is not connected to. One waiting on/// this browser connects with a click — a computer trusts the account's other@@ -178,61 +177,27 @@ class _ComputerRow extends StatelessWidget {final busy =link == ComputerLinkState.linking ||link == ComputerLinkState.connecting;- return Container(- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),- decoration: BoxDecoration(- color: DesktopChrome.field,- border: Border.all(color: DesktopChrome.rim),- borderRadius: BorderRadius.circular(DesktopChrome.dialogRadius),- ),- child: Row(- children: [- Icon(- link == ComputerLinkState.offline ||- link == ComputerLinkState.removed- ? AppIcons.monitorOff- : AppIcons.laptop,- size: 18,- color: DesktopChrome.foreground,- ),- const SizedBox(width: 12),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- state.machine.displayName,- style: DesktopChrome.text(medium: true),- ),- Semantics(- liveRegion: true,- child: Text(status, style: DesktopChrome.metadata()),- ),- ],- ),- ),- if (busy)- SizedBox.square(- dimension: 14,- child: CircularProgressIndicator(- strokeWidth: 1.5,- color: DesktopChrome.muted,+ return ComputerRow(+ name: state.machine.displayName,+ status: status,+ offline:+ link == ComputerLinkState.offline ||+ link == ComputerLinkState.removed,+ trailing: busy+ ? const ComputerRowSpinner()+ : switch (link) {+ ComputerLinkState.ready => FilledButton(+ style: webOnboardingButton,+ onPressed: onConnect,+ child: const Text('Connect'),),- )- else if (link == ComputerLinkState.ready)- FilledButton(- style: webOnboardingButton,- onPressed: onConnect,- child: const Text('Connect'),- )- else if (link == ComputerLinkState.failed)- FilledButton(- style: webOnboardingButton,- onPressed: onConnect,- child: const Text('Try again'),- ),- ],- ),+ ComputerLinkState.failed => FilledButton(+ style: webOnboardingButton,+ onPressed: onConnect,+ child: const Text('Try again'),+ ),+ _ => null,+ },);}}diff --git a/desktop/lib/web/parts/attachment_text_viewer.dart b/desktop/lib/web/parts/attachment_text_viewer.dartnew file mode 100644index 000000000..d0b1f160e--- /dev/null+++ b/desktop/lib/web/parts/attachment_text_viewer.dart@@ -0,0 +1,30 @@+import 'package:flutter/widgets.dart';++import '../../super_tabs/attachment_text_viewer.dart' deferred as viewer;+import '../../super_tabs/model.dart';+import 'deferred_part.dart';++/// The chat's text viewer, built on the Finder's editor and its colours:+/// left out of `main.dart.js`. A browser opens chat files in a new tab+/// (`opensAsText`), so today it is downloaded only if that changes.+final attachmentTextPart = DeferredPart(viewer.loadLibrary);++/// The browser's stand-in for `super_tabs/attachment_text_viewer.dart`, picked+/// by the attachment chips' conditional import: the same viewer, once+/// [attachmentTextPart] is in.+class AttachmentTextViewer extends StatelessWidget {+ const AttachmentTextViewer({+ super.key,+ required this.file,+ required this.url,+ });++ final SuperTabAttachment file;+ final Uri url;++ @override+ Widget build(BuildContext context) => DeferredPartView(+ part: attachmentTextPart,+ builder: (_) => viewer.AttachmentTextViewer(file: file, url: url),+ );+}diff --git a/desktop/lib/web/parts/deferred_part.dart b/desktop/lib/web/parts/deferred_part.dartnew file mode 100644index 000000000..78aefac8e--- /dev/null+++ b/desktop/lib/web/parts/deferred_part.dart@@ -0,0 +1,227 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../../shared/theme/app_icons.dart';+import '../../shared/theme/app_theme.dart' as grid;+import '../../widgets/desktop_chrome.dart';+import 'page_reload.dart' if (dart.library.js_interop) 'page_reload_web.dart';++/// A part of the browser build that `main.dart.js` leaves out: a `deferred`+/// library, downloaded the first time something needs it. One download is+/// shared by every place that asks; a failed one is forgotten, so the next ask+/// downloads it again (dart2js has already retried it three times by then).+/// A download still pending is not asked again: dart2js would hand back the+/// same one.+class DeferredPart {+ DeferredPart(this._download);++ /// The library's `loadLibrary`.+ final Future<void> Function() _download;+ Future<void>? _loading;++ /// Whether the part is in, so a view of it draws at once.+ bool get loaded => _loaded;+ bool _loaded = false;++ Future<void> load() => _loading ??= _download().then(+ (_) => _loaded = true,+ onError: (Object error, StackTrace stack) {+ _loading = null;+ Error.throwWithStackTrace(error, stack);+ },+ );+}++/// [builder]'s widget once [part] is in. Until then a loading line in its+/// place; if the download fails, a sentence and Retry instead of a blank, and+/// a Retry that fails too offers to reload the page: an older page cannot+/// download a part a release replaced. A download still going after+/// [stallAfter] offers Reload alone: asked again, dart2js hands back the same+/// pending download.+class DeferredPartView extends StatefulWidget {+ const DeferredPartView({+ super.key,+ required this.part,+ required this.builder,+ this.reload = reloadPage,+ });++ final DeferredPart part;+ final WidgetBuilder builder;++ /// Reloads the page; tests pass a recorder.+ final VoidCallback reload;++ /// How long a download goes before Reload is offered.+ static const stallAfter = Duration(seconds: 20);++ @override+ State<DeferredPartView> createState() => _DeferredPartViewState();+}++class _DeferredPartViewState extends State<DeferredPartView> {+ var _failures = 0;+ bool _failed = false, _stalled = false;+ Timer? _stall;++ @override+ void initState() {+ super.initState();+ if (!widget.part.loaded) _load(widget.part.load());+ }++ @override+ void dispose() {+ _stall?.cancel();+ super.dispose();+ }++ void _load(Future<void> download) {+ _stall?.cancel();+ _stall = Timer(DeferredPartView.stallAfter, () {+ if (mounted) setState(() => _stalled = true);+ });+ download.then(+ (_) {+ _stall?.cancel();+ if (mounted) setState(() => _failed = _stalled = false);+ },+ onError: (Object _) {+ _stall?.cancel();+ if (!mounted) return;+ setState(() {+ _failures++;+ _failed = true;+ _stalled = false;+ });+ },+ );+ }++ void _retry() {+ setState(() => _failed = _stalled = false);+ _load(widget.part.load());+ }++ @override+ Widget build(BuildContext context) {+ if (widget.part.loaded) return widget.builder(context);+ grid.AppTheme.watch(context);+ final Widget shown;+ if (_failed && _failures > 1) {+ shown = _Problem(+ title: 'Could not load this part of Harness',+ detail:+ 'Harness may have been updated since this page opened. '+ 'Reload the page to get the new version.',+ onRetry: _retry,+ onReload: widget.reload,+ );+ } else if (_failed) {+ shown = _Problem(+ title: 'Could not load this part of Harness',+ detail: 'Check the connection, then retry.',+ onRetry: _retry,+ );+ } else if (_stalled) {+ shown = _Problem(+ title: 'Still loading this part of Harness',+ detail: 'Check the connection, then reload the page.',+ onReload: widget.reload,+ );+ } else {+ shown = const _Loading();+ }+ // Its own Material: the workspace's part is drawn above any page.+ return Material(+ type: MaterialType.transparency,+ child: Center(+ child: Padding(padding: const EdgeInsets.all(16), child: shown),+ ),+ );+ }+}++class _Loading extends StatelessWidget {+ const _Loading();++ @override+ Widget build(BuildContext context) => Semantics(+ liveRegion: true,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox.square(+ dimension: 12,+ child: CircularProgressIndicator(+ strokeWidth: 1.5,+ color: DesktopChrome.muted,+ ),+ ),+ const SizedBox(width: 10),+ Text('Loading…', style: DesktopChrome.metadata()),+ ],+ ),+ );+}++/// What went wrong in a sentence, and what to do: Retry, Reload, or both.+class _Problem extends StatelessWidget {+ const _Problem({+ required this.title,+ required this.detail,+ this.onRetry,+ this.onReload,+ });++ final String title;+ final String detail;+ final VoidCallback? onRetry;+ final VoidCallback? onReload;++ @override+ Widget build(BuildContext context) {+ final buttonStyle = TextButton.styleFrom(minimumSize: const Size(44, 44));+ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Semantics(+ liveRegion: true,+ child: Text(+ title,+ textAlign: TextAlign.center,+ style: DesktopChrome.text(color: DesktopChrome.foreground),+ ),+ ),+ const SizedBox(height: 4),+ Text(+ detail,+ textAlign: TextAlign.center,+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 8),+ Wrap(+ alignment: WrapAlignment.center,+ spacing: 8,+ children: [+ if (onReload case final reload?)+ TextButton.icon(+ style: buttonStyle,+ onPressed: reload,+ icon: const Icon(AppIcons.refreshCw, size: 14),+ label: const Text('Reload'),+ ),+ if (onRetry case final retry?)+ TextButton.icon(+ style: buttonStyle,+ onPressed: retry,+ icon: const Icon(AppIcons.rotateCw, size: 14),+ label: const Text('Retry'),+ ),+ ],+ ),+ ],+ );+ }+}diff --git a/desktop/lib/web/parts/finder_pane_panel.dart b/desktop/lib/web/parts/finder_pane_panel.dartnew file mode 100644index 000000000..46d1d188e--- /dev/null+++ b/desktop/lib/web/parts/finder_pane_panel.dart@@ -0,0 +1,38 @@+import 'package:flutter/widgets.dart';++import '../../finder/widgets/finder_pane_panel.dart' deferred as finder;+import 'deferred_part.dart';++/// The Finder and its editor, with every language's colours (re_highlight,+/// about 2 MB): a browser cannot open a Finder yet (`canOpenFinderOn`), so+/// they stay out of `main.dart.js` until a Finder tile is drawn.+final finderPart = DeferredPart(finder.loadLibrary);++/// The browser's stand-in for `finder/widgets/finder_pane_panel.dart`, picked+/// by the pane grid's conditional import: the same tile, once [finderPart] is+/// in. It takes what the grid hands a Finder tile.+class FinderPanePanel extends StatelessWidget {+ const FinderPanePanel({+ super.key,+ required this.root,+ this.onGuardClose,+ this.compactHeader = false,+ this.onFixedWidth,+ });++ final String root;+ final void Function(Future<bool> Function()? guard)? onGuardClose;+ final bool compactHeader;+ final ValueChanged<double?>? onFixedWidth;++ @override+ Widget build(BuildContext context) => DeferredPartView(+ part: finderPart,+ builder: (_) => finder.FinderPanePanel(+ root: root,+ onGuardClose: onGuardClose,+ compactHeader: compactHeader,+ onFixedWidth: onFixedWidth,+ ),+ );+}diff --git a/desktop/lib/web/parts/page_reload.dart b/desktop/lib/web/parts/page_reload.dartnew file mode 100644index 000000000..a5366d3e4--- /dev/null+++ b/desktop/lib/web/parts/page_reload.dart@@ -0,0 +1,3 @@+/// Reloads the page; a native build has none (`page_reload_web.dart` is the+/// browser's, picked by the import in `deferred_part.dart`).+void reloadPage() {}diff --git a/desktop/lib/web/parts/page_reload_web.dart b/desktop/lib/web/parts/page_reload_web.dartnew file mode 100644index 000000000..dcd7ed083--- /dev/null+++ b/desktop/lib/web/parts/page_reload_web.dart@@ -0,0 +1,4 @@+import 'package:web/web.dart' as web;++/// Reloads the page, for a part an older page can no longer download.+void reloadPage() => web.window.location.reload();diff --git a/desktop/lib/web/parts/workspace_part.dart b/desktop/lib/web/parts/workspace_part.dartnew file mode 100644index 000000000..0252f8cd9--- /dev/null+++ b/desktop/lib/web/parts/workspace_part.dart@@ -0,0 +1,54 @@+import 'dart:async';++import 'package:flutter/widgets.dart';++import '../../state/app_state.dart';+import '../shell/web_workspace.dart' deferred as workspace;+import 'deferred_part.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);++/// The browser's workspace once [workspacePart] is in.+class DeferredWorkspace extends StatelessWidget {+ const DeferredWorkspace({super.key, required this.app});++ final AppNotifier app;++ @override+ Widget build(BuildContext context) => DeferredPartView(+ part: workspacePart,+ builder: (_) => workspace.WebWorkspace(app: app),+ );+}++/// Starts downloading [part] after the first frame is drawn: early enough+/// that a signed-in boot rarely waits for it, late enough that a first+/// visit's sign-in page does not share the network with it.+class WorkspacePrefetch extends StatefulWidget {+ WorkspacePrefetch({super.key, DeferredPart? part, required this.child})+ : part = part ?? workspacePart;++ final DeferredPart part;+ final Widget child;++ @override+ State<WorkspacePrefetch> createState() => _WorkspacePrefetchState();+}++class _WorkspacePrefetchState extends State<WorkspacePrefetch> {+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ // Nothing waits on it yet: a failure here is asked again by the+ // workspace when it is drawn, which shows it with Retry.+ unawaited(widget.part.load().then((_) {}, onError: (Object _) {}));+ });+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/desktop/lib/web/shell/web_chrome.dart b/desktop/lib/web/shell/web_chrome.dartindex bdcfc67be..6b03ff06e 100644--- a/desktop/lib/web/shell/web_chrome.dart+++ b/desktop/lib/web/shell/web_chrome.dart@@ -1,6 +1,7 @@import '../../state/app_state.dart';import '../../super_tabs/reading.dart';import '../../state/workspace_chrome.dart';+import '../onboarding/saved_computers.dart';import '../onboarding/web_first_machine.dart';import '../footer/web_footer_bar.dart';import '../tabs/web_tab_switcher.dart';@@ -39,7 +40,8 @@ WorkspaceChrome _webWorkspaceChrome(AppNotifier app) => WorkspaceChrome(compactFooter: (context, footer) => WebFooterBar(footer: footer),compactBelow: kWebCompactBelow,twoPaneColumnsBelow: 1000,- firstMachine: (context) => WebFirstMachine(app: app),+ firstMachine: (context) =>+ WebFirstMachine(app: app, saved: savedComputersOf(app)),menuOnEveryTab: true,labelsPaneStatus: true,compactPaneHeader: true,diff --git a/desktop/lib/web/shell/web_workspace.dart b/desktop/lib/web/shell/web_workspace.dartindex a810db54f..3fbf85f43 100644--- a/desktop/lib/web/shell/web_workspace.dart+++ b/desktop/lib/web/shell/web_workspace.dart@@ -2,6 +2,7 @@ import 'package:flutter/widgets.dart';import '../../screens/swarm_screen.dart';import '../../state/app_state.dart';+import '../onboarding/saved_computers.dart';import 'web_chrome.dart';/// The signed-in browser workspace: the shared swarm of panes, with the@@ -12,6 +13,10 @@ class WebWorkspace extends StatelessWidget {final AppNotifier app;@override- Widget build(BuildContext context) =>- SwarmScreen(notifier: app, chrome: webWorkspaceChrome(app));+ Widget build(BuildContext context) {+ // Made once per app, here rather than with the connect page: the list is+ // kept whenever it answers, also when a computer connects before the page shows.+ savedComputersOf(app);+ return SwarmScreen(notifier: app, chrome: webWorkspaceChrome(app));+ }}diff --git a/desktop/lib/web/web_entry.dart b/desktop/lib/web/web_entry.dartindex 7fedc6c3a..bee3ffd03 100644--- a/desktop/lib/web/web_entry.dart+++ b/desktop/lib/web/web_entry.dart@@ -5,18 +5,20 @@ import '../community/hub_return_web.dart';import '../widgets/key_hints.dart';import '../ws/terminal_transport_plugin.dart';import 'p2p/p2p_resume_retry.dart';+import 'onboarding/saved_computers.dart';import 'p2p/web_terminal_p2p.dart';+import 'parts/workspace_part.dart';import 'shell/web_focus_ring.dart';import 'shell/web_store_banner.dart';-import 'shell/web_workspace.dart';import 'web_console.dart';/// The signed-in screen of a browser build, chosen over/// `desktop_workspace.dart` by the conditional import in `main.dart`: the-/// shared workspace, composed for a mouse.+/// shared workspace, composed for a mouse, in a part of its own that a first+/// visit's sign-in page does not wait for ([workspacePart]).Widget authenticatedWorkspace(AppNotifier app) => P2pResumeRetry(plugins: webTerminalP2p,- child: HubReturn(child: WebWorkspace(app: app)),+ child: HubReturn(child: DeferredWorkspace(app: app)),);/// A released browser build's console carries errors, not traces (see [prepareWebConsole]).@@ -25,8 +27,14 @@ void prepareConsole() => prepareWebConsole();/// What a browser build draws around every screen: on a phone, the bar that/// sends it to the Harness app in its store. Above the Navigator, so every/// screen and route under it shows no key hints: the web is mouse-first.-Widget appFrame(Widget app) => WebFocusRing(- child: WebAppStoreFrame(child: KeyHints(visible: false, child: app)),+/// Its first frame starts the workspace's download, and from the start it+/// keeps (and forgets) the account's computers.+Widget appFrame(Widget app) => WorkspacePrefetch(+ child: KeptComputers(+ child: WebFocusRing(+ child: WebAppStoreFrame(child: KeyHints(visible: false, child: app)),+ ),+ ),);/// A browser reaches a machine through the relay, so each connection gets adiff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 4cd2889ba..17bc7c3db 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -1,4 +1,6 @@-import '../finder/widgets/finder_pane_panel.dart';+// A browser leaves the Finder out of main.dart.js until a Finder tile is drawn.+import '../finder/widgets/finder_pane_panel.dart'+ if (dart.library.js_interop) '../web/parts/finder_pane_panel.dart';import '../super_tabs/pane.dart';import '../super_tabs/saved_session.dart';import '../sharing/shared_harness_panel.dart';diff --git a/desktop/scripts/build-web-release.sh b/desktop/scripts/build-web-release.shindex 061baed9b..f223abe76 100644--- a/desktop/scripts/build-web-release.sh+++ b/desktop/scripts/build-web-release.sh@@ -14,6 +14,8 @@ if [[ -n "$(git status --porcelain -- .)" ]]; thenexit 1fisource_commit="$(git rev-parse HEAD)"+# The backend a release talks to: AppConfig.defaultApiUrl, which a release build does not override.+api_url='https://harness-api.autonomous.ai'"${FLUTTER_BIN:-flutter}" build web --release --no-wasm-dry-run \--no-web-resources-cdn --base-href=/harness-web/ \--output=build/web-release --build-name="$version"@@ -44,12 +46,14 @@ PY# Flutter asks for the font manifest, then its fonts, only once main.dart.js has run: a step in# series after the app's 3 MB on a phone (0.7 s on fast 4G, 3.3 s on slow 4G, #180's report).# Preloaded with the same fetch Flutter makes, they come beside main.dart.js and Flutter reuses them.-python3 - <<'PY'+# The website moves these hrefs into the release's own folder (website/scripts/harness-web-assets.mjs).+python3 - "$api_url" <<'PY'import htmlimport jsonfrom pathlib import Pathimport sys+api_url = sys.argv[1]root = Path('build/web-release')index_path = root / 'index.html'index = index_path.read_text()@@ -61,24 +65,28 @@ links = ''.join(f' <link rel="preload" href="assets/{html.escape(asset)}" as="fetch" crossorigin>\n'for asset in assets)+# The first API call (who is signed in, then the machines) would otherwise open its connection+# only after the app has run: DNS, TCP and TLS, three round trips, in series after it.+# Anonymous, as the app's requests are, so the browser can hand them this connection.+links += f' <link rel="preconnect" href="{html.escape(api_url)}" crossorigin>\n'index_path.write_text(index.replace('</head>', links + '</head>', 1))-print(f"Preloaded the font manifest and {len(assets) - 1} fonts.")+print(f"Preloaded the font manifest and {len(assets) - 1} fonts; preconnected to {api_url}.")PY-python3 - "$version" "$source_commit" <<'PY'+python3 - "$version" "$source_commit" "$api_url" <<'PY'import hashlibimport jsonfrom pathlib import Pathimport tarfileimport sys-version, commit = sys.argv[1:]+version, commit, api_url = sys.argv[1:]root = Path('build/web-release')release = {'version': version,'sourceCommit': commit,'baseHref': '/harness-web/',- 'apiUrl': 'https://harness-api.autonomous.ai',+ 'apiUrl': api_url,}(root / 'release.json').write_text(json.dumps(release, indent=2) + '\n')output = Path('build/web-dist')diff --git a/desktop/test/pane_grid_finder_test.dart b/desktop/test/pane_grid_finder_test.dartnew file mode 100644index 000000000..87e457af9--- /dev/null+++ b/desktop/test/pane_grid_finder_test.dart@@ -0,0 +1,48 @@+// A Finder tile on a computer. The grid imports the Finder through a switch+// that hands a browser a part it downloads later (web/parts/); a computer+// must keep drawing the Finder itself, in the first frame.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/finder/widgets/finder_pane_panel.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/web/parts/deferred_part.dart';+import 'package:harness/widgets/pane_grid.dart';++void main() {+ testWidgets(+ 'a computer draws a Finder tile at once, with nothing to download',+ (tester) async {+ final notifier = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ notifier.panes.add(+ TerminalPane(+ id: 1,+ machineId: 'm',+ kind: PaneKind.finder,+ finderRoot: '/work/repo',+ ),+ );+ await tester.binding.setSurfaceSize(const Size(1200, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));++ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(body: PaneGrid(notifier: notifier)),+ ),+ );++ expect(+ tester.widget<FinderPanePanel>(find.byType(FinderPanePanel)).root,+ '/work/repo',+ );+ expect(find.byType(DeferredPartView), findsNothing);+ expect(find.text('Loading…'), findsNothing);+ },+ );+}diff --git a/desktop/test/settings_saved_super_tabs_test.dart b/desktop/test/settings_saved_super_tabs_test.dartindex 038d47043..5e760935a 100644--- a/desktop/test/settings_saved_super_tabs_test.dart+++ b/desktop/test/settings_saved_super_tabs_test.dart@@ -12,6 +12,7 @@ import 'package:harness/core/config.dart';import 'package:harness/settings/sections/account_section.dart';import 'package:harness/settings/sections/saved_super_tabs_row.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/state/browser_copies.dart';import 'package:harness/state/pane_layout_store.dart';import 'package:harness/super_tabs/client.dart';import 'package:harness/super_tabs/reading.dart';@@ -53,8 +54,8 @@ void main() {expect(find.text('Super Tabs in this browser'), findsOneWidget);expect(find.text(- 'This browser keeps a copy of the Super Tabs you open, so they show '- 'at once. Signing out removes it.',+ 'This browser keeps a copy of the Super Tabs you open and the names '+ 'of your computers, so they show at once. Signing out removes it.',),findsOneWidget,);@@ -86,12 +87,49 @@ void main() {expect(find.text('Your Harness sign-in on this computer.'), findsOneWidget);});+ testWidgets('Clear now clears the browser\'s other copies too', (+ tester,+ ) async {+ final app = await mount(tester);+ var cleared = 0;+ app.browserCopies.add(() async => cleared++);++ await tester.tap(find.widgetWithText(OutlinedButton, 'Clear now'));+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));+ await tester.pump();++ expect(cleared, 1);+ expect(find.widgetWithText(OutlinedButton, 'Cleared'), findsOneWidget);+ });++ testWidgets('a copy that cannot be cleared says so, and keeps Clear now', (+ tester,+ ) async {+ final app = await mount(tester);+ app.browserCopies.add(() => Future.error(StateError('quota')));++ await tester.tap(find.widgetWithText(OutlinedButton, 'Clear now'));+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));+ await tester.pump();++ expect(find.widgetWithText(OutlinedButton, 'Clear now'), findsOneWidget);+ expect(+ find.text('This browser did not let Harness clear it. Try again.'),+ findsOneWidget,+ );+ });+group('Clear now says only what happened', () {/// The row on its own, over [client].Future<void> row(WidgetTester tester, SuperTabClient client) =>tester.pumpWidget(MaterialApp(- home: Scaffold(body: SavedSuperTabsRow(superTabs: client)),+ home: Scaffold(+ body: SavedSuperTabsRow(+ superTabs: client,+ copies: BrowserCopies(),+ ),+ ),),);diff --git a/desktop/test/web/attachment_viewer_web_test.dart b/desktop/test/web/attachment_viewer_web_test.dartindex 92c7d7013..c4db969ea 100644--- a/desktop/test/web/attachment_viewer_web_test.dart+++ b/desktop/test/web/attachment_viewer_web_test.dart@@ -13,6 +13,7 @@ import 'package:harness/core/open_in_browser.dart';import 'package:harness/super_tabs/attachment_chips.dart';import 'package:harness/super_tabs/attachment_viewer.dart';import 'package:harness/super_tabs/model.dart';+import 'package:harness/web/parts/attachment_text_viewer.dart';void main() {testWidgets('a text file opens in the browser, not fetched in the page', (diff --git a/desktop/test/web/web_focus_ring_web_test.dart b/desktop/test/web/web_focus_ring_web_test.dartindex b72399f92..379e3e9e8 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/workspace_part.dart';import 'package:harness/web/web_entry.dart';void main() {@@ -55,5 +56,9 @@ void main() {await tester.tapAt(const Offset(5, 500));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));+ expect(workspacePart.loaded, isTrue);});}diff --git a/desktop/test/web_attachment_text_part_test.dart b/desktop/test/web_attachment_text_part_test.dartnew file mode 100644index 000000000..a28a27474--- /dev/null+++ b/desktop/test/web_attachment_text_part_test.dart@@ -0,0 +1,44 @@+import 'dart:convert';+import 'dart:typed_data';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/attachment_text_viewer.dart' as viewer;+import 'package:harness/super_tabs/attachment_viewer.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/web/parts/attachment_text_viewer.dart' as web;++void main() {+ testWidgets(+ 'a browser downloads the text viewer, then opens the file in it',+ (tester) async {+ final fetcher = attachmentFetcher;+ attachmentFetcher = (url, {maxBytes}) async =>+ Uint8List.fromList(utf8.encode('# Spec'));+ addTearDown(() => attachmentFetcher = fetcher);+ final file = SuperTabAttachment.fromJson({+ 'id': 'a1',+ 'name': 'spec.md',+ 'mime': 'text/markdown',+ 'size': 5,+ 'url': 'https://cdn.harness.autonomous.ai/a1/spec.md',+ });+ final url = Uri.parse(file.url);+ await tester.pumpWidget(+ MaterialApp(+ home: web.AttachmentTextViewer(file: file, url: url),+ ),+ );+ expect(find.text('Loading…'), findsOneWidget);++ // A native test has no part to fetch; loadLibrary answers on a timer.+ await tester.pump(const Duration(milliseconds: 1));++ final opened = tester.widget<viewer.AttachmentTextViewer>(+ find.byType(viewer.AttachmentTextViewer),+ );+ expect(opened.file, same(file));+ expect(opened.url, url);+ },+ );+}diff --git a/desktop/test/web_deferred_part_test.dart b/desktop/test/web_deferred_part_test.dartnew file mode 100644index 000000000..23d180751--- /dev/null+++ b/desktop/test/web_deferred_part_test.dart@@ -0,0 +1,209 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/web/parts/deferred_part.dart';++/// A part whose download the test finishes by hand, like a slow phone link.+/// Asked again while a download is pending, it hands back that same download,+/// as dart2js's loadLibrary does; [next] starts a fresh one after a failure.+class _Download {+ var calls = 0;+ Completer<void> pending = Completer<void>();++ Future<void> call() {+ calls++;+ return pending.future;+ }++ void fail() =>+ pending.completeError(Exception('net::ERR_INTERNET_DISCONNECTED'));++ void next() => pending = Completer<void>();+}++Widget _host(DeferredPart part, {VoidCallback? reload}) => MaterialApp(+ home: Scaffold(+ body: DeferredPartView(+ part: part,+ reload: reload ?? () {},+ builder: (_) => const Text('Finder'),+ ),+ ),+);++void main() {+ testWidgets('waits with a loading line, then draws the part', (tester) async {+ final download = _Download();+ await tester.pumpWidget(_host(DeferredPart(download.call)));++ expect(find.text('Loading…'), findsOneWidget);+ expect(find.text('Finder'), findsNothing);++ download.pending.complete();+ await tester.pump();++ expect(find.text('Finder'), findsOneWidget);+ expect(find.text('Loading…'), findsNothing);+ });++ testWidgets('a failed download says so and Retry downloads it again', (+ tester,+ ) async {+ final download = _Download();+ await tester.pumpWidget(_host(DeferredPart(download.call)));+ download.fail();+ await tester.pump();++ expect(find.text('Could not load this part of Harness'), findsOneWidget);+ expect(find.text('Finder'), findsNothing);++ download.next();+ await tester.tap(find.text('Retry'));+ await tester.pump();+ expect(download.calls, 2);+ expect(find.text('Loading…'), findsOneWidget);++ download.pending.complete();+ await tester.pump();+ expect(find.text('Finder'), findsOneWidget);+ });++ testWidgets(+ 'a part already downloaded draws at once, with no loading frame',+ (tester) async {+ final download = _Download()..pending.complete();+ final part = DeferredPart(download.call);+ await part.load();++ await tester.pumpWidget(_host(part));++ expect(find.text('Finder'), findsOneWidget);+ expect(download.calls, 1);+ },+ );++ testWidgets('two places opening one part download it once', (tester) async {+ final download = _Download();+ final part = DeferredPart(download.call);+ await tester.pumpWidget(+ MaterialApp(+ home: Column(+ children: [+ DeferredPartView(part: part, builder: (_) => const Text('one')),+ DeferredPartView(part: part, builder: (_) => const Text('two')),+ ],+ ),+ ),+ );+ download.pending.complete();+ await tester.pump();++ expect(download.calls, 1);+ expect(find.text('one'), findsOneWidget);+ expect(find.text('two'), findsOneWidget);+ });++ testWidgets('it stands on its own above any page, as the workspace does', (+ tester,+ ) async {+ final download = _Download();+ await tester.pumpWidget(+ MaterialApp(+ home: DeferredPartView(+ part: DeferredPart(download.call),+ builder: (_) => const Text('Finder'),+ ),+ ),+ );+ download.fail();+ await tester.pump();++ expect(tester.takeException(), isNull);+ expect(find.text('Retry'), findsOneWidget);+ // Not the bare framework's missing-Material style: underlined in yellow.+ for (final line in [+ 'Could not load this part of Harness',+ 'Check the connection, then retry.',+ ]) {+ final drawn = tester.widget<RichText>(+ find.descendant(of: find.text(line), matching: find.byType(RichText)),+ );+ expect(drawn.text.style?.decoration, isNot(TextDecoration.underline));+ }+ });++ testWidgets('a download that stalls offers Reload after about 20 s', (+ tester,+ ) async {+ final download = _Download();+ var reloads = 0;+ await tester.pumpWidget(+ _host(DeferredPart(download.call), reload: () => reloads++),+ );++ await tester.pump(const Duration(seconds: 19));+ expect(find.text('Reload'), findsNothing);+ await tester.pump(const Duration(seconds: 2));+ expect(find.text('Still loading this part of Harness'), findsOneWidget);+ expect(find.text('Loading…'), findsNothing);+ // Asking dart2js again would only wait on the same download.+ expect(find.text('Retry'), findsNothing);++ await tester.tap(find.text('Reload'));+ expect(reloads, 1);+ expect(download.calls, 1);++ // A stalled download that lands after all still draws the part.+ download.pending.complete();+ await tester.pump();+ expect(find.text('Finder'), findsOneWidget);+ });++ testWidgets(+ 'a Retry that fails again says Harness may have been updated, and offers Reload',+ (tester) async {+ final download = _Download();+ var reloads = 0;+ await tester.pumpWidget(+ _host(DeferredPart(download.call), reload: () => reloads++),+ );+ download.fail();+ await tester.pump();+ expect(find.text('Reload'), findsNothing);++ download.next();+ await tester.tap(find.text('Retry'));+ await tester.pump();+ download.fail();+ await tester.pump();++ expect(+ find.text(+ 'Harness may have been updated since this page opened. '+ 'Reload the page to get the new version.',+ ),+ findsOneWidget,+ );+ await tester.tap(find.text('Reload'));+ expect(reloads, 1);+ expect(find.text('Retry'), findsOneWidget);+ },+ );++ testWidgets('Retry is a 44 px target on a phone', (tester) async {+ tester.view.physicalSize = const Size(390, 844);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ final download = _Download();+ await tester.pumpWidget(_host(DeferredPart(download.call)));+ download.fail();+ await tester.pump();++ final retry = tester.getSize(+ find.ancestor(of: find.text('Retry'), matching: find.byType(TextButton)),+ );+ expect(retry.width, greaterThanOrEqualTo(44));+ expect(retry.height, greaterThanOrEqualTo(44));+ });+}diff --git a/desktop/test/web_finder_part_test.dart b/desktop/test/web_finder_part_test.dartnew file mode 100644index 000000000..76f3528bb--- /dev/null+++ b/desktop/test/web_finder_part_test.dart@@ -0,0 +1,40 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/finder/widgets/finder_pane_panel.dart' as finder;+import 'package:harness/web/parts/finder_pane_panel.dart' as web;++void main() {+ testWidgets('a browser Finder tile downloads the Finder, then draws it', (+ tester,+ ) async {+ Future<bool> Function()? guard;+ double? width;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: web.FinderPanePanel(+ key: const ValueKey('finder-pane-p1'),+ root: '/nowhere',+ onGuardClose: (check) => guard = check,+ onFixedWidth: (value) => width = value,+ compactHeader: true,+ ),+ ),+ ),+ );+ expect(find.text('Loading…'), findsOneWidget);++ // A native test has no part to fetch; loadLibrary answers on a timer.+ await tester.pump(const Duration(milliseconds: 1));++ final panel = tester.widget<finder.FinderPanePanel>(+ find.byType(finder.FinderPanePanel),+ );+ expect(panel.root, '/nowhere');+ expect(panel.compactHeader, isTrue);+ panel.onGuardClose!(() async => true);+ panel.onFixedWidth!(44);+ expect(guard, isNotNull);+ expect(width, 44);+ });+}diff --git a/desktop/test/web_release_script_test.dart b/desktop/test/web_release_script_test.dartindex c57fbff47..f9f35522b 100644--- a/desktop/test/web_release_script_test.dart+++ b/desktop/test/web_release_script_test.dart@@ -159,6 +159,27 @@ void main() {}}, skip: skip);+ test('the page connects to the API while the app downloads', () 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>'));+ // Anonymous, as the app's requests are: a credentialed preconnect would+ // open a connection they never use.+ expect(+ head,+ contains(+ '<link rel="preconnect" href="https://harness-api.autonomous.ai" crossorigin>',+ ),+ );+ final release = jsonDecode(+ File(p.join(repo.path, 'build', 'web-release', 'release.json'))+ .readAsStringSync(),+ );+ 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]);diff --git a/desktop/test/web_saved_computers_test.dart b/desktop/test/web_saved_computers_test.dartnew file mode 100644index 000000000..5a652e1af--- /dev/null+++ b/desktop/test/web_saved_computers_test.dart@@ -0,0 +1,377 @@+import 'package:flutter/material.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/web/onboarding/saved_computers.dart';+import 'package:harness/web/onboarding/web_first_machine.dart';+import 'package:harness/web/shell/web_workspace.dart';++import 'swarm_state_test.dart' show MemoryStore, createApp;++/// Storage a full or private-mode browser hands out: every call throws.+class _RefusingStore implements LocalKeyValueStore {+ @override+ Future<String?> read(String key) => Future.error(StateError('quota'));+ @override+ Future<void> write(String key, String value) =>+ Future.error(StateError('quota'));+ @override+ Future<void> delete(String key) => Future.error(StateError('quota'));+}++/// An account whose machine list has not answered yet, unless a test says so.+class _Account extends AppNotifier {+ _Account()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );++ bool loaded = false;++ @override+ bool get machineInventoryLoaded => loaded;++ void list(String id, String name) {+ final machine = Machine(+ machineId: id,+ name: name,+ authMode: MachineAuthMode.remote,+ );+ machines.add(machine);+ machineStates[id] = MachineState(machine)..nodeOnline = false;+ }++ void answer() {+ loaded = true;+ notifyListeners();+ }+}++const _ann = CurrentUserProfile(id: 'ann', email: '[email protected]');+const _bob = CurrentUserProfile(id: 'bob', email: '[email protected]');+const _macs = [+ SavedComputer(id: 'm1', name: 'Studio'),+ SavedComputer(id: 'm2', name: 'MacBookPro2021.local'),+];++void main() {+ group('kept computers', () {+ late MemoryStore storage;+ late SavedComputers saved;+ setUp(() {+ storage = MemoryStore();+ saved = SavedComputers(storage);+ });++ test('an account reads back the computers it kept', () async {+ await saved.claim('ann');+ await saved.write('ann', _macs);++ expect(await saved.read('ann'), _macs);+ });++ test('another account on this browser forgets them first', () async {+ await saved.claim('ann');+ await saved.write('ann', _macs);++ await saved.claim('bob');++ expect(await saved.read('ann'), isNull);+ expect(storage.values.keys.where((k) => k.contains('ann')), isEmpty);+ });++ test('signing out forgets them', () async {+ await saved.claim('ann');+ await saved.write('ann', _macs);++ await saved.claim(null);++ expect(storage.values, isEmpty);+ });++ test('a late write for an account that left keeps nothing', () async {+ await saved.claim('ann');+ await saved.claim('bob');++ await saved.write('ann', _macs);++ expect(await saved.read('ann'), isNull);+ });++ test(+ 'anything unreadable is no list, and a refusing storage never throws',+ () async {+ await saved.claim('ann');+ storage.values['web.computers.ann'] = '{not json';+ expect(await saved.read('ann'), isNull);++ final refusing = SavedComputers(_RefusingStore());+ await refusing.claim('ann');+ await refusing.write('ann', _macs);+ expect(await refusing.read('ann'), isNull);+ },+ );+ });++ group('the watch', () {+ late _Account app;+ late MemoryStore storage;+ setUp(() {+ app = _Account();+ storage = MemoryStore();+ });+ tearDown(() => app.dispose());++ test(+ 'keeps the computers the answered list shows, for its account',+ () async {+ final watch = SavedComputersWatch(app, SavedComputers(storage));+ addTearDown(watch.dispose);+ app.currentUser = _ann;+ app.list('m1', 'Studio');+ app.answer();+ await pumpEventQueue();++ expect(await SavedComputers(storage).read('ann'), [+ const SavedComputer(id: 'm1', name: 'Studio'),+ ]);+ },+ );++ test(+ 'offers them while the list is read, and not once it answers',+ () async {+ final store = SavedComputers(storage);+ await store.claim('ann');+ await store.write('ann', _macs);+ final watch = SavedComputersWatch(app, store);+ addTearDown(watch.dispose);++ // The app says so once it knows who signed in (status, then notify).+ app+ ..currentUser = _ann+ ..notifyListeners();+ await pumpEventQueue();+ expect(watch.shown, _macs);++ app.answer();+ expect(watch.shown, isNull);+ },+ );++ test('never offers one account\'s computers to another', () async {+ final store = SavedComputers(storage);+ await store.claim('ann');+ await store.write('ann', _macs);+ final watch = SavedComputersWatch(app, store);+ addTearDown(watch.dispose);++ app+ ..currentUser = _bob+ ..notifyListeners();+ await pumpEventQueue();++ expect(watch.shown, isNull);+ expect(await store.read('ann'), isNull);+ });+ });++ testWidgets(+ 'the web workspace keeps the list from its first frame, connect page or not',+ (tester) async {+ final storage = MemoryStore();+ final app = createApp(store: storage, connected: true)+ ..currentUser = _ann;+ addTearDown(app.dispose);+ tester.view.physicalSize = const Size(1280, 800);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);++ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: WebWorkspace(app: app),+ ),+ );+ await tester.runAsync(pumpEventQueue);++ expect(savedComputersOf(app), same(savedComputersOf(app)));+ expect(storage.values['web.computers.saved_by'], 'ann');+ await tester.pumpWidget(const SizedBox.shrink());+ },+ );++ test('Clear now takes the kept computers, and an unchanged list is not kept again', () async {+ final storage = MemoryStore();+ final app = _Account()..currentUser = _ann;+ addTearDown(app.dispose);+ final store = SavedComputers(storage);+ final own = SavedComputersWatch(app, store);+ addTearDown(own.dispose);+ app+ ..list('m1', 'Studio')+ ..answer();+ await pumpEventQueue();+ expect(await store.read('ann'), isNotNull);++ await own.clear();+ app.notifyListeners();+ await pumpEventQueue();+ expect(await store.read('ann'), isNull);+ expect(storage.values['web.computers.saved_by'], 'ann');++ app+ ..list('m2', 'Build server')+ ..notifyListeners();+ await pumpEventQueue();+ expect((await store.read('ann'))?.map((c) => c.name), [+ 'Studio',+ 'Build server',+ ]);+ });++ test('the browser\'s Clear now reaches the kept computers', () async {+ final storage = MemoryStore();+ final app = createApp(store: storage)..currentUser = _ann;+ addTearDown(app.dispose);+ savedComputersOf(app);+ await pumpEventQueue();+ await SavedComputers(storage).write('ann', _macs);+ expect(storage.values['web.computers.ann'], isNotNull);++ await app.browserCopies.clear();++ expect(storage.values['web.computers.ann'], isNull);+ });++ test('a session that expires forgets the kept computers, as it does the Super Tab views', () async {+ final storage = MemoryStore();+ final app = createApp(store: storage)+ ..status = AppStatus.authenticated+ ..currentUser = _ann;+ addTearDown(app.dispose);+ savedComputersOf(app);+ app.notifyListeners();+ await pumpEventQueue();+ await SavedComputers(storage).write('ann', _macs);+ expect(storage.values['web.computers.ann'], isNotNull);++ app.expireSessionForTest('Your sign-in expired. Sign in again.');+ await pumpEventQueue();++ expect(storage.values['web.computers.ann'], isNull);+ expect(storage.values['web.computers.saved_by'], isNull);+ });++ test('a browser that boots into an expired session forgets the last account\'s computers', () async {+ final storage = MemoryStore();+ await SavedComputers(storage).claim('ann');+ await SavedComputers(storage).write('ann', _macs);+ final app = createApp(store: storage);+ addTearDown(app.dispose);+ savedComputersOf(app);+ await pumpEventQueue();+ // Booting: who signed in is not known yet, so nothing is forgotten.+ expect(storage.values['web.computers.ann'], isNotNull);++ app+ ..status = AppStatus.unauthenticated+ ..notifyListeners();+ await pumpEventQueue();++ expect(storage.values['web.computers.ann'], isNull);+ expect(storage.values['web.computers.saved_by'], isNull);+ });++ testWidgets('the web frame keeps the computers from the app\'s start, before any workspace', (+ tester,+ ) async {+ final storage = MemoryStore();+ final app = createApp(store: storage)..status = AppStatus.unauthenticated;+ addTearDown(app.dispose);+ await tester.runAsync(() async {+ await SavedComputers(storage).claim('ann');+ await SavedComputers(storage).write('ann', _macs);+ });++ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: const KeptComputers(child: SizedBox.shrink()),+ ),+ );+ await tester.runAsync(pumpEventQueue);++ expect(storage.values['web.computers.ann'], isNull);+ });++ group('the connect page', () {+ late _Account app;+ setUp(() => app = _Account()..currentUser = _ann);+ tearDown(() => app.dispose());++ Future<void> mount(WidgetTester tester, SavedComputersWatch saved) async {+ tester.view.physicalSize = const Size(390, 844);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SingleChildScrollView(+ child: WebFirstMachine(app: app, saved: saved),+ ),+ ),+ ),+ );+ }++ testWidgets('draws the kept computers at once while the list is read', (+ tester,+ ) async {+ final store = SavedComputers(MemoryStore());+ await tester.runAsync(() async {+ await store.claim('ann');+ await store.write('ann', _macs);+ });+ final watch = SavedComputersWatch(app, store);+ addTearDown(watch.dispose);+ await tester.runAsync(pumpEventQueue);+ await mount(tester, watch);++ expect(find.text('Finding your computers…'), findsNothing);+ expect(find.text('Connect your computer'), findsOneWidget);+ expect(find.text('Studio'), findsOneWidget);+ expect(find.text('MacBookPro2021.local'), findsOneWidget);+ expect(find.text('Checking…'), findsNWidgets(2));+ expect(find.widgetWithText(FilledButton, 'Connect'), findsNothing);++ app+ ..list('m1', 'Studio')+ ..answer();+ await tester.pump();+ expect(find.text('Checking…'), findsNothing);+ expect(+ find.text('Offline. Open Harness on it, or run harness start there.'),+ findsOneWidget,+ );+ expect(find.text('MacBookPro2021.local'), findsNothing);+ });++ testWidgets('with nothing kept, it says it is looking', (tester) async {+ final watch = SavedComputersWatch(app, SavedComputers(MemoryStore()));+ addTearDown(watch.dispose);+ await tester.runAsync(pumpEventQueue);+ await mount(tester, watch);++ expect(find.text('Finding your computers…'), findsOneWidget);+ });+ });+}diff --git a/desktop/test/web_workspace_part_test.dart b/desktop/test/web_workspace_part_test.dartnew file mode 100644index 000000000..5f131018a--- /dev/null+++ b/desktop/test/web_workspace_part_test.dart@@ -0,0 +1,68 @@+import 'package:flutter/material.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/workspace_part.dart';+import 'package:harness/web/shell/web_workspace.dart';++import 'swarm_state_test.dart' show createApp;++void main() {+ testWidgets('the signed-in workspace waits for its part, then draws', (+ tester,+ ) async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ tester.view.physicalSize = const Size(1280, 800);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);++ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: DeferredWorkspace(app: app),+ ),+ );+ expect(find.text('Loading…'), findsOneWidget);+ expect(find.byType(WebWorkspace), findsNothing);++ // A native test has no part to fetch; loadLibrary answers on a timer.+ await tester.pump(const Duration(milliseconds: 1));++ expect(find.byType(WebWorkspace), findsOneWidget);+ await tester.pumpWidget(const SizedBox.shrink());+ });++ testWidgets('the workspace starts downloading with the first frame, once', (+ tester,+ ) async {+ var asked = 0;+ final part = DeferredPart(() async => asked++);++ await tester.pumpWidget(+ WorkspacePrefetch(part: part, child: const SizedBox.shrink()),+ );+ expect(asked, 1);++ // The frame is rebuilt with the app; it asks once.+ await tester.pumpWidget(+ WorkspacePrefetch(part: part, child: const SizedBox()),+ );+ await tester.pump();+ expect(asked, 1);+ });++ testWidgets('a download that fails while nothing waits on it is no error', (+ tester,+ ) async {+ final part = DeferredPart(() => Future.error(Exception('offline')));++ await tester.pumpWidget(+ WorkspacePrefetch(part: part, child: const SizedBox.shrink()),+ );+ await tester.pump();++ expect(tester.takeException(), isNull);+ expect(part.loaded, isFalse);+ });+}diff --git a/desktop/tool/web_ux/deferred-parts.mjs b/desktop/tool/web_ux/deferred-parts.mjsnew file mode 100644index 000000000..2ac65dd93--- /dev/null+++ b/desktop/tool/web_ux/deferred-parts.mjs@@ -0,0 +1,102 @@+// The parts main.dart.js leaves out (lib/web/parts/), loaded as a browser+// loads them.+//+// node tool/web_ux/deferred-parts.mjs <fixture-build> <release-build> [out-dir]+//+// 1. <release-build> (build/web-release from scripts/build-web-release.sh),+// served as the website serves it (serve-release.mjs): every part the app+// names is in the release folder, cached as immutable and compressed.+// 2. <fixture-build> (tool/web_ux_fixture.dart, as capture.mjs builds it), on+// the finder-part scenario: the signed-in workspace and then its Finder+// tile download their parts and draw. With every part's download failing,+// the page says so and offers Retry, and Retry once the network is back+// draws both. Screens of each go to [out-dir].+// Prints what it saw and exits 1 if any check failed.+import { chromium } from './playwright.mjs';+import { readdirSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { settle } from './capture.mjs';+import { serve } from './serve.mjs';+import { serveRelease } from './serve-release.mjs';++const [fixtureDir, releaseDir, outDir] = process.argv.slice(2);+if (outDir) mkdirSync(outDir, { recursive: true });+const failures = [];+const check = (ok, what) => {+ console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`);+ if (!ok) failures.push(what);+};++// 1. The release folder serves every part.+const parts = readdirSync(releaseDir).filter((f) => /^main\.dart\.js_\d+\.part\.js$/.test(f));+check(parts.length > 0, `the release build has parts: ${parts.join(', ')}`);+const release = await serveRelease(releaseDir);+const page = await (await fetch(`${release.origin}/harness-web/`)).text();+const base = page.match(/"entrypointBaseUrl":"([^"]+)"/)?.[1];+for (const part of parts) {+ const response = await fetch(`${release.origin}${base}${part}`);+ check(+ response.ok && /immutable/.test(response.headers.get('cache-control') ?? ''),+ `${base}${part}: ${response.status}, ${response.headers.get('cache-control')}`,+ );+}+release.close();++// 2. A Finder tile, with the network and without.+const fixture = await serve(fixtureDir);+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH });+const url = `${fixture.origin}/?scenario=finder-part&theme=dark`;+// No service worker, as the website starts none (harness-web-assets.mjs): the+// fixture's would fetch the part itself, past the page's network.+const PAGE = { viewport: { width: 1440, height: 900 }, serviceWorkers: 'block' };+// dart2js asks again for a part that failed, three times, as ?dart2jsRetry=N.+const isPart = (url) => new URL(url).pathname.endsWith('.part.js');+const partRequests = (tab) => {+ const seen = [];+ tab.on('requestfinished', async (r) => {+ if (isPart(r.url())) seen.push((await r.response())?.status());+ });+ tab.on('requestfailed', (r) => { if (isPart(r.url())) seen.push('failed'); });+ return seen;+};+const shot = (tab, name) => outDir && tab.screenshot({ path: join(outDir, `${name}.png`) });++{+ const context = await browser.newContext(PAGE);+ const tab = await context.newPage();+ const seen = partRequests(tab);+ await tab.goto(url);+ await settle(tab);+ check(seen.length >= 2 && seen.every((s) => s === 200), `online: the workspace's and the Finder's parts downloaded (${seen.join(', ')})`);+ check(await tab.getByText('Loading…').count() === 0, 'online: no loading line left');+ check(await tab.getByText('Could not load this part of Harness').count() === 0, 'online: no failure');+ await shot(tab, 'finder-part-online');+ await context.close();+}+{+ const context = await browser.newContext(PAGE);+ const tab = await context.newPage();+ const seen = partRequests(tab);+ let offline = true;+ await tab.route(isPart, (route) => (offline ? route.abort('internetdisconnected') : route.continue()));+ await tab.goto(url);+ await settle(tab);+ await tab.getByText('Could not load this part of Harness').first()+ .waitFor({ timeout: 30000 }).catch(() => {});+ check(await tab.getByText('Could not load this part of Harness').count() === 1, 'offline: the page says it could not load');+ const retry = tab.getByRole('button', { name: 'Retry' });+ check(await retry.count() === 1, 'offline: it offers Retry');+ await shot(tab, 'finder-part-offline');+ offline = false;+ if (await retry.count() === 0) throw new Error('no Retry to press');+ await retry.first().click();+ await tab.waitForTimeout(3000);+ check(seen.filter((s) => s === 200).length >= 2, `back online: Retry downloaded the parts (${seen.join(', ')})`);+ check(await tab.getByText('Could not load this part of Harness').count() === 0, 'back online: the failure is gone');+ check(await tab.getByText('Loading…').count() === 0, 'back online: the workspace and its Finder tile are drawn');+ await shot(tab, 'finder-part-retried');+ await context.close();+}+await browser.close();+fixture.close();+process.exit(failures.length ? 1 : 0);diff --git a/desktop/tool/web_ux/flows/speed.mjs b/desktop/tool/web_ux/flows/speed.mjsnew file mode 100644index 000000000..2cebda424--- /dev/null+++ b/desktop/tool/web_ux/flows/speed.mjs@@ -0,0 +1,8 @@+// Flows for first load and connect speed.+//+// Fix group: speed (first load and connect). Each group keeps its flows here, so parallel groups never+// edit the same file; load-flows.mjs reads every file in this folder.+export const FLOWS = [+ { name: 'first-machine-saved', scenario: 'first-machine-saved' },+ { name: 'finder-part', scenario: 'finder-part', only: 'wide' },+];diff --git a/desktop/tool/web_ux/load-time.mjs b/desktop/tool/web_ux/load-time.mjsindex c55671425..731116f83 100644--- a/desktop/tool/web_ux/load-time.mjs+++ b/desktop/tool/web_ux/load-time.mjs@@ -1,80 +1,60 @@-// First load of a release build of the web app, as a new visitor sees it.+// First load of a release build of the web app, as a new visitor and a+// returning one see it.//-// node tool/web_ux/load-time.mjs <release-build-dir> [screenshot-dir]+// node tool/web_ux/load-time.mjs <release-build-dir> [out-dir] [runs]//-// <release-build-dir> is `flutter build web --release --no-wasm-dry-run-// --no-web-resources-cdn --base-href=/harness-web/` (scripts/build-web-release.sh-// without packaging). It is served at /harness-web/ with gzip, like a static-// host, with every request off the page blocked, so the app stops at the-// sign-in page. Each profile loads with an empty cache three times; the-// median is reported: time until the loading screen from web/index.html is-// visible (null when there is none), time until Flutter's view is in the page,-// time until the screen stops changing (the sign-in page drawn; a release build-// has no accessibility tree to wait on), and bytes transferred. Every run also-// lists the fonts it fetched, the requests that failed and the console errors-// from the page itself, and whether the loading screen was gone by the end.-// The last screen of each profile is saved beside the results so the end state-// can be checked.+// <release-build-dir> is build/web-release from scripts/build-web-release.sh,+// served as the website serves a release (serve-release.mjs). Every request+// off the page fails, so the app stops at the sign-in page.+//+// Each profile loads [runs] times (3) with an empty cache (cold), and [runs]+// times comes back to it in a browser profile kept on disk, as a person's is:+// once after a first visit (second), and once more (returning). Chrome keeps+// the compiled script only from the second visit on, and never in a private+// window, which Playwright's own contexts are. The median of each is+// reported: time until the loading screen from web/index.html is visible+// (null when there is none), until Flutter's first frame, until the screen+// stops changing (the sign-in page drawn), and the bytes transferred. Every run+// also lists the files it fetched, any fetched twice, the revalidations, the+// 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.import { chromium } from './playwright.mjs';-import { createServer } from 'node:http';-import { readFile } from 'node:fs/promises';-import { extname, join, normalize } from 'node:path';-import { gzipSync } from 'node:zlib';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { createHash } from 'node:crypto';-import { writeFileSync } from 'node:fs';--const TYPES = {- '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json',- '.wasm': 'application/wasm', '.png': 'image/png', '.ttf': 'font/ttf',- '.otf': 'font/otf', '.webp': 'image/webp', '.jpg': 'image/jpeg', '.bin': 'application/octet-stream',-};+import { serveRelease } from './serve-release.mjs';// How long a page without a loading screen is waited on before it is reported as having none.const SPLASH_LIMIT_MS = 5000;+// A phone as #180 and #1710 measured it: 390x844 at 3x, touch, an iPhone's+// user agent, 4x CPU, and Chrome DevTools' own network presets+// (front_end/core/sdk/NetworkManager.ts: latency and throughput scaled as there).+const PHONE = {+ viewport: { width: 390, height: 844 },+ deviceScaleFactor: 3,+ isMobile: true,+ hasTouch: true,+ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1',+};const PROFILES = [- { name: 'computer, cable', viewport: { width: 1440, height: 900 }, network: null, cpu: 1 },- // Lighthouse's mobile preset: 1.6 Mbps down, 750 kbps up, 150 ms RTT, 4x CPU.+ { name: 'computer, cable', context: { viewport: { width: 1440, height: 900 } }, network: null, cpu: 1 },{- name: 'phone, slow 4G',- viewport: { width: 390, height: 844 },- network: { latency: 150, downloadThroughput: 1.6e6 / 8, uploadThroughput: 750e3 / 8 },+ name: 'phone, fast 4G',+ context: PHONE,+ network: { latency: 60 * 2.75, downloadThroughput: (9e6 / 8) * 0.9, uploadThroughput: (1.5e6 / 8) * 0.9 },cpu: 4,},- // A good phone connection: 9 Mbps down, 40 ms RTT, 2x CPU.{- name: 'phone, fast 4G',- viewport: { width: 390, height: 844 },- network: { latency: 40, downloadThroughput: 9e6 / 8, uploadThroughput: 1.5e6 / 8 },- cpu: 2,+ name: 'phone, slow 4G',+ context: PHONE,+ network: { latency: 150 * 3.75, downloadThroughput: (1.6e6 / 8) * 0.9, uploadThroughput: (750e3 / 8) * 0.9 },+ cpu: 4,},];-function serve(root) {- const cache = new Map();- const server = createServer(async (req, res) => {- let path = normalize(decodeURIComponent(new URL(req.url, 'http://x').pathname));- if (!path.startsWith('/harness-web/')) { res.writeHead(404); return res.end(); }- path = path.slice('/harness-web/'.length) || 'index.html';- const file = join(root, path);- let body = cache.get(file);- if (!body) {- // Unknown paths get index.html, as /s/… links do on the host, but a missing- // asset is a 404 so a manifest naming a deleted file shows in the request log.- const fallback = extname(file) === '' || extname(file) === '.html';- const raw = await readFile(file).catch(() =>- fallback ? readFile(join(root, 'index.html')) : null);- if (!raw) { res.writeHead(404); return res.end(); }- body = gzipSync(raw, { level: 6 });- cache.set(file, body);- }- res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'text/html', 'content-encoding': 'gzip' });- res.end(body);- });- return new Promise((resolve) => server.listen(0, '127.0.0.1', () =>- resolve({ origin: `http://127.0.0.1:${server.address().port}`, close: () => server.close() })));-}-/// When the page last changed, once it has held still for [quietMs]. A page/// that keeps animating is cut off after [limitMs] and reported as such.async function settled(page, start, quietMs = 2000, limitMs = 120000) {@@ -90,34 +70,44 @@ async function settled(page, start, quietMs = 2000, limitMs = 120000) {}}-async function once(browser, origin, profile) {- const context = await browser.newContext({ viewport: profile.viewport, deviceScaleFactor: 1 });- await context.route('**/*', (route) =>- route.request().url().startsWith(origin) ? route.continue() : route.abort());+async function once(context, origin, profile) {const page = await context.newPage();const cdp = await context.newCDPSession(page);await cdp.send('Network.enable');- await cdp.send('Network.setCacheDisabled', { cacheDisabled: true });if (profile.network) {await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network });}await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu });- let bytes = 0;- const urls = new Map();+ const requests = new Map();const failed = [];const consoleErrors = [];- cdp.on('Network.loadingFinished', (e) => { bytes += e.encodedDataLength; });- cdp.on('Network.requestWillBeSent', (e) => urls.set(e.requestId, e.request.url));+ cdp.on('Network.requestWillBeSent', (e) => requests.set(e.requestId, { url: e.request.url, bytes: 0 }));cdp.on('Network.responseReceived', (e) => {+ const request = requests.get(e.requestId);+ if (request) {+ request.status = e.response.status;+ request.fromCache = e.response.fromDiskCache || e.response.fromServiceWorker || false;+ }if (e.response.status >= 400) failed.push(`${e.response.status} ${e.response.url}`);});+ cdp.on('Network.requestServedFromCache', (e) => {+ const request = requests.get(e.requestId);+ if (request) request.fromCache = true;+ });+ cdp.on('Network.loadingFinished', (e) => {+ const request = requests.get(e.requestId);+ if (request) request.bytes = e.encodedDataLength;+ });cdp.on('Network.loadingFailed', (e) => {- const url = urls.get(e.requestId);+ const url = requests.get(e.requestId)?.url;if (url?.startsWith(origin)) failed.push(`${e.errorText} ${url}`);});page.on('console', (msg) => {if (msg.type() === 'error' && msg.location().url.startsWith(origin)) consoleErrors.push(msg.text());});+ await page.addInitScript(() => {+ addEventListener('flutter-first-frame', () => { window.__firstFrame = performance.now(); }, { once: true });+ });const start = Date.now();const splash = page.waitForFunction(() => {@@ -125,16 +115,27 @@ async function once(browser, origin, profile) {return !!el && el.getBoundingClientRect().width > 0 && el.innerText.includes('Opening Harness…');}, null, { polling: 50, timeout: SPLASH_LIMIT_MS }).then(() => Date.now() - start, () => null);- await page.goto(`${origin}/harness-web/`);- await page.waitForSelector('flutter-view', { timeout: 180000 });- const firstFrame = Date.now() - start;+ // Not the load event: the page's preloads hold it back, and on slow 4G past any sane timeout.+ await page.goto(`${origin}/harness-web/`, { waitUntil: 'commit' });+ await page.waitForFunction(() => window.__firstFrame !== undefined, null, { polling: 50, timeout: 180000 });+ const firstFrame = Math.round(await page.evaluate(() => window.__firstFrame));const { at: signIn, shot } = await settled(page, start);const splashRemoved = await page.evaluate(() => !document.getElementById('harness-splash'));- const fonts = [...new Set([...urls.values()].filter((u) => /\.(ttf|otf)$/.test(u)).map((u) => u.split('/harness-web/')[1]))].sort();- await context.close();+ await page.close();+ const fetched = [...requests.values()].filter((r) => r.url.startsWith(origin));+ const name = (url) => url.slice(origin.length).replace(/^\/harness-web\/(releases\/[^/]+\/)?/, '');+ const counts = new Map();+ for (const r of fetched) if (!r.fromCache && r.status === 200) counts.set(name(r.url), (counts.get(name(r.url)) ?? 0) + 1);return {- splash: await splash, firstFrame, signIn, megabytes: +(bytes / 1e6).toFixed(2),- fonts, failed, consoleErrors, splashRemoved, shot,+ splash: await splash,+ firstFrame,+ signIn,+ megabytes: +(fetched.reduce((sum, r) => sum + r.bytes, 0) / 1e6).toFixed(2),+ files: Object.fromEntries(fetched.filter((r) => r.bytes > 0 && r.status === 200)+ .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)),+ failed, consoleErrors, splashRemoved, shot,};}@@ -142,24 +143,56 @@ const median = (xs) => xs.includes(null)? null: [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];-const [root, shotDir] = process.argv.slice(2);-const server = await serve(root);-const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH });-const results = [];-for (const profile of PROFILES) {- const runs = [];- for (let i = 0; i < 3; i++) runs.push(await once(browser, server.origin, profile));- if (shotDir) writeFileSync(`${shotDir}/load-${profile.name.replace(/\W+/g, '-')}.jpg`, runs.at(-1).shot);- for (const run of runs) delete run.shot;- results.push({- profile: profile.name,+function summary(runs) {+ return {splashMs: median(runs.map((r) => r.splash)),firstFrameMs: median(runs.map((r) => r.firstFrame)),settledMs: median(runs.map((r) => r.signIn)),transferredMB: median(runs.map((r) => r.megabytes)),- runs,+ };+}++const [root, outDir, runsArg] = process.argv.slice(2);+const count = Number(runsArg ?? 3);+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 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();+await once(prime, server.origin, { ...PROFILES[0], network: null, cpu: 1 });+await prime.close();+const results = [];+for (const profile of PROFILES) {+ const cold = [], second = [], returning = [];+ for (let i = 0; i < count; i++) {+ const context = await browser.newContext(profile.context);+ cold.push(await once(context, server.origin, profile));+ await context.close();+ }+ for (let i = 0; i < count; i++) {+ const dir = mkdtempSync(join(tmpdir(), 'load-time-'));+ const context = await chromium.launchPersistentContext(dir, {+ executablePath: process.env.CHROME_PATH, args, ...profile.context,+ });+ await once(context, server.origin, { ...profile, network: null, cpu: 1 });+ second.push(await once(context, server.origin, profile));+ returning.push(await once(context, server.origin, profile));+ await context.close();+ rmSync(dir, { recursive: true, force: true });+ }+ if (outDir) writeFileSync(join(outDir, `load-${profile.name.replace(/\W+/g, '-')}.jpg`), returning.at(-1).shot);+ for (const run of [...cold, ...second, ...returning]) delete run.shot;+ results.push({+ profile: profile.name,+ cold: summary(cold), second: summary(second), returning: summary(returning),+ runs: { cold, second, returning },});}-console.log(JSON.stringify(results, null, 2));+const text = JSON.stringify(results, null, 2);+if (outDir) writeFileSync(join(outDir, 'results.json'), text);+console.log(JSON.stringify(results.map(({ runs, ...medians }) => medians), null, 2));await browser.close();server.close();diff --git a/desktop/tool/web_ux/scenarios/speed.dart b/desktop/tool/web_ux/scenarios/speed.dartnew file mode 100644index 000000000..8a10b7915--- /dev/null+++ b/desktop/tool/web_ux/scenarios/speed.dart@@ -0,0 +1,56 @@+/// Scenarios for first load and connect speed.+///+/// Fix group: speed (first load and connect). Each group keeps its scenarios here, so parallel groups never+/// edit the same file; `tool/web_ux_scenarios.dart` merges every group's map.+library;++import 'dart:async';++import 'package:harness/core/harness_file_store.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/web/onboarding/saved_computers.dart';++import '../../../test/support/web_ux_app.dart';+import '../../web_ux_seed.dart';+import 'scenario.dart';++const _account = 'jamie';++/// Signed in as an account with an id, which kept computers are keyed by.+WebUxApp _signedInWithId() => signedIn()+ ..currentUser = const CurrentUserProfile(+ id: _account,+ name: 'Jamie Rivera',+ email: webUxEmail,+ );++final Map<String, WebUxScenario> speedScenarios = {+ // A returning browser before the machine list answers: the computers it+ // kept from the last answer, each checking.+ 'first-machine-saved': WebUxScenario(() {+ final kept = SavedComputers(HarnessFileStore.shared);+ unawaited(+ kept.claim(_account).then(+ (_) => kept.write(_account, const [+ SavedComputer(id: 'm1', name: 'Studio Mac'),+ SavedComputer(id: 'm2', name: 'Build server (ubuntu-24)'),+ ]),+ ),+ );+ return _signedInWithId()..inventoryLoaded = false;+ }),+ // A Finder tile beside its chat: the Finder is a part main.dart.js leaves out.+ 'finder-part': WebUxScenario(() {+ final app = withPanes(signedIn(), 1);+ app.activeSwarm.panes.add(+ TerminalPane(+ id: 900,+ machineId: 'm1',+ kind: PaneKind.finder,+ finderRoot: '/Users/jamie/shop',+ ),+ );+ return app;+ }),+};diff --git a/desktop/tool/web_ux/serve-release.mjs b/desktop/tool/web_ux/serve-release.mjsnew file mode 100644index 000000000..10618b588--- /dev/null+++ b/desktop/tool/web_ux/serve-release.mjs@@ -0,0 +1,98 @@+// A release build of the web app, served the way the website serves one+// (website/next.config.js headers(), website/scripts/fetch-harness-web.mjs):+// the page at /harness-web/ with no-store, rewritten by the website's own+// configureReleaseAssets to load the app from a folder named for this build,+// which is cached as immutable; the unversioned copy beside it revalidated+// every time; ETags. The release folder's app, engine, manifests and fonts are+// sent as the website pre-compresses them (brotli at its highest level,+// website/scripts/precompress.mjs), anything else at the level Cloudflare uses. Any other path without an extension gets the page, as /s/… links do.+//+// node tool/web_ux/serve-release.mjs <release-build-dir> [port]+import { createServer } from 'node:http';+import { readFile } from 'node:fs/promises';+import { extname, join, normalize } from 'node:path';+import { fileURLToPath } from 'node:url';+import { brotliCompressSync, constants } from 'node:zlib';+import { createHash } from 'node:crypto';+import { configureReleaseAssets, releaseAssetBase } from '../../../website/scripts/harness-web-assets.mjs';+import { PRECOMPRESSED } from '../../../website/scripts/precompress.mjs';++const TYPES = {+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',+ '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png',+ '.ttf': 'font/ttf', '.otf': 'font/otf', '.webp': 'image/webp', '.jpg': 'image/jpeg',+ '.ico': 'image/x-icon', '.bin': 'application/octet-stream', '.svg': 'image/svg+xml',+};++// The website's Cache-Control for each kind of path (next.config.js headers()).+const NO_STORE = 'no-store';+const IMMUTABLE = 'public, max-age=31536000, immutable';+const REVALIDATE = 'public, max-age=0, must-revalidate';++/// The release as the website publishes it: the page rewritten to load the+/// app from a folder named for this build, which is never reused.+async function release(root) {+ const main = await readFile(join(root, 'main.dart.js'));+ const meta = JSON.parse(await readFile(join(root, 'release.json'), 'utf8').catch(() => '{}'));+ const sha256 = createHash('sha256').update(main).digest('hex');+ const published = { version: meta.version ?? '0.0.0', sha256 };+ const page = configureReleaseAssets(await readFile(join(root, 'index.html'), 'utf8'), published);+ return { page, base: releaseAssetBase(published) };+}++export async function serveRelease(root, port = 0) {+ const { page, base } = await release(root);+ const files = new Map();+ async function file(path, versioned) {+ const key = `${versioned}:${path}`;+ if (!files.has(key)) {+ const raw = await readFile(join(root, path)).catch(() => null);+ const quality = versioned && PRECOMPRESSED.includes(extname(path).slice(1))+ ? constants.BROTLI_MAX_QUALITY+ : 3;+ files.set(key, raw && {+ body: brotliCompressSync(raw, {+ params: { [constants.BROTLI_PARAM_QUALITY]: quality, [constants.BROTLI_PARAM_SIZE_HINT]: raw.length },+ }),+ etag: `"${createHash('sha1').update(raw).digest('hex')}"`,+ });+ }+ return files.get(key);+ }+ const server = createServer(async (req, res) => {+ const pathname = normalize(decodeURIComponent(new URL(req.url, 'http://x').pathname));+ if (!pathname.startsWith('/harness-web/')) { res.writeHead(404); return res.end(); }+ let path = pathname.slice('/harness-web/'.length);+ let cacheControl = REVALIDATE;+ if (pathname.startsWith(base)) {+ path = pathname.slice(base.length);+ cacheControl = IMMUTABLE;+ }+ // The page, and any unknown path as /s/… links get it, is the versioned page.+ const entry = extname(path) === '' || path === 'index.html'+ ? null+ : await file(path, cacheControl === IMMUTABLE);+ if (!entry && extname(path) !== '' && path !== 'index.html') { res.writeHead(404); return res.end(); }+ const body = entry ? entry.body : brotliCompressSync(page);+ const headers = {+ 'content-type': TYPES[extname(path)] ?? 'text/html',+ 'content-encoding': 'br',+ 'cache-control': entry ? cacheControl : NO_STORE,+ };+ if (entry) headers.etag = entry.etag;+ if (entry && req.headers['if-none-match'] === entry.etag) {+ res.writeHead(304, { 'cache-control': headers['cache-control'], etag: entry.etag });+ return res.end();+ }+ res.writeHead(200, headers);+ res.end(body);+ });+ return new Promise((resolve) => server.listen(port, '127.0.0.1', () =>+ resolve({ origin: `http://127.0.0.1:${server.address().port}`, close: () => server.close() })));+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ const [root, port] = process.argv.slice(2);+ const { origin } = await serveRelease(root, Number(port ?? 0));+ console.log(`${origin}/harness-web/`);+}diff --git a/desktop/tool/web_ux_scenarios.dart b/desktop/tool/web_ux_scenarios.dartindex b294f8920..dc60fc445 100644--- a/desktop/tool/web_ux_scenarios.dart+++ b/desktop/tool/web_ux_scenarios.dart@@ -10,6 +10,7 @@ import 'web_ux/scenarios/first_load.dart';import 'web_ux/scenarios/menus.dart';import 'web_ux/scenarios/pane.dart';import 'web_ux/scenarios/scenario.dart';+import 'web_ux/scenarios/speed.dart';import 'web_ux/scenarios/states.dart';import 'web_ux/scenarios/store.dart';import 'web_ux/scenarios/welcome.dart';@@ -26,6 +27,7 @@ final Map<String, WebUxScenario> webUxScenarios = mergeScenarios([paneScenarios,welcomeScenarios,statesScenarios,+ speedScenarios,]);/// Every group's scenarios in one map; a name in two groups is an error.diff --git a/website/next.config.js b/website/next.config.jsindex 65eeb9ece..fbd29a938 100644--- a/website/next.config.js+++ b/website/next.config.js@@ -1,3 +1,31 @@+// The release's app, engine, manifests and fonts are compressed once at build time+// (scripts/precompress.mjs): each one's .br, else .gz, copy goes to a browser that takes it.+// The Content-Type Next sends for the file itself, so every encoding of it says the same.+const PRECOMPRESSED_TYPES = {+ js: 'application/javascript; charset=UTF-8',+ mjs: 'application/javascript; charset=UTF-8',+ wasm: 'application/wasm',+ json: 'application/json; charset=UTF-8',+ ttf: 'font/ttf',+ otf: 'font/otf',+ svg: 'image/svg+xml',+ html: 'text/html; charset=UTF-8',+}+const ENCODINGS = [+ { name: 'br', suffix: 'br' },+ { name: 'gzip', suffix: 'gz' },+]+// An Accept-Encoding that takes [name]: listed, and not at q=0 (scripts/precompress.mjs).+const accepts = (acceptsEncoding, name) => [{ type: 'header', key: 'accept-encoding', value: acceptsEncoding(name) }]+const releaseFile = (ext) => `/harness-web/releases/:path*/:file.${ext}`++async function precompression() {+ const { PRECOMPRESSED, acceptsEncoding } = await import('./scripts/precompress.mjs')+ const missing = PRECOMPRESSED.filter((ext) => !PRECOMPRESSED_TYPES[ext])+ if (missing.length) throw new Error(`No Content-Type for pre-compressed .${missing.join(', .')}`)+ return { precompressed: PRECOMPRESSED, acceptsEncoding }+}+module.exports = {// Self-contained build (.next/standalone: server.js + pruned node_modules) for a lean// production container — the runtime image copies this instead of installing deps.@@ -63,8 +91,15 @@ module.exports = {// install and download pages, and installer redirects. Flutter's base// href places its assets under /harness-web/ without changing the visible URL.async rewrites() {+ const { precompressed, acceptsEncoding } = await precompression()return {beforeFiles: [+ // The browser's first accepted encoding wins; one that takes neither gets the file as is.+ ...ENCODINGS.flatMap(({ name, suffix }) => precompressed.map((ext) => ({+ source: releaseFile(ext),+ has: accepts(acceptsEncoding, name),+ destination: `/harness-web/releases/:path*/:file.${ext}.${suffix}`,+ }))),// Older desktop builds consume snapshots without following redirects.{ source: '/explore/:id/snapshot', destination: '/hub/:id/snapshot' },{ source: '/explore/:id/download', destination: '/hub/:id/download' },@@ -82,6 +117,7 @@ module.exports = {}},async headers() {+ const { precompressed, acceptsEncoding } = await precompression()return [{source: '/:path*',@@ -139,6 +175,20 @@ module.exports = {{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },],},+ ...precompressed.map((ext) => ({+ source: releaseFile(ext),+ headers: [{ key: 'Vary', value: 'Accept-Encoding' }],+ })),+ // After the rewrite above the file sent is its .br or .gz copy: say what it holds and how.+ // In the rewrites' order reversed, so a browser taking both gets brotli's last, which wins.+ ...[...ENCODINGS].reverse().flatMap(({ name }) => precompressed.map((ext) => ({+ source: releaseFile(ext),+ has: accepts(acceptsEncoding, name),+ headers: [+ { key: 'Content-Encoding', value: name },+ { key: 'Content-Type', value: PRECOMPRESSED_TYPES[ext] },+ ],+ }))),...['/', '/s/:id', '/auth/callback', '/callback', '/harness-web', '/harness-web/index.html', '/harness-web/release.json'].map((source) => ({source,headers: [diff --git a/website/scripts/check-harness-web.mjs b/website/scripts/check-harness-web.mjsindex 057fdff63..969f11eaf 100644--- a/website/scripts/check-harness-web.mjs+++ b/website/scripts/check-harness-web.mjs@@ -1,5 +1,7 @@import assert from 'node:assert/strict';import { readFile } from 'node:fs/promises';+import { request } from 'node:http';+import { brotliDecompressSync, gunzipSync } from 'node:zlib';import { releaseAssetBase } from './harness-web-assets.mjs';const base = new URL(process.argv[2] || 'http://127.0.0.1:3000');@@ -47,6 +49,34 @@ for (const [route, type] of [});assert.equal(stale.status, 200, `Changed asset must load the new release: ${route}`);}+// The bytes as sent, which fetch would decode on its own.+const raw = (url, acceptEncoding) => new Promise((resolve, reject) => {+ request(url, { headers: { 'accept-encoding': acceptEncoding } }, (response) => {+ const chunks = [];+ response.on('data', (chunk) => chunks.push(chunk));+ response.on('end', () => resolve({ headers: response.headers, body: Buffer.concat(chunks) }));+ }).on('error', reject).end();+});+// Pre-compressed at build time (scripts/precompress.mjs): brotli to a browser that takes it, gzip+// to one that takes only gzip, the file as is to one that takes neither; one cache entry per encoding.+for (const route of [`${assetBase}main.dart.js`, `${assetBase}canvaskit/chromium/canvaskit.wasm`]) {+ const plain = await raw(new URL(route, base), 'identity');+ assert.equal(plain.headers['content-encoding'], undefined, route);+ for (const [acceptEncoding, encoding, decode] of [+ ['gzip, deflate, br, zstd', 'br', brotliDecompressSync],+ ['gzip, deflate', 'gzip', gunzipSync],+ // q=0 refuses an encoding: this browser takes gzip, not brotli.+ ['br;q=0, gzip', 'gzip', gunzipSync],+ ]) {+ const sent = await raw(new URL(route, base), acceptEncoding);+ assert.equal(sent.headers['content-encoding'], encoding, `${route} for ${acceptEncoding}`);+ assert.equal(sent.headers['content-type'], plain.headers['content-type'], route);+ assert.match(sent.headers.vary ?? '', /accept-encoding/i, route);+ assert.match(sent.headers['cache-control'], /immutable/, route);+ assert.ok(sent.body.length < plain.body.length, `${route} must be smaller as ${encoding}`);+ assert.ok(decode(sent.body).equals(plain.body), `${route} as ${encoding} must decode to the file`);+ }+}const published = await (await fetch(new URL('/harness-web/release.json', base))).json();assert.equal(published.version, release.version);assert.equal(published.sourceCommit, release.sourceCommit);diff --git a/website/scripts/fetch-harness-web.mjs b/website/scripts/fetch-harness-web.mjsindex 27c0b17d9..14e610cbf 100644--- a/website/scripts/fetch-harness-web.mjs+++ b/website/scripts/fetch-harness-web.mjs@@ -6,6 +6,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { configureReleaseAssets, releaseAssetBase } from './harness-web-assets.mjs';import { moveDirectory } from './move-directory.mjs';+import { precompressFolder } from './precompress.mjs';// This package hosts the compiled app; its only source is desktop/ in the same repository.// Release builds pass the bundle CI just built via HARNESS_WEB_ARCHIVE (see Dockerfile.k8s and@@ -52,6 +53,8 @@ try {const entry = configureReleaseAssets(index, release);const versioned = path.join(temporary, 'versioned');await cp(extracted, versioned, { recursive: true });+ // Only the release folder new pages load from; the unversioned copy serves tabs already open.+ await precompressFolder(versioned);const versionedDestination = path.join(extracted, releaseAssetBase(release).slice('/harness-web/'.length));await mkdir(path.dirname(versionedDestination), { recursive: true });await moveDirectory(versioned, versionedDestination);diff --git a/website/scripts/harness-web-assets.mjs b/website/scripts/harness-web-assets.mjsindex b07de3ace..71f8b9d56 100644--- a/website/scripts/harness-web-assets.mjs+++ b/website/scripts/harness-web-assets.mjs@@ -17,5 +17,9 @@ export function configureReleaseAssets(html, release) {};// The host serves online workspaces. Do not start the deprecated generated// service worker, which can independently retain an older application.- return html.replace(startup, `_flutter.loader.load(${JSON.stringify({ config })});\n`);+ return html+ .replace(startup, `_flutter.loader.load(${JSON.stringify({ config })});\n`)+ // The release script preloads the fonts Flutter asks for (build-web-release.sh); it asks+ // for them under assetBase, so a preload of the unversioned copy would only fetch them twice.+ .replace(/(<link rel="preload" href=")(?![/a-z]+:|\/)/g, `$1${assetBase}`);}diff --git a/website/scripts/harness-web-assets.test.mjs b/website/scripts/harness-web-assets.test.mjsindex 04c1c5f29..ab5e24755 100644--- a/website/scripts/harness-web-assets.test.mjs+++ b/website/scripts/harness-web-assets.test.mjs@@ -30,6 +30,18 @@ describe('release asset caching', () => {expect(options.serviceWorkerSettings).toBeUndefined();});+ it('preloads the fonts from the archive namespace Flutter fetches them from', () => {+ const preloads = '<link rel="preload" href="assets/FontManifest.json" as="fetch" crossorigin>\n'+ + '<link rel="preload" href="assets/fonts/MaterialIcons-Regular.otf" as="fetch" crossorigin>\n';+ const output = configureReleaseAssets(html.replace('<html>', `<html><head>${preloads}</head>`), release);+ const root = 'https://harness.example/harness-web/';+ const hrefs = [...output.matchAll(/<link rel="preload" href="([^"]+)"/g)].map((m) => new URL(m[1], root).href);+ expect(hrefs).toEqual([+ `${root}releases/0.1.4-aaaaaaaaaaaa/assets/FontManifest.json`,+ `${root}releases/0.1.4-aaaaaaaaaaaa/assets/fonts/MaterialIcons-Regular.otf`,+ ]);+ });+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) }]) {diff --git a/website/scripts/precompress.mjs b/website/scripts/precompress.mjsnew file mode 100644index 000000000..92885437e--- /dev/null+++ b/website/scripts/precompress.mjs@@ -0,0 +1,54 @@+import { readdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';+import { brotliCompress, constants, gzip } from 'node:zlib';++const brotli = promisify(brotliCompress);+const gzipped = promisify(gzip);++// What a release loads that compresses: the app, the engine and its WebAssembly, manifests and+// fonts. Images are compressed already and *.symbols are never fetched. next.config.js serves+// these extensions' .br or .gz copy to a browser that accepts it.+export const PRECOMPRESSED = ['js', 'mjs', 'wasm', 'json', 'ttf', 'otf', 'svg', 'html'];++/// A pattern for an Accept-Encoding header that takes [encoding]: listed as a+/// token, with no q-value or a q-value above 0 (`br;q=0` refuses brotli).+/// Whole-header, as Next.js tests a has-condition (`^value$`).+export function acceptsEncoding(encoding) {+ const nonZero = String.raw`(?:1(?:\.0{0,3})?|0?\.\d*[1-9]\d*)`;+ return String.raw`(?:.*[\s,])?${encoding}(?:\s*;\s*q\s*=\s*${nonZero})?\s*(?:,.*)?`;+}++const compressible = (file) => PRECOMPRESSED.includes(path.extname(file).slice(1));++async function* files(folder) {+ for (const entry of await readdir(folder, { withFileTypes: true })) {+ const at = path.join(folder, entry.name);+ if (entry.isDirectory()) yield* files(at);+ else if (entry.isFile() && compressible(at)) yield at;+ }+}++/// Writes `<file>.br` (brotli at its highest level) and `<file>.gz` (gzip at+/// its highest) beside each file of [folder] a browser fetches, once, at+/// build time: Cloudflare compresses on the fly at brotli 3, which leaves+/// main.dart.js and canvaskit.wasm about 1.4 MB larger than this.+export async function precompressFolder(folder) {+ const work = [];+ for await (const file of files(folder)) {+ work.push((async () => {+ const raw = await readFile(file);+ const [br, gz] = await Promise.all([+ brotli(raw, {+ params: {+ [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,+ [constants.BROTLI_PARAM_SIZE_HINT]: raw.length,+ },+ }),+ gzipped(raw, { level: constants.Z_BEST_COMPRESSION }),+ ]);+ await Promise.all([writeFile(`${file}.br`, br), writeFile(`${file}.gz`, gz)]);+ })());+ }+ await Promise.all(work);+}diff --git a/website/scripts/precompress.test.mjs b/website/scripts/precompress.test.mjsnew file mode 100644index 000000000..66a84c01f--- /dev/null+++ b/website/scripts/precompress.test.mjs@@ -0,0 +1,60 @@+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { brotliDecompressSync, gunzipSync } from 'node:zlib';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { acceptsEncoding, precompressFolder } from './precompress.mjs';++let folder;+beforeEach(async () => {+ folder = await mkdtemp(path.join(tmpdir(), 'precompress-'));+ await mkdir(path.join(folder, 'canvaskit', 'chromium'), { recursive: true });+});+afterEach(() => rm(folder, { recursive: true, force: true }));++const script = 'void main() { print("Harness"); }\n'.repeat(400);++describe('pre-compressed release files', () => {+ it('writes a brotli and a gzip copy beside each file a browser fetches, each decoding to it', async () => {+ const wasm = Buffer.alloc(4096, 7);+ await writeFile(path.join(folder, 'main.dart.js'), script);+ await writeFile(path.join(folder, 'canvaskit', 'chromium', 'canvaskit.wasm'), wasm);++ await precompressFolder(folder);++ for (const [file, original] of [['main.dart.js', Buffer.from(script)], ['canvaskit/chromium/canvaskit.wasm', wasm]]) {+ const at = path.join(folder, file);+ expect(brotliDecompressSync(await readFile(`${at}.br`))).toEqual(original);+ expect(gunzipSync(await readFile(`${at}.gz`))).toEqual(original);+ }+ });++ it('leaves already-compressed images and debug symbols alone', async () => {+ await writeFile(path.join(folder, 'app_icon.png'), Buffer.alloc(4096, 1));+ await writeFile(path.join(folder, 'canvaskit', 'canvaskit.js.symbols'), script);++ await precompressFolder(folder);++ expect((await readdir(folder)).sort()).toEqual(['app_icon.png', 'canvaskit']);+ expect(await readdir(path.join(folder, 'canvaskit'))).toEqual(['canvaskit.js.symbols', 'chromium']);+ });+});++describe('which copy a browser takes', () => {+ // As Next.js tests a has-condition's value: the whole header, anchored.+ const takes = (encoding, header) => new RegExp(`^${acceptsEncoding(encoding)}$`).test(header);++ it('takes an encoding the browser lists, wherever it stands', () => {+ for (const header of ['br', 'gzip, deflate, br, zstd', 'br, gzip', 'gzip,br', 'br;q=1.0, gzip;q=0.8', 'gzip;q=0.5, br;q=0.9']) {+ expect(takes('br', header), header).toBe(true);+ }+ expect(takes('gzip', 'gzip, deflate')).toBe(true);+ });++ it('does not take one it lists at q=0, or does not list', () => {+ for (const header of ['br;q=0, gzip', 'gzip, br; q=0', 'br;q=0.0', 'brotli', 'gzip, deflate', '']) {+ expect(takes('br', header), header).toBe(false);+ }+ expect(takes('gzip', 'br, gzip;q=0')).toBe(false);+ });+});