Merge main into run token usage branch

This commit is contained in:
2026-11-03 22:21:38 +00:00
118 changed files with 4294 additions and 1483 deletions
+7
View File
@@ -53,6 +53,9 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
| `labels=name` | write the visible semantics labels, keys and rects to JSON |
| `film=<target>` | screencast a click for `--film-ms` (900) and write the frames plus a contact sheet |
| `wait=ms` | sleep |
| `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 |
| `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 |
@@ -69,6 +72,10 @@ Targets:
When a target is missing, the step fails. The kit lists the visible labels,
saves `NN-FAILED.png` and exits with status 1.
An HTML artifact: `--params html=1` adds `release-dashboard.html` to run 7.
Its bytes are served from the build, so copy the fixture in after building:
`mkdir -p build/probe-app/artifacts/7/2 && cp tool/capture/fixtures/release-dashboard.html build/probe-app/artifacts/7/2/`.
## Recipes (run from `app/` after building `build/probe-app`)
Capture a page at phone and fold widths, in Material and in Cupertino. Use 560
+3
View File
@@ -91,6 +91,9 @@ export async function openBrowser({ cdp, chromePath = process.env.CHROME_PATH ??
listeners.set(method, [...(listeners.get(method) ?? []), fn]);
return () => listeners.set(method, listeners.get(method).filter((f) => f !== fn));
},
/** Every open page target (tabs a link opened included): `{ url, type }`. */
targets: async () => (await raw('Target.getTargets')).targetInfos
.filter((t) => t.type === 'page').map((t) => ({ url: t.url, type: t.type })),
newPage: async () => {
const page = await raw('Target.createTarget', { url: 'about:blank' });
const { sessionId: sid } = await raw('Target.attachToTarget', { targetId: page.targetId, flatten: true });
+23 -2
View File
@@ -20,10 +20,12 @@ options: --script <steps.json> --size WxH (880x1000) --platform material|cuperti
--theme light|dark --q <search> --wait <ms after actions, 1000>
--film-ms <ms, 900> --cdp http://127.0.0.1:<port> --probe true|false
--params <query, e.g. chats=2&rich=1, added to every open>
--touch true (emulate a touch screen: mobile metrics, touch input)
steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target>
type=<text> press=<Enter|Escape|Tab|...> scroll=<dy> size=WxH
film=<target> labels=<name> eval=<js> expect=<js> hover=<target>
film=<target> labels=<name> tabs=<name> eval=<js> expect=<js> hover=<target>
drag=<target>><dx>,<dy> (JSON: drag, dx, dy, steps, gap, hold)
swipe=<target>><dx>,<dy> pinch=<target>><scale> (with --touch true)
target: <label> | label:<label> | key:<semantics identifier> | x,y`;
const opts = { wait: '1000', 'film-ms': '900' };
@@ -86,7 +88,7 @@ let exitCode = 0;
try {
const base = opts.build ? (server = await serveBuild(opts.build)).origin : opts.url;
browser = await openBrowser({ cdp: opts.cdp });
page = flutterPage(browser, log);
page = flutterPage(browser, log, { touch: opts.touch === 'true' });
for (const step of steps) {
const [verb] = Object.keys(step);
const value = step[verb];
@@ -137,6 +139,24 @@ try {
await delay(step.wait ?? settle);
break;
}
case 'swipe': {
const [target, by] = String(value).split('>');
const [bx, by2] = (by ?? '').split(',').map(Number);
const moved = await page.swipe(target, {
dx: Number(step.dx ?? bx ?? 0) || 0, dy: Number(step.dy ?? by2 ?? 0) || 0,
steps: Number(step.steps ?? 12), gap: Number(step.gap ?? 16),
});
log(` swiped ${Math.round(moved.from.x)},${Math.round(moved.from.y)} -> ${Math.round(moved.to.x)},${Math.round(moved.to.y)}`);
await delay(step.wait ?? settle);
break;
}
case 'pinch': {
const [target, scale] = String(value).split('>');
const at = await page.pinch(target, Number(step.scale ?? scale ?? 2));
log(` pinched at ${Math.round(at.x)},${Math.round(at.y)}`);
await delay(step.wait ?? settle);
break;
}
case 'eval': {
const result = await page.evaluate(String(value));
log(` = ${JSON.stringify(result)}`);
@@ -150,6 +170,7 @@ try {
log(` ok ${step.name ?? ''}`);
break;
}
case 'tabs': await save(file(value || 'tabs', 'json'), JSON.stringify(await browser.targets(), null, 2)); break;
case 'labels': await save(file(value || 'labels', 'json'), JSON.stringify(await page.labels(), null, 2)); break;
case 'film': {
const name = step.name ?? `film-${describe(parseTarget(value)).replace(/\W+/g, '-').replace(/^-|-$/g, '')}`;
@@ -0,0 +1,21 @@
{
"size": "880x1000",
"params": "chats=1&msgs=4&links=1",
"steps": [
{ "open": "/chat" },
{ "click": "OpenCode harness\nFixture chat 1\n/workspace/demo", "wait": 2000 },
{ "eval": "window.__opened = []; window.open = (u) => { window.__opened.push(String(u)); return null; }" },
{ "shot": "chat" },
{ "drag": "480,719>5,0", "steps": 3, "wait": 600 },
{
"expect": "window.__opened.length === 1 && window.__opened[0] === 'https://example.com/releases/v2'",
"name": "a click that drifts 5 px still opens the link"
},
{ "drag": "380,719>240,0", "steps": 12, "wait": 600 },
{ "shot": "drag-select-across-links" },
{
"expect": "window.__opened.length === 1",
"name": "a selection drag from plain text across links opens nothing"
}
]
}
@@ -0,0 +1,32 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Release dashboard</title>
<style>
body { font-family: sans-serif; margin: 16px; color: #222; }
h1 { color: #0b5394; }
.wide { width: 1800px; border-collapse: collapse; }
.wide td { border: 1px solid #999; padding: 6px 10px; white-space: nowrap; }
.section { padding: 24px; margin: 16px 0; background: #eef3fb; border-left: 6px solid #0b5394; }
</style>
</head>
<body>
<h1>Release dashboard (top)</h1>
<p id="links">Links: <a href="#section-5">Jump to section 5</a> · <a href="https://example.com/">example.com</a> · <a href="javascript:alert(1)">script link</a> · <a href="other.html">relative link</a></p>
<p>Fixture document for the artifact viewer captures: taller and wider than the screen, no viewport meta.</p>
<table class="wide">
<tr><td>Column A</td><td>Column B</td><td>Column C</td><td>Column D</td><td>Column E</td><td>Column F</td><td>Column G</td><td>Column H</td><td>Column I</td><td>Column J</td><td>Right edge column</td></tr>
<tr><td>a1</td><td>b1</td><td>c1</td><td>d1</td><td>e1</td><td>f1</td><td>g1</td><td>h1</td><td>i1</td><td>j1</td><td>RIGHT EDGE</td></tr>
</table>
<div class="section" id="section-1"><h2>Section 1 of 8</h2><p>Build green across all targets.</p></div>
<div class="section" id="section-2"><h2>Section 2 of 8</h2><p>Integration suites passed.</p></div>
<div class="section" id="section-3"><h2>Section 3 of 8</h2><p>Release notes drafted.</p></div>
<div class="section" id="section-4"><h2>Section 4 of 8</h2><p>Migration checked on staging.</p></div>
<div class="section" id="section-5"><h2>Section 5 of 8</h2><p>Rollback plan recorded.</p></div>
<div class="section" id="section-6"><h2>Section 6 of 8</h2><p>Owners notified.</p></div>
<div class="section" id="section-7"><h2>Section 7 of 8</h2><p>Artifacts signed.</p></div>
<div class="section" id="section-8"><h2>Section 8 of 8</h2><p>Bottom of the document reached.</p></div>
<h1>Release dashboard (bottom)</h1>
</body>
</html>
+9 -1
View File
@@ -2,6 +2,7 @@
// enable semantics, find targets by semantics label / identifier / point,
// click, type, screenshot and film.
import { setTimeout as delay } from 'node:timers/promises';
import { enableTouch, pinch, swipe } from './touch.mjs';
/** Parses `label:Text`, `key:id`, `xy:10,20`, `10,20` or bare `Text` (a label). */
export function parseTarget(target) {
@@ -45,7 +46,7 @@ const LABELS = `(() => [...document.querySelectorAll('flt-semantics, [aria-label
rect: [r.left, r.top, r.width, r.height].map(Math.round) }; })
.filter((n) => (n.label || n.key) && n.rect[2] > 0 && n.rect[3] > 0))()`;
export function flutterPage(browser, log) {
export function flutterPage(browser, log, { touch = false } = {}) {
const { send } = browser;
let viewport = { width: 880, height: 1000 };
const errors = [];
@@ -110,6 +111,9 @@ export function flutterPage(browser, log) {
await until(() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 'Flutter to start', 30000);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await until(() => evaluate("document.querySelectorAll('flt-semantics').length > 0"), 'the semantics tree', 15000);
// Touch starts once semantics is on: the placeholder's click does not
// turn semantics on under touch emulation.
if (touch) await enableTouch(send, viewport);
await delay(800);
},
async click(target, timeout) {
@@ -181,6 +185,10 @@ export function flutterPage(browser, log) {
if (!hold) await mouse('mouseReleased', at.x + dx, at.y + dy, { buttons: 0, clickCount: 1 });
return { from: at, to: { x: at.x + dx, y: at.y + dy } };
},
/** One-finger touch swipe from [target] by dx/dy (needs `--touch true`). */
swipe: async (target, moves) => swipe(send, await locate(target), moves),
/** Two-finger touch pinch at [target] by [scale] (needs `--touch true`). */
pinch: async (target, scale) => pinch(send, await locate(target), scale),
evaluate,
/** Screencasts [ms] after clicking [target]; frames are `{ data, ms }` relative to the click. */
async film(target, ms) {
+33
View File
@@ -0,0 +1,33 @@
// Touch input over one DevTools page session, for phone/tablet review:
// a touch-screen emulation switch, one-finger swipes and two-finger pinches.
// The events are trusted browser input, so they reach whatever the page puts
// under the finger (a Flutter canvas or an iframe platform view alike).
import { setTimeout as delay } from 'node:timers/promises';
/** Emulates a touch screen (mobile metrics, 5 touch points). */
export async function enableTouch(send, { width, height }) {
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: true });
await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
}
/** One finger down at [at], moved by dx/dy in [steps] moves [gap] ms apart, lifted. */
export async function swipe(send, at, { dx = 0, dy = 0, steps = 12, gap = 16 } = {}) {
const touch = (type, x, y) => send('Input.dispatchTouchEvent', {
type, touchPoints: type === 'touchEnd' ? [] : [{ x, y, id: 1 }],
});
await touch('touchStart', at.x, at.y);
for (let i = 1; i <= steps; i++) {
await delay(gap);
await touch('touchMove', at.x + (dx * i) / steps, at.y + (dy * i) / steps);
}
await touch('touchEnd');
return { from: at, to: { x: at.x + dx, y: at.y + dy } };
}
/** Two fingers spread (scale > 1) or closed (< 1) around [at]. */
export async function pinch(send, at, scale) {
await send('Input.synthesizePinchGesture', {
x: at.x, y: at.y, scaleFactor: scale, relativeSpeed: 300, gestureSourceType: 'touch',
});
return at;
}
+86
View File
@@ -0,0 +1,86 @@
// An agent question for captures over the full-app fixture's `?chats=N`
// sessions (tool/perf/perf_fixture.dart). Off by default.
//
// `?question=opencode` 1.5 s after a chat subscribes, a pending question
// form arrives; chat_answer is acknowledged and then
// the server's `form.replied` resolution frame follows
// (OpenCode);
// `?question=claude` the same, but only the reply ack settles it (Claude
// Code's AskUserQuestion: the resolution comes later
// from the server's readback);
// `?question=fail` chat_answer is refused, so the card must stay.
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
Map<String, String> _params = const {};
void configureChatQuestionFixture(Map<String, String> params) =>
_params = params;
String get _mode => _params['question'] ?? '';
JsonMap _event(String sessionId, JsonMap body) => {
'type': 'chat_event',
'chat_event': {'session_id': sessionId, ...body},
};
/// Pushes the pending question into [sessionId] through [emit].
void chatQuestionStream(String sessionId, void Function(JsonMap frame) emit) {
if (_mode.isEmpty) return;
Timer(const Duration(milliseconds: 1500), () {
emit(
_event(sessionId, {
'kind': 'form',
'form': {
'id': '$sessionId-question',
'session_id': sessionId,
'kind': 'question',
'title': 'Database',
'fields': [
{
'key': 'q0',
'title': 'Which database should the release use?',
'type': 'string',
'required': true,
'options': [
{'value': 'Postgres', 'label': 'Postgres'},
{'value': 'SQLite', 'label': 'SQLite'},
],
},
],
},
}),
);
});
}
/// The chat_answer reply, or null when `?question=` is off.
JsonMap? chatQuestionReply(JsonMap request) {
if (_mode.isEmpty || request['type'] != 'chat_answer') return null;
final id = request['id'];
if (_mode == 'fail') {
return {
'id': id,
'type': 'error',
'error': 'the question is no longer awaiting an answer',
};
}
return {'id': id, 'type': 'chat_answer'};
}
/// The OpenCode resolution frame that follows an accepted answer.
List<JsonMap> chatQuestionFollowUps(JsonMap request) {
if (_mode != 'opencode' || request['type'] != 'chat_answer') {
return const [];
}
final body = request['chat_answer'];
if (body is! Map) return const [];
final session = '${body['session_id'] ?? ''}';
return [
_event(session, {
'kind': 'form',
'form': {'id': body['form_id'], 'session_id': session, 'resolved': true},
}),
];
}
+23
View File
@@ -10,13 +10,17 @@
// that harness's account quota after a chat subscribes.
// `?colors=1` (with `?chats=N`) names the chats, stars and colours some of
// them, and keeps colours picked with chat_color;
// `?activity=1` (with `?chats=N`) lists a running chat, one with
// background tasks and idle ones;
// `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for
// scroll captures (tool/perf/chat_scroll_fixture.dart).
// `?question=` pushes an agent question (tool/perf/chat_question_fixture.dart).
// `/new` in a fixture chat moves it to a fresh, empty session
// (tool/perf/chat_new_session_fixture.dart).
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_new_session_fixture.dart';
import 'chat_question_fixture.dart';
import 'chat_scroll_fixture.dart';
Map<String, String> _params = const {};
@@ -25,6 +29,7 @@ Map<String, String> _params = const {};
void configurePerfFixture(Map<String, String> params) {
_params = params;
configureChatScrollFixture(params);
configureChatQuestionFixture(params);
}
int get _hits => int.tryParse(_params['hits'] ?? '') ?? 0;
@@ -32,6 +37,18 @@ int get _chats => int.tryParse(_params['chats'] ?? '') ?? 0;
bool get perfRunGraph => _params['graph'] == '1';
bool get _colors => _params['colors'] == '1';
/// `?activity=1` (with `?chats=N`): the first chat's turn is running, the
/// second is idle with two background tasks, the rest are idle, as the
/// server's `activity` row field reports them.
JsonMap? _activityFor(int i) {
if (_params['activity'] != '1') return null;
return switch (i) {
0 => {'turn_running': true, 'background_tasks': 1, 'seq': 3},
1 => {'background_tasks': 2, 'seq': 2},
_ => {'seq': 1},
};
}
/// `?colors=1`: titles, directories, stars and colours per chat index.
const _colorTitles = [
'Release notes',
@@ -58,6 +75,7 @@ JsonMap _chatRow(int i) {
if (_harness != 'opencode') 'backend': _harness,
'resume_command': _resumeCommand(id),
'native_export': _harness == 'claude',
'activity': ?_activityFor(i),
};
}
final color = _pickedColors.containsKey(id)
@@ -72,6 +90,7 @@ JsonMap _chatRow(int i) {
'updated_at': DateTime.now().millisecondsSinceEpoch - (i + 1) * 600000,
if (_colorStarred.contains(i)) 'starred': true,
'color': ?color,
'activity': ?_activityFor(i),
};
}
@@ -91,6 +110,8 @@ bool get _scrollVariety => ['msgs', 'rich', 'older'].any(_params.containsKey);
/// Unsolicited envelopes that follow a reply: the `?quota=` usage frame.
List<JsonMap> perfChatFollowUps(JsonMap request) {
final answered = chatQuestionFollowUps(request);
if (answered.isNotEmpty) return answered;
final quota = _params['quota'];
if (_chats == 0 || quota == null || request['type'] != 'chat_subscribe') {
return const [];
@@ -189,6 +210,8 @@ String _answer(int i) =>
/// Chat replies for `?chats=N`, or null to fall through to the fixture.
JsonMap? perfChatReply(JsonMap request) {
if (_chats == 0) return null;
final question = chatQuestionReply(request);
if (question != null) return question;
final id = request['id'];
switch ('${request['type']}') {
case 'chat_sessions':
+19 -2
View File
@@ -28,6 +28,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
import 'fixture_host/fixture_host.dart';
import 'perf/chat_search_fixture.dart';
import 'perf/chat_question_fixture.dart';
import 'perf/chat_scroll_fixture.dart';
import 'perf/perf_fixture.dart';
import 'probe_folder_fixture.dart';
@@ -73,6 +74,13 @@ JsonMap probeRunDetail() => {
'size_bytes': 12,
'url': '/artifacts/7/2/release-report.txt',
},
if (_htmlArtifact)
{
'name': 'release-dashboard.html',
'content_type': 'text/html',
'size_bytes': 4096,
'url': '/artifacts/7/2/release-dashboard.html',
},
],
'file_changes': _probeChanges([
'lib/release/train.dart',
@@ -124,6 +132,10 @@ JsonMap _probeChanges(List<String> paths) => {
int _fillerRunCount = 0;
int _fillerStepCount = 0;
/// `?html=1` adds `release-dashboard.html` to run 7's build visit; the capture
/// serves its bytes from the build directory (see notes/artifact-fullscreen.md).
bool _htmlArtifact = false;
List<JsonMap> _fillerSteps() => [
for (var i = 0; i < _fillerStepCount; i++)
{
@@ -544,9 +556,12 @@ class _FixtureChannel implements WebSocketChannel {
final followUps = perfChatFollowUps(decoded);
final subscribe = decoded['chat_subscribe'];
if (subscribe is Map) {
chatScrollStream('${subscribe['session_id'] ?? ''}', (frame) {
void emit(JsonMap frame) {
if (!_incoming.isClosed) _incoming.add(jsonEncode(frame));
});
}
chatScrollStream('${subscribe['session_id'] ?? ''}', emit);
chatQuestionStream('${subscribe['session_id'] ?? ''}', emit);
}
if (reply == null && followUps.isEmpty) return;
Future<void>.delayed(const Duration(milliseconds: 120), () {
@@ -600,6 +615,7 @@ class _FixtureSink implements WebSocketSink {
/// `?route=/runs/7/stage/build%3Fvisit%3D1` opens that app location;
/// `?runs=200` / `?steps=60` append filler runs / run-7 steps for scroll
/// performance captures;
/// `?html=1` adds an HTML artifact to run 7 (`release-dashboard.html`);
/// `?q=release` types that query into Search once its field is shown;
/// `?platform=cupertino` renders the Cupertino host (`material`, the
/// default, renders Material as browsers do);
@@ -624,6 +640,7 @@ void main() {
_fillerRunCount = int.tryParse(params['runs'] ?? '') ?? 0;
_fillerStepCount = int.tryParse(params['steps'] ?? '') ?? 0;
probeUsage = params['usage'] == '1';
_htmlArtifact = params['html'] == '1';
final cupertino = params['platform'] == 'cupertino';
final route = params['route'];
final opensRoute = route != null && route.startsWith('/');