Merge branch 'main' into worktree-agent-a3cb3553b5c91a345

This commit is contained in:
2026-12-03 14:21:22 +00:00
135 changed files with 7973 additions and 443 deletions
+1
View File
@@ -88,6 +88,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
| `swipe=<target>>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) |
| `pinch=<target>>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) |
| `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab |
| `follow=/window/chat/` | move the following steps to the page whose URL contains the text (a window the app opened with `window.open`, at its own size, semantics on); `follow=main` returns to the page the kit opened (`examples/detached-chat-window.json`) |
| `eval=<js>` | evaluate an expression in the page and log/record its value |
| `expect=<js>` | fail the run (status 1) unless the expression is truthy; JSON `name` labels the check |
+28
View File
@@ -88,6 +88,7 @@ export async function openBrowser({ cdp, gpu = false, args = [], chromePath = pr
ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }));
});
let targetId;
let main;
try {
({ targetId } = await raw('Target.createTarget', { url: 'about:blank' }));
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
@@ -114,6 +115,33 @@ export async function openBrowser({ cdp, gpu = false, args = [], chromePath = pr
},
/** Brings the kit's own page to the front again (after a scratch page). */
front: () => raw('Target.activateTarget', { targetId }),
/**
* Moves the kit's page session to another page target: the first one
* whose URL contains [match] (a window the page opened with
* `window.open`), waited for up to [timeout] ms; `main` returns to the
* page the kit opened. Resolves to the target's URL.
*/
follow: async (match, timeout = 10000) => {
main ??= { targetId, sessionId };
if (match === 'main') {
({ targetId, sessionId } = main);
await raw('Target.activateTarget', { targetId });
return (await raw('Target.getTargets')).targetInfos.find((t) => t.targetId === targetId)?.url;
}
const end = Date.now() + timeout;
for (;;) {
const hit = (await raw('Target.getTargets')).targetInfos
.find((t) => t.type === 'page' && t.targetId !== main.targetId && t.url.includes(match));
if (hit) {
targetId = hit.targetId;
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
await raw('Target.activateTarget', { targetId });
return hit.url;
}
if (Date.now() > end) throw new Error(`no page whose URL contains ${JSON.stringify(match)} within ${timeout} ms`);
await new Promise((ok) => setTimeout(ok, 100));
}
},
close: async () => {
await raw('Target.closeTarget', { targetId }).catch(() => {});
ws.close();
+10 -1
View File
@@ -28,7 +28,7 @@ options: --script <steps.json> --size WxH (880x1000)
steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target>
type=<text> press=<Enter|Escape|Tab|...> scroll=<dy> size=WxH
files=<path>[,<path>] (answers the next file chooser)
film=<target> labels=<name> tabs=<name> eval=<js> expect=<js> hover=<target>
film=<target> labels=<name> tabs=<name> follow=<url part|main> eval=<js> expect=<js> hover=<target>
keys=<json events> grant=clipboard
clipboard=read|write:<text> (the browser's clipboard, from a scratch
page on the loopback origin, so it works for an --insecure page)
@@ -246,6 +246,15 @@ try {
break;
}
case 'tabs': await save(file(value || 'tabs', 'json'), JSON.stringify(await browser.targets(), null, 2)); break;
case 'follow': {
// follow=<url part>: the steps after it act on that window (one the
// page opened); follow=main returns to the page the kit opened.
const url = await browser.follow(String(value), step.timeout);
log(` now on ${url}`);
if (value !== 'main') await page.adopt();
await delay(step.wait ?? settle);
break;
}
case 'labels': await save(file(value || 'labels', 'json'), JSON.stringify(await page.labels(), null, 2)); break;
case 'film': {
const what = String(value).startsWith('press:') ? String(value) : describe(parseTarget(value));
@@ -0,0 +1,24 @@
{ "size": "1400x900", "params": "chats=2",
"steps": [
{ "open": "/chat/perf-chat-0" },
{ "wait": 1500 },
{ "shot": "main-before" },
{ "click": "More actions" },
{ "shot": "pane-menu" },
{ "click": "Open in new window (Alt+Shift+Y)", "wait": 1500 },
{ "tabs": "tabs" },
{ "follow": "/window/chat/", "wait": 2500 },
{ "shot": "detached-chat" },
{ "eval": "document.title" },
{ "expect": "document.title === 'Fixture chat 1 · Pipelines'", "name": "the window is named after its chat" },
{ "expect": "location.pathname === '/window/chat/perf-chat-0'", "name": "the window keeps its location" },
{ "follow": "main", "wait": 800 },
{ "shot": "main-after" },
{ "follow": "/window/chat/", "wait": 500 },
{ "click": "More actions" },
{ "shot": "detached-menu" },
{ "click": "Bring back to main window", "wait": 1500 },
{ "follow": "main", "wait": 1200 },
{ "tabs": "tabs-after-return" },
{ "shot": "main-returned" }
] }
@@ -0,0 +1,13 @@
{ "size": "1400x900", "params": "chats=2&terminals=1&terminal=panel",
"steps": [
{ "open": "/chat/perf-chat-0" },
{ "wait": 2000 },
{ "click": "Terminal options" },
{ "shot": "terminal-menu" },
{ "click": "Open in new window", "wait": 1500 },
{ "shot": "main-after" },
{ "follow": "/window/terminal", "wait": 3000 },
{ "shot": "detached-terminal" },
{ "eval": "document.title" },
{ "expect": "document.title.startsWith('Terminal')", "name": "the window is named after its terminal" }
] }
+15
View File
@@ -125,6 +125,21 @@ export function flutterPage(browser, log, { touch = false, semantics = true, use
if (touch) await enableTouch(send, viewport);
await delay(800);
},
/**
* Takes over a page that is already loading (a window the app opened)
* at its own size: waits for Flutter and turns semantics on.
*/
async adopt() {
await send('Page.enable');
await send('Runtime.enable');
// A window followed before already has its semantics tree.
const started = "Boolean(document.querySelector('flt-semantics-placeholder, flt-semantics'))";
await until(() => evaluate(started), 'Flutter to start', 30000);
if (!semantics) return;
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await until(() => evaluate("document.querySelectorAll('flt-semantics').length > 0"), 'the semantics tree', 15000);
await delay(800);
},
async click(target, timeout) {
const point = await locate(target, timeout);
await tap(point);
@@ -4,6 +4,7 @@ import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import '../perf/frame_log_native.dart';
import 'fixture_steps.dart';
import 'narrow_view.dart';
@@ -31,8 +32,10 @@ Map<String, String> fixtureParams() {
return raw.isEmpty ? const {} : Uri.splitQueryString(raw);
}
/// The DevTools probes are browser-only.
void installHostProbes(Map<String, String> params) {}
/// The DevTools probes are browser-only; `perf=1` prints frame timings to
/// stdout (tool/perf/frame_log_native.dart).
void installHostProbes(Map<String, String> params) =>
installNativeFrameLog(params);
/// The route goes through [fixtureRouteProvider] instead.
void openFixtureRoute(String route) {}
+24 -1
View File
@@ -9,7 +9,10 @@ import 'package:flutter/services.dart';
/// [script] is `;`-separated steps run after the first frame, 700 ms apart:
/// `wait:<ms>`, `tap:<label>` (a Text, Tooltip, Semantics label or field
/// hint; `tap:<label>#<n>` picks the n-th match), `tapxy:<x>,<y>`,
/// `drag:<x>,<y>,<dx>,<dy>`, `type:<text>` (into the focused field; `\n`
/// `drag:<x>,<y>,<dx>,<dy>`, `wheel:<x>,<y>,<dy>,<count>` (mouse-wheel
/// notches 16 ms apart, as the web interaction bench sends), `mark:<name>`
/// (prints `FIXTURE_MARK <name>`, so a bench can tell its phases apart),
/// `type:<text>` (into the focused field; `\n`
/// is a newline), `orient:landscape|portrait` and `labels` (prints the
/// visible labels with their centres to the device log).
void runFixtureSteps(String script) {
@@ -54,6 +57,12 @@ Future<void> _run(String verb, String value) async {
case 'drag':
final p = value.split(',').map(double.parse).toList();
await _drag(Offset(p[0], p[1]), Offset(p[2], p[3]));
case 'mark':
// ignore: avoid_print
print('FIXTURE_MARK $value');
case 'wheel':
final p = value.split(',').map(double.parse).toList();
await _wheel(Offset(p[0], p[1]), p[2], p[3].toInt());
case 'type':
_type(value.replaceAll(r'\n', '\n'));
case 'orient':
@@ -141,6 +150,20 @@ Future<void> _drag(Offset from, Offset by) async {
);
}
Future<void> _wheel(Offset at, double dy, int count) async {
final binding = GestureBinding.instance;
for (var i = 0; i < count; i++) {
binding.handlePointerEvent(
PointerScrollEvent(
kind: PointerDeviceKind.mouse,
position: at,
scrollDelta: Offset(0, dy),
),
);
await Future<void>.delayed(const Duration(milliseconds: 16));
}
}
void _type(String text) {
EditableTextState? focused;
void visit(Element element) {
+28
View File
@@ -0,0 +1,28 @@
// Frame report for native fixture builds (the Linux desktop bench,
// tool/perf/linux_desktop_bench.py), the native twin of frame_log.dart.
//
// With `perf=1` in FIXTURE_QUERY it prints every frame's Flutter timings as
// `PERF_FRAME <build us> <raster us> <total us>`, and the first rasterised
// frame as `PERF_FIRST_FRAME_EPOCH <ms since the Unix epoch>`, which the
// bench subtracts from its own launch time. Without the flag nothing is
// installed.
import 'package:flutter/widgets.dart';
void installNativeFrameLog(Map<String, String> params) {
if (params['perf'] != '1') return;
final binding = WidgetsFlutterBinding.ensureInitialized();
binding.addTimingsCallback((timings) {
for (final timing in timings) {
// ignore: avoid_print
print(
'PERF_FRAME ${timing.buildDuration.inMicroseconds} '
'${timing.rasterDuration.inMicroseconds} '
'${timing.totalSpan.inMicroseconds}',
);
}
});
binding.waitUntilFirstFrameRasterized.then((_) {
// ignore: avoid_print
print('PERF_FIRST_FRAME_EPOCH ${DateTime.now().millisecondsSinceEpoch}');
});
}
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Startup and chat-scroll bench for the Linux desktop build of the full-app
fixture, the native counterpart of interaction_bench.mjs's `startup` and
`desktop: scroll a rich chat` scenarios.
Build the fixture as a Linux bundle (release, or profile for engine switches):
docker run ... pipelines-app-build linux --target tool/search_selection_probe_entry.dart
then:
python3 tool/perf/linux_desktop_bench.py --bundle <bundle dir> [--repeat 5]
[--switch enable-impeller=true] # profile builds only
Each run starts the bundle on a private Xvfb display (never the desktop
session) with an isolated HOME and its own D-Bus session, with FIXTURE_QUERY
`perf=1` (tool/perf/frame_log_native.dart). Startup is launch to the first
rasterised frame; the scroll is 30 mouse-wheel notches of -240 px over the
open rich chat. Xvfb has no GPU: Mesa's llvmpipe rasterises on the CPU, as
headless Chrome without --gpu does, so compare builds and engines with each
other rather than predicting a desktop with a GPU.
"""
import argparse
import json
import os
from pathlib import Path
import shutil
import statistics
import subprocess
import tempfile
import time
QUERY = ("route=/chat/perf-chat-0&chats=2&header=1&rich=1&perf=1"
"&do=wait:500;tap:Later;wait:800;mark:scroll;wheel:860,400,-240,30;wait:1500;mark:end")
def run_once(bundle, display, switches, timeout, extra_env=()):
root = Path(tempfile.mkdtemp(prefix="linux-bench-"))
runtime = root / "run"
runtime.mkdir(mode=0o700)
env = {"HOME": str(root / "home"), "XDG_RUNTIME_DIR": str(runtime), "DISPLAY": f":{display}",
"GDK_BACKEND": "x11", "PATH": "/usr/bin:/bin", "FIXTURE_QUERY": QUERY,
**dict(e.split("=", 1) for e in extra_env)}
if switches:
env["FLUTTER_ENGINE_SWITCHES"] = str(len(switches))
for index, switch in enumerate(switches, 1):
env[f"FLUTTER_ENGINE_SWITCH_{index}"] = switch
xvfb = subprocess.Popen(["Xvfb", f":{display}", "-screen", "0", "1280x800x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
lines = []
try:
time.sleep(1)
launched = time.time() * 1000
app = subprocess.Popen(["dbus-run-session", "--", str(Path(bundle) / "pipelines-app")], env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
start_new_session=True)
deadline = time.time() + timeout
try:
for line in app.stdout:
lines.append(line.strip())
if line.startswith("FIXTURE_MARK end") or time.time() > deadline:
break
finally:
os.killpg(app.pid, 15)
app.wait(timeout=10)
finally:
xvfb.terminate()
xvfb.wait(timeout=10)
shutil.rmtree(root, ignore_errors=True)
first = next((int(l.split()[1]) for l in lines if l.startswith("PERF_FIRST_FRAME_EPOCH ")), None)
phase, scroll = None, []
for line in lines:
if line.startswith("FIXTURE_MARK "):
phase = line.split()[1]
elif line.startswith("PERF_FRAME ") and phase == "scroll":
build, raster, total = (int(v) for v in line.split()[1:4])
scroll.append((build, raster, total))
if first is None or not scroll:
raise RuntimeError("the run reported no first frame or no scroll frames:\n" + "\n".join(lines[-20:]))
return {"startupMs": first - launched, "frames": len(scroll),
"buildSumMs": sum(f[0] for f in scroll) / 1000, "buildMaxMs": max(f[0] for f in scroll) / 1000,
"rasterSumMs": sum(f[1] for f in scroll) / 1000, "rasterMaxMs": max(f[1] for f in scroll) / 1000,
"rasterMedianMs": statistics.median(f[1] for f in scroll) / 1000,
"worstFrameMs": max(f[2] for f in scroll) / 1000}
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--bundle", required=True)
parser.add_argument("--repeat", type=int, default=5)
parser.add_argument("--display", type=int, default=97)
parser.add_argument("--switch", action="append", default=[], help="engine switch (profile builds)")
parser.add_argument("--timeout", type=float, default=60)
parser.add_argument("--env", action="append", default=[], help="extra VAR=value for the app")
args = parser.parse_args()
runs = [run_once(args.bundle, args.display, args.switch, args.timeout, args.env) for _ in range(args.repeat)]
median = {key: round(statistics.median(r[key] for r in runs), 1) for key in runs[0]}
print(json.dumps({"bundle": args.bundle, "switches": args.switch, "runs": len(runs), "median": median}, indent=2))
if __name__ == "__main__":
main()
+40 -19
View File
@@ -28,6 +28,9 @@ import 'dart:convert';
import 'package:pipelines_app/application/app_url_strategy.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/detached/detached_app.dart';
import 'package:pipelines_app/application/detached/detached_platform.dart';
import 'package:pipelines_app/application/detached/detached_route.dart';
import 'package:pipelines_app/application/bootstrap.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
@@ -1080,25 +1083,43 @@ Future<void> main() async {
},
)
: null;
final app = PipelinesApp(
serverId: machines?.catalog.active?.id,
servers: machines,
chatPool: pool,
server: fixtureServer(params),
webPlatform: params['nativeUpdate'] == null ? kIsWeb : false,
androidSupported: params['nativeUpdate'] == null ? null : true,
installedVersionReader: () async => 1,
androidFeedReader: (base) async => AppUpdate(
versionCode: 2,
versionName: '0.1.2',
apk: base.resolve('Pipelines.zip'),
platform: params['nativeUpdate'] ?? 'android',
sourceName: 'Home Linux',
),
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
routeInformationProvider: fixtureRouteProvider(opensRoute ? route : null),
windows: probeWindows(params),
);
// A detached window (`/window/chat/<id>`, opened by Open in new window)
// runs on the same fixture: its URL carries this page's parameters.
DetachedPlatform.extraQuery = () => {
for (final entry in params.entries)
if (entry.key != 'route' && entry.key != 'q') entry.key: entry.value,
};
final detached = kIsWeb ? DetachedRoute.parse(Uri.base.toString()) : null;
final app = detached != null
? DetachedWindowApp(
route: detached,
server: fixtureServer(params),
serverId: machines?.catalog.active?.id,
servers: machines,
chatPool: pool,
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
)
: PipelinesApp(
serverId: machines?.catalog.active?.id,
servers: machines,
chatPool: pool,
server: fixtureServer(params),
webPlatform: params['nativeUpdate'] == null ? kIsWeb : false,
androidSupported: params['nativeUpdate'] == null ? null : true,
installedVersionReader: () async => 1,
androidFeedReader: (base) async => AppUpdate(
versionCode: 2,
versionName: '0.1.2',
apk: base.resolve('Pipelines.zip'),
platform: params['nativeUpdate'] ?? 'android',
sourceName: 'Home Linux',
),
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
routeInformationProvider: fixtureRouteProvider(
opensRoute ? route : null,
),
windows: probeWindows(params),
);
final brightness = switch (params['theme']) {
'dark' => Brightness.dark,
'light' => Brightness.light,