merge(app): expose native run rename in live details

This commit is contained in:
2026-10-21 19:23:56 +01:00
11 changed files with 973 additions and 8 deletions
+6 -1
View File
@@ -106,7 +106,12 @@ class _RunsScreenState extends State<RunsScreen> {
child: RunsList(controller: controller, onSelected: _select), child: RunsList(controller: controller, onSelected: _select),
), ),
), ),
if (selected) RunDetailView(controller: controller, onBack: _back), if (selected)
RunDetailView(
controller: controller,
gateway: widget.gateway,
onBack: _back,
),
], ],
); );
} }
@@ -10,6 +10,7 @@ import 'run_detail_content.dart';
Widget buildCupertinoRunDetail({ Widget buildCupertinoRunDetail({
required BuildContext context, required BuildContext context,
required JsonMap run, required JsonMap run,
required Widget titleAction,
required bool detailLoading, required bool detailLoading,
required String? error, required String? error,
required bool copying, required bool copying,
@@ -60,6 +61,13 @@ Widget buildCupertinoRunDetail({
], ],
), ),
), ),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: titleAction,
),
),
if (detailLoading) const _CupertinoNotice('Refreshing run details…'), if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
if (error != null) _CupertinoNotice(error), if (error != null) _CupertinoNotice(error),
if (prompt != null) if (prompt != null)
@@ -8,6 +8,7 @@ import 'run_detail_content.dart';
Widget buildMaterialRunDetail({ Widget buildMaterialRunDetail({
required BuildContext context, required BuildContext context,
required JsonMap run, required JsonMap run,
required Widget titleAction,
required bool detailLoading, required bool detailLoading,
required String? error, required String? error,
required bool copying, required bool copying,
@@ -41,6 +42,7 @@ Widget buildMaterialRunDetail({
Chip(label: Text(runStatusLabel(run))), Chip(label: Text(runStatusLabel(run))),
Text('Run ${run['id']}'), Text('Run ${run['id']}'),
Text('Pipeline ${detailPipeline(run)}'), Text('Pipeline ${detailPipeline(run)}'),
titleAction,
], ],
), ),
if (detailLoading) const _Notice('Refreshing run details…'), if (detailLoading) const _Notice('Refreshing run details…'),
@@ -2,7 +2,9 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart'; import '../../../ui/adaptive/host.dart';
import '../actions/title_action.dart';
import 'run_detail_content.dart'; import 'run_detail_content.dart';
import 'run_detail_cupertino.dart'; import 'run_detail_cupertino.dart';
import 'run_detail_material.dart'; import 'run_detail_material.dart';
@@ -12,10 +14,14 @@ class RunDetailView extends StatefulWidget {
const RunDetailView({ const RunDetailView({
super.key, super.key,
required this.controller, required this.controller,
required this.gateway,
required this.onBack, required this.onBack,
}); });
final RunsController controller; final RunsController controller;
/// The app's shared gateway; the rename action sends through it.
final ApiGateway gateway;
final VoidCallback onBack; final VoidCallback onBack;
@override @override
@@ -34,10 +40,16 @@ class _RunDetailViewState extends State<RunDetailView> {
final run = widget.controller.detail; final run = widget.controller.detail;
if (run == null) return _placeholder(context, cupertino: cupertino); if (run == null) return _placeholder(context, cupertino: cupertino);
final prompt = detailPrompt(run); final prompt = detailPrompt(run);
final titleAction = RunTitleAction(
run: run,
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
);
return cupertino return cupertino
? buildCupertinoRunDetail( ? buildCupertinoRunDetail(
context: context, context: context,
run: run, run: run,
titleAction: titleAction,
detailLoading: widget.controller.detailLoading, detailLoading: widget.controller.detailLoading,
error: widget.controller.error, error: widget.controller.error,
copying: _copying, copying: _copying,
@@ -48,6 +60,7 @@ class _RunDetailViewState extends State<RunDetailView> {
: buildMaterialRunDetail( : buildMaterialRunDetail(
context: context, context: context,
run: run, run: run,
titleAction: titleAction,
detailLoading: widget.controller.detailLoading, detailLoading: widget.controller.detailLoading,
error: widget.controller.error, error: widget.controller.error,
copying: _copying, copying: _copying,
@@ -104,6 +104,27 @@ class RunsController extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
/// Folds the server's accepted run detail into the open detail and the
/// matching list row, mirroring the web's `applyRunTitle`.
///
/// A reply for a run that is no longer selected never replaces the open
/// detail; no title or other field is invented locally.
void acceptRunDetail(JsonMap run) {
final id = run['id'];
if (id == null) return;
var changed = false;
if (detail?['id'] == id) {
detail = run;
changed = true;
}
final index = runs.indexWhere((row) => row['id'] == id);
if (index >= 0) {
runs = [...runs]..[index] = {...runs[index], 'title': run['title'] ?? ''};
changed = true;
}
if (changed) notifyListeners();
}
void setQuery(String value) { void setQuery(String value) {
query = value; query = value;
notifyListeners(); notifyListeners();
+94
View File
@@ -0,0 +1,94 @@
# R2 — title wiring into the real run detail
## Result
The already-landed `RunTitleAction` is now rendered by the real run detail under
both native hosts, and its accepted server `run_detail` is folded into the open
detail and the matching list row through `RunsController`. Nothing is sent while
typing or on Cancel, nothing is applied before the server replies, and a stale
reply cannot replace another selected run.
No server, shell, pubspec, main, dialog, repository or protocol file changed.
The action, wording and gateway are reused exactly as landed in R2d.
## Files
| File | Change |
| --- | --- |
| `lib/features/runs/screen.dart` | Passes the app's shared `ApiGateway` into `RunDetailView` |
| `lib/features/runs/ui/run_detail_view.dart` | Builds `RunTitleAction` from the current server detail; folds accepted replies through `controller.acceptRunDetail` |
| `lib/features/runs/ui/run_detail_material.dart` | Adds the action to the existing title/identity `Wrap` |
| `lib/features/runs/ui/run_detail_cupertino.dart` | Adds the action as its own native row below the title block |
| `lib/features/runs/ui/runs_controller.dart` | `acceptRunDetail`: replaces the open detail only for the selected id, updates only the matching list row's server title |
| `test/features/runs/ui/run_title_wiring_test.dart` | New: both hosts, exact Save payload, Cancel, refusal, no optimistic title |
| `test/features/runs/ui/runs_controller_test.dart` | Stale accepted reply cannot replace another run; list fold preserves other fields |
| `test/features/runs/ui/run_detail_widget_test.dart` | Existing detail tests supply the gateway |
| `tool/title_wiring_probe.dart` | Real-composition browser entrypoint |
| `tool/title_wiring_probe.mjs` | Isolated loopback protocol fixture + Chrome driver |
Production diff: 5 files, about 51 added lines and 2 replaced lines.
## Behaviour
- Material detail: `Rename` is an `OutlinedButton` inside the existing identity
`Wrap`. Cupertino detail: a `CupertinoButton` in its own row, so it remains a
separate semantics node instead of merging into the title block.
- Opening the prompt sends nothing. The prompt is seeded from
`storedRunTitle(run)`, never the prompt/output fallback.
- Save sends exactly `set_run_title {"run_id": <id>, "title": <typed text>}`
through `RunsRepository.setRunTitle`, i.e. the one shared gateway.
- Cancel sends nothing. A refusal keeps the prompt open with the typed title and
the server's words verbatim; the stored detail is unchanged.
- Only the returned `run_detail` is delivered. `RunsController.acceptRunDetail`
ignores a map without an id, replaces `detail` only when its id matches, and
updates only that list row's `title` (web `applyRunTitle` behaviour) while
preserving row fields such as `name`/`status`. A late reply for run A while
run B is selected updates A's list row but never B's detail.
## Checks actually run
```
flutter pub get
dart format lib/features/runs test/features/runs/ui/...
flutter test test/features/runs/ui/run_title_wiring_test.dart \
test/features/runs/ui/runs_controller_test.dart \
test/features/runs/ui/run_detail_widget_test.dart # 26 passed
flutter analyze # No issues found!
flutter test # 544 passed
flutter build web # Built build/web
flutter build web --target=tool/title_wiring_probe.dart \
-o build/title_probe_web # Built
OPENCODE_ARTIFACT_DIR=... node tool/title_wiring_probe.mjs \
build/title_probe_web # ok: true
```
Browser probe (real bundle, isolated loopback websocket fixture, 390×844):
- Cupertino detail shows `Rename`; the prompt seeds `Run title` with
`Fixture live run` (DOM field value).
- Cancel after typing `Discarded title` sent no `set_run_title`, left the stored
title visible, and closed the prompt.
- Cupertino Save sent exactly `{run_id: 1, title: "Cupertino renamed run"}`; the
returned server detail replaced the title in the detail and in the list row.
- Material host (Linux UA reload, same deep link `/runs/1`) seeded from the
current server title and Save sent exactly
`{run_id: 1, title: "Material renamed run"}`.
- Seven PNG captures, OCR-checked for the visible title:
`/Users/alan/.local/share/pipelines/data/artifacts/68/public/r2-title-wire/`
(`r2-title-cupertino-detail.png`, `-dialog`, `-cancelled`, `-renamed`,
`-list`, `r2-title-material-dialog.png`, `r2-title-material-renamed.png`).
## Integration note for the parallel Changes lane
Run 67 adds a Changes button to `run_detail_material.dart` and
`run_detail_cupertino.dart`. This change adds a `titleAction` parameter and one
insertion in each file. When merging main, keep both: the title action and the
Changes button are independent additions to the same detail bodies.
## Honest limits
- Mobile (Android/iOS) is unverified: no device, emulator, ADB or mobile build
was used. Source uses portable Material/Cupertino widgets only.
- No real Pipelines server or operator run was touched. The browser probe used
an isolated loopback fixture, not production data or credentials.
- Nothing was committed, pushed, merged to main or deployed.
@@ -75,7 +75,8 @@ JsonMap usageFixture({int known = 1}) => {
Future<void> pumpDetail( Future<void> pumpDetail(
WidgetTester tester, WidgetTester tester,
AppPlatform platform, AppPlatform platform,
RunsController controller, { RunsController controller,
FakeGateway gateway, {
VoidCallback? onBack, VoidCallback? onBack,
bool settle = true, bool settle = true,
}) async { }) async {
@@ -83,7 +84,11 @@ Future<void> pumpDetail(
tester.view.devicePixelRatio = 1; tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.view.resetDevicePixelRatio);
final view = RunDetailView(controller: controller, onBack: onBack ?? () {}); final view = RunDetailView(
controller: controller,
gateway: gateway,
onBack: onBack ?? () {},
);
final page = MediaQuery( final page = MediaQuery(
data: MediaQueryData.fromView( data: MediaQueryData.fromView(
tester.view, tester.view,
@@ -142,7 +147,7 @@ void main() {
testWidgets('${platform.name} detail at 390 with 2x text', (tester) async { testWidgets('${platform.name} detail at 390 with 2x text', (tester) async {
gateway.detail = runFixture(steps: 12); gateway.detail = runFixture(steps: 12);
await controller.select(1); await controller.select(1);
await pumpDetail(tester, platform, controller); await pumpDetail(tester, platform, controller, gateway);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
expect(find.text('Nightly build'), findsOneWidget); expect(find.text('Nightly build'), findsOneWidget);
expect(find.textContaining('Original prompt'), findsOneWidget); expect(find.textContaining('Original prompt'), findsOneWidget);
@@ -192,7 +197,7 @@ void main() {
) async { ) async {
gateway.hold = Completer<JsonMap>(); gateway.hold = Completer<JsonMap>();
final pending = controller.select(1); final pending = controller.select(1);
await pumpDetail(tester, platform, controller, settle: false); await pumpDetail(tester, platform, controller, gateway, settle: false);
expect(find.text('Loading run details…'), findsOneWidget); expect(find.text('Loading run details…'), findsOneWidget);
expect( expect(
find.byType( find.byType(
@@ -213,7 +218,13 @@ void main() {
controller = RunsController(RunsRepository(gateway)); controller = RunsController(RunsRepository(gateway));
await controller.select(1); await controller.select(1);
var backs = 0; var backs = 0;
await pumpDetail(tester, platform, controller, onBack: () => backs++); await pumpDetail(
tester,
platform,
controller,
gateway,
onBack: () => backs++,
);
expect(find.textContaining('server unavailable'), findsOneWidget); expect(find.textContaining('server unavailable'), findsOneWidget);
await tester.tap(find.text('Back to list')); await tester.tap(find.text('Back to list'));
expect(backs, 1); expect(backs, 1);
@@ -229,7 +240,7 @@ void main() {
? find.byTooltip('Copy prompt') ? find.byTooltip('Copy prompt')
: find.text('Copy prompt'); : find.text('Copy prompt');
await controller.select(1); await controller.select(1);
await pumpDetail(tester, platform, controller); await pumpDetail(tester, platform, controller, gateway);
await tester.tap(copy); await tester.tap(copy);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(copied.single, prompt); expect(copied.single, prompt);
@@ -248,7 +259,7 @@ void main() {
testWidgets('reported zero and missing usage stay distinct', (tester) async { testWidgets('reported zero and missing usage stay distinct', (tester) async {
gateway.detail = runFixture(usage: usageFixture()); gateway.detail = runFixture(usage: usageFixture());
await controller.select(1); await controller.select(1);
await pumpDetail(tester, AppPlatform.material, controller); await pumpDetail(tester, AppPlatform.material, controller, gateway);
await tester.tap(find.text('Metrics')); await tester.tap(find.text('Metrics'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Unavailable'), findsNothing); expect(find.text('Unavailable'), findsNothing);
@@ -0,0 +1,182 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
import 'package:pipelines_app/features/runs/screen.dart';
JsonMap _run(int id, String title) => {
'id': id,
'title': title,
'name': 'fixture',
'status': 'running',
};
JsonMap _detail(int id, String title) => {
..._run(id, title),
'input': {'prompt': 'the stored prompt'},
'steps': const [],
};
/// Records the exact rename request and answers only when the test releases it,
/// so an optimistic title would be visible before the server reply.
class _Gateway implements ApiGateway {
final framesController = StreamController<JsonMap>.broadcast();
final saves = <({JsonMap fields, Completer<JsonMap> reply})>[];
final titles = {1: 'Nightly build', 2: 'Other run'};
@override
Stream<JsonMap> get frames => framesController.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
switch (type) {
case 'list_runs':
return Future.value({
'runs': [
for (final entry in titles.entries) _run(entry.key, entry.value),
],
});
case 'get_run':
final id = (fields['run_id'] as num).toInt();
return Future.value({'run_detail': _detail(id, titles[id]!)});
case 'set_run_title':
final reply = Completer<JsonMap>();
saves.add((fields: Map<String, dynamic>.from(fields), reply: reply));
return reply.future;
}
return Future.error(UnsupportedError(type));
}
void accept(String title) {
final save = saves.removeAt(0);
final id = (save.fields['run_id'] as num).toInt();
titles[id] = title;
save.reply.complete({'run_detail': _detail(id, title)});
}
void refuse(Object error) => saves.removeAt(0).reply.completeError(error);
}
Future<_Gateway> _mount(
WidgetTester tester, {
required bool cupertino,
int initialRunId = 1,
}) async {
final gateway = _Gateway();
final screen = RunsScreen(gateway: gateway, initialRunId: initialRunId);
await tester.pumpWidget(
cupertino
? CupertinoApp(
home: CupertinoPageScaffold(child: SafeArea(child: screen)),
)
: MaterialApp(home: Scaffold(body: screen)),
);
await tester.pumpAndSettle();
return gateway;
}
String _fieldText(WidgetTester tester, {required bool cupertino}) => cupertino
? tester
.widget<CupertinoTextField>(find.byKey(runTitleFieldKey))
.controller!
.text
: tester.widget<TextField>(find.byKey(runTitleFieldKey)).controller!.text;
void main() {
testWidgets('material detail renames through the shared gateway and folds '
'only the server reply into the detail and list', (tester) async {
final gateway = await _mount(tester, cupertino: false);
expect(find.text('Nightly build'), findsOneWidget);
expect(find.byKey(runTitleActionKey), findsOneWidget);
expect(find.byType(OutlinedButton), findsOneWidget);
expect(gateway.saves, isEmpty);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(_fieldText(tester, cupertino: false), 'Nightly build');
await tester.enterText(find.byKey(runTitleFieldKey), 'Draft only');
await tester.pump();
expect(gateway.saves, isEmpty);
await tester.tap(find.byKey(runTitleCancelKey));
await tester.pumpAndSettle();
expect(gateway.saves, isEmpty);
expect(find.text('Nightly build'), findsOneWidget);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(runTitleFieldKey), ' Release build ');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pump();
expect(gateway.saves.single.fields, {
'run_id': 1,
'title': ' Release build ',
});
// Still the stored title: nothing is applied before the server replies.
expect(find.text('Nightly build'), findsOneWidget);
expect(find.text('Release build'), findsNothing);
gateway.accept('Release build');
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.text('Release build'), findsOneWidget);
expect(find.text('Nightly build'), findsNothing);
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(find.text('Release build'), findsOneWidget);
});
testWidgets('cupertino detail shows the native rename entry point', (
tester,
) async {
final gateway = await _mount(tester, cupertino: true);
expect(find.byKey(runTitleActionKey), findsOneWidget);
expect(find.byType(OutlinedButton), findsNothing);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
await tester.enterText(find.byKey(runTitleFieldKey), 'Release build');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pump();
expect(gateway.saves.single.fields, {
'run_id': 1,
'title': 'Release build',
});
gateway.accept('Release build');
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsNothing);
expect(find.text('Release build'), findsOneWidget);
});
testWidgets('a refused rename keeps the typed title and the stored detail', (
tester,
) async {
final gateway = await _mount(tester, cupertino: false);
await tester.tap(find.byKey(runTitleActionKey));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(runTitleFieldKey), ' locked ');
await tester.tap(find.byKey(runTitleSaveKey));
await tester.pump();
gateway.refuse(const ProtocolError('rename refused by the server'));
await tester.pumpAndSettle();
expect(find.text('rename refused by the server'), findsOneWidget);
expect(_fieldText(tester, cupertino: false), ' locked ');
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('Nightly build'), findsOneWidget);
});
}
@@ -341,4 +341,43 @@ void main() {
await Future<void>.delayed(Duration.zero); await Future<void>.delayed(Duration.zero);
expect(controller.detail?['id'], 1); expect(controller.detail?['id'], 1);
}); });
test(
'an accepted rename folds into the selected detail and its list row',
() async {
final load = controller.load();
gateway.listReply(0, [
{'id': 1, 'title': 'Old title', 'status': 'running', 'name': 'one'},
{'id': 2, 'title': 'Other run', 'status': 'running'},
]);
await load;
final first = controller.select(1);
gateway.detailReply(1, 0, {
'id': 1,
'title': 'Old title',
'input': {'prompt': 'stored'},
});
await first;
controller.acceptRunDetail({
'id': 1,
'title': 'Renamed',
'status': 'succeeded',
});
expect(controller.detail?['title'], 'Renamed');
expect(controller.runs.first['title'], 'Renamed');
expect(controller.runs.first['name'], 'one');
expect(controller.runs[1]['title'], 'Other run');
final second = controller.select(2);
gateway.detailReply(2, 0, {'id': 2, 'title': 'Other run'});
await second;
controller.acceptRunDetail({'id': 1, 'title': 'Late rename'});
expect(controller.detail?['id'], 2);
expect(controller.detail?['title'], 'Other run');
expect(controller.runs.first['title'], 'Late rename');
},
);
} }
+8
View File
@@ -0,0 +1,8 @@
import 'package:pipelines_app/application/bootstrap.dart';
/// Browser acceptance entrypoint for the run-title wiring probe.
///
/// This is the normal app composition; the deterministic run detail and rename
/// replies come from the isolated loopback fixture in
/// `tool/title_wiring_probe.mjs`, never from app-side fake data.
void main() => runPipelinesApp();
+582
View File
@@ -0,0 +1,582 @@
import { spawn, execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, mkdir, rm, writeFile, readFile, realpath, stat } from 'node:fs/promises';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import { extname, join, resolve, sep } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
// Real-browser acceptance for the run title wiring.
//
// Usage (from app/):
// flutter build web --target=tool/title_wiring_probe.dart -o build/title_probe_web
// OPENCODE_ARTIFACT_DIR=<dir> node tool/title_wiring_probe.mjs build/title_probe_web
//
// The fixture serves the real bundle over loopback and answers the same
// websocket protocol as the app server: one run, `get_run`, and
// `set_run_title`. It records the exact rename payload and returns the stored
// run detail. Requires Google Chrome and Tesseract (OCR checks cover the
// canvas-rendered titles).
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 root = await realpath(process.argv[2] ?? 'build/title_probe_web');
const RUN = {
id: 1,
title: 'Fixture live run',
name: 'fixture-live',
status: 'running',
created_at: '2026-10-21T12:00:00Z',
};
let storedTitle = RUN.title;
const renames = [];
const counters = { listRuns: 0, getRun: 0 };
function runRow() {
return { ...RUN, title: storedTitle };
}
function runDetail() {
return {
...runRow(),
input: { prompt: ' fixture prompt with spaces ' },
output: { answer: 42 },
steps: [
{ stage: 'build', sequence: 3, status: 'completed', outcome: 'success' },
],
};
}
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
function accept(key) {
return createHash('sha1')
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
.digest('base64');
}
function frame(opcode, payload) {
const length = payload.length;
let header;
if (length < 126) {
header = Buffer.from([0x80 | opcode, length]);
} else if (length < 65536) {
header = Buffer.alloc(4);
header[0] = 0x80 | opcode;
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[0] = 0x80 | opcode;
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
return Buffer.concat([header, payload]);
}
class Connection {
constructor(socket) {
this.socket = socket;
this.buffer = Buffer.alloc(0);
}
push(chunk) {
if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= 2) {
const first = this.buffer[0];
const second = this.buffer[1];
const opcode = first & 0x0f;
let length = second & 0x7f;
let offset = 2;
if (length === 126) {
if (this.buffer.length < 4) return;
length = this.buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (this.buffer.length < 10) return;
length = Number(this.buffer.readBigUInt64BE(2));
offset = 10;
}
const masked = (second & 0x80) !== 0;
const maskOffset = offset;
if (masked) {
if (this.buffer.length < offset + 4) return;
offset += 4;
}
if (this.buffer.length < offset + length) return;
let payload = Buffer.from(this.buffer.subarray(offset, offset + length));
if (masked) {
const mask = this.buffer.subarray(maskOffset, maskOffset + 4);
for (let index = 0; index < payload.length; index++) {
payload[index] ^= mask[index % 4];
}
}
this.buffer = this.buffer.subarray(offset + length);
if (opcode === 0x8) return this.close();
if (opcode === 0x9) {
this.socket.write(frame(0x0a, payload));
continue;
}
if (opcode !== 0x1) continue;
let request;
try {
request = JSON.parse(payload.toString('utf8'));
} catch {
continue;
}
this.message(request);
}
}
message(request) {
if (request.type === 'subscribe' || request.type === 'unsubscribe') return;
if (request.type === 'ping') {
this.send({ id: request.id, type: 'pong', build: { version: 'Title fixture' } });
return;
}
if (request.type === 'list_runs') {
counters.listRuns++;
this.send({ id: request.id, type: 'runs', runs: [runRow()], usage: null });
return;
}
if (request.type === 'get_run') {
counters.getRun++;
this.send({ id: request.id, type: 'run', run_detail: runDetail() });
return;
}
if (request.type === 'set_run_title') {
renames.push({ run_id: request.run_id, title: request.title });
storedTitle = request.title;
this.send({ id: request.id, type: 'run', run_detail: runDetail() });
return;
}
this.send({
id: request.id,
type: 'error',
error: `Fixture does not implement ${request.type}`,
});
}
send(value) {
if (!this.socket.destroyed) {
this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value))));
}
}
close() {
if (!this.socket.destroyed) this.socket.end();
}
}
async function staticFile(base, pathname, res) {
let file = resolve(base, `.${pathname}`);
if (file !== base && !file.startsWith(base + sep)) {
res.writeHead(403).end();
return;
}
try {
if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
} catch {
if (extname(pathname)) {
res.writeHead(404).end('not found');
return;
}
file = join(base, 'index.html');
}
try {
const body = await readFile(file);
res
.writeHead(200, {
'content-type': MIME[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
.end(body);
} catch {
res.writeHead(404).end('not found');
}
}
const sockets = new Set();
const server = createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://fixture').pathname;
if (pathname === '/fixture/state') {
res
.writeHead(200, { 'content-type': 'application/json' })
.end(JSON.stringify({ storedTitle, renames, ...counters }));
return;
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405).end();
return;
}
await staticFile(root, pathname, res);
});
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url, 'http://fixture');
if (
url.pathname !== '/connect' ||
req.headers.upgrade?.toLowerCase() !== 'websocket' ||
!req.headers['sec-websocket-key']
) {
socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
return;
}
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`,
);
const connection = new Connection(socket);
socket.on('data', (chunk) => connection.push(chunk));
socket.on('error', () => socket.destroy());
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
connection.push(head);
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const fixtureUrl = `http://127.0.0.1:${server.address().port}`;
const profile = await mkdtemp(join(tmpdir(), 'r2-title-chrome-'));
const chrome = spawn(
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
[
'--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;
});
async function waitFor(check, label, attempts = 160) {
for (let attempt = 0; attempt < attempts; attempt++) {
const value = await check();
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();
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails));
}
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 target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
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(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`);
}
return response.result?.result?.value;
};
const enableSemantics = async () => {
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'Flutter semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(700);
};
const semanticText = () =>
evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('flt-semantics')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
const value = el.getAttribute('aria-valuetext');
if (value) chunks.push(value);
if (el.value) chunks.push(String(el.value));
if (!el.children.length && el.innerText) chunks.push(el.innerText);
}
for (const el of document.querySelectorAll('input, textarea')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
if (el.value) chunks.push(String(el.value));
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const assertBody = async (text) => {
try {
await waitFor(
async () => (await semanticText()).includes(text),
`body to contain ${JSON.stringify(text)}`,
);
} catch (error) {
throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`);
}
};
const clickText = async (text) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(text)};
const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => {
const label = (el.getAttribute('aria-label') || el.innerText || '').trim();
return label === wanted;
});
const target = candidates.find((el) =>
['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')),
) ?? candidates[0];
if (!target) return false;
target.click();
return true;
})()`);
if (!clicked) {
const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')]
.map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)`);
throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`);
}
await delay(400);
};
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const path = join(output, `${name}.png`);
await writeFile(path, Buffer.from(data, 'base64'));
return path;
};
const ocr = async (path) =>
(await promisify(execFile)('tesseract', [path, 'stdout'])).stdout;
const assertOcr = async (path, text) => {
const read = await ocr(path);
if (!read.toLowerCase().includes(text.toLowerCase())) {
throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 2000)}`);
}
};
const state = async () => (await (await fetch(`${fixtureUrl}/fixture/state`)).json());
const setSize = async (width, height) => {
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
session,
);
await delay(400);
};
const dialogOpen = async () => (await semanticText()).includes('Save');
const focusRenameField = async () => {
const focused = await evaluate(`(() => {
const node = document.querySelector('input.flt-text-editing, flt-semantics input, input, textarea');
if (!node) return false;
node.focus();
node.select?.();
node.setSelectionRange?.(0, (node.value || '').length);
return true;
})()`);
if (!focused) throw new Error('The rename field was not exposed as a semantics input');
await delay(350);
return evaluate(`(() => {
const node = document.querySelector('input.flt-text-editing, flt-semantics input, input, textarea');
return node ? { value: node.value, label: node.getAttribute('aria-label'), placeholder: node.getAttribute('placeholder') } : null;
})()`);
};
const rename = async (value, { initial } = {}) => {
await assertBody('Rename');
await clickText('Rename');
await waitFor(dialogOpen, 'the rename prompt');
const field = await focusRenameField();
if (initial != null && field?.value !== initial) {
throw new Error(`Rename field seeded with ${JSON.stringify(field)}, expected ${JSON.stringify(initial)}`);
}
await send('Input.insertText', { text: value }, session);
await delay(400);
const typed = await evaluate(`(() => {
const node = document.querySelector('input.flt-text-editing, flt-semantics input, input, textarea');
return node ? node.value : null;
})()`);
if (typed !== value) {
throw new Error(`Rename field holds ${JSON.stringify(typed)}, expected ${JSON.stringify(value)}`);
}
await clickText('Save');
await waitFor(
async () => {
const text = await semanticText();
return text.includes(value) && !text.includes('Save');
},
'the saved title from the server',
);
const now = await state();
const last = now.renames.at(-1);
if (last?.title !== value || last?.run_id !== 1) {
throw new Error(`Server did not receive the exact rename: ${JSON.stringify(last)}`);
}
return { ...now, field };
};
const captures = [];
const checks = [];
await setSize(390, 844);
const open = async (expectedTitle) => {
const navigation = await send('Page.navigate', { url: `${fixtureUrl}/runs/1` }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
await enableSemantics();
await assertBody(expectedTitle);
if ((await evaluate('location.pathname')) !== '/runs/1') {
throw new Error(`Deep link moved to ${await evaluate('location.pathname')}`);
}
};
// Cupertino host (macOS browser): Cancel sends nothing, then Save applies the
// exact server reply to the detail and the list row.
await open('Fixture live run');
await assertBody('Original prompt');
captures.push(await capture('r2-title-cupertino-detail'));
await assertOcr(captures[0], 'Fixture live run');
await clickText('Rename');
await waitFor(dialogOpen, 'the rename prompt');
const cancelField = await focusRenameField();
if (cancelField?.value !== 'Fixture live run') {
throw new Error(`Rename field seeded with ${JSON.stringify(cancelField)}`);
}
await send('Input.insertText', { text: 'Discarded title' }, session);
await delay(300);
captures.push(await capture('r2-title-cupertino-dialog'));
await clickText('Cancel');
if ((await state()).renames.length !== 0) {
throw new Error('Cancel sent set_run_title');
}
await assertBody('Fixture live run');
await waitFor(async () => !(await dialogOpen()), 'the closed rename prompt');
checks.push({ check: 'Cancel sent nothing and kept the stored title', sent: 0 });
captures.push(await capture('r2-title-cupertino-cancelled'));
const cupertinoState = await rename('Cupertino renamed run', {
initial: 'Fixture live run',
});
captures.push(await capture('r2-title-cupertino-renamed'));
await assertOcr(captures.at(-1), 'Cupertino renamed run');
checks.push({
check: 'Cupertino Save sent the exact payload',
rename: cupertinoState.renames.at(-1),
field: cupertinoState.field,
});
await clickText('Back');
await assertBody('Cupertino renamed run');
captures.push(await capture('r2-title-cupertino-list'));
await assertOcr(captures.at(-1), 'Cupertino renamed run');
checks.push({ check: 'The list row shows the server title', path: await evaluate('location.pathname') });
// Material host: the same deep link and the same shared gateway.
await send(
'Emulation.setUserAgentOverride',
{
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
platform: 'Linux x86_64',
},
session,
);
await open('Cupertino renamed run');
await assertBody('Original prompt');
await clickText('Rename');
await waitFor(dialogOpen, 'the material rename prompt');
const materialField = await focusRenameField();
if (materialField?.value !== 'Cupertino renamed run') {
throw new Error(`Material rename field seeded with ${JSON.stringify(materialField)}`);
}
await send('Input.insertText', { text: 'Material renamed run' }, session);
await delay(300);
captures.push(await capture('r2-title-material-dialog'));
await clickText('Save');
await waitFor(
async () => {
const text = await semanticText();
return text.includes('Material renamed run') && !text.includes('Save');
},
'the material server title',
);
const materialState = await state();
checks.push({
check: 'Material Save sent the exact payload',
rename: materialState.renames.at(-1),
field: materialField,
});
captures.push(await capture('r2-title-material-renamed'));
await assertOcr(captures.at(-1), 'Material renamed run');
if (materialState.renames.length !== 2) {
throw new Error(`Expected two renames, saw ${JSON.stringify(materialState.renames)}`);
}
if (!materialState.renames[0].title.endsWith('Cupertino renamed run')) {
throw new Error(`First rename drifted: ${JSON.stringify(materialState.renames[0])}`);
}
console.log(JSON.stringify({ ok: true, fixture: fixtureUrl, checks, captures }, null, 2));
} finally {
ws?.close();
for (const socket of sockets) socket.destroy();
await new Promise((resolveClose) => server.close(resolveClose));
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
await rm(profile, { recursive: true, force: true });
}