feat(app): wire saved schedules into the pipeline summary

This commit is contained in:
2026-10-22 00:41:55 +01:00
parent 2adecfff5e
commit ea2179cd66
22 changed files with 2381 additions and 11 deletions
+407
View File
@@ -0,0 +1,407 @@
import { createServer } from 'node:http';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { deepStrictEqual } from 'node:assert/strict';
// Real-browser acceptance for the pipeline Summary schedule section.
//
// flutter build web -t tool/schedule_pipeline_probe_app.dart \
// -o build/schedule_pipeline_probe_web
// OPENCODE_ARTIFACT_DIR=<dir> node tool/schedule_pipeline_probe.mjs
//
// The fake gateway and records are in-process; no Pipelines server,
// authentication or real schedule is contacted.
const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/schedule_pipeline_probe_web');
const output = process.env.OPENCODE_ARTIFACT_DIR;
if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(output, { recursive: true });
const chromePath = process.env.CHROME_PATH
?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.css': 'text/css; charset=utf-8',
'.otf': 'font/otf',
'.ttf': 'font/ttf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.bin': 'application/octet-stream',
};
const server = createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
const path = resolve(root, `.${pathname}`);
if (path !== root && !path.startsWith(root + sep)) {
return res.writeHead(403).end();
}
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
const file = await readFile(filePath);
res
.writeHead(200, {
'content-type': mime[extname(filePath)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
.end(file);
} catch {
res.writeHead(404).end('not found');
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = `http://127.0.0.1:${server.address().port}`;
const profile = await mkdtemp(join(tmpdir(), 's1-wire-chrome-'));
const chrome = spawn(chromePath, [
'--headless=new',
'--no-first-run',
'--no-default-browser-check',
'--disable-gpu',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
chrome.stderr.on('data', (data) => { stderr += data; });
const waitFor = async (fn, label, attempts = 220) => {
for (let i = 0; i < attempts; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`);
};
let ws;
try {
const endpoint = await waitFor(
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
'Chrome DevTools',
);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
const pageErrors = [];
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
pageErrors.push(message.params?.exceptionDetails?.exception?.description ?? 'page exception');
}
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
});
const send = (method, params = {}, sessionId) => new Promise((resolveCall) => {
const callId = ++id;
pending.set(callId, resolveCall);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: 'about:blank' });
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
const target = created.result.targetId;
const session = (
await send('Target.attachToTarget', { targetId: target, flatten: true })
).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
let width = 390;
let height = 844;
const evaluate = async (expression) => {
const response = await send(
'Runtime.evaluate',
{ expression, returnByValue: true, awaitPromise: true },
session,
);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
if (response.result?.exceptionDetails) {
throw new Error(`Runtime exception: ${JSON.stringify(response.result.exceptionDetails)}`);
}
return response.result?.result?.value;
};
const text = () => evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('[aria-label]')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
}
for (const el of document.querySelectorAll('flt-semantics')) {
if (!el.children.length && el.innerText) chunks.push(el.innerText);
}
for (const el of document.querySelectorAll('input, textarea')) {
if (el.getAttribute('aria-label')) chunks.push(el.getAttribute('aria-label') + '=' + el.value);
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const assertText = async (needle) => {
try {
await waitFor(async () => (await text()).includes(needle), `text ${JSON.stringify(needle)}`);
} catch (error) {
throw new Error(`${error.message}\nText now:\n${(await text()).slice(0, 4000)}`);
}
};
const assertNoText = async (needle) => {
if ((await text()).includes(needle)) {
throw new Error(`Unexpected text ${JSON.stringify(needle)}\n${(await text()).slice(0, 4000)}`);
}
};
const click = async (needle, { index = 0, optional = false } = {}) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(needle)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const matches = nodes.filter((x) => (x.getAttribute('aria-label') || '').trim() === wanted)
.concat(nodes.filter((x) => (x.innerText || '').trim() === wanted))
.concat(nodes.filter((x) => (x.getAttribute('aria-label') || x.innerText || '').trim().startsWith(wanted)));
const node = matches[${index}];
if (!node) return false;
node.click();
return true;
})()`);
if (!clicked && !optional) {
throw new Error(`Could not click ${JSON.stringify(needle)} #${index}\n${(await text()).slice(0, 4000)}`);
}
await delay(400);
return clicked;
};
const inputs = () => evaluate(`[...document.querySelectorAll('input,textarea')].map((el) => ({
label: el.getAttribute('aria-label') || '',
value: el.value,
disabled: el.disabled,
}))`);
const typeField = async (label, value) => {
const focused = await evaluate(`(() => {
const wanted = ${JSON.stringify(label)};
const el = [...document.querySelectorAll('input, textarea')].find((input) => {
const name = input.getAttribute('aria-label') || '';
return name === wanted || name.startsWith(wanted + '\\n');
});
if (!el) return false;
el.focus();
el.select?.();
el.setSelectionRange?.(0, (el.value || '').length);
return true;
})()`);
if (!focused) throw new Error(`No field ${JSON.stringify(label)}\n${(await text()).slice(0, 4000)}`);
await delay(250);
await send('Input.insertText', { text: value }, session);
await delay(350);
};
const state = () => evaluate('globalThis.schedulePipelineProbe ?? null');
const wheel = async (delta) => {
await send(
'Input.dispatchMouseEvent',
{ type: 'mouseWheel', x: Math.floor(width / 2), y: Math.floor(height / 2), deltaX: 0, deltaY: delta },
session,
);
await delay(450);
};
const captures = [];
const checks = [];
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const file = `${name}.png`;
await writeFile(join(output, file), Buffer.from(data, 'base64'));
captures.push({ name, file, width, height });
return file;
};
const load = async (query, nextWidth, nextHeight) => {
width = nextWidth;
height = nextHeight;
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
session,
);
const navigation = await send('Page.navigate', { url: `${origin}/?${query}` }, session);
if (navigation.error || navigation.result?.errorText) {
throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`);
}
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(1400);
};
const saveAtBottom = async () => {
await wheel(1800);
await click('Save schedule');
await delay(350);
};
// One host runs list -> new -> invalid -> valid save -> conflict -> retry,
// then pause and delete against the same fixture.
const runFlow = async (name, { host, brightness = 'platform', scale = 1, width: w, height: h }) => {
await load(
`host=${host}&scale=${scale}${brightness === 'dark' ? '&brightness=dark' : ''}`,
w,
h,
);
await assertText('Schedules (2)');
await assertText('Research batteries');
await assertText('Nightly report');
await assertText('Pinned v3 · Every 24h · mon, wed · Europe/London');
await assertText('Pinned v3 · 10:00, 18:30 · Server timezone');
await capture(`${name}-list`);
checks.push({ check: `${host} listed the pipeline schedules`, lists: (await state()).lists });
await click('Add schedule');
await assertText('Future runs only; does not publish or change the workflow.');
await capture(`${name}-editor`);
await saveAtBottom();
let fields = await inputs();
if (!fields.find((field) => field.label.startsWith('Name'))?.label.includes('Enter a schedule name.')) {
throw new Error(`Name error missing: ${JSON.stringify(fields)}`);
}
if (!fields.find((field) => field.label.startsWith('Prompt'))?.label.includes('Enter a prompt.')) {
throw new Error(`Prompt error missing: ${JSON.stringify(fields)}`);
}
if ((await state()).saves !== 0) throw new Error('Invalid form sent a save');
await wheel(-2200);
await capture(`${name}-invalid`);
checks.push({ check: `${host} invalid fields sent nothing`, saves: (await state()).saves });
await typeField('Name', 'Probe schedule');
await typeField('Prompt', 'Summarise the release notes.');
await saveAtBottom();
await waitFor(async () => (await state()).saves === 1, 'the accepted create');
await assertText('Schedules (3)');
await assertText('Probe schedule');
const created = await state();
if (created.lastSaved?.id !== 0
|| created.lastSaved?.pipeline_id !== 4
|| created.lastSaved?.version !== 3
|| created.lastSaved?.workspace !== '/srv/research'
|| created.lastSaved?.name !== 'Probe schedule') {
throw new Error(`Create record drifted: ${JSON.stringify(created.lastSaved)}`);
}
if (typeof created.lastRequestKey !== 'string' || !created.lastRequestKey) {
throw new Error(`Create request key missing: ${JSON.stringify(created.lastRequestKey)}`);
}
await capture(`${name}-created`);
checks.push({
check: `${host} create sent the pinned, workspace-seeded record with one key and refreshed`,
saves: created.saves,
requestKey: created.lastRequestKey,
record: created.lastSaved,
rows: created.rows,
});
// First edit is refused; the draft and the server's reason stay visible.
await click('Edit');
await assertText('Edit schedule');
await typeField('Name', 'Edited schedule');
await saveAtBottom();
await assertText('conflict: revision 3 is stale');
await assertText('Your draft is preserved.');
fields = await inputs();
if (fields.find((field) => field.label.startsWith('Name'))?.value !== 'Edited schedule') {
throw new Error(`Conflict lost the draft: ${JSON.stringify(fields)}`);
}
if ((await state()).saves !== 2) throw new Error('Conflict retried without the operator');
await capture(`${name}-conflict`);
checks.push({
check: `${host} conflict kept the draft and showed the server words`,
saves: (await state()).saves,
lastSaved: (await state()).lastSaved,
});
await saveAtBottom();
await waitFor(async () => (await state()).saves === 3, 'the accepted edit');
await assertText('Edited schedule');
await assertText('Schedules (3)');
checks.push({ check: `${host} accepted edit refreshed the list`, saves: (await state()).saves });
// Pause sends only the enabled flip and the loaded revision.
const beforePause = (await state()).rows.find((row) => row.name === 'Edited schedule');
await click('Pause');
await waitFor(async () => (await state()).saves === 4, 'the accepted pause');
const pause = (await state()).lastSaved;
if (pause?.enabled !== false || pause?.id !== beforePause.id || pause?.revision !== beforePause.revision) {
throw new Error(`Pause payload drifted: ${JSON.stringify(pause)} vs ${JSON.stringify(beforePause)}`);
}
await assertText('Enable');
checks.push({ check: `${host} pause sent only enabled with the loaded revision`, pause });
// Delete confirms once, then sends the exact id + expected revision.
await click('Delete');
await assertText('Delete Edited schedule?');
await assertText('Future runs only. Run history and active runs will not be deleted.');
await click('Keep schedule');
if ((await state()).deletes !== 0) throw new Error('Keep deleted a schedule');
await assertText('Edited schedule');
await assertNoText('Delete Edited schedule?');
await click('Delete');
await click('Delete schedule');
await waitFor(async () => (await state()).deletes === 1, 'the accepted delete');
const deleted = (await state()).lastDeleted;
if (deleted?.schedule_id !== beforePause.id || typeof deleted?.expected_revision !== 'number') {
throw new Error(`Delete payload drifted: ${JSON.stringify(deleted)}`);
}
await assertText('Schedules (2)');
await assertNoText('Edited schedule');
checks.push({ check: `${host} delete confirmed and sent id + revision`, deleted });
};
await runFlow('s1w-material-390', { host: 'material', width: 390, height: 844 });
await runFlow('s1w-cupertino-dark-390', {
host: 'cupertino',
brightness: 'dark',
width: 390,
height: 844,
});
// Narrow phone at 2x text on the material host.
await load('host=material&scale=2', 320, 844);
await assertText('Schedules (2)');
await capture('s1w-material-320-2x-list');
await click('Add schedule');
await assertText('Future runs only; does not publish or change the workflow.');
await capture('s1w-material-320-2x-editor-top');
await wheel(2000);
await capture('s1w-material-320-2x-editor-bottom');
await assertText('Save schedule');
checks.push({ check: '320px at 2x kept the section and editor usable', width: 320, scale: 2 });
if (pageErrors.length) throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`);
const manifest = {
url: origin,
fixture: 'tool/schedule_pipeline_probe_app.dart',
output,
checks,
captures,
};
await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2));
console.log(JSON.stringify(manifest, null, 2));
} finally {
ws?.close();
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
server.close();
await rm(profile, { recursive: true, force: true });
}
+208
View File
@@ -0,0 +1,208 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/schedules/ui/pipeline/schedule_pipeline_section.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
/// Isolated browser fixture for the pipeline Summary schedule section.
///
/// flutter build web -t tool/schedule_pipeline_probe_app.dart
///
/// Query: `host=cupertino`, `brightness=dark`, `scale=2`. The fake gateway keeps
/// its schedules in memory, accepts one create, refuses the first edit with a
/// stale revision, then accepts the retry. It never opens a socket or contacts a
/// real server. State is published at `globalThis.schedulePipelineProbe`.
void main() => runApp(const _ProbeApp());
class _Refusal implements Exception {
const _Refusal();
@override
String toString() => 'conflict: revision 3 is stale';
}
class _ProbeApp extends StatelessWidget {
const _ProbeApp();
@override
Widget build(BuildContext context) {
final parameters = Uri.base.queryParameters;
final cupertino = parameters['host'] == 'cupertino';
final dark = parameters['brightness'] == 'dark';
final scale = double.tryParse(parameters['scale'] ?? '') ?? 1.0;
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: app!,
);
final gateway = _FixtureGateway();
final section = SchedulePipelineSection(
gateway: gateway,
pipelineId: 4,
version: 3,
settingsStore: MemorySettingsStore(workspace: '/srv/research'),
);
final body = SafeArea(
child: ListView(children: [section, const SizedBox(height: 24)]),
);
if (cupertino) {
return CupertinoApp(
debugShowCheckedModeBanner: false,
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
builder: media,
home: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Alpha review'),
),
child: body,
),
);
}
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
platform: TargetPlatform.android,
),
builder: media,
home: Scaffold(
appBar: AppBar(title: const Text('Alpha review')),
body: body,
),
);
}
}
class _FixtureGateway implements ApiGateway {
_FixtureGateway() {
_publish();
}
final List<Map<String, dynamic>> _rows = [
{
'id': 8,
'revision': 3,
'name': 'Research batteries',
'pipeline_id': 4,
'version': 3,
'enabled': true,
'input': {'prompt': 'Find battery chemistry sources'},
'workspace': '/srv/research',
'rule': {
'every': '24h',
'days': ['mon', 'wed'],
'timezone': 'Europe/London',
},
'next_due': '2026-10-22T09:00:00Z',
},
{
'id': 9,
'revision': 1,
'name': 'Nightly report',
'pipeline_id': 4,
'version': 3,
'enabled': false,
'input': {'prompt': 'Summarise the open issues'},
'workspace': '/srv/reports',
'rule': {
'times': ['10:00', '18:30'],
'days': <String>[],
'timezone': 'Local',
},
},
];
int _nextId = 10;
int _lists = 0;
int _saves = 0;
int _deletes = 0;
bool _refuseEdit = true;
JsonMap? _lastSaved;
JsonMap? _lastDeleted;
String? _lastRequestKey;
void _publish() {
globalContext.setProperty(
'schedulePipelineProbe'.toJS,
<String, Object?>{
'lists': _lists,
'saves': _saves,
'deletes': _deletes,
'lastSaved': _lastSaved,
'lastDeleted': _lastDeleted,
'lastRequestKey': _lastRequestKey,
'rows': [
for (final row in _rows)
{
'id': row['id'],
'revision': row['revision'],
'name': row['name'],
'enabled': row['enabled'],
},
],
}.jsify(),
);
}
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
switch (type) {
case 'list_schedules':
_lists++;
_publish();
return {
'type': 'schedules',
'schedules': [
for (final row in _rows) Map<String, dynamic>.from(row),
],
};
case 'save_schedule':
_saves++;
final sent = Map<String, dynamic>.from(fields['schedule'] as Map);
_lastSaved = sent;
_lastRequestKey = fields['request_key'] as String?;
if (sent['id'] == 0) {
final stored = {
...sent,
'id': _nextId++,
'revision': 1,
'next_due': '2026-10-23T09:00:00Z',
};
_rows.add(stored);
_publish();
return {'type': 'schedule', 'schedule': stored};
}
if (_refuseEdit && sent['id'] == 8) {
_refuseEdit = false;
_publish();
throw const _Refusal();
}
final index = _rows.indexWhere((row) => row['id'] == sent['id']);
final stored = {
...sent,
'revision': (sent['revision'] as int) + 1,
'next_due': sent['enabled'] == true ? '2026-10-23T09:00:00Z' : null,
};
if (index >= 0) _rows[index] = stored;
_publish();
return {'type': 'schedule', 'schedule': stored};
case 'delete_schedule':
_deletes++;
final id = fields['schedule_id'];
_lastDeleted = Map<String, dynamic>.from(fields);
_rows.removeWhere((row) => row['id'] == id);
_publish();
return {'type': 'schedule_deleted', 'schedule_id': id};
default:
throw StateError('unexpected $type');
}
}
@override
Stream<JsonMap> get frames => const Stream.empty();
}