Merge branch 'main' into worktree-agent-a35ac03e196ffae50
# Conflicts: # app/lib/features/runs/ui/run_detail_content.dart # app/lib/features/runs/ui/run_list_row.dart # app/tool/search_selection_probe_entry.dart
This commit is contained in:
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# Bounded `flutter analyze` for agents (from app/): tool/analyze.sh [paths...]
|
||||
# Prints one verdict line with error/warning/info counts and the duration, at
|
||||
# most ANALYZE_MAX_ISSUES (default 40) issue lines, and the full log path.
|
||||
# Exits with flutter analyze's own status.
|
||||
FLUTTER=${FLUTTER:-/Users/alan/development/flutter/bin/flutter}
|
||||
max=${ANALYZE_MAX_ISSUES:-40}
|
||||
[ -f pubspec.yaml ] || cd "$(dirname "$0")/.." || exit 1
|
||||
tmp=${TMPDIR:-/tmp}
|
||||
log=$(mktemp "${tmp%/}/flutter-analyze.XXXXXX") || exit 1
|
||||
start=$SECONDS
|
||||
"$FLUTTER" analyze "$@" > "$log" 2>&1; status=$?
|
||||
issues=$(grep -cE '^ *(error|warning|info) • ' "$log")
|
||||
count() { grep -cE "^ *$1 • " "$log"; }
|
||||
if [ "$status" = 0 ] && [ "$issues" = 0 ]; then
|
||||
echo "analyze: clean; $((SECONDS-start))s; exit 0"
|
||||
else
|
||||
echo "analyze: $(count error) errors, $(count warning) warnings, $(count info) infos; $((SECONDS-start))s; exit $status"
|
||||
if [ "$issues" = 0 ]; then
|
||||
tail -20 "$log" | cut -c1-300
|
||||
else
|
||||
grep -E '^ *(error|warning|info) • ' "$log" | head -n "$max" | cut -c1-300
|
||||
[ "$issues" -gt "$max" ] && echo "... and $((issues-max)) more issues"
|
||||
fi
|
||||
fi
|
||||
echo "full output: $log"
|
||||
exit $status
|
||||
@@ -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
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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>
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Fixture for tool/memwatch/quiet_test.sh: one passing test, one plain
|
||||
// expectation failure and one widget-test failure that prints far more than
|
||||
// the quiet summary may show. It lives outside test/ so the app suite skips it.
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('passing neighbour', () => expect(1, 1));
|
||||
|
||||
test('plain expectation fails', () {
|
||||
expect('memwatch-actual', 'memwatch-expected');
|
||||
});
|
||||
|
||||
testWidgets('widget failure with long output', (tester) async {
|
||||
for (var i = 0; i < 2000; i++) {
|
||||
// ignore: avoid_print
|
||||
print('memwatch-flood line $i ${'x' * 60}');
|
||||
}
|
||||
await tester.pumpWidget(const Text('memwatch', textDirection: TextDirection.ltr));
|
||||
expect(find.text('memwatch-missing-widget'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Fixture for tool/memwatch/quiet_test.sh: a passing suite whose output must
|
||||
// not appear in quiet mode. It lives outside test/ so the app suite skips it.
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
for (var i = 0; i < 3; i++) {
|
||||
test('passing fixture $i', () {
|
||||
// Printed output of a passing test is not part of the quiet summary.
|
||||
// ignore: avoid_print
|
||||
print('memwatch-noise-from-passing-test $i');
|
||||
expect(i, lessThan(3));
|
||||
});
|
||||
}
|
||||
test('skipped fixture', () {}, skip: 'fixture skip');
|
||||
}
|
||||
@@ -2,4 +2,6 @@
|
||||
# THE way to run app tests (from app/): tool/memwatch/full.sh test
|
||||
# Also for focused runs: tool/memwatch/full.sh test/features/runs
|
||||
# Concurrency 4, 12 GB cap for this run only (see run.sh beside this file).
|
||||
# Off a terminal the output is quiet: one verdict line, the failing tests only
|
||||
# (bounded), and the full log path. MEMWATCH_OUTPUT=full also prints the log.
|
||||
CONC=4 CAP_KB=12000000 exec "$(dirname "$0")/run.sh" "$@"
|
||||
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/bash
|
||||
# End-to-end check of the memwatch output modes against tiny fixture suites,
|
||||
# always under the watchdog (full.sh / run.sh). Exit 0 when every check passes.
|
||||
#
|
||||
# Usage (from app/): tool/memwatch/quiet_test.sh
|
||||
set -u
|
||||
cd "$(dirname "$0")/../.." || exit 1
|
||||
tmp=${TMPDIR:-/tmp}
|
||||
dir=$(mktemp -d "${tmp%/}/memwatch-quiet-test.XXXXXX") || exit 1
|
||||
trap 'rm -rf "$dir"' EXIT
|
||||
export MEMWATCH_DIR="$dir/logs"
|
||||
pass=tool/memwatch/fixtures/passing_fixture_test.dart
|
||||
fail=tool/memwatch/fixtures/failing_fixture_test.dart
|
||||
failures=0
|
||||
check() { # check <description> <command...>
|
||||
local what=$1; shift
|
||||
if "$@"; then echo "ok $what"; else echo "FAIL $what"; failures=$((failures+1)); fi
|
||||
}
|
||||
has() { grep -qF -- "$2" "$1"; }
|
||||
lacks() { ! grep -qF -- "$2" "$1"; }
|
||||
|
||||
# Stdout is a file here, so quiet is the default.
|
||||
tool/memwatch/full.sh "$pass" > "$dir/pass.out"; status=$?
|
||||
check "passing suite exits 0" [ $status = 0 ]
|
||||
check "passing verdict line" has "$dir/pass.out" "memwatch: PASS: 3 passed, 0 failed, 1 skipped; peak "
|
||||
check "passing output omits test prints" lacks "$dir/pass.out" "memwatch-noise"
|
||||
check "passing output is three lines" [ "$(wc -l < "$dir/pass.out")" -le 3 ]
|
||||
|
||||
tool/memwatch/full.sh "$fail" > "$dir/fail.out"; status=$?
|
||||
check "failing suite exits 1" [ $status = 1 ]
|
||||
check "failing verdict line" has "$dir/fail.out" "memwatch: FAIL: 1 passed, 2 failed, 0 skipped; peak "
|
||||
check "names the expectation failure" has "$dir/fail.out" "FAILED $fail: plain expectation fails"
|
||||
check "shows the expectation values" has "$dir/fail.out" "Actual: 'memwatch-actual'"
|
||||
check "names the widget failure" has "$dir/fail.out" "FAILED $fail: widget failure with long output"
|
||||
check "shows the widget exception" has "$dir/fail.out" "memwatch-missing-widget"
|
||||
check "shows the failing app frame" has "$dir/fail.out" "$fail:20:5"
|
||||
check "bounds the flood of prints" has "$dir/fail.out" "printed output (last 8 of 2000 lines):"
|
||||
check "quiet failure output under 6 KB" [ "$(wc -c < "$dir/fail.out")" -lt 6000 ]
|
||||
log=$(sed -n 's/^full output: //p' "$dir/fail.out")
|
||||
check "full log keeps every line" has "$log" "memwatch-flood line 0 "
|
||||
|
||||
MEMWATCH_OUTPUT=full tool/memwatch/full.sh "$fail" > "$dir/full.out"; status=$?
|
||||
check "full mode keeps exit 1" [ $status = 1 ]
|
||||
check "full mode prints the log" has "$dir/full.out" "memwatch-flood line 0 "
|
||||
check "full mode ends with the summary" has "$dir/full.out" "memwatch: FAIL: 1 passed, 2 failed"
|
||||
|
||||
# A 1 KB cap forces the watchdog to kill the run: the exit status stays 137.
|
||||
CAP_KB=1 tool/memwatch/run.sh "$pass" > "$dir/killed.out"; status=$?
|
||||
check "killed run exits 137" [ $status = 137 ]
|
||||
check "watchdog reports the kill" has "$dir/killed.out" "KILLED at "
|
||||
check "summary reports the kill" has "$dir/killed.out" "memwatch: KILLED: "
|
||||
|
||||
tool/memwatch/full.sh tool/memwatch/fixtures/missing_test.dart > "$dir/missing.out"; status=$?
|
||||
check "missing test file exits non-zero" [ $status != 0 ]
|
||||
check "missing test file still summarised" has "$dir/missing.out" "memwatch: FAIL: "
|
||||
|
||||
[ $failures = 0 ] && echo "quiet_test: all checks passed" || echo "quiet_test: $failures checks failed"
|
||||
[ $failures = 0 ]
|
||||
@@ -6,22 +6,31 @@
|
||||
# CONC flutter test --concurrency (default 1)
|
||||
# CAP_KB total RSS cap for this run's own test processes (default 3 GB)
|
||||
# MEMWATCH_DIR per-invocation output directory (default /tmp/memwatch)
|
||||
# FLUTTER flutter executable
|
||||
# FLUTTER flutter executable; DART the dart beside it (runs summary.dart)
|
||||
# MEMWATCH_OUTPUT quiet or full. Default: quiet when stdout is not a terminal
|
||||
# (agents, pipelines, pipes), full on a terminal. full prints the whole
|
||||
# flutter log before the summary; quiet prints only the summary.
|
||||
#
|
||||
# Runs flutter test in the background and polls the RSS of ITS OWN descendant
|
||||
# processes only; above CAP_KB it kills them (never another run's flutter_tester).
|
||||
# Prints the peak and the suite's last line, and exits with flutter's status
|
||||
# (137 when killed). A runaway test once grew to ~30 GB per process and crashed
|
||||
# the Mac twice, so never run `flutter test` outside this watchdog.
|
||||
# Then summary.dart prints a bounded report from flutter's JSON results: one
|
||||
# verdict line (pass/fail/skip counts, peak MB, duration, exit status), only
|
||||
# the failing tests with their error and app stack frames, and the paths of
|
||||
# the full log and JSON. Exits with flutter's status (137 when killed). A
|
||||
# runaway test once grew to ~30 GB per process and crashed the Mac twice, so
|
||||
# never run `flutter test` outside this watchdog.
|
||||
CONC=${CONC:-1}; CAP_KB=${CAP_KB:-3000000}
|
||||
MEMWATCH_DIR=${MEMWATCH_DIR:-/tmp/memwatch}
|
||||
FLUTTER=${FLUTTER:-/Users/alan/development/flutter/bin/flutter}
|
||||
DART=${DART:-$(dirname "$FLUTTER")/dart}
|
||||
here=$(cd "$(dirname "$0")" && pwd) || exit 1
|
||||
# Called from elsewhere (for example the repo root): run in this script's app/.
|
||||
[ -f pubspec.yaml ] || cd "$(dirname "$0")/../.." || exit 1
|
||||
[ -f pubspec.yaml ] || cd "$here/../.." || exit 1
|
||||
mkdir -p "$MEMWATCH_DIR" || exit 1
|
||||
out=$(mktemp "$MEMWATCH_DIR/out.XXXXXX")
|
||||
start=$SECONDS
|
||||
# $1 is deliberately unquoted: it carries the test path plus extra arguments.
|
||||
"$FLUTTER" test --concurrency="$CONC" $1 > "$out" 2>&1 &
|
||||
"$FLUTTER" test --concurrency="$CONC" --file-reporter "json:$out.json" $1 > "$out" 2>&1 &
|
||||
pid=$!
|
||||
descendants() { local p; for p in $(pgrep -P "$1"); do echo "$p"; descendants "$p"; done; }
|
||||
peak=0; killed=0
|
||||
@@ -38,6 +47,12 @@ while kill -0 $pid 2>/dev/null; do
|
||||
done
|
||||
wait $pid 2>/dev/null; status=$?
|
||||
[ $killed = 1 ] && status=137
|
||||
echo "peak $((peak/1024)) MB: $1 :: $(tail -1 "$out")"
|
||||
echo "full output: $out"
|
||||
mode=${MEMWATCH_OUTPUT:-}
|
||||
if [ -z "$mode" ]; then if [ -t 1 ]; then mode=full; else mode=quiet; fi; fi
|
||||
[ "$mode" = full ] && cat "$out"
|
||||
# The summary never changes the exit status; if it cannot run, keep the old lines.
|
||||
if ! "$DART" "$here/summary.dart" "$status" "$((peak/1024))" "$((SECONDS-start))" "$1" "$out" "$out.json" 2>/dev/null; then
|
||||
echo "peak $((peak/1024)) MB: $1 :: $(tail -1 "$out")"
|
||||
echo "full output: $out"
|
||||
fi
|
||||
exit $status
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// Bounded summary of one memwatch run, read from flutter test's JSON file
|
||||
// reporter. run.sh calls it after the watchdog has finished:
|
||||
//
|
||||
// dart tool/memwatch/summary.dart <exit> <peak MB> <seconds> <target> <log> <json>
|
||||
//
|
||||
// It prints one verdict line (counts, peak memory, duration, exit status),
|
||||
// then only the failing tests with their bounded error output, then the log
|
||||
// paths. Passing tests print nothing. The process exit status is always 0:
|
||||
// run.sh owns the real exit status.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// Failures shown with their output; later failures are listed by name only.
|
||||
const maxDetailedFailures = 8;
|
||||
|
||||
/// Failure names listed at all; the rest are counted.
|
||||
const maxListedFailures = 30;
|
||||
|
||||
/// Error lines and characters kept per failing test.
|
||||
const maxLinesPerFailure = 40;
|
||||
const maxCharsPerFailure = 4000;
|
||||
|
||||
/// Trailing lines of a failing test's ordinary print() output.
|
||||
const maxPrintedLines = 8;
|
||||
|
||||
/// Characters of failure detail across the whole summary.
|
||||
const maxDetailChars = 12000;
|
||||
|
||||
/// Characters kept per output line.
|
||||
const maxLineChars = 300;
|
||||
|
||||
/// App stack frames kept per error block; framework frames are dropped.
|
||||
const maxFramesPerBlock = 6;
|
||||
|
||||
/// What one test reported: Flutter exception dumps, test errors and other prints.
|
||||
class _Output {
|
||||
final exceptions = <String>[];
|
||||
final errors = <String>[];
|
||||
final prints = <String>[];
|
||||
}
|
||||
|
||||
String summarize(
|
||||
Iterable<String> events, {
|
||||
required int status,
|
||||
required int peakMb,
|
||||
required int seconds,
|
||||
required String target,
|
||||
required String logPath,
|
||||
required String jsonPath,
|
||||
List<String> logTail = const [],
|
||||
String appPackage = '',
|
||||
String appRoot = '',
|
||||
}) {
|
||||
final names = <int, String>{};
|
||||
final suiteOf = <int, int>{};
|
||||
final suitePaths = <int, String>{};
|
||||
final outputs = <int, _Output>{};
|
||||
final finished = <int>{};
|
||||
final failed = <int>[];
|
||||
var passed = 0, skipped = 0, sawEvent = false;
|
||||
for (final line in events) {
|
||||
final Object? event;
|
||||
try {
|
||||
event = jsonDecode(line);
|
||||
} on FormatException {
|
||||
continue;
|
||||
}
|
||||
if (event is! Map) continue;
|
||||
sawEvent = true;
|
||||
final id = event['testID'];
|
||||
switch (event['type']) {
|
||||
case 'suite':
|
||||
final suite = event['suite'] as Map;
|
||||
suitePaths[suite['id'] as int] = _relative('${suite['path'] ?? ''}', appRoot);
|
||||
case 'testStart':
|
||||
final test = event['test'] as Map;
|
||||
names[test['id'] as int] = '${test['name'] ?? ''}';
|
||||
suiteOf[test['id'] as int] = test['suiteID'] as int? ?? -1;
|
||||
case 'print' when id is int:
|
||||
final message = '${event['message'] ?? ''}';
|
||||
final output = outputs.putIfAbsent(id, _Output.new);
|
||||
(message.contains('EXCEPTION CAUGHT BY') ? output.exceptions : output.prints).add(message);
|
||||
case 'error' when id is int:
|
||||
outputs.putIfAbsent(id, _Output.new).errors.add('${event['error'] ?? ''}\n${event['stackTrace'] ?? ''}');
|
||||
// An error reported after a test finished (for example in tearDown) still fails it.
|
||||
if (!failed.contains(id)) failed.add(id);
|
||||
case 'testDone' when id is int:
|
||||
finished.add(id);
|
||||
if (event['result'] != 'success') {
|
||||
if (!failed.contains(id)) failed.add(id);
|
||||
} else if (event['skipped'] == true) {
|
||||
skipped++;
|
||||
} else if (event['hidden'] != true) {
|
||||
passed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
final verdict = status == 0 ? 'PASS' : (status == 137 ? 'KILLED' : 'FAIL');
|
||||
final out = StringBuffer()
|
||||
..writeln('memwatch: $verdict: $passed passed, ${failed.length} failed, $skipped skipped; '
|
||||
'peak $peakMb MB; ${seconds}s; exit $status ($target)');
|
||||
String label(int id) {
|
||||
final path = suitePaths[suiteOf[id]] ?? '';
|
||||
final name = names[id] ?? 'test $id';
|
||||
return path.isEmpty || name.startsWith('loading ') ? _relative(name, appRoot) : '$path: $name';
|
||||
}
|
||||
|
||||
var budget = maxDetailChars;
|
||||
for (final (index, id) in failed.indexed) {
|
||||
if (index >= maxListedFailures) {
|
||||
out.writeln('... and ${failed.length - index} more failures (see full log)');
|
||||
break;
|
||||
}
|
||||
out.writeln('FAILED ${label(id)}');
|
||||
if (index >= maxDetailedFailures || budget <= 0) continue;
|
||||
var detail = _detail(outputs[id] ?? _Output(), appPackage, appRoot);
|
||||
if (detail.length > budget) detail = '${detail.substring(0, budget)}\n ... (summary detail budget reached)';
|
||||
budget -= detail.length;
|
||||
if (detail.isNotEmpty) out.writeln(detail);
|
||||
}
|
||||
if (status == 137) {
|
||||
for (final id in names.keys.where((id) => !finished.contains(id)).take(5)) {
|
||||
out.writeln('RUNNING when killed: ${label(id)}');
|
||||
}
|
||||
}
|
||||
if (!sawEvent && status != 0) {
|
||||
out.writeln('no test results were recorded; last log lines:');
|
||||
for (final line in logTail.take(20)) {
|
||||
out.writeln(' ${_clip(line)}');
|
||||
}
|
||||
}
|
||||
out
|
||||
..writeln('full output: $logPath')
|
||||
..write('json results: $jsonPath');
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/// The failure cause first (Flutter exception dumps, then test errors, minus
|
||||
/// framework frames), capped; then the tail of the test's ordinary prints.
|
||||
String _detail(_Output output, String appPackage, String appRoot) {
|
||||
final errors = output.exceptions.isEmpty
|
||||
? output.errors
|
||||
: output.errors.where((e) => !e.startsWith('Test failed. See exception logs above.'));
|
||||
final lines = <String>[];
|
||||
var dropped = 0;
|
||||
for (final block in [...output.exceptions, ...errors]) {
|
||||
var frames = 0;
|
||||
for (final raw in const LineSplitter().convert(block)) {
|
||||
final line = raw.trimRight();
|
||||
if (_isNoise(line)) continue;
|
||||
if (_isFrame(line)) {
|
||||
if (!_isAppFrame(line, appPackage, appRoot) || frames >= maxFramesPerBlock) continue;
|
||||
frames++;
|
||||
}
|
||||
if (line.trim().isEmpty && (lines.isEmpty || lines.last.isEmpty)) continue;
|
||||
if (lines.length >= maxLinesPerFailure) {
|
||||
dropped++;
|
||||
continue;
|
||||
}
|
||||
lines.add(line.trim().isEmpty ? '' : _relative(line, appRoot));
|
||||
}
|
||||
}
|
||||
while (lines.isNotEmpty && lines.last.isEmpty) {
|
||||
lines.removeLast();
|
||||
}
|
||||
final buffer = StringBuffer();
|
||||
for (final line in lines) {
|
||||
if (buffer.length >= maxCharsPerFailure) {
|
||||
dropped++;
|
||||
continue;
|
||||
}
|
||||
buffer.writeln(line.isEmpty ? '' : ' ${_clip(line)}');
|
||||
}
|
||||
if (dropped > 0) buffer.writeln(' ... ($dropped more error lines in the full log)');
|
||||
final printed = output.prints.expand(const LineSplitter().convert).toList();
|
||||
if (printed.isNotEmpty) {
|
||||
final tail = printed.length > maxPrintedLines ? printed.sublist(printed.length - maxPrintedLines) : printed;
|
||||
buffer.writeln(' printed output (last ${tail.length} of ${printed.length} lines):');
|
||||
for (final line in tail) {
|
||||
buffer.writeln(' | ${_clip(line)}');
|
||||
}
|
||||
}
|
||||
return buffer.toString().trimRight();
|
||||
}
|
||||
|
||||
final _frame = RegExp(r'^(#\d+\s|package:|dart:|file:///|\S+\.dart\s+\d+)');
|
||||
|
||||
bool _isFrame(String line) => _frame.hasMatch(line.trimLeft());
|
||||
|
||||
bool _isNoise(String line) {
|
||||
final trimmed = line.trim();
|
||||
return trimmed == '<asynchronous suspension>' ||
|
||||
trimmed.startsWith('===== asynchronous gap') ||
|
||||
trimmed.startsWith('(elided ');
|
||||
}
|
||||
|
||||
bool _isAppFrame(String line, String appPackage, String appRoot) {
|
||||
if (line.contains('packages/flutter/') || line.contains('/.pub-cache/') || line.contains('/flutter/bin/cache/')) {
|
||||
return false;
|
||||
}
|
||||
if (appPackage.isNotEmpty && line.contains('package:$appPackage/')) return true;
|
||||
if (appRoot.isNotEmpty && line.contains(appRoot)) return true;
|
||||
// A terse frame with a relative path (test/x_test.dart 12:3) is app code.
|
||||
return RegExp(r'^\S+\.dart\s+\d+').hasMatch(line.trimLeft()) && !RegExp(r'^(package|dart):').hasMatch(line.trimLeft());
|
||||
}
|
||||
|
||||
/// Strips the app root (with any file:// scheme) so paths read as test/....
|
||||
String _relative(String text, String appRoot) {
|
||||
if (appRoot.isEmpty) return text;
|
||||
return text.replaceAll('file://$appRoot/', '').replaceAll('$appRoot/', '');
|
||||
}
|
||||
|
||||
String _clip(String line) => line.length <= maxLineChars ? line : '${line.substring(0, maxLineChars)}...';
|
||||
|
||||
List<String> _readLines(String path) {
|
||||
final file = File(path);
|
||||
if (!file.existsSync()) return const [];
|
||||
return file.readAsLinesSync();
|
||||
}
|
||||
|
||||
String _appPackage() {
|
||||
final pubspec = File('pubspec.yaml');
|
||||
if (!pubspec.existsSync()) return '';
|
||||
return RegExp(r'^name:\s*(\S+)', multiLine: true).firstMatch(pubspec.readAsStringSync())?.group(1) ?? '';
|
||||
}
|
||||
|
||||
void main(List<String> args) {
|
||||
if (args.length != 6) {
|
||||
stderr.writeln('usage: summary.dart <exit> <peak MB> <seconds> <target> <log> <json>');
|
||||
exit(2);
|
||||
}
|
||||
final log = _readLines(args[4]);
|
||||
stdout.writeln(summarize(
|
||||
_readLines(args[5]),
|
||||
status: int.parse(args[0]),
|
||||
peakMb: int.parse(args[1]),
|
||||
seconds: int.parse(args[2]),
|
||||
target: args[3],
|
||||
logPath: args[4],
|
||||
jsonPath: args[5],
|
||||
logTail: log.length > 20 ? log.sublist(log.length - 20) : log,
|
||||
appPackage: _appPackage(),
|
||||
appRoot: Directory.current.path,
|
||||
));
|
||||
}
|
||||
@@ -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},
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -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':
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
/// Opt-in (`?usage=1`) size and reported token usage for the capture
|
||||
/// fixture's runs, shaped exactly as the server sends them: a run-level
|
||||
/// `usage` total (list and detail) and a per-step `usage`. Without the
|
||||
/// parameter the fixture keeps the old-server shape with neither.
|
||||
bool probeUsage = false;
|
||||
|
||||
/// Per-step usage of run 7, by recorded sequence. The build visit is mostly
|
||||
/// cache reads, as a caching harness reports; plan 1 predates the cache split.
|
||||
const _stepUsage = <int, JsonMap>{
|
||||
5: {
|
||||
'tokens_total': 1200000,
|
||||
'tokens_known': true,
|
||||
'split_known': true,
|
||||
'tokens_in': 300000,
|
||||
'tokens_out': 60000,
|
||||
'tokens_reasoning': 40000,
|
||||
'cache_read': 780000,
|
||||
'cache_write': 20000,
|
||||
'cache_known': true,
|
||||
'cost_known': true,
|
||||
},
|
||||
2: {
|
||||
'tokens_total': 20100000,
|
||||
'tokens_known': true,
|
||||
'split_known': true,
|
||||
'tokens_in': 500000,
|
||||
'tokens_out': 80000,
|
||||
'tokens_reasoning': 20000,
|
||||
'cache_read': 19480000,
|
||||
'cache_write': 20000,
|
||||
'cache_known': true,
|
||||
'cost_usd': 1.42,
|
||||
'cost_known': true,
|
||||
},
|
||||
1: {
|
||||
'tokens_total': 1100000,
|
||||
'tokens_known': true,
|
||||
'split_known': true,
|
||||
'tokens_in': 1000000,
|
||||
'tokens_out': 100000,
|
||||
'cache_known': true,
|
||||
'cache_read': 0,
|
||||
'cost_known': true,
|
||||
},
|
||||
};
|
||||
|
||||
/// Run 7's total over [_stepUsage], as the server's aggregate sums it.
|
||||
const _run7Usage = <String, dynamic>{
|
||||
'stages': 3,
|
||||
'tokens_total': 22400000,
|
||||
'tokens_known_stages': 3,
|
||||
'split_known': true,
|
||||
'tokens_in': 1800000,
|
||||
'tokens_out': 240000,
|
||||
'tokens_reasoning': 60000,
|
||||
'cache_read': 20260000,
|
||||
'cache_write': 40000,
|
||||
'cache_known': true,
|
||||
'cache_known_stages': 3,
|
||||
'cost_usd': 1.42,
|
||||
'cost_known_stages': 3,
|
||||
};
|
||||
|
||||
/// Run 6: one of its two stages reported no token count, so its total is a
|
||||
/// lower bound; no stage reported a positive cost.
|
||||
const _run6Usage = <String, dynamic>{
|
||||
'stages': 2,
|
||||
'tokens_total': 9100000,
|
||||
'tokens_known_stages': 1,
|
||||
'split_known': false,
|
||||
'split_unknown_stages': 1,
|
||||
'cost_known_stages': 1,
|
||||
'cost_unknown_stages': 1,
|
||||
};
|
||||
|
||||
/// Adds the run's size and usage to a list row or detail when enabled.
|
||||
JsonMap withProbeUsage(JsonMap run) {
|
||||
if (!probeUsage) return run;
|
||||
return switch (run['id']) {
|
||||
7 => {...run, 'size_bytes': 340 * 1024 * 1024, 'usage': _run7Usage},
|
||||
6 => {...run, 'size_bytes': 4404019, 'usage': _run6Usage},
|
||||
_ => run,
|
||||
};
|
||||
}
|
||||
|
||||
/// Adds the recorded per-step usage to run 7's steps when enabled.
|
||||
JsonMap withProbeStepUsage(JsonMap step) {
|
||||
final usage = _stepUsage[step['sequence']];
|
||||
return probeUsage && usage != null ? {...step, 'usage': usage} : step;
|
||||
}
|
||||
@@ -23,14 +23,18 @@ import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
||||
import 'package:pipelines_app/features/search/ui/search_bar_controls.dart'
|
||||
show searchFieldKey;
|
||||
import 'package:pipelines_app/ui/input/app_search_field.dart';
|
||||
import 'package:pipelines_app/ui/theme/app_font.dart';
|
||||
import 'package:pipelines_app/ui/theme/app_font_controller.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
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';
|
||||
import 'probe_usage_fixture.dart';
|
||||
|
||||
/// The run every run-scoped hit names. Its recorded sequences are deliberately
|
||||
/// not its row indexes (plan 5, build 2, plan 1), exactly like the unit
|
||||
@@ -72,6 +76,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',
|
||||
@@ -127,6 +138,10 @@ int _fillerStepCount = 0;
|
||||
/// capture shows its duration ticking. Absent by default.
|
||||
DateTime? _runningSince;
|
||||
|
||||
/// `?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++)
|
||||
{
|
||||
@@ -431,12 +446,28 @@ JsonMap? probeReply(JsonMap request) {
|
||||
'time': '2026-10-20T09:00:00Z',
|
||||
};
|
||||
case 'list_runs':
|
||||
return {'id': id, 'type': 'runs', 'runs': probeRuns(), 'usage': null};
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'runs',
|
||||
'runs': probeRuns().map(withProbeUsage).toList(),
|
||||
'usage': null,
|
||||
};
|
||||
case 'get_run':
|
||||
if (request['run_id'] != 7) {
|
||||
return error('Fixture run ${request['run_id']} is unavailable');
|
||||
}
|
||||
return {'id': id, 'type': 'run', 'run_detail': probeRunDetail()};
|
||||
final detail = withProbeUsage(probeRunDetail());
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'run',
|
||||
'run_detail': {
|
||||
...detail,
|
||||
'steps': [
|
||||
for (final step in detail['steps'] as List)
|
||||
withProbeStepUsage(step as JsonMap),
|
||||
],
|
||||
},
|
||||
};
|
||||
case 'list_pipelines':
|
||||
return {'id': id, 'type': 'pipelines', 'pipelines': probePipelines()};
|
||||
case 'get_pipeline':
|
||||
@@ -544,9 +575,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), () {
|
||||
@@ -601,6 +635,7 @@ class _FixtureSink implements WebSocketSink {
|
||||
/// `?runs=200` / `?steps=60` append filler runs / run-7 steps for scroll
|
||||
/// performance captures;
|
||||
/// `?running=1` adds an executing run 8 whose duration ticks;
|
||||
/// `?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);
|
||||
@@ -622,6 +657,13 @@ void main() {
|
||||
return;
|
||||
}
|
||||
configurePerfFixture(params);
|
||||
// `?font=inter` chooses a font as Settings would; otherwise the stored one.
|
||||
final font = params['font'];
|
||||
unawaited(
|
||||
font == null
|
||||
? AppFontController.instance.restore()
|
||||
: AppFontController.instance.select(AppFont.fromId(font)),
|
||||
);
|
||||
_fillerRunCount = int.tryParse(params['runs'] ?? '') ?? 0;
|
||||
_fillerStepCount = int.tryParse(params['steps'] ?? '') ?? 0;
|
||||
if (params['running'] == '1') {
|
||||
@@ -629,6 +671,8 @@ void main() {
|
||||
const Duration(minutes: 3, seconds: 50),
|
||||
);
|
||||
}
|
||||
probeUsage = params['usage'] == '1';
|
||||
_htmlArtifact = params['html'] == '1';
|
||||
final cupertino = params['platform'] == 'cupertino';
|
||||
final route = params['route'];
|
||||
final opensRoute = route != null && route.startsWith('/');
|
||||
|
||||
Reference in New Issue
Block a user