Merge branch 'worktree-agent-a69b1e8a6164ea62e'

This commit is contained in:
2026-12-01 21:05:51 +00:00
17 changed files with 737 additions and 17 deletions
+4 -1
View File
@@ -14,7 +14,10 @@ cd /tmp/work
flutter pub get
case "$kind" in
web)
flutter build web --release --no-web-resources-cdn "$@"
# WebAssembly (skwasm) with the JavaScript (CanvasKit) build beside it:
# the loader picks wasm where the browser has WasmGC, else JavaScript.
# No source maps: they are not served.
flutter build web --release --wasm --no-web-resources-cdn --no-source-maps "$@"
cp -R build/web/. /out/
;;
apk)
@@ -4,7 +4,10 @@ import 'package:flutter_tts/flutter_tts.dart';
import 'speech_engine.dart';
/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, web).
/// The platform engine off the web (the web uses `web_speech_engine.dart`).
SpeechEngine createSpeechEngine() => FlutterTtsSpeechEngine();
/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, Windows).
/// The plugin is created on first use so merely building the UI opens no
/// platform channel.
class FlutterTtsSpeechEngine extends SpeechEngine {
@@ -2,7 +2,8 @@ import 'dart:async';
import 'package:flutter/widgets.dart';
import 'flutter_tts_speech_engine.dart';
import 'flutter_tts_speech_engine.dart'
if (dart.library.js_interop) 'web_speech_engine.dart';
import 'speech_document.dart';
import 'speech_engine.dart';
import 'speech_preferences.dart';
@@ -13,7 +14,7 @@ enum SpeechState { idle, speaking, paused }
/// changes; the spoken word moves on the separate, frequent [word].
class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store})
: engine = engine ?? FlutterTtsSpeechEngine(),
: engine = engine ?? createSpeechEngine(),
_store = store ?? const SharedSpeechPreferencesStore() {
WidgetsBinding.instance.addObserver(this);
this.engine
@@ -0,0 +1,155 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:web/web.dart' as web;
import 'speech_engine.dart';
/// The platform engine on the web: the browser's Web Speech API directly.
SpeechEngine createSpeechEngine() => WebSpeechEngine();
/// [SpeechEngine] over `window.speechSynthesis` through `package:web`.
///
/// It replaces the flutter_tts web plugin, whose JS interop casts
/// (`event['charIndex'] as int`) and method-channel error payloads fail
/// under WebAssembly: word progress and error reports never arrived there.
/// The behaviour matches that plugin: speaking while paused resumes, and a
/// remote voice is kept alive with a pause/resume every 14 seconds (Chrome
/// stops a network voice after about 15 seconds of speech).
class WebSpeechEngine extends SpeechEngine {
web.SpeechSynthesisUtterance? _utterance;
web.SpeechSynthesisVoice? _voice;
double _rate = 1;
bool _paused = false;
Timer? _keepAlive;
@override
bool get supported => web.window.has('speechSynthesis');
web.SpeechSynthesis get _synth => web.window.speechSynthesis;
@override
Future<void> speak(String text) async {
if (text.isEmpty) return;
if (_paused && _utterance != null) {
_paused = false;
_synth.resume();
return;
}
final utterance = web.SpeechSynthesisUtterance(text)..rate = _rate;
final voice = _voice;
if (voice != null) {
utterance
..voice = voice
..lang = voice.lang;
}
_listen(utterance);
_utterance = utterance;
_paused = false;
_synth.speak(utterance);
}
void _listen(web.SpeechSynthesisUtterance utterance) {
bool current() => identical(_utterance, utterance);
utterance
..onstart = ((web.Event _) {
if (!current()) return;
onStart?.call();
if (!(utterance.voice?.localService ?? false)) _keepAliveWhileSpeaking();
}).toJS
..onend = ((web.Event _) {
if (!current()) return;
_finish();
onCompletion?.call();
}).toJS
..onpause = ((web.Event _) {
if (current() && _paused) onPause?.call();
}).toJS
..onresume = ((web.Event _) {
if (current() && !_paused) onResume?.call();
}).toJS
..onerror = ((web.SpeechSynthesisErrorEvent event) {
if (!current()) return;
_finish();
onError?.call(event.error);
}).toJS
..onboundary = ((web.SpeechSynthesisEvent event) {
if (!current() || event.name == 'sentence') return;
final text = utterance.text;
final start = event.charIndex.clamp(0, text.length);
onProgress?.call(text, start, _wordEnd(text, start, event.charLength));
}).toJS;
}
/// The end of the word at [start]: the browser's length when it reports
/// one, else the next space or punctuation (as flutter_tts did).
static int _wordEnd(String text, int start, int length) {
if (length > 0) return (start + length).clamp(start, text.length);
var end = start;
while (end < text.length && !RegExp(r'[\s,.!?]').hasMatch(text[end])) {
end++;
}
return end;
}
void _keepAliveWhileSpeaking() {
_keepAlive?.cancel();
_keepAlive = Timer.periodic(const Duration(seconds: 14), (_) {
if (_paused || _utterance == null) return;
_synth
..pause()
..resume();
});
}
void _finish() {
_keepAlive?.cancel();
_keepAlive = null;
_paused = false;
}
@override
Future<void> pause() async {
if (_utterance == null || _paused) return;
_paused = true;
_synth.pause();
}
@override
Future<void> stop() async {
_paused = false;
_keepAlive?.cancel();
_keepAlive = null;
_synth.cancel();
}
@override
Future<void> setRate(double rate) async => _rate = rate;
@override
Future<void> setVoice(SpeechVoice? voice) async {
_voice = voice == null
? null
: _browserVoices().where(
(item) => item.name == voice.name && item.lang == voice.locale,
).firstOrNull;
}
@override
Future<List<SpeechVoice>> voices() async {
var voices = _browserVoices();
// Browsers load their voice list asynchronously after the first request.
for (var attempt = 0; voices.isEmpty && attempt < 4; attempt++) {
await Future<void>.delayed(const Duration(milliseconds: 250));
voices = _browserVoices();
}
return [
for (final voice in voices)
SpeechVoice.fromPlatform({'name': voice.name, 'locale': voice.lang}),
];
}
List<web.SpeechSynthesisVoice> _browserVoices() =>
supported ? _synth.getVoices().toDart : const [];
}
+90
View File
@@ -0,0 +1,90 @@
# Web build: WebAssembly, isolation, caching and compression
## Decision
The installed web app is built with `flutter build web --wasm`
(`app/docker/build.sh`): dart2wasm + skwasm in Chromium-based browsers with
WasmGC and WebGL (Flutter's loader allows wasm only on Blink by default), and
the dart2js + CanvasKit build beside it, which the loader picks otherwise
(Firefox, Safari, no WebGL). The proxy serves the app
cross-origin isolated (COOP `same-origin`, COEP `credentialless`), so skwasm
renders on a worker thread.
`credentialless`, not `require-corp`: a sandboxed HTML artifact (srcdoc
iframe, which inherits the page's COEP) and chat markdown can show images
from other sites that send no Cross-Origin-Resource-Policy. Checked in the
browser: an HTML artifact with a cross-origin, no-CORP `<img>` still renders
under isolation. The WebSocket, same-origin `/artifacts/` fetches, video and
the Roboto fallback font from fonts.gstatic.com (CORS) are unaffected
(WebSocket against a live server not exercised here).
## Compatibility
- Our own web code already used `dart:js_interop`/`package:web`; the wasm
dry run reported only `flutter_tts`'s web plugin (`event['charIndex'] as
int`, a `JSAny` error payload sent over a method channel). Both break word
highlighting and error reports under wasm, so the web now uses
`lib/features/chat/speech/web_speech_engine.dart` (Web Speech API through
`package:web`, same behaviour as the plugin). The plugin still registers
on the web, so the dry-run warning remains. Read aloud with real voices
under wasm is unverified: headless Chrome has no voices.
- `app/web/flutter_bootstrap.js` registers no service worker (Flutter's is
deprecated; it only unregistered itself and reloaded the page, a second
startup after every install).
## Serving (web/src/appFiles.js)
- An installed build has `release.json`; the shell page gets
`<meta name="pipelines-asset-base" content="/_v/<buildId>/">` and the
bootstrap loads the entrypoint, renderer and assets from there. Those
responses are `private, max-age=31536000, immutable`. Another build's id
(a tab left open over an install) gets the current file, `no-cache`.
- The shell is `no-store`; every other file is `no-cache` with an ETag (304).
- `scripts/precompress_web.mjs` (run by `scripts/app_build.py`, cached with
the build) writes `.br`/`.gz`; the proxy sends them by `Accept-Encoding`.
main.dart.wasm 4.8 MB -> 1.4 MB br, skwasm.wasm 3.6 -> 1.2, main.dart.js
5.3 -> 1.2, canvaskit.wasm 7.2 -> 2.2. A first load on wasm transfers about
2.7 MB instead of 12.5 MB uncompressed JS + CanvasKit.
- A reload transfers only the shell and a 304 for flutter_bootstrap.js.
- `./install --web` installs the build; the proxy (`lib/web`) changes take
effect after a full install restarts it. The new build also works behind the
old proxy (no isolation: skwasm single-threaded; no immutable caching).
## Measurements (2026-12-01, Linux, RTX 2080 Ti, Chromium 155, load avg 10-20)
`tool/perf/interaction_bench.mjs --gpu --repeat 3 --memory` over the probe
fixture (release builds), medians. A = JS/CanvasKit as installed before (with
the service-worker registration), B = JS with the new bootstrap and isolation,
C = wasm without isolation, D = wasm isolated (what is installed now).
| scenario | metric | A js | B js+iso | C wasm | D wasm+iso |
| --- | --- | --- | --- | --- | --- |
| startup | first frame ms | 784 | 479 | 262 | 318 |
| startup | build sum ms | 184 | 109 | 49 | 73 |
| chat list -> open chat | build sum / longest ms | 48.9 / 21.4 | 22.1 / 9.6 | 6.3 / 3.5 | 8.6 / 22.1 |
| scroll a rich chat | build sum / max ms | 426 / 33.7 | 312 / 20.4 | 113 / 9.4 | 110 / 10.1 |
| scroll a rich chat | frames over 16 ms | 7 | 6 | 0 | 0 |
| switch chat | build sum / longest ms | 171 / 53.6 | 133 / 38.2 | 56 / 12.1 | 59 / 25.8 |
| open terminal panel | build sum / longest ms | 263 / 65.9 | 298 / 79.5 | 143 / 28.7 | 146 / 35.5 |
| tab runs -> chat (150) | build max / longest ms | 130 / 139 | 78 / 82 | 33 / 35 | 36 / 56 |
| memory | Chrome RSS after scroll, MB | 1477 | 1398 | 1332 | 1306 |
Build (UI thread) time drops 2-4x with wasm. With isolation, skwasm's raster
runs on a worker, so its reported raster time (and frame span) includes the
hand-off; the main thread is what stays free. The terminal stream bench
(headless, no `--gpu`, 30 MB per workload) shows that directly in the page's
own rAF intervals (ms):
| workload | js rAF p99 / max | wasm rAF p99 / max | wasm+iso rAF p99 / max | build p50 js / wasm |
| --- | --- | --- | --- | --- |
| seq | 33.3 / 66.6 | 33.3 / 33.3 | 16.7 / 16.7 | 2.3 / 1.0 |
| yes | 16.8 / 49.9 | 16.8 / 33.3 | 16.7 / 16.7 | 1.5 / 0.6 |
| unicode | 116.7 / 166.7 | 49.9 / 100.1 | 33.3 / 66.7 | 3.0 / 1.2 |
| colors | 33.4 / 50 | 16.8 / 33.2 | 16.7 / 16.7 | 2.6 / 1.2 |
| screen | 33.3 / 66.7 | 16.8 / 33.3 | 16.7 / 16.7 | 3.6 / 2.1 |
Headed Chromium on Xvfb has no WebGL, so the wasm build fell back to
CanvasKit there (confirming the fallback); its numbers equal the JS build's.
Headless without `--gpu` still had WebGL (SwiftShader), so skwasm ran.
The machine was shared with other agents' builds and tests; compare columns,
not absolute values.
+4
View File
@@ -13,6 +13,10 @@ no longer matches the app.
removes Chrome, the profile and the server.
- It needs no npm packages: Node 22+ (global `WebSocket` and `fetch`) and
Google Chrome (`CHROME_PATH` overrides the macOS default).
- `CAPTURE_ISOLATE=1` serves the build with the web proxy's cross-origin
isolation headers, so a `--wasm` build renders multi-threaded as installed.
`CAPTURE_HEADED=1` opens a real X11 window instead of headless (run under
`xvfb-run -a`; Xvfb has no WebGL, so the wasm build falls back to CanvasKit).
## The fixture app
+2 -1
View File
@@ -14,7 +14,8 @@ const DEFAULT_CHROME ='/Applications/Google Chrome.app/Contents/MacOS/Google Chr
async function launch(chromePath, gpu, args = []) {
const profile = await mkdtemp(join(tmpdir(), 'pipelines-capture-chrome-'));
const chrome = spawn(chromePath, [
'--headless=new', '--no-first-run', '--no-default-browser-check',
// CAPTURE_HEADED=1 opens a real X11 window (under xvfb-run) instead.
...(process.env.CAPTURE_HEADED === '1' ? ['--ozone-platform=x11'] : ['--headless=new']), '--no-first-run', '--no-default-browser-check',
// Without a GPU CanvasKit rasterises on the CPU; `gpu` keeps WebGL (Metal
// through ANGLE on a Mac) for benches that measure raster time.
// Linux keeps the GPU through ANGLE on Vulkan.
+8
View File
@@ -21,6 +21,13 @@ const MIME = {
'.woff2': 'font/woff2',
};
// `CAPTURE_ISOLATE=1` adds the Pipelines proxy's cross-origin isolation
// headers (web/src/appFiles.js), so a `--wasm` build renders multi-threaded as
// it does when installed; without them skwasm runs single-threaded.
const ISOLATE = process.env.CAPTURE_ISOLATE === '1'
? { 'cross-origin-opener-policy': 'same-origin', 'cross-origin-embedder-policy': 'credentialless' }
: {};
/** Serves [dir]; resolves to `{ origin, close() }`. */
export async function serveBuild(dir) {
const root = resolve(dir);
@@ -41,6 +48,7 @@ export async function serveBuild(dir) {
res.writeHead(200, {
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
...ISOLATE,
}).end(body);
} catch {
res.writeHead(404).end('not found');
+24 -4
View File
@@ -7,6 +7,9 @@
// Startup reports the first rasterised frame (ms since navigation) and the
// main.dart.js / canvaskit fetch times.
//
// --memory (Linux) adds `rssMB`: the resident memory of every process of the
// private Chrome (renderer, GPU, workers) once the measured steps settle.
//
// --cpuprofile records a V8 CPU profile of the measured steps (first rep),
// writes `<scenario>.cpuprofile` and prints the functions with the most
// inclusive and self time; use a `flutter build web --profile` build so the
@@ -22,7 +25,7 @@
// CanvasKit rasterises on the CPU, so compare builds with each other rather
// than predicting a device. --gpu keeps the GPU (WebGL), which is what a
// desktop user has: use it to judge raster time.
import { mkdir, writeFile } from 'node:fs/promises';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { parseArgs } from 'node:util';
import { setTimeout as delay } from 'node:timers/promises';
@@ -33,7 +36,7 @@ import { attribute, loadSourceMap } from './cpu_attribution.mjs';
const { values: opts } = parseArgs({
options: {
build: { type: 'string' }, out: { type: 'string' }, repeat: { type: 'string', default: '5' },
only: { type: 'string' }, cpuprofile: { type: 'boolean' }, frames: { type: 'boolean' }, shots: { type: 'boolean' }, gpu: { type: 'boolean' }, size: { type: 'string', default: '560x900' },
only: { type: 'string' }, cpuprofile: { type: 'boolean' }, frames: { type: 'boolean' }, shots: { type: 'boolean' }, gpu: { type: 'boolean' }, memory: { type: 'boolean' }, size: { type: 'string', default: '560x900' },
},
});
if (!opts.build || !opts.out) throw new Error('usage: --build <dir> --out <dir>');
@@ -106,6 +109,16 @@ const lookup = opts.cpuprofile ? await loadSourceMap(opts.build) : null;
const server = await serveBuild(opts.build);
const browser = await openBrowser({ gpu: Boolean(opts.gpu) });
const { send, on } = browser;
// Sums VmRSS over the browser's processes (SystemInfo ids are OS pids).
async function chromeRssMB() {
const { processInfo } = await browser.sendBrowser('SystemInfo.getProcessInfo');
let kb = 0;
for (const { id } of processInfo) {
const status = await readFile(`/proc/${id}/status`, 'utf8').catch(() => '');
kb += Number(status.match(/^VmRSS:\s+(\d+)/m)?.[1] ?? 0);
}
return kb / 1024;
}
const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value;
let frames = [];
let firstFrame = null;
@@ -191,8 +204,14 @@ try {
await delay(2000);
const startup = s.name.startsWith('startup');
const loads = startup ? await evaluate(`Object.fromEntries(performance.getEntriesByType('resource')
.filter((e) => /main\\.dart\\.js|canvaskit\\.wasm/.test(e.name))
.filter((e) => /main\\.dart\\.(js|wasm)$|canvaskit\\.wasm|skwasm(_heavy)?\\.wasm/.test(e.name))
.map((e) => [e.name.split('/').pop(), Math.round(e.responseEnd)]))`) : null;
if (startup && rep === 0) {
// Which build the loader picked: WebAssembly (skwasm, threaded only
// when cross-origin isolated) or JavaScript (CanvasKit).
console.log(` renderer: ${await evaluate(`(window._flutter_skwasmInstance ? 'skwasm' : window.flutterCanvasKit ? 'canvaskit' : '?')
+ (window.crossOriginIsolated ? ' isolated' : '')`)}`);
}
await run(s.setup);
await settle();
const startFrames = startup ? 0 : frames.length;
@@ -218,7 +237,8 @@ try {
const sum = (i) => f.reduce((a, x) => a + x[i], 0) / 1000;
const max = (i) => f.reduce((a, x) => Math.max(a, x[i]), 0) / 1000;
reps.push({ frames: f.length, buildSum: sum(0), buildMax: max(0), rasterSum: sum(1), rasterMax: max(1),
longest: max(2), over16: f.filter((x) => x[2] > 16667).length, firstFrame, ...loads });
longest: max(2), over16: f.filter((x) => x[2] > 16667).length, firstFrame, ...loads,
...(opts.memory ? { rssMB: await chromeRssMB() } : {}) });
}
const keys = Object.keys(reps[0]).filter((k) => typeof reps[0][k] === 'number');
results[s.name] = Object.fromEntries(keys.map((k) => [k, r1(median(reps.map((r) => r[k])))]));
+18
View File
@@ -0,0 +1,18 @@
{{flutter_js}}
{{flutter_build_config}}
// The Pipelines web proxy (web/serve.mjs) names an installed build's
// versioned asset base, cached as immutable: the entrypoint, the renderer
// (skwasm or CanvasKit) and the app's assets all load from it. Without it (a
// development server) everything loads from the page's own base.
//
// No service worker is registered: Flutter's is deprecated and now only
// unregisters itself and reloads the page, which cost a second startup after
// every install. HTTP caching keeps repeat loads fast instead.
(() => {
const base = document.querySelector('meta[name="pipelines-asset-base"]')?.content;
const config = base
? { entrypointBaseUrl: base, assetBase: base, canvasKitBaseUrl: base + "canvaskit/" }
: {};
_flutter.loader.load({ config });
})();